id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
216,800
moodle/moodle
course/classes/category.php
core_course_category.get
public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null) { if (!$id) { // Top-level category. if ($alwaysreturnhidden || self::top()->is_uservisible()) { return self::top(); } if ($strictness == MUST_EXIST) { throw new moodle_exception('cannotviewcategory'); } return null; } // Try to get category from cache or retrieve from the DB. $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $coursecat = $coursecatrecordcache->get($id); if ($coursecat === false) { if ($records = self::get_records('cc.id = :id', array('id' => $id))) { $record = reset($records); $coursecat = new self($record); // Store in cache. $coursecatrecordcache->set($id, $coursecat); } } if (!$coursecat) { // Course category not found. if ($strictness == MUST_EXIST) { throw new moodle_exception('unknowncategory'); } $coursecat = null; } else if (!$alwaysreturnhidden && !$coursecat->is_uservisible($user)) { // Course category is found but user can not access it. if ($strictness == MUST_EXIST) { throw new moodle_exception('cannotviewcategory'); } $coursecat = null; } return $coursecat; }
php
public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null) { if (!$id) { // Top-level category. if ($alwaysreturnhidden || self::top()->is_uservisible()) { return self::top(); } if ($strictness == MUST_EXIST) { throw new moodle_exception('cannotviewcategory'); } return null; } // Try to get category from cache or retrieve from the DB. $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $coursecat = $coursecatrecordcache->get($id); if ($coursecat === false) { if ($records = self::get_records('cc.id = :id', array('id' => $id))) { $record = reset($records); $coursecat = new self($record); // Store in cache. $coursecatrecordcache->set($id, $coursecat); } } if (!$coursecat) { // Course category not found. if ($strictness == MUST_EXIST) { throw new moodle_exception('unknowncategory'); } $coursecat = null; } else if (!$alwaysreturnhidden && !$coursecat->is_uservisible($user)) { // Course category is found but user can not access it. if ($strictness == MUST_EXIST) { throw new moodle_exception('cannotviewcategory'); } $coursecat = null; } return $coursecat; }
[ "public", "static", "function", "get", "(", "$", "id", ",", "$", "strictness", "=", "MUST_EXIST", ",", "$", "alwaysreturnhidden", "=", "false", ",", "$", "user", "=", "null", ")", "{", "if", "(", "!", "$", "id", ")", "{", "// Top-level category.", "if", "(", "$", "alwaysreturnhidden", "||", "self", "::", "top", "(", ")", "->", "is_uservisible", "(", ")", ")", "{", "return", "self", "::", "top", "(", ")", ";", "}", "if", "(", "$", "strictness", "==", "MUST_EXIST", ")", "{", "throw", "new", "moodle_exception", "(", "'cannotviewcategory'", ")", ";", "}", "return", "null", ";", "}", "// Try to get category from cache or retrieve from the DB.", "$", "coursecatrecordcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecatrecords'", ")", ";", "$", "coursecat", "=", "$", "coursecatrecordcache", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "coursecat", "===", "false", ")", "{", "if", "(", "$", "records", "=", "self", "::", "get_records", "(", "'cc.id = :id'", ",", "array", "(", "'id'", "=>", "$", "id", ")", ")", ")", "{", "$", "record", "=", "reset", "(", "$", "records", ")", ";", "$", "coursecat", "=", "new", "self", "(", "$", "record", ")", ";", "// Store in cache.", "$", "coursecatrecordcache", "->", "set", "(", "$", "id", ",", "$", "coursecat", ")", ";", "}", "}", "if", "(", "!", "$", "coursecat", ")", "{", "// Course category not found.", "if", "(", "$", "strictness", "==", "MUST_EXIST", ")", "{", "throw", "new", "moodle_exception", "(", "'unknowncategory'", ")", ";", "}", "$", "coursecat", "=", "null", ";", "}", "else", "if", "(", "!", "$", "alwaysreturnhidden", "&&", "!", "$", "coursecat", "->", "is_uservisible", "(", "$", "user", ")", ")", "{", "// Course category is found but user can not access it.", "if", "(", "$", "strictness", "==", "MUST_EXIST", ")", "{", "throw", "new", "moodle_exception", "(", "'cannotviewcategory'", ")", ";", "}", "$", "coursecat", "=", "null", ";", "}", "return", "$", "coursecat", ";", "}" ]
Returns coursecat object for requested category If category is not visible to the given user, it is treated as non existing unless $alwaysreturnhidden is set to true If id is 0, the pseudo object for root category is returned (convenient for calling other functions such as get_children()) @param int $id category id @param int $strictness whether to throw an exception (MUST_EXIST) or return null (IGNORE_MISSING) in case the category is not found or not visible to current user @param bool $alwaysreturnhidden set to true if you want an object to be returned even if this category is not visible to the current user (category is hidden and user does not have 'moodle/category:viewhiddencategories' capability). Use with care! @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user. @return null|self @throws moodle_exception
[ "Returns", "coursecat", "object", "for", "requested", "category" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L230-L268
216,801
moodle/moodle
course/classes/category.php
core_course_category.user_top
public static function user_top() { $children = self::top()->get_children(); if (count($children) == 1) { // User has access to only one category on the top level. Return this category as "user top category". return reset($children); } if (count($children) > 1) { // User has access to more than one category on the top level. Return the top as "user top category". // In this case user actually may not have capability 'moodle/category:viewcourselist' on the top level. return self::top(); } // User can not access any categories on the top level. // TODO MDL-10965 find ANY/ALL categories in the tree where user has access to. return self::get(0, IGNORE_MISSING); }
php
public static function user_top() { $children = self::top()->get_children(); if (count($children) == 1) { // User has access to only one category on the top level. Return this category as "user top category". return reset($children); } if (count($children) > 1) { // User has access to more than one category on the top level. Return the top as "user top category". // In this case user actually may not have capability 'moodle/category:viewcourselist' on the top level. return self::top(); } // User can not access any categories on the top level. // TODO MDL-10965 find ANY/ALL categories in the tree where user has access to. return self::get(0, IGNORE_MISSING); }
[ "public", "static", "function", "user_top", "(", ")", "{", "$", "children", "=", "self", "::", "top", "(", ")", "->", "get_children", "(", ")", ";", "if", "(", "count", "(", "$", "children", ")", "==", "1", ")", "{", "// User has access to only one category on the top level. Return this category as \"user top category\".", "return", "reset", "(", "$", "children", ")", ";", "}", "if", "(", "count", "(", "$", "children", ")", ">", "1", ")", "{", "// User has access to more than one category on the top level. Return the top as \"user top category\".", "// In this case user actually may not have capability 'moodle/category:viewcourselist' on the top level.", "return", "self", "::", "top", "(", ")", ";", "}", "// User can not access any categories on the top level.", "// TODO MDL-10965 find ANY/ALL categories in the tree where user has access to.", "return", "self", "::", "get", "(", "0", ",", "IGNORE_MISSING", ")", ";", "}" ]
Returns the top-most category for the current user Examples: 1. User can browse courses everywhere - return self::top() - pseudo-category with id=0 2. User does not have capability to browse courses on the system level but has it in ONE course category - return this course category 3. User has capability to browse courses in two course categories - return self::top() @return core_course_category|null
[ "Returns", "the", "top", "-", "most", "category", "for", "the", "current", "user" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L299-L313
216,802
moodle/moodle
course/classes/category.php
core_course_category.get_many
public static function get_many(array $ids) { global $DB; $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $categories = $coursecatrecordcache->get_many($ids); $toload = array(); foreach ($categories as $id => $result) { if ($result === false) { $toload[] = $id; } } if (!empty($toload)) { list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED); $records = self::get_records('cc.id '.$where, $params); $toset = array(); foreach ($records as $record) { $categories[$record->id] = new self($record); $toset[$record->id] = $categories[$record->id]; } $coursecatrecordcache->set_many($toset); } return $categories; }
php
public static function get_many(array $ids) { global $DB; $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $categories = $coursecatrecordcache->get_many($ids); $toload = array(); foreach ($categories as $id => $result) { if ($result === false) { $toload[] = $id; } } if (!empty($toload)) { list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED); $records = self::get_records('cc.id '.$where, $params); $toset = array(); foreach ($records as $record) { $categories[$record->id] = new self($record); $toset[$record->id] = $categories[$record->id]; } $coursecatrecordcache->set_many($toset); } return $categories; }
[ "public", "static", "function", "get_many", "(", "array", "$", "ids", ")", "{", "global", "$", "DB", ";", "$", "coursecatrecordcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecatrecords'", ")", ";", "$", "categories", "=", "$", "coursecatrecordcache", "->", "get_many", "(", "$", "ids", ")", ";", "$", "toload", "=", "array", "(", ")", ";", "foreach", "(", "$", "categories", "as", "$", "id", "=>", "$", "result", ")", "{", "if", "(", "$", "result", "===", "false", ")", "{", "$", "toload", "[", "]", "=", "$", "id", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "toload", ")", ")", "{", "list", "(", "$", "where", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "toload", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "records", "=", "self", "::", "get_records", "(", "'cc.id '", ".", "$", "where", ",", "$", "params", ")", ";", "$", "toset", "=", "array", "(", ")", ";", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "categories", "[", "$", "record", "->", "id", "]", "=", "new", "self", "(", "$", "record", ")", ";", "$", "toset", "[", "$", "record", "->", "id", "]", "=", "$", "categories", "[", "$", "record", "->", "id", "]", ";", "}", "$", "coursecatrecordcache", "->", "set_many", "(", "$", "toset", ")", ";", "}", "return", "$", "categories", ";", "}" ]
Load many core_course_category objects. @param array $ids An array of category ID's to load. @return core_course_category[]
[ "Load", "many", "core_course_category", "objects", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L321-L342
216,803
moodle/moodle
course/classes/category.php
core_course_category.get_all
public static function get_all($options = []) { global $DB; $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx'); $catsql = "SELECT cc.*, {$catcontextsql} FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid"; $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel"; $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC"; $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [ 'contextlevel' => CONTEXT_COURSECAT, ]); $types['categories'] = []; $categories = []; $toset = []; foreach ($catrs as $record) { $category = new self($record); $toset[$category->id] = $category; if (!empty($options['returnhidden']) || $category->is_uservisible()) { $categories[$record->id] = $category; } } $catrs->close(); $coursecatrecordcache->set_many($toset); return $categories; }
php
public static function get_all($options = []) { global $DB; $coursecatrecordcache = cache::make('core', 'coursecatrecords'); $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx'); $catsql = "SELECT cc.*, {$catcontextsql} FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid"; $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel"; $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC"; $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [ 'contextlevel' => CONTEXT_COURSECAT, ]); $types['categories'] = []; $categories = []; $toset = []; foreach ($catrs as $record) { $category = new self($record); $toset[$category->id] = $category; if (!empty($options['returnhidden']) || $category->is_uservisible()) { $categories[$record->id] = $category; } } $catrs->close(); $coursecatrecordcache->set_many($toset); return $categories; }
[ "public", "static", "function", "get_all", "(", "$", "options", "=", "[", "]", ")", "{", "global", "$", "DB", ";", "$", "coursecatrecordcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecatrecords'", ")", ";", "$", "catcontextsql", "=", "\\", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "catsql", "=", "\"SELECT cc.*, {$catcontextsql}\n FROM {course_categories} cc\n JOIN {context} ctx ON cc.id = ctx.instanceid\"", ";", "$", "catsqlwhere", "=", "\"WHERE ctx.contextlevel = :contextlevel\"", ";", "$", "catsqlorder", "=", "\"ORDER BY cc.depth ASC, cc.sortorder ASC\"", ";", "$", "catrs", "=", "$", "DB", "->", "get_recordset_sql", "(", "\"{$catsql} {$catsqlwhere} {$catsqlorder}\"", ",", "[", "'contextlevel'", "=>", "CONTEXT_COURSECAT", ",", "]", ")", ";", "$", "types", "[", "'categories'", "]", "=", "[", "]", ";", "$", "categories", "=", "[", "]", ";", "$", "toset", "=", "[", "]", ";", "foreach", "(", "$", "catrs", "as", "$", "record", ")", "{", "$", "category", "=", "new", "self", "(", "$", "record", ")", ";", "$", "toset", "[", "$", "category", "->", "id", "]", "=", "$", "category", ";", "if", "(", "!", "empty", "(", "$", "options", "[", "'returnhidden'", "]", ")", "||", "$", "category", "->", "is_uservisible", "(", ")", ")", "{", "$", "categories", "[", "$", "record", "->", "id", "]", "=", "$", "category", ";", "}", "}", "$", "catrs", "->", "close", "(", ")", ";", "$", "coursecatrecordcache", "->", "set_many", "(", "$", "toset", ")", ";", "return", "$", "categories", ";", "}" ]
Load all core_course_category objects. @param array $options Options: - returnhidden Return categories even if they are hidden @return core_course_category[]
[ "Load", "all", "core_course_category", "objects", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L351-L384
216,804
moodle/moodle
course/classes/category.php
core_course_category.get_default
public static function get_default() { if ($visiblechildren = self::top()->get_children()) { $defcategory = reset($visiblechildren); } else { $toplevelcategories = self::get_tree(0); $defcategoryid = $toplevelcategories[0]; $defcategory = self::get($defcategoryid, MUST_EXIST, true); } return $defcategory; }
php
public static function get_default() { if ($visiblechildren = self::top()->get_children()) { $defcategory = reset($visiblechildren); } else { $toplevelcategories = self::get_tree(0); $defcategoryid = $toplevelcategories[0]; $defcategory = self::get($defcategoryid, MUST_EXIST, true); } return $defcategory; }
[ "public", "static", "function", "get_default", "(", ")", "{", "if", "(", "$", "visiblechildren", "=", "self", "::", "top", "(", ")", "->", "get_children", "(", ")", ")", "{", "$", "defcategory", "=", "reset", "(", "$", "visiblechildren", ")", ";", "}", "else", "{", "$", "toplevelcategories", "=", "self", "::", "get_tree", "(", "0", ")", ";", "$", "defcategoryid", "=", "$", "toplevelcategories", "[", "0", "]", ";", "$", "defcategory", "=", "self", "::", "get", "(", "$", "defcategoryid", ",", "MUST_EXIST", ",", "true", ")", ";", "}", "return", "$", "defcategory", ";", "}" ]
Returns the first found category Note that if there are no categories visible to the current user on the first level, the invisible category may be returned @return core_course_category
[ "Returns", "the", "first", "found", "category" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L394-L403
216,805
moodle/moodle
course/classes/category.php
core_course_category.can_view_category
public static function can_view_category($category, $user = null) { if (!$category->id) { return has_capability('moodle/category:viewcourselist', context_system::instance(), $user); } $context = context_coursecat::instance($category->id); if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', $context, $user)) { return false; } return has_capability('moodle/category:viewcourselist', $context, $user); }
php
public static function can_view_category($category, $user = null) { if (!$category->id) { return has_capability('moodle/category:viewcourselist', context_system::instance(), $user); } $context = context_coursecat::instance($category->id); if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', $context, $user)) { return false; } return has_capability('moodle/category:viewcourselist', $context, $user); }
[ "public", "static", "function", "can_view_category", "(", "$", "category", ",", "$", "user", "=", "null", ")", "{", "if", "(", "!", "$", "category", "->", "id", ")", "{", "return", "has_capability", "(", "'moodle/category:viewcourselist'", ",", "context_system", "::", "instance", "(", ")", ",", "$", "user", ")", ";", "}", "$", "context", "=", "context_coursecat", "::", "instance", "(", "$", "category", "->", "id", ")", ";", "if", "(", "!", "$", "category", "->", "visible", "&&", "!", "has_capability", "(", "'moodle/category:viewhiddencategories'", ",", "$", "context", ",", "$", "user", ")", ")", "{", "return", "false", ";", "}", "return", "has_capability", "(", "'moodle/category:viewcourselist'", ",", "$", "context", ",", "$", "user", ")", ";", "}" ]
Checks if current user has access to the category @param stdClass|core_course_category $category @param int|stdClass $user The user id or object. By default (null) checks access for the current user. @return bool
[ "Checks", "if", "current", "user", "has", "access", "to", "the", "category" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L654-L663
216,806
moodle/moodle
course/classes/category.php
core_course_category.can_view_course_info
public static function can_view_course_info($course, $user = null) { if ($course->id == SITEID) { return true; } if (!$course->visible) { $coursecontext = context_course::instance($course->id); if (!has_capability('moodle/course:viewhiddencourses', $coursecontext, $user)) { return false; } } $categorycontext = isset($course->category) ? context_coursecat::instance($course->category) : context_course::instance($course->id)->get_parent_context(); return has_capability('moodle/category:viewcourselist', $categorycontext, $user); }
php
public static function can_view_course_info($course, $user = null) { if ($course->id == SITEID) { return true; } if (!$course->visible) { $coursecontext = context_course::instance($course->id); if (!has_capability('moodle/course:viewhiddencourses', $coursecontext, $user)) { return false; } } $categorycontext = isset($course->category) ? context_coursecat::instance($course->category) : context_course::instance($course->id)->get_parent_context(); return has_capability('moodle/category:viewcourselist', $categorycontext, $user); }
[ "public", "static", "function", "can_view_course_info", "(", "$", "course", ",", "$", "user", "=", "null", ")", "{", "if", "(", "$", "course", "->", "id", "==", "SITEID", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "course", "->", "visible", ")", "{", "$", "coursecontext", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "if", "(", "!", "has_capability", "(", "'moodle/course:viewhiddencourses'", ",", "$", "coursecontext", ",", "$", "user", ")", ")", "{", "return", "false", ";", "}", "}", "$", "categorycontext", "=", "isset", "(", "$", "course", "->", "category", ")", "?", "context_coursecat", "::", "instance", "(", "$", "course", "->", "category", ")", ":", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", "->", "get_parent_context", "(", ")", ";", "return", "has_capability", "(", "'moodle/category:viewcourselist'", ",", "$", "categorycontext", ",", "$", "user", ")", ";", "}" ]
Checks if current user can view course information or enrolment page. This method does not check if user is already enrolled in the course @param stdClass $course course object (must have 'id', 'visible' and 'category' fields) @param null|stdClass $user The user id or object. By default (null) checks access for the current user.
[ "Checks", "if", "current", "user", "can", "view", "course", "information", "or", "enrolment", "page", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L673-L686
216,807
moodle/moodle
course/classes/category.php
core_course_category.get_db_record
public function get_db_record() { global $DB; if ($record = $DB->get_record('course_categories', array('id' => $this->id))) { return $record; } else { return (object)convert_to_array($this); } }
php
public function get_db_record() { global $DB; if ($record = $DB->get_record('course_categories', array('id' => $this->id))) { return $record; } else { return (object)convert_to_array($this); } }
[ "public", "function", "get_db_record", "(", ")", "{", "global", "$", "DB", ";", "if", "(", "$", "record", "=", "$", "DB", "->", "get_record", "(", "'course_categories'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ")", ")", ")", "{", "return", "$", "record", ";", "}", "else", "{", "return", "(", "object", ")", "convert_to_array", "(", "$", "this", ")", ";", "}", "}" ]
Returns the complete corresponding record from DB table course_categories Mostly used in deprecated functions @return stdClass
[ "Returns", "the", "complete", "corresponding", "record", "from", "DB", "table", "course_categories" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L695-L702
216,808
moodle/moodle
course/classes/category.php
core_course_category.get_tree
protected static function get_tree($id) { global $DB; $coursecattreecache = cache::make('core', 'coursecattree'); $rv = $coursecattreecache->get($id); if ($rv !== false) { return $rv; } // Re-build the tree. $sql = "SELECT cc.id, cc.parent, cc.visible FROM {course_categories} cc ORDER BY cc.sortorder"; $rs = $DB->get_recordset_sql($sql, array()); $all = array(0 => array(), '0i' => array()); $count = 0; foreach ($rs as $record) { $all[$record->id] = array(); $all[$record->id. 'i'] = array(); if (array_key_exists($record->parent, $all)) { $all[$record->parent][] = $record->id; if (!$record->visible) { $all[$record->parent. 'i'][] = $record->id; } } else { // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it. $all[0][] = $record->id; if (!$record->visible) { $all['0i'][] = $record->id; } } $count++; } $rs->close(); if (!$count) { // No categories found. // This may happen after upgrade of a very old moodle version. // In new versions the default category is created on install. $defcoursecat = self::create(array('name' => get_string('miscellaneous'))); set_config('defaultrequestcategory', $defcoursecat->id); $all[0] = array($defcoursecat->id); $all[$defcoursecat->id] = array(); $count++; } // We must add countall to all in case it was the requested ID. $all['countall'] = $count; $coursecattreecache->set_many($all); if (array_key_exists($id, $all)) { return $all[$id]; } // Requested non-existing category. return array(); }
php
protected static function get_tree($id) { global $DB; $coursecattreecache = cache::make('core', 'coursecattree'); $rv = $coursecattreecache->get($id); if ($rv !== false) { return $rv; } // Re-build the tree. $sql = "SELECT cc.id, cc.parent, cc.visible FROM {course_categories} cc ORDER BY cc.sortorder"; $rs = $DB->get_recordset_sql($sql, array()); $all = array(0 => array(), '0i' => array()); $count = 0; foreach ($rs as $record) { $all[$record->id] = array(); $all[$record->id. 'i'] = array(); if (array_key_exists($record->parent, $all)) { $all[$record->parent][] = $record->id; if (!$record->visible) { $all[$record->parent. 'i'][] = $record->id; } } else { // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it. $all[0][] = $record->id; if (!$record->visible) { $all['0i'][] = $record->id; } } $count++; } $rs->close(); if (!$count) { // No categories found. // This may happen after upgrade of a very old moodle version. // In new versions the default category is created on install. $defcoursecat = self::create(array('name' => get_string('miscellaneous'))); set_config('defaultrequestcategory', $defcoursecat->id); $all[0] = array($defcoursecat->id); $all[$defcoursecat->id] = array(); $count++; } // We must add countall to all in case it was the requested ID. $all['countall'] = $count; $coursecattreecache->set_many($all); if (array_key_exists($id, $all)) { return $all[$id]; } // Requested non-existing category. return array(); }
[ "protected", "static", "function", "get_tree", "(", "$", "id", ")", "{", "global", "$", "DB", ";", "$", "coursecattreecache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecattree'", ")", ";", "$", "rv", "=", "$", "coursecattreecache", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "rv", "!==", "false", ")", "{", "return", "$", "rv", ";", "}", "// Re-build the tree.", "$", "sql", "=", "\"SELECT cc.id, cc.parent, cc.visible\n FROM {course_categories} cc\n ORDER BY cc.sortorder\"", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "array", "(", ")", ")", ";", "$", "all", "=", "array", "(", "0", "=>", "array", "(", ")", ",", "'0i'", "=>", "array", "(", ")", ")", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "rs", "as", "$", "record", ")", "{", "$", "all", "[", "$", "record", "->", "id", "]", "=", "array", "(", ")", ";", "$", "all", "[", "$", "record", "->", "id", ".", "'i'", "]", "=", "array", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "record", "->", "parent", ",", "$", "all", ")", ")", "{", "$", "all", "[", "$", "record", "->", "parent", "]", "[", "]", "=", "$", "record", "->", "id", ";", "if", "(", "!", "$", "record", "->", "visible", ")", "{", "$", "all", "[", "$", "record", "->", "parent", ".", "'i'", "]", "[", "]", "=", "$", "record", "->", "id", ";", "}", "}", "else", "{", "// Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.", "$", "all", "[", "0", "]", "[", "]", "=", "$", "record", "->", "id", ";", "if", "(", "!", "$", "record", "->", "visible", ")", "{", "$", "all", "[", "'0i'", "]", "[", "]", "=", "$", "record", "->", "id", ";", "}", "}", "$", "count", "++", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "if", "(", "!", "$", "count", ")", "{", "// No categories found.", "// This may happen after upgrade of a very old moodle version.", "// In new versions the default category is created on install.", "$", "defcoursecat", "=", "self", "::", "create", "(", "array", "(", "'name'", "=>", "get_string", "(", "'miscellaneous'", ")", ")", ")", ";", "set_config", "(", "'defaultrequestcategory'", ",", "$", "defcoursecat", "->", "id", ")", ";", "$", "all", "[", "0", "]", "=", "array", "(", "$", "defcoursecat", "->", "id", ")", ";", "$", "all", "[", "$", "defcoursecat", "->", "id", "]", "=", "array", "(", ")", ";", "$", "count", "++", ";", "}", "// We must add countall to all in case it was the requested ID.", "$", "all", "[", "'countall'", "]", "=", "$", "count", ";", "$", "coursecattreecache", "->", "set_many", "(", "$", "all", ")", ";", "if", "(", "array_key_exists", "(", "$", "id", ",", "$", "all", ")", ")", "{", "return", "$", "all", "[", "$", "id", "]", ";", "}", "// Requested non-existing category.", "return", "array", "(", ")", ";", "}" ]
Returns the entry from categories tree and makes sure the application-level tree cache is built The following keys can be requested: 'countall' - total number of categories in the system (always present) 0 - array of ids of top-level categories (always present) '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array) $id (int) - array of ids of categories that are direct children of category with id $id. If category with id $id does not exist returns false. If category has no children returns empty array $id.'i' - array of ids of children categories that have visible=0 @param int|string $id @return mixed
[ "Returns", "the", "entry", "from", "categories", "tree", "and", "makes", "sure", "the", "application", "-", "level", "tree", "cache", "is", "built" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L719-L769
216,809
moodle/moodle
course/classes/category.php
core_course_category.get_records
protected static function get_records($whereclause, $params) { global $DB; // Retrieve from DB only the fields that need to be stored in cache. $fields = array_keys(array_filter(self::$coursecatfields)); $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat WHERE ". $whereclause." ORDER BY cc.sortorder"; return $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT) + $params); }
php
protected static function get_records($whereclause, $params) { global $DB; // Retrieve from DB only the fields that need to be stored in cache. $fields = array_keys(array_filter(self::$coursecatfields)); $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat WHERE ". $whereclause." ORDER BY cc.sortorder"; return $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT) + $params); }
[ "protected", "static", "function", "get_records", "(", "$", "whereclause", ",", "$", "params", ")", "{", "global", "$", "DB", ";", "// Retrieve from DB only the fields that need to be stored in cache.", "$", "fields", "=", "array_keys", "(", "array_filter", "(", "self", "::", "$", "coursecatfields", ")", ")", ";", "$", "ctxselect", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "sql", "=", "\"SELECT cc.\"", ".", "join", "(", "',cc.'", ",", "$", "fields", ")", ".", "\", $ctxselect\n FROM {course_categories} cc\n JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat\n WHERE \"", ".", "$", "whereclause", ".", "\" ORDER BY cc.sortorder\"", ";", "return", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "array", "(", "'contextcoursecat'", "=>", "CONTEXT_COURSECAT", ")", "+", "$", "params", ")", ";", "}" ]
Retrieves number of records from course_categories table Only cached fields are retrieved. Records are ready for preloading context @param string $whereclause @param array $params @return array array of stdClass objects
[ "Retrieves", "number", "of", "records", "from", "course_categories", "table" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L807-L818
216,810
moodle/moodle
course/classes/category.php
core_course_category.role_assignment_changed
public static function role_assignment_changed($roleid, $context) { global $CFG, $DB; if ($context->contextlevel > CONTEXT_COURSE) { // No changes to course contacts if role was assigned on the module/block level. return; } // Trigger a purge for all caches listening for changes to category enrolment. cache_helper::purge_by_event('changesincategoryenrolment'); if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) { // The role is not one of course contact roles. return; } // Remove from cache course contacts of all affected courses. $cache = cache::make('core', 'coursecontacts'); if ($context->contextlevel == CONTEXT_COURSE) { $cache->delete($context->instanceid); } else if ($context->contextlevel == CONTEXT_SYSTEM) { $cache->purge(); } else { $sql = "SELECT ctx.instanceid FROM {context} ctx WHERE ctx.path LIKE ? AND ctx.contextlevel = ?"; $params = array($context->path . '/%', CONTEXT_COURSE); if ($courses = $DB->get_fieldset_sql($sql, $params)) { $cache->delete_many($courses); } } }
php
public static function role_assignment_changed($roleid, $context) { global $CFG, $DB; if ($context->contextlevel > CONTEXT_COURSE) { // No changes to course contacts if role was assigned on the module/block level. return; } // Trigger a purge for all caches listening for changes to category enrolment. cache_helper::purge_by_event('changesincategoryenrolment'); if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) { // The role is not one of course contact roles. return; } // Remove from cache course contacts of all affected courses. $cache = cache::make('core', 'coursecontacts'); if ($context->contextlevel == CONTEXT_COURSE) { $cache->delete($context->instanceid); } else if ($context->contextlevel == CONTEXT_SYSTEM) { $cache->purge(); } else { $sql = "SELECT ctx.instanceid FROM {context} ctx WHERE ctx.path LIKE ? AND ctx.contextlevel = ?"; $params = array($context->path . '/%', CONTEXT_COURSE); if ($courses = $DB->get_fieldset_sql($sql, $params)) { $cache->delete_many($courses); } } }
[ "public", "static", "function", "role_assignment_changed", "(", "$", "roleid", ",", "$", "context", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "if", "(", "$", "context", "->", "contextlevel", ">", "CONTEXT_COURSE", ")", "{", "// No changes to course contacts if role was assigned on the module/block level.", "return", ";", "}", "// Trigger a purge for all caches listening for changes to category enrolment.", "cache_helper", "::", "purge_by_event", "(", "'changesincategoryenrolment'", ")", ";", "if", "(", "!", "$", "CFG", "->", "coursecontact", "||", "!", "in_array", "(", "$", "roleid", ",", "explode", "(", "','", ",", "$", "CFG", "->", "coursecontact", ")", ")", ")", "{", "// The role is not one of course contact roles.", "return", ";", "}", "// Remove from cache course contacts of all affected courses.", "$", "cache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecontacts'", ")", ";", "if", "(", "$", "context", "->", "contextlevel", "==", "CONTEXT_COURSE", ")", "{", "$", "cache", "->", "delete", "(", "$", "context", "->", "instanceid", ")", ";", "}", "else", "if", "(", "$", "context", "->", "contextlevel", "==", "CONTEXT_SYSTEM", ")", "{", "$", "cache", "->", "purge", "(", ")", ";", "}", "else", "{", "$", "sql", "=", "\"SELECT ctx.instanceid\n FROM {context} ctx\n WHERE ctx.path LIKE ? AND ctx.contextlevel = ?\"", ";", "$", "params", "=", "array", "(", "$", "context", "->", "path", ".", "'/%'", ",", "CONTEXT_COURSE", ")", ";", "if", "(", "$", "courses", "=", "$", "DB", "->", "get_fieldset_sql", "(", "$", "sql", ",", "$", "params", ")", ")", "{", "$", "cache", "->", "delete_many", "(", "$", "courses", ")", ";", "}", "}", "}" ]
Resets course contact caches when role assignments were changed @param int $roleid role id that was given or taken away @param context $context context where role assignment has been changed
[ "Resets", "course", "contact", "caches", "when", "role", "assignments", "were", "changed" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L826-L857
216,811
moodle/moodle
course/classes/category.php
core_course_category.user_enrolment_changed
public static function user_enrolment_changed($courseid, $userid, $status, $timestart = null, $timeend = null) { $cache = cache::make('core', 'coursecontacts'); $contacts = $cache->get($courseid); if ($contacts === false) { // The contacts for the affected course were not cached anyway. return; } $enrolmentactive = ($status == 0) && (!$timestart || $timestart < time()) && (!$timeend || $timeend > time()); if (!$enrolmentactive) { $isincontacts = false; foreach ($contacts as $contact) { if ($contact->id == $userid) { $isincontacts = true; } } if (!$isincontacts) { // Changed user's enrolment does not exist or is not active, // and he is not in cached course contacts, no changes to be made. return; } } // Either enrolment of manager was deleted/suspended // or user enrolment was added or activated. // In order to see if the course contacts for this course need // changing we would need to make additional queries, they will // slow down bulk enrolment changes. It is better just to remove // course contacts cache for this course. $cache->delete($courseid); }
php
public static function user_enrolment_changed($courseid, $userid, $status, $timestart = null, $timeend = null) { $cache = cache::make('core', 'coursecontacts'); $contacts = $cache->get($courseid); if ($contacts === false) { // The contacts for the affected course were not cached anyway. return; } $enrolmentactive = ($status == 0) && (!$timestart || $timestart < time()) && (!$timeend || $timeend > time()); if (!$enrolmentactive) { $isincontacts = false; foreach ($contacts as $contact) { if ($contact->id == $userid) { $isincontacts = true; } } if (!$isincontacts) { // Changed user's enrolment does not exist or is not active, // and he is not in cached course contacts, no changes to be made. return; } } // Either enrolment of manager was deleted/suspended // or user enrolment was added or activated. // In order to see if the course contacts for this course need // changing we would need to make additional queries, they will // slow down bulk enrolment changes. It is better just to remove // course contacts cache for this course. $cache->delete($courseid); }
[ "public", "static", "function", "user_enrolment_changed", "(", "$", "courseid", ",", "$", "userid", ",", "$", "status", ",", "$", "timestart", "=", "null", ",", "$", "timeend", "=", "null", ")", "{", "$", "cache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecontacts'", ")", ";", "$", "contacts", "=", "$", "cache", "->", "get", "(", "$", "courseid", ")", ";", "if", "(", "$", "contacts", "===", "false", ")", "{", "// The contacts for the affected course were not cached anyway.", "return", ";", "}", "$", "enrolmentactive", "=", "(", "$", "status", "==", "0", ")", "&&", "(", "!", "$", "timestart", "||", "$", "timestart", "<", "time", "(", ")", ")", "&&", "(", "!", "$", "timeend", "||", "$", "timeend", ">", "time", "(", ")", ")", ";", "if", "(", "!", "$", "enrolmentactive", ")", "{", "$", "isincontacts", "=", "false", ";", "foreach", "(", "$", "contacts", "as", "$", "contact", ")", "{", "if", "(", "$", "contact", "->", "id", "==", "$", "userid", ")", "{", "$", "isincontacts", "=", "true", ";", "}", "}", "if", "(", "!", "$", "isincontacts", ")", "{", "// Changed user's enrolment does not exist or is not active,", "// and he is not in cached course contacts, no changes to be made.", "return", ";", "}", "}", "// Either enrolment of manager was deleted/suspended", "// or user enrolment was added or activated.", "// In order to see if the course contacts for this course need", "// changing we would need to make additional queries, they will", "// slow down bulk enrolment changes. It is better just to remove", "// course contacts cache for this course.", "$", "cache", "->", "delete", "(", "$", "courseid", ")", ";", "}" ]
Executed when user enrolment was changed to check if course contacts cache needs to be cleared @param int $courseid course id @param int $userid user id @param int $status new enrolment status (0 - active, 1 - suspended) @param int $timestart new enrolment time start @param int $timeend new enrolment time end
[ "Executed", "when", "user", "enrolment", "was", "changed", "to", "check", "if", "course", "contacts", "cache", "needs", "to", "be", "cleared" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L869-L900
216,812
moodle/moodle
course/classes/category.php
core_course_category.preload_custom_fields
public static function preload_custom_fields(array &$records) { $customfields = \core_course\customfield\course_handler::create()->get_instances_data(array_keys($records)); foreach ($customfields as $courseid => $data) { $records[$courseid]->customfields = $data; } }
php
public static function preload_custom_fields(array &$records) { $customfields = \core_course\customfield\course_handler::create()->get_instances_data(array_keys($records)); foreach ($customfields as $courseid => $data) { $records[$courseid]->customfields = $data; } }
[ "public", "static", "function", "preload_custom_fields", "(", "array", "&", "$", "records", ")", "{", "$", "customfields", "=", "\\", "core_course", "\\", "customfield", "\\", "course_handler", "::", "create", "(", ")", "->", "get_instances_data", "(", "array_keys", "(", "$", "records", ")", ")", ";", "foreach", "(", "$", "customfields", "as", "$", "courseid", "=>", "$", "data", ")", "{", "$", "records", "[", "$", "courseid", "]", "->", "customfields", "=", "$", "data", ";", "}", "}" ]
Preloads the custom fields values in bulk @param array $records
[ "Preloads", "the", "custom", "fields", "values", "in", "bulk" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1020-L1025
216,813
moodle/moodle
course/classes/category.php
core_course_category.ensure_users_enrolled
protected static function ensure_users_enrolled($courseusers) { global $DB; // If the input array is too big, split it into chunks. $maxcoursesinquery = 20; if (count($courseusers) > $maxcoursesinquery) { $rv = array(); for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) { $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true); $rv = $rv + self::ensure_users_enrolled($chunk); } return $rv; } // Create a query verifying valid user enrolments for the number of courses. $sql = "SELECT DISTINCT e.courseid, ue.userid FROM {user_enrolments} ue JOIN {enrol} e ON e.id = ue.enrolid WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; $now = round(time(), -2); // Rounding helps caching in DB. $params = array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'now1' => $now, 'now2' => $now); $cnt = 0; $subsqls = array(); $enrolled = array(); foreach ($courseusers as $id => $userids) { $enrolled[$id] = array(); if (count($userids)) { list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_'); $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")"; $params = $params + array('courseid'.$cnt => $id) + $params2; $cnt++; } } if (count($subsqls)) { $sql .= "AND (". join(' OR ', $subsqls).")"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $record) { $enrolled[$record->courseid][] = $record->userid; } $rs->close(); } return $enrolled; }
php
protected static function ensure_users_enrolled($courseusers) { global $DB; // If the input array is too big, split it into chunks. $maxcoursesinquery = 20; if (count($courseusers) > $maxcoursesinquery) { $rv = array(); for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) { $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true); $rv = $rv + self::ensure_users_enrolled($chunk); } return $rv; } // Create a query verifying valid user enrolments for the number of courses. $sql = "SELECT DISTINCT e.courseid, ue.userid FROM {user_enrolments} ue JOIN {enrol} e ON e.id = ue.enrolid WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; $now = round(time(), -2); // Rounding helps caching in DB. $params = array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'now1' => $now, 'now2' => $now); $cnt = 0; $subsqls = array(); $enrolled = array(); foreach ($courseusers as $id => $userids) { $enrolled[$id] = array(); if (count($userids)) { list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_'); $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")"; $params = $params + array('courseid'.$cnt => $id) + $params2; $cnt++; } } if (count($subsqls)) { $sql .= "AND (". join(' OR ', $subsqls).")"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $record) { $enrolled[$record->courseid][] = $record->userid; } $rs->close(); } return $enrolled; }
[ "protected", "static", "function", "ensure_users_enrolled", "(", "$", "courseusers", ")", "{", "global", "$", "DB", ";", "// If the input array is too big, split it into chunks.", "$", "maxcoursesinquery", "=", "20", ";", "if", "(", "count", "(", "$", "courseusers", ")", ">", "$", "maxcoursesinquery", ")", "{", "$", "rv", "=", "array", "(", ")", ";", "for", "(", "$", "offset", "=", "0", ";", "$", "offset", "<", "count", "(", "$", "courseusers", ")", ";", "$", "offset", "+=", "$", "maxcoursesinquery", ")", "{", "$", "chunk", "=", "array_slice", "(", "$", "courseusers", ",", "$", "offset", ",", "$", "maxcoursesinquery", ",", "true", ")", ";", "$", "rv", "=", "$", "rv", "+", "self", "::", "ensure_users_enrolled", "(", "$", "chunk", ")", ";", "}", "return", "$", "rv", ";", "}", "// Create a query verifying valid user enrolments for the number of courses.", "$", "sql", "=", "\"SELECT DISTINCT e.courseid, ue.userid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON e.id = ue.enrolid\n WHERE ue.status = :active\n AND e.status = :enabled\n AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)\"", ";", "$", "now", "=", "round", "(", "time", "(", ")", ",", "-", "2", ")", ";", "// Rounding helps caching in DB.", "$", "params", "=", "array", "(", "'enabled'", "=>", "ENROL_INSTANCE_ENABLED", ",", "'active'", "=>", "ENROL_USER_ACTIVE", ",", "'now1'", "=>", "$", "now", ",", "'now2'", "=>", "$", "now", ")", ";", "$", "cnt", "=", "0", ";", "$", "subsqls", "=", "array", "(", ")", ";", "$", "enrolled", "=", "array", "(", ")", ";", "foreach", "(", "$", "courseusers", "as", "$", "id", "=>", "$", "userids", ")", "{", "$", "enrolled", "[", "$", "id", "]", "=", "array", "(", ")", ";", "if", "(", "count", "(", "$", "userids", ")", ")", "{", "list", "(", "$", "sql2", ",", "$", "params2", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "userids", ",", "SQL_PARAMS_NAMED", ",", "'userid'", ".", "$", "cnt", ".", "'_'", ")", ";", "$", "subsqls", "[", "]", "=", "\"(e.courseid = :courseid$cnt AND ue.userid \"", ".", "$", "sql2", ".", "\")\"", ";", "$", "params", "=", "$", "params", "+", "array", "(", "'courseid'", ".", "$", "cnt", "=>", "$", "id", ")", "+", "$", "params2", ";", "$", "cnt", "++", ";", "}", "}", "if", "(", "count", "(", "$", "subsqls", ")", ")", "{", "$", "sql", ".=", "\"AND (\"", ".", "join", "(", "' OR '", ",", "$", "subsqls", ")", ".", "\")\"", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "foreach", "(", "$", "rs", "as", "$", "record", ")", "{", "$", "enrolled", "[", "$", "record", "->", "courseid", "]", "[", "]", "=", "$", "record", "->", "userid", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "}", "return", "$", "enrolled", ";", "}" ]
Verify user enrollments for multiple course-user combinations @param array $courseusers array where keys are course ids and values are array of users in this course whose enrolment we wish to verify @return array same structure as input array but values list only users from input who are enrolled in the course
[ "Verify", "user", "enrollments", "for", "multiple", "course", "-", "user", "combinations" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1035-L1080
216,814
moodle/moodle
course/classes/category.php
core_course_category.get_course_records
protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) { global $DB; $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $fields = array('c.id', 'c.category', 'c.sortorder', 'c.shortname', 'c.fullname', 'c.idnumber', 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev'); if (!empty($options['summary'])) { $fields[] = 'c.summary'; $fields[] = 'c.summaryformat'; } else { $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary'; } $sql = "SELECT ". join(',', $fields). ", $ctxselect FROM {course} c JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse WHERE ". $whereclause." ORDER BY c.sortorder"; $list = $DB->get_records_sql($sql, array('contextcourse' => CONTEXT_COURSE) + $params); if ($checkvisibility) { $mycourses = enrol_get_my_courses(); // Loop through all records and make sure we only return the courses accessible by user. foreach ($list as $course) { if (isset($list[$course->id]->hassummary)) { $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0; } context_helper::preload_from_record($course); $context = context_course::instance($course->id); // Check that course is accessible by user. if (!array_key_exists($course->id, $mycourses) && !self::can_view_course_info($course)) { unset($list[$course->id]); } } } return $list; }
php
protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) { global $DB; $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $fields = array('c.id', 'c.category', 'c.sortorder', 'c.shortname', 'c.fullname', 'c.idnumber', 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev'); if (!empty($options['summary'])) { $fields[] = 'c.summary'; $fields[] = 'c.summaryformat'; } else { $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary'; } $sql = "SELECT ". join(',', $fields). ", $ctxselect FROM {course} c JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse WHERE ". $whereclause." ORDER BY c.sortorder"; $list = $DB->get_records_sql($sql, array('contextcourse' => CONTEXT_COURSE) + $params); if ($checkvisibility) { $mycourses = enrol_get_my_courses(); // Loop through all records and make sure we only return the courses accessible by user. foreach ($list as $course) { if (isset($list[$course->id]->hassummary)) { $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0; } context_helper::preload_from_record($course); $context = context_course::instance($course->id); // Check that course is accessible by user. if (!array_key_exists($course->id, $mycourses) && !self::can_view_course_info($course)) { unset($list[$course->id]); } } } return $list; }
[ "protected", "static", "function", "get_course_records", "(", "$", "whereclause", ",", "$", "params", ",", "$", "options", ",", "$", "checkvisibility", "=", "false", ")", "{", "global", "$", "DB", ";", "$", "ctxselect", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "fields", "=", "array", "(", "'c.id'", ",", "'c.category'", ",", "'c.sortorder'", ",", "'c.shortname'", ",", "'c.fullname'", ",", "'c.idnumber'", ",", "'c.startdate'", ",", "'c.enddate'", ",", "'c.visible'", ",", "'c.cacherev'", ")", ";", "if", "(", "!", "empty", "(", "$", "options", "[", "'summary'", "]", ")", ")", "{", "$", "fields", "[", "]", "=", "'c.summary'", ";", "$", "fields", "[", "]", "=", "'c.summaryformat'", ";", "}", "else", "{", "$", "fields", "[", "]", "=", "$", "DB", "->", "sql_substr", "(", "'c.summary'", ",", "1", ",", "1", ")", ".", "' as hassummary'", ";", "}", "$", "sql", "=", "\"SELECT \"", ".", "join", "(", "','", ",", "$", "fields", ")", ".", "\", $ctxselect\n FROM {course} c\n JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse\n WHERE \"", ".", "$", "whereclause", ".", "\" ORDER BY c.sortorder\"", ";", "$", "list", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "array", "(", "'contextcourse'", "=>", "CONTEXT_COURSE", ")", "+", "$", "params", ")", ";", "if", "(", "$", "checkvisibility", ")", "{", "$", "mycourses", "=", "enrol_get_my_courses", "(", ")", ";", "// Loop through all records and make sure we only return the courses accessible by user.", "foreach", "(", "$", "list", "as", "$", "course", ")", "{", "if", "(", "isset", "(", "$", "list", "[", "$", "course", "->", "id", "]", "->", "hassummary", ")", ")", "{", "$", "list", "[", "$", "course", "->", "id", "]", "->", "hassummary", "=", "strlen", "(", "$", "list", "[", "$", "course", "->", "id", "]", "->", "hassummary", ")", ">", "0", ";", "}", "context_helper", "::", "preload_from_record", "(", "$", "course", ")", ";", "$", "context", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "// Check that course is accessible by user.", "if", "(", "!", "array_key_exists", "(", "$", "course", "->", "id", ",", "$", "mycourses", ")", "&&", "!", "self", "::", "can_view_course_info", "(", "$", "course", ")", ")", "{", "unset", "(", "$", "list", "[", "$", "course", "->", "id", "]", ")", ";", "}", "}", "}", "return", "$", "list", ";", "}" ]
Retrieves number of records from course table Not all fields are retrieved. Records are ready for preloading context @param string $whereclause @param array $params @param array $options may indicate that summary needs to be retrieved @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked on not visible courses and 'moodle/category:viewcourselist' on all courses @return array array of stdClass objects
[ "Retrieves", "number", "of", "records", "from", "course", "table" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1094-L1130
216,815
moodle/moodle
course/classes/category.php
core_course_category.get_not_visible_children_ids
protected function get_not_visible_children_ids() { global $DB; $coursecatcache = cache::make('core', 'coursecat'); if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) { // We never checked visible children before. $hidden = self::get_tree($this->id.'i'); $catids = self::get_tree($this->id); $invisibleids = array(); if ($catids) { // Preload categories contexts. list($sql, $params) = $DB->get_in_or_equal($catids, SQL_PARAMS_NAMED, 'id'); $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql, array('contextcoursecat' => CONTEXT_COURSECAT) + $params); foreach ($contexts as $record) { context_helper::preload_from_record($record); } // Check access for each category. foreach ($catids as $id) { $cat = (object)['id' => $id, 'visible' => in_array($id, $hidden) ? 0 : 1]; if (!self::can_view_category($cat)) { $invisibleids[] = $id; } } } $coursecatcache->set('ic'. $this->id, $invisibleids); } return $invisibleids; }
php
protected function get_not_visible_children_ids() { global $DB; $coursecatcache = cache::make('core', 'coursecat'); if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) { // We never checked visible children before. $hidden = self::get_tree($this->id.'i'); $catids = self::get_tree($this->id); $invisibleids = array(); if ($catids) { // Preload categories contexts. list($sql, $params) = $DB->get_in_or_equal($catids, SQL_PARAMS_NAMED, 'id'); $ctxselect = context_helper::get_preload_record_columns_sql('ctx'); $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql, array('contextcoursecat' => CONTEXT_COURSECAT) + $params); foreach ($contexts as $record) { context_helper::preload_from_record($record); } // Check access for each category. foreach ($catids as $id) { $cat = (object)['id' => $id, 'visible' => in_array($id, $hidden) ? 0 : 1]; if (!self::can_view_category($cat)) { $invisibleids[] = $id; } } } $coursecatcache->set('ic'. $this->id, $invisibleids); } return $invisibleids; }
[ "protected", "function", "get_not_visible_children_ids", "(", ")", "{", "global", "$", "DB", ";", "$", "coursecatcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecat'", ")", ";", "if", "(", "(", "$", "invisibleids", "=", "$", "coursecatcache", "->", "get", "(", "'ic'", ".", "$", "this", "->", "id", ")", ")", "===", "false", ")", "{", "// We never checked visible children before.", "$", "hidden", "=", "self", "::", "get_tree", "(", "$", "this", "->", "id", ".", "'i'", ")", ";", "$", "catids", "=", "self", "::", "get_tree", "(", "$", "this", "->", "id", ")", ";", "$", "invisibleids", "=", "array", "(", ")", ";", "if", "(", "$", "catids", ")", "{", "// Preload categories contexts.", "list", "(", "$", "sql", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "catids", ",", "SQL_PARAMS_NAMED", ",", "'id'", ")", ";", "$", "ctxselect", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "contexts", "=", "$", "DB", "->", "get_records_sql", "(", "\"SELECT $ctxselect FROM {context} ctx\n WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid \"", ".", "$", "sql", ",", "array", "(", "'contextcoursecat'", "=>", "CONTEXT_COURSECAT", ")", "+", "$", "params", ")", ";", "foreach", "(", "$", "contexts", "as", "$", "record", ")", "{", "context_helper", "::", "preload_from_record", "(", "$", "record", ")", ";", "}", "// Check access for each category.", "foreach", "(", "$", "catids", "as", "$", "id", ")", "{", "$", "cat", "=", "(", "object", ")", "[", "'id'", "=>", "$", "id", ",", "'visible'", "=>", "in_array", "(", "$", "id", ",", "$", "hidden", ")", "?", "0", ":", "1", "]", ";", "if", "(", "!", "self", "::", "can_view_category", "(", "$", "cat", ")", ")", "{", "$", "invisibleids", "[", "]", "=", "$", "id", ";", "}", "}", "}", "$", "coursecatcache", "->", "set", "(", "'ic'", ".", "$", "this", "->", "id", ",", "$", "invisibleids", ")", ";", "}", "return", "$", "invisibleids", ";", "}" ]
Returns array of ids of children categories that current user can not see This data is cached in user session cache @return array
[ "Returns", "array", "of", "ids", "of", "children", "categories", "that", "current", "user", "can", "not", "see" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1139-L1168
216,816
moodle/moodle
course/classes/category.php
core_course_category.sort_records
protected static function sort_records(&$records, $sortfields) { if (empty($records)) { return; } // If sorting by course display name, calculate it (it may be fullname or shortname+fullname). if (array_key_exists('displayname', $sortfields)) { foreach ($records as $key => $record) { if (!isset($record->displayname)) { $records[$key]->displayname = get_course_display_name_for_list($record); } } } // Sorting by one field - use core_collator. if (count($sortfields) == 1) { $property = key($sortfields); if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) { $sortflag = core_collator::SORT_NUMERIC; } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) { $sortflag = core_collator::SORT_STRING; } else { $sortflag = core_collator::SORT_REGULAR; } core_collator::asort_objects_by_property($records, $property, $sortflag); if ($sortfields[$property] < 0) { $records = array_reverse($records, true); } return; } // Sort by multiple fields - use custom sorting. uasort($records, function($a, $b) use ($sortfields) { foreach ($sortfields as $field => $mult) { // Nulls first. if (is_null($a->$field) && !is_null($b->$field)) { return -$mult; } if (is_null($b->$field) && !is_null($a->$field)) { return $mult; } if (is_string($a->$field) || is_string($b->$field)) { // String fields. if ($cmp = strcoll($a->$field, $b->$field)) { return $mult * $cmp; } } else { // Int fields. if ($a->$field > $b->$field) { return $mult; } if ($a->$field < $b->$field) { return -$mult; } } } return 0; }); }
php
protected static function sort_records(&$records, $sortfields) { if (empty($records)) { return; } // If sorting by course display name, calculate it (it may be fullname or shortname+fullname). if (array_key_exists('displayname', $sortfields)) { foreach ($records as $key => $record) { if (!isset($record->displayname)) { $records[$key]->displayname = get_course_display_name_for_list($record); } } } // Sorting by one field - use core_collator. if (count($sortfields) == 1) { $property = key($sortfields); if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) { $sortflag = core_collator::SORT_NUMERIC; } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) { $sortflag = core_collator::SORT_STRING; } else { $sortflag = core_collator::SORT_REGULAR; } core_collator::asort_objects_by_property($records, $property, $sortflag); if ($sortfields[$property] < 0) { $records = array_reverse($records, true); } return; } // Sort by multiple fields - use custom sorting. uasort($records, function($a, $b) use ($sortfields) { foreach ($sortfields as $field => $mult) { // Nulls first. if (is_null($a->$field) && !is_null($b->$field)) { return -$mult; } if (is_null($b->$field) && !is_null($a->$field)) { return $mult; } if (is_string($a->$field) || is_string($b->$field)) { // String fields. if ($cmp = strcoll($a->$field, $b->$field)) { return $mult * $cmp; } } else { // Int fields. if ($a->$field > $b->$field) { return $mult; } if ($a->$field < $b->$field) { return -$mult; } } } return 0; }); }
[ "protected", "static", "function", "sort_records", "(", "&", "$", "records", ",", "$", "sortfields", ")", "{", "if", "(", "empty", "(", "$", "records", ")", ")", "{", "return", ";", "}", "// If sorting by course display name, calculate it (it may be fullname or shortname+fullname).", "if", "(", "array_key_exists", "(", "'displayname'", ",", "$", "sortfields", ")", ")", "{", "foreach", "(", "$", "records", "as", "$", "key", "=>", "$", "record", ")", "{", "if", "(", "!", "isset", "(", "$", "record", "->", "displayname", ")", ")", "{", "$", "records", "[", "$", "key", "]", "->", "displayname", "=", "get_course_display_name_for_list", "(", "$", "record", ")", ";", "}", "}", "}", "// Sorting by one field - use core_collator.", "if", "(", "count", "(", "$", "sortfields", ")", "==", "1", ")", "{", "$", "property", "=", "key", "(", "$", "sortfields", ")", ";", "if", "(", "in_array", "(", "$", "property", ",", "array", "(", "'sortorder'", ",", "'id'", ",", "'visible'", ",", "'parent'", ",", "'depth'", ")", ")", ")", "{", "$", "sortflag", "=", "core_collator", "::", "SORT_NUMERIC", ";", "}", "else", "if", "(", "in_array", "(", "$", "property", ",", "array", "(", "'idnumber'", ",", "'displayname'", ",", "'name'", ",", "'shortname'", ",", "'fullname'", ")", ")", ")", "{", "$", "sortflag", "=", "core_collator", "::", "SORT_STRING", ";", "}", "else", "{", "$", "sortflag", "=", "core_collator", "::", "SORT_REGULAR", ";", "}", "core_collator", "::", "asort_objects_by_property", "(", "$", "records", ",", "$", "property", ",", "$", "sortflag", ")", ";", "if", "(", "$", "sortfields", "[", "$", "property", "]", "<", "0", ")", "{", "$", "records", "=", "array_reverse", "(", "$", "records", ",", "true", ")", ";", "}", "return", ";", "}", "// Sort by multiple fields - use custom sorting.", "uasort", "(", "$", "records", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "sortfields", ")", "{", "foreach", "(", "$", "sortfields", "as", "$", "field", "=>", "$", "mult", ")", "{", "// Nulls first.", "if", "(", "is_null", "(", "$", "a", "->", "$", "field", ")", "&&", "!", "is_null", "(", "$", "b", "->", "$", "field", ")", ")", "{", "return", "-", "$", "mult", ";", "}", "if", "(", "is_null", "(", "$", "b", "->", "$", "field", ")", "&&", "!", "is_null", "(", "$", "a", "->", "$", "field", ")", ")", "{", "return", "$", "mult", ";", "}", "if", "(", "is_string", "(", "$", "a", "->", "$", "field", ")", "||", "is_string", "(", "$", "b", "->", "$", "field", ")", ")", "{", "// String fields.", "if", "(", "$", "cmp", "=", "strcoll", "(", "$", "a", "->", "$", "field", ",", "$", "b", "->", "$", "field", ")", ")", "{", "return", "$", "mult", "*", "$", "cmp", ";", "}", "}", "else", "{", "// Int fields.", "if", "(", "$", "a", "->", "$", "field", ">", "$", "b", "->", "$", "field", ")", "{", "return", "$", "mult", ";", "}", "if", "(", "$", "a", "->", "$", "field", "<", "$", "b", "->", "$", "field", ")", "{", "return", "-", "$", "mult", ";", "}", "}", "}", "return", "0", ";", "}", ")", ";", "}" ]
Sorts list of records by several fields @param array $records array of stdClass objects @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc @return int
[ "Sorts", "list", "of", "records", "by", "several", "fields" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1177-L1234
216,817
moodle/moodle
course/classes/category.php
core_course_category.has_capability_on_any
public static function has_capability_on_any($capabilities) { global $DB; if (!isloggedin() || isguestuser()) { return false; } if (!is_array($capabilities)) { $capabilities = array($capabilities); } $keys = array(); foreach ($capabilities as $capability) { $keys[$capability] = sha1($capability); } /** @var cache_session $cache */ $cache = cache::make('core', 'coursecat'); $hascapability = $cache->get_many($keys); $needtoload = false; foreach ($hascapability as $capability) { if ($capability === '1') { return true; } else if ($capability === false) { $needtoload = true; } } if ($needtoload === false) { // All capabilities were retrieved and the user didn't have any. return false; } $haskey = null; $fields = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT ctx.instanceid AS categoryid, $fields FROM {context} ctx WHERE contextlevel = :contextlevel ORDER BY depth ASC"; $params = array('contextlevel' => CONTEXT_COURSECAT); $recordset = $DB->get_recordset_sql($sql, $params); foreach ($recordset as $context) { context_helper::preload_from_record($context); $context = context_coursecat::instance($context->categoryid); foreach ($capabilities as $capability) { if (has_capability($capability, $context)) { $haskey = $capability; break 2; } } } $recordset->close(); if ($haskey === null) { $data = array(); foreach ($keys as $key) { $data[$key] = '0'; } $cache->set_many($data); return false; } else { $cache->set($haskey, '1'); return true; } }
php
public static function has_capability_on_any($capabilities) { global $DB; if (!isloggedin() || isguestuser()) { return false; } if (!is_array($capabilities)) { $capabilities = array($capabilities); } $keys = array(); foreach ($capabilities as $capability) { $keys[$capability] = sha1($capability); } /** @var cache_session $cache */ $cache = cache::make('core', 'coursecat'); $hascapability = $cache->get_many($keys); $needtoload = false; foreach ($hascapability as $capability) { if ($capability === '1') { return true; } else if ($capability === false) { $needtoload = true; } } if ($needtoload === false) { // All capabilities were retrieved and the user didn't have any. return false; } $haskey = null; $fields = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT ctx.instanceid AS categoryid, $fields FROM {context} ctx WHERE contextlevel = :contextlevel ORDER BY depth ASC"; $params = array('contextlevel' => CONTEXT_COURSECAT); $recordset = $DB->get_recordset_sql($sql, $params); foreach ($recordset as $context) { context_helper::preload_from_record($context); $context = context_coursecat::instance($context->categoryid); foreach ($capabilities as $capability) { if (has_capability($capability, $context)) { $haskey = $capability; break 2; } } } $recordset->close(); if ($haskey === null) { $data = array(); foreach ($keys as $key) { $data[$key] = '0'; } $cache->set_many($data); return false; } else { $cache->set($haskey, '1'); return true; } }
[ "public", "static", "function", "has_capability_on_any", "(", "$", "capabilities", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "isloggedin", "(", ")", "||", "isguestuser", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "is_array", "(", "$", "capabilities", ")", ")", "{", "$", "capabilities", "=", "array", "(", "$", "capabilities", ")", ";", "}", "$", "keys", "=", "array", "(", ")", ";", "foreach", "(", "$", "capabilities", "as", "$", "capability", ")", "{", "$", "keys", "[", "$", "capability", "]", "=", "sha1", "(", "$", "capability", ")", ";", "}", "/** @var cache_session $cache */", "$", "cache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecat'", ")", ";", "$", "hascapability", "=", "$", "cache", "->", "get_many", "(", "$", "keys", ")", ";", "$", "needtoload", "=", "false", ";", "foreach", "(", "$", "hascapability", "as", "$", "capability", ")", "{", "if", "(", "$", "capability", "===", "'1'", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "capability", "===", "false", ")", "{", "$", "needtoload", "=", "true", ";", "}", "}", "if", "(", "$", "needtoload", "===", "false", ")", "{", "// All capabilities were retrieved and the user didn't have any.", "return", "false", ";", "}", "$", "haskey", "=", "null", ";", "$", "fields", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "sql", "=", "\"SELECT ctx.instanceid AS categoryid, $fields\n FROM {context} ctx\n WHERE contextlevel = :contextlevel\n ORDER BY depth ASC\"", ";", "$", "params", "=", "array", "(", "'contextlevel'", "=>", "CONTEXT_COURSECAT", ")", ";", "$", "recordset", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "foreach", "(", "$", "recordset", "as", "$", "context", ")", "{", "context_helper", "::", "preload_from_record", "(", "$", "context", ")", ";", "$", "context", "=", "context_coursecat", "::", "instance", "(", "$", "context", "->", "categoryid", ")", ";", "foreach", "(", "$", "capabilities", "as", "$", "capability", ")", "{", "if", "(", "has_capability", "(", "$", "capability", ",", "$", "context", ")", ")", "{", "$", "haskey", "=", "$", "capability", ";", "break", "2", ";", "}", "}", "}", "$", "recordset", "->", "close", "(", ")", ";", "if", "(", "$", "haskey", "===", "null", ")", "{", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "data", "[", "$", "key", "]", "=", "'0'", ";", "}", "$", "cache", "->", "set_many", "(", "$", "data", ")", ";", "return", "false", ";", "}", "else", "{", "$", "cache", "->", "set", "(", "$", "haskey", ",", "'1'", ")", ";", "return", "true", ";", "}", "}" ]
Checks if the user has at least one of the given capabilities on any category. @param array|string $capabilities One or more capabilities to check. Check made is an OR. @return bool
[ "Checks", "if", "the", "user", "has", "at", "least", "one", "of", "the", "given", "capabilities", "on", "any", "category", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1363-L1423
216,818
moodle/moodle
course/classes/category.php
core_course_category.get_children_count
public function get_children_count() { $sortedids = self::get_tree($this->id); $invisibleids = $this->get_not_visible_children_ids(); return count($sortedids) - count($invisibleids); }
php
public function get_children_count() { $sortedids = self::get_tree($this->id); $invisibleids = $this->get_not_visible_children_ids(); return count($sortedids) - count($invisibleids); }
[ "public", "function", "get_children_count", "(", ")", "{", "$", "sortedids", "=", "self", "::", "get_tree", "(", "$", "this", "->", "id", ")", ";", "$", "invisibleids", "=", "$", "this", "->", "get_not_visible_children_ids", "(", ")", ";", "return", "count", "(", "$", "sortedids", ")", "-", "count", "(", "$", "invisibleids", ")", ";", "}" ]
Returns number of subcategories visible to the current user @return int
[ "Returns", "number", "of", "subcategories", "visible", "to", "the", "current", "user" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1446-L1450
216,819
moodle/moodle
course/classes/category.php
core_course_category.search_courses_count
public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) { $coursecatcache = cache::make('core', 'coursecat'); $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities); if (($cnt = $coursecatcache->get($cntcachekey)) === false) { // Cached value not found. Retrieve ALL courses and return their count. unset($options['offset']); unset($options['limit']); unset($options['summary']); unset($options['coursecontacts']); $options['idonly'] = true; $courses = self::search_courses($search, $options, $requiredcapabilities); $cnt = count($courses); } return $cnt; }
php
public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) { $coursecatcache = cache::make('core', 'coursecat'); $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities); if (($cnt = $coursecatcache->get($cntcachekey)) === false) { // Cached value not found. Retrieve ALL courses and return their count. unset($options['offset']); unset($options['limit']); unset($options['summary']); unset($options['coursecontacts']); $options['idonly'] = true; $courses = self::search_courses($search, $options, $requiredcapabilities); $cnt = count($courses); } return $cnt; }
[ "public", "static", "function", "search_courses_count", "(", "$", "search", ",", "$", "options", "=", "array", "(", ")", ",", "$", "requiredcapabilities", "=", "array", "(", ")", ")", "{", "$", "coursecatcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecat'", ")", ";", "$", "cntcachekey", "=", "'scnt-'", ".", "serialize", "(", "$", "search", ")", ".", "serialize", "(", "$", "requiredcapabilities", ")", ";", "if", "(", "(", "$", "cnt", "=", "$", "coursecatcache", "->", "get", "(", "$", "cntcachekey", ")", ")", "===", "false", ")", "{", "// Cached value not found. Retrieve ALL courses and return their count.", "unset", "(", "$", "options", "[", "'offset'", "]", ")", ";", "unset", "(", "$", "options", "[", "'limit'", "]", ")", ";", "unset", "(", "$", "options", "[", "'summary'", "]", ")", ";", "unset", "(", "$", "options", "[", "'coursecontacts'", "]", ")", ";", "$", "options", "[", "'idonly'", "]", "=", "true", ";", "$", "courses", "=", "self", "::", "search_courses", "(", "$", "search", ",", "$", "options", ",", "$", "requiredcapabilities", ")", ";", "$", "cnt", "=", "count", "(", "$", "courses", ")", ";", "}", "return", "$", "cnt", ";", "}" ]
Returns number of courses in the search results It is recommended to call this function after {@link core_course_category::search_courses()} and not before because only course ids are cached. Otherwise search_courses() may perform extra DB queries. @param array $search search criteria, see method search_courses() for more details @param array $options display options. They do not affect the result but the 'sort' property is used in cache key for storing list of course ids @param array $requiredcapabilities List of capabilities required to see return course. @return int
[ "Returns", "number", "of", "courses", "in", "the", "search", "results" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1654-L1668
216,820
moodle/moodle
course/classes/category.php
core_course_category.get_courses_count
public function get_courses_count($options = array()) { $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : ''); $coursecatcache = cache::make('core', 'coursecat'); if (($cnt = $coursecatcache->get($cntcachekey)) === false) { // Cached value not found. Retrieve ALL courses and return their count. unset($options['offset']); unset($options['limit']); unset($options['summary']); unset($options['coursecontacts']); $options['idonly'] = true; $courses = $this->get_courses($options); $cnt = count($courses); } return $cnt; }
php
public function get_courses_count($options = array()) { $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : ''); $coursecatcache = cache::make('core', 'coursecat'); if (($cnt = $coursecatcache->get($cntcachekey)) === false) { // Cached value not found. Retrieve ALL courses and return their count. unset($options['offset']); unset($options['limit']); unset($options['summary']); unset($options['coursecontacts']); $options['idonly'] = true; $courses = $this->get_courses($options); $cnt = count($courses); } return $cnt; }
[ "public", "function", "get_courses_count", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "cntcachekey", "=", "'lcnt-'", ".", "$", "this", "->", "id", ".", "'-'", ".", "(", "!", "empty", "(", "$", "options", "[", "'recursive'", "]", ")", "?", "'r'", ":", "''", ")", ";", "$", "coursecatcache", "=", "cache", "::", "make", "(", "'core'", ",", "'coursecat'", ")", ";", "if", "(", "(", "$", "cnt", "=", "$", "coursecatcache", "->", "get", "(", "$", "cntcachekey", ")", ")", "===", "false", ")", "{", "// Cached value not found. Retrieve ALL courses and return their count.", "unset", "(", "$", "options", "[", "'offset'", "]", ")", ";", "unset", "(", "$", "options", "[", "'limit'", "]", ")", ";", "unset", "(", "$", "options", "[", "'summary'", "]", ")", ";", "unset", "(", "$", "options", "[", "'coursecontacts'", "]", ")", ";", "$", "options", "[", "'idonly'", "]", "=", "true", ";", "$", "courses", "=", "$", "this", "->", "get_courses", "(", "$", "options", ")", ";", "$", "cnt", "=", "count", "(", "$", "courses", ")", ";", "}", "return", "$", "cnt", ";", "}" ]
Returns number of courses visible to the user @param array $options similar to get_courses() except some options do not affect number of courses (i.e. sort, summary, offset, limit etc.) @return int
[ "Returns", "number", "of", "courses", "visible", "to", "the", "user" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1807-L1821
216,821
moodle/moodle
course/classes/category.php
core_course_category.can_delete_full
public function can_delete_full() { global $DB; if (!$this->id) { // Fool-proof. return false; } $context = $this->get_context(); if (!$this->is_uservisible() || !has_capability('moodle/category:manage', $context)) { return false; } // Check all child categories (not only direct children). $sql = context_helper::get_preload_record_columns_sql('ctx'); $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql. ' FROM {context} ctx '. ' JOIN {course_categories} c ON c.id = ctx.instanceid'. ' WHERE ctx.path like ? AND ctx.contextlevel = ?', array($context->path. '/%', CONTEXT_COURSECAT)); foreach ($childcategories as $childcat) { context_helper::preload_from_record($childcat); $childcontext = context_coursecat::instance($childcat->id); if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) || !has_capability('moodle/category:manage', $childcontext)) { return false; } } // Check courses. $sql = context_helper::get_preload_record_columns_sql('ctx'); $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '. $sql. ' FROM {context} ctx '. 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel', array('pathmask' => $context->path. '/%', 'courselevel' => CONTEXT_COURSE)); foreach ($coursescontexts as $ctxrecord) { context_helper::preload_from_record($ctxrecord); if (!can_delete_course($ctxrecord->courseid)) { return false; } } return true; }
php
public function can_delete_full() { global $DB; if (!$this->id) { // Fool-proof. return false; } $context = $this->get_context(); if (!$this->is_uservisible() || !has_capability('moodle/category:manage', $context)) { return false; } // Check all child categories (not only direct children). $sql = context_helper::get_preload_record_columns_sql('ctx'); $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql. ' FROM {context} ctx '. ' JOIN {course_categories} c ON c.id = ctx.instanceid'. ' WHERE ctx.path like ? AND ctx.contextlevel = ?', array($context->path. '/%', CONTEXT_COURSECAT)); foreach ($childcategories as $childcat) { context_helper::preload_from_record($childcat); $childcontext = context_coursecat::instance($childcat->id); if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) || !has_capability('moodle/category:manage', $childcontext)) { return false; } } // Check courses. $sql = context_helper::get_preload_record_columns_sql('ctx'); $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '. $sql. ' FROM {context} ctx '. 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel', array('pathmask' => $context->path. '/%', 'courselevel' => CONTEXT_COURSE)); foreach ($coursescontexts as $ctxrecord) { context_helper::preload_from_record($ctxrecord); if (!can_delete_course($ctxrecord->courseid)) { return false; } } return true; }
[ "public", "function", "can_delete_full", "(", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "$", "this", "->", "id", ")", "{", "// Fool-proof.", "return", "false", ";", "}", "$", "context", "=", "$", "this", "->", "get_context", "(", ")", ";", "if", "(", "!", "$", "this", "->", "is_uservisible", "(", ")", "||", "!", "has_capability", "(", "'moodle/category:manage'", ",", "$", "context", ")", ")", "{", "return", "false", ";", "}", "// Check all child categories (not only direct children).", "$", "sql", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "childcategories", "=", "$", "DB", "->", "get_records_sql", "(", "'SELECT c.id, c.visible, '", ".", "$", "sql", ".", "' FROM {context} ctx '", ".", "' JOIN {course_categories} c ON c.id = ctx.instanceid'", ".", "' WHERE ctx.path like ? AND ctx.contextlevel = ?'", ",", "array", "(", "$", "context", "->", "path", ".", "'/%'", ",", "CONTEXT_COURSECAT", ")", ")", ";", "foreach", "(", "$", "childcategories", "as", "$", "childcat", ")", "{", "context_helper", "::", "preload_from_record", "(", "$", "childcat", ")", ";", "$", "childcontext", "=", "context_coursecat", "::", "instance", "(", "$", "childcat", "->", "id", ")", ";", "if", "(", "(", "!", "$", "childcat", "->", "visible", "&&", "!", "has_capability", "(", "'moodle/category:viewhiddencategories'", ",", "$", "childcontext", ")", ")", "||", "!", "has_capability", "(", "'moodle/category:manage'", ",", "$", "childcontext", ")", ")", "{", "return", "false", ";", "}", "}", "// Check courses.", "$", "sql", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "coursescontexts", "=", "$", "DB", "->", "get_records_sql", "(", "'SELECT ctx.instanceid AS courseid, '", ".", "$", "sql", ".", "' FROM {context} ctx '", ".", "'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel'", ",", "array", "(", "'pathmask'", "=>", "$", "context", "->", "path", ".", "'/%'", ",", "'courselevel'", "=>", "CONTEXT_COURSE", ")", ")", ";", "foreach", "(", "$", "coursescontexts", "as", "$", "ctxrecord", ")", "{", "context_helper", "::", "preload_from_record", "(", "$", "ctxrecord", ")", ";", "if", "(", "!", "can_delete_course", "(", "$", "ctxrecord", "->", "courseid", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if user can delete current category and all its contents To be able to delete course category the user must have permission 'moodle/category:manage' in ALL child course categories AND be able to delete all courses @return bool
[ "Returns", "true", "if", "user", "can", "delete", "current", "category", "and", "all", "its", "contents" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1848-L1892
216,822
moodle/moodle
course/classes/category.php
core_course_category.delete_full
public function delete_full($showfeedback = true) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->libdir.'/questionlib.php'); require_once($CFG->dirroot.'/cohort/lib.php'); // Make sure we won't timeout when deleting a lot of courses. $settimeout = core_php_time_limit::raise(); // Allow plugins to use this category before we completely delete it. if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) { $category = $this->get_db_record(); foreach ($pluginsfunction as $plugintype => $plugins) { foreach ($plugins as $pluginfunction) { $pluginfunction($category); } } } $deletedcourses = array(); // Get children. Note, we don't want to use cache here because it would be rebuilt too often. $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC'); foreach ($children as $record) { $coursecat = new self($record); $deletedcourses += $coursecat->delete_full($showfeedback); } if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course, false)) { throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname); } $deletedcourses[] = $course; } } // Move or delete cohorts in this context. cohort_delete_category($this); // Now delete anything that may depend on course category context. grade_course_category_delete($this->id, 0, $showfeedback); if (!question_delete_course_category($this, 0, $showfeedback)) { throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name()); } // Delete all events in the category. $DB->delete_records('event', array('categoryid' => $this->id)); // Finally delete the category and it's context. $DB->delete_records('course_categories', array('id' => $this->id)); $coursecatcontext = context_coursecat::instance($this->id); $coursecatcontext->delete(); cache_helper::purge_by_event('changesincoursecat'); // Trigger a course category deleted event. /** @var \core\event\course_category_deleted $event */ $event = \core\event\course_category_deleted::create(array( 'objectid' => $this->id, 'context' => $coursecatcontext, 'other' => array('name' => $this->name) )); $event->set_coursecat($this); $event->trigger(); // If we deleted $CFG->defaultrequestcategory, make it point somewhere else. if ($this->id == $CFG->defaultrequestcategory) { set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0))); } return $deletedcourses; }
php
public function delete_full($showfeedback = true) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->libdir.'/questionlib.php'); require_once($CFG->dirroot.'/cohort/lib.php'); // Make sure we won't timeout when deleting a lot of courses. $settimeout = core_php_time_limit::raise(); // Allow plugins to use this category before we completely delete it. if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) { $category = $this->get_db_record(); foreach ($pluginsfunction as $plugintype => $plugins) { foreach ($plugins as $pluginfunction) { $pluginfunction($category); } } } $deletedcourses = array(); // Get children. Note, we don't want to use cache here because it would be rebuilt too often. $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC'); foreach ($children as $record) { $coursecat = new self($record); $deletedcourses += $coursecat->delete_full($showfeedback); } if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course, false)) { throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname); } $deletedcourses[] = $course; } } // Move or delete cohorts in this context. cohort_delete_category($this); // Now delete anything that may depend on course category context. grade_course_category_delete($this->id, 0, $showfeedback); if (!question_delete_course_category($this, 0, $showfeedback)) { throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name()); } // Delete all events in the category. $DB->delete_records('event', array('categoryid' => $this->id)); // Finally delete the category and it's context. $DB->delete_records('course_categories', array('id' => $this->id)); $coursecatcontext = context_coursecat::instance($this->id); $coursecatcontext->delete(); cache_helper::purge_by_event('changesincoursecat'); // Trigger a course category deleted event. /** @var \core\event\course_category_deleted $event */ $event = \core\event\course_category_deleted::create(array( 'objectid' => $this->id, 'context' => $coursecatcontext, 'other' => array('name' => $this->name) )); $event->set_coursecat($this); $event->trigger(); // If we deleted $CFG->defaultrequestcategory, make it point somewhere else. if ($this->id == $CFG->defaultrequestcategory) { set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0))); } return $deletedcourses; }
[ "public", "function", "delete_full", "(", "$", "showfeedback", "=", "true", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/gradelib.php'", ")", ";", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/questionlib.php'", ")", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/cohort/lib.php'", ")", ";", "// Make sure we won't timeout when deleting a lot of courses.", "$", "settimeout", "=", "core_php_time_limit", "::", "raise", "(", ")", ";", "// Allow plugins to use this category before we completely delete it.", "if", "(", "$", "pluginsfunction", "=", "get_plugins_with_function", "(", "'pre_course_category_delete'", ")", ")", "{", "$", "category", "=", "$", "this", "->", "get_db_record", "(", ")", ";", "foreach", "(", "$", "pluginsfunction", "as", "$", "plugintype", "=>", "$", "plugins", ")", "{", "foreach", "(", "$", "plugins", "as", "$", "pluginfunction", ")", "{", "$", "pluginfunction", "(", "$", "category", ")", ";", "}", "}", "}", "$", "deletedcourses", "=", "array", "(", ")", ";", "// Get children. Note, we don't want to use cache here because it would be rebuilt too often.", "$", "children", "=", "$", "DB", "->", "get_records", "(", "'course_categories'", ",", "array", "(", "'parent'", "=>", "$", "this", "->", "id", ")", ",", "'sortorder ASC'", ")", ";", "foreach", "(", "$", "children", "as", "$", "record", ")", "{", "$", "coursecat", "=", "new", "self", "(", "$", "record", ")", ";", "$", "deletedcourses", "+=", "$", "coursecat", "->", "delete_full", "(", "$", "showfeedback", ")", ";", "}", "if", "(", "$", "courses", "=", "$", "DB", "->", "get_records", "(", "'course'", ",", "array", "(", "'category'", "=>", "$", "this", "->", "id", ")", ",", "'sortorder ASC'", ")", ")", "{", "foreach", "(", "$", "courses", "as", "$", "course", ")", "{", "if", "(", "!", "delete_course", "(", "$", "course", ",", "false", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'cannotdeletecategorycourse'", ",", "''", ",", "''", ",", "$", "course", "->", "shortname", ")", ";", "}", "$", "deletedcourses", "[", "]", "=", "$", "course", ";", "}", "}", "// Move or delete cohorts in this context.", "cohort_delete_category", "(", "$", "this", ")", ";", "// Now delete anything that may depend on course category context.", "grade_course_category_delete", "(", "$", "this", "->", "id", ",", "0", ",", "$", "showfeedback", ")", ";", "if", "(", "!", "question_delete_course_category", "(", "$", "this", ",", "0", ",", "$", "showfeedback", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'cannotdeletecategoryquestions'", ",", "''", ",", "''", ",", "$", "this", "->", "get_formatted_name", "(", ")", ")", ";", "}", "// Delete all events in the category.", "$", "DB", "->", "delete_records", "(", "'event'", ",", "array", "(", "'categoryid'", "=>", "$", "this", "->", "id", ")", ")", ";", "// Finally delete the category and it's context.", "$", "DB", "->", "delete_records", "(", "'course_categories'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ")", ")", ";", "$", "coursecatcontext", "=", "context_coursecat", "::", "instance", "(", "$", "this", "->", "id", ")", ";", "$", "coursecatcontext", "->", "delete", "(", ")", ";", "cache_helper", "::", "purge_by_event", "(", "'changesincoursecat'", ")", ";", "// Trigger a course category deleted event.", "/** @var \\core\\event\\course_category_deleted $event */", "$", "event", "=", "\\", "core", "\\", "event", "\\", "course_category_deleted", "::", "create", "(", "array", "(", "'objectid'", "=>", "$", "this", "->", "id", ",", "'context'", "=>", "$", "coursecatcontext", ",", "'other'", "=>", "array", "(", "'name'", "=>", "$", "this", "->", "name", ")", ")", ")", ";", "$", "event", "->", "set_coursecat", "(", "$", "this", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "// If we deleted $CFG->defaultrequestcategory, make it point somewhere else.", "if", "(", "$", "this", "->", "id", "==", "$", "CFG", "->", "defaultrequestcategory", ")", "{", "set_config", "(", "'defaultrequestcategory'", ",", "$", "DB", "->", "get_field", "(", "'course_categories'", ",", "'MIN(id)'", ",", "array", "(", "'parent'", "=>", "0", ")", ")", ")", ";", "}", "return", "$", "deletedcourses", ";", "}" ]
Recursively delete category including all subcategories and courses Function {@link core_course_category::can_delete_full()} MUST be called prior to calling this function because there is no capability check inside this function @param boolean $showfeedback display some notices @return array return deleted courses @throws moodle_exception
[ "Recursively", "delete", "category", "including", "all", "subcategories", "and", "courses" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L1905-L1978
216,823
moodle/moodle
course/classes/category.php
core_course_category.can_move_content_to
public function can_move_content_to($newcatid) { global $CFG; require_once($CFG->libdir . '/questionlib.php'); $context = $this->get_context(); if (!$this->is_uservisible() || !has_capability('moodle/category:manage', $context)) { return false; } $testcaps = array(); // If this category has courses in it, user must have 'course:create' capability in target category. if ($this->has_courses()) { $testcaps[] = 'moodle/course:create'; } // If this category has subcategories or questions, user must have 'category:manage' capability in target category. if ($this->has_children() || question_context_has_any_questions($context)) { $testcaps[] = 'moodle/category:manage'; } if (!empty($testcaps)) { return has_all_capabilities($testcaps, context_coursecat::instance($newcatid)); } // There is no content but still return true. return true; }
php
public function can_move_content_to($newcatid) { global $CFG; require_once($CFG->libdir . '/questionlib.php'); $context = $this->get_context(); if (!$this->is_uservisible() || !has_capability('moodle/category:manage', $context)) { return false; } $testcaps = array(); // If this category has courses in it, user must have 'course:create' capability in target category. if ($this->has_courses()) { $testcaps[] = 'moodle/course:create'; } // If this category has subcategories or questions, user must have 'category:manage' capability in target category. if ($this->has_children() || question_context_has_any_questions($context)) { $testcaps[] = 'moodle/category:manage'; } if (!empty($testcaps)) { return has_all_capabilities($testcaps, context_coursecat::instance($newcatid)); } // There is no content but still return true. return true; }
[ "public", "function", "can_move_content_to", "(", "$", "newcatid", ")", "{", "global", "$", "CFG", ";", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/questionlib.php'", ")", ";", "$", "context", "=", "$", "this", "->", "get_context", "(", ")", ";", "if", "(", "!", "$", "this", "->", "is_uservisible", "(", ")", "||", "!", "has_capability", "(", "'moodle/category:manage'", ",", "$", "context", ")", ")", "{", "return", "false", ";", "}", "$", "testcaps", "=", "array", "(", ")", ";", "// If this category has courses in it, user must have 'course:create' capability in target category.", "if", "(", "$", "this", "->", "has_courses", "(", ")", ")", "{", "$", "testcaps", "[", "]", "=", "'moodle/course:create'", ";", "}", "// If this category has subcategories or questions, user must have 'category:manage' capability in target category.", "if", "(", "$", "this", "->", "has_children", "(", ")", "||", "question_context_has_any_questions", "(", "$", "context", ")", ")", "{", "$", "testcaps", "[", "]", "=", "'moodle/category:manage'", ";", "}", "if", "(", "!", "empty", "(", "$", "testcaps", ")", ")", "{", "return", "has_all_capabilities", "(", "$", "testcaps", ",", "context_coursecat", "::", "instance", "(", "$", "newcatid", ")", ")", ";", "}", "// There is no content but still return true.", "return", "true", ";", "}" ]
Checks if user has capability to move all category content to the new parent before removing this category @param int $newcatid @return bool
[ "Checks", "if", "user", "has", "capability", "to", "move", "all", "category", "content", "to", "the", "new", "parent", "before", "removing", "this", "category" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2024-L2047
216,824
moodle/moodle
course/classes/category.php
core_course_category.can_change_parent
public function can_change_parent($newparentcat) { if (!has_capability('moodle/category:manage', $this->get_context())) { return false; } if (is_object($newparentcat)) { $newparentcat = self::get($newparentcat->id, IGNORE_MISSING); } else { $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING); } if (!$newparentcat) { return false; } if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) { // Can not move to itself or it's own child. return false; } if ($newparentcat->id) { return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id)); } else { return has_capability('moodle/category:manage', context_system::instance()); } }
php
public function can_change_parent($newparentcat) { if (!has_capability('moodle/category:manage', $this->get_context())) { return false; } if (is_object($newparentcat)) { $newparentcat = self::get($newparentcat->id, IGNORE_MISSING); } else { $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING); } if (!$newparentcat) { return false; } if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) { // Can not move to itself or it's own child. return false; } if ($newparentcat->id) { return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id)); } else { return has_capability('moodle/category:manage', context_system::instance()); } }
[ "public", "function", "can_change_parent", "(", "$", "newparentcat", ")", "{", "if", "(", "!", "has_capability", "(", "'moodle/category:manage'", ",", "$", "this", "->", "get_context", "(", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "is_object", "(", "$", "newparentcat", ")", ")", "{", "$", "newparentcat", "=", "self", "::", "get", "(", "$", "newparentcat", "->", "id", ",", "IGNORE_MISSING", ")", ";", "}", "else", "{", "$", "newparentcat", "=", "self", "::", "get", "(", "(", "int", ")", "$", "newparentcat", ",", "IGNORE_MISSING", ")", ";", "}", "if", "(", "!", "$", "newparentcat", ")", "{", "return", "false", ";", "}", "if", "(", "$", "newparentcat", "->", "id", "==", "$", "this", "->", "id", "||", "in_array", "(", "$", "this", "->", "id", ",", "$", "newparentcat", "->", "get_parents", "(", ")", ")", ")", "{", "// Can not move to itself or it's own child.", "return", "false", ";", "}", "if", "(", "$", "newparentcat", "->", "id", ")", "{", "return", "has_capability", "(", "'moodle/category:manage'", ",", "context_coursecat", "::", "instance", "(", "$", "newparentcat", "->", "id", ")", ")", ";", "}", "else", "{", "return", "has_capability", "(", "'moodle/category:manage'", ",", "context_system", "::", "instance", "(", ")", ")", ";", "}", "}" ]
Checks if user can move current category to the new parent This checks if new parent category exists, user has manage cap there and new parent is not a child of this category @param int|stdClass|core_course_category $newparentcat @return bool
[ "Checks", "if", "user", "can", "move", "current", "category", "to", "the", "new", "parent" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2151-L2172
216,825
moodle/moodle
course/classes/category.php
core_course_category.change_parent_raw
protected function change_parent_raw(core_course_category $newparentcat) { global $DB; $context = $this->get_context(); $hidecat = false; if (empty($newparentcat->id)) { $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id)); $newparent = context_system::instance(); } else { if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) { // Can not move to itself or it's own child. throw new moodle_exception('cannotmovecategory'); } $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id)); $newparent = context_coursecat::instance($newparentcat->id); if (!$newparentcat->visible and $this->visible) { // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children // will be restored properly. $hidecat = true; } } $this->parent = $newparentcat->id; $context->update_moved($newparent); // Now make it last in new category. $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES, ['id' => $this->id]); if ($hidecat) { fix_course_sortorder(); $this->restore(); // Hide object but store 1 in visibleold, because when parent category visibility changes this category must // become visible again. $this->hide_raw(1); } }
php
protected function change_parent_raw(core_course_category $newparentcat) { global $DB; $context = $this->get_context(); $hidecat = false; if (empty($newparentcat->id)) { $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id)); $newparent = context_system::instance(); } else { if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) { // Can not move to itself or it's own child. throw new moodle_exception('cannotmovecategory'); } $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id)); $newparent = context_coursecat::instance($newparentcat->id); if (!$newparentcat->visible and $this->visible) { // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children // will be restored properly. $hidecat = true; } } $this->parent = $newparentcat->id; $context->update_moved($newparent); // Now make it last in new category. $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES, ['id' => $this->id]); if ($hidecat) { fix_course_sortorder(); $this->restore(); // Hide object but store 1 in visibleold, because when parent category visibility changes this category must // become visible again. $this->hide_raw(1); } }
[ "protected", "function", "change_parent_raw", "(", "core_course_category", "$", "newparentcat", ")", "{", "global", "$", "DB", ";", "$", "context", "=", "$", "this", "->", "get_context", "(", ")", ";", "$", "hidecat", "=", "false", ";", "if", "(", "empty", "(", "$", "newparentcat", "->", "id", ")", ")", "{", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'parent'", ",", "0", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ")", ")", ";", "$", "newparent", "=", "context_system", "::", "instance", "(", ")", ";", "}", "else", "{", "if", "(", "$", "newparentcat", "->", "id", "==", "$", "this", "->", "id", "||", "in_array", "(", "$", "this", "->", "id", ",", "$", "newparentcat", "->", "get_parents", "(", ")", ")", ")", "{", "// Can not move to itself or it's own child.", "throw", "new", "moodle_exception", "(", "'cannotmovecategory'", ")", ";", "}", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'parent'", ",", "$", "newparentcat", "->", "id", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ")", ")", ";", "$", "newparent", "=", "context_coursecat", "::", "instance", "(", "$", "newparentcat", "->", "id", ")", ";", "if", "(", "!", "$", "newparentcat", "->", "visible", "and", "$", "this", "->", "visible", ")", "{", "// Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children", "// will be restored properly.", "$", "hidecat", "=", "true", ";", "}", "}", "$", "this", "->", "parent", "=", "$", "newparentcat", "->", "id", ";", "$", "context", "->", "update_moved", "(", "$", "newparent", ")", ";", "// Now make it last in new category.", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'sortorder'", ",", "MAX_COURSES_IN_CATEGORY", "*", "MAX_COURSE_CATEGORIES", ",", "[", "'id'", "=>", "$", "this", "->", "id", "]", ")", ";", "if", "(", "$", "hidecat", ")", "{", "fix_course_sortorder", "(", ")", ";", "$", "this", "->", "restore", "(", ")", ";", "// Hide object but store 1 in visibleold, because when parent category visibility changes this category must", "// become visible again.", "$", "this", "->", "hide_raw", "(", "1", ")", ";", "}", "}" ]
Moves the category under another parent category. All associated contexts are moved as well This is protected function, use change_parent() or update() from outside of this class @see core_course_category::change_parent() @see core_course_category::update() @param core_course_category $newparentcat @throws moodle_exception
[ "Moves", "the", "category", "under", "another", "parent", "category", ".", "All", "associated", "contexts", "are", "moved", "as", "well" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2185-L2222
216,826
moodle/moodle
course/classes/category.php
core_course_category.change_parent
public function change_parent($newparentcat) { // Make sure parent category exists but do not check capabilities here that it is visible to current user. if (is_object($newparentcat)) { $newparentcat = self::get($newparentcat->id, MUST_EXIST, true); } else { $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true); } if ($newparentcat->id != $this->parent) { $this->change_parent_raw($newparentcat); fix_course_sortorder(); cache_helper::purge_by_event('changesincoursecat'); $this->restore(); $event = \core\event\course_category_updated::create(array( 'objectid' => $this->id, 'context' => $this->get_context() )); $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id)); $event->trigger(); } }
php
public function change_parent($newparentcat) { // Make sure parent category exists but do not check capabilities here that it is visible to current user. if (is_object($newparentcat)) { $newparentcat = self::get($newparentcat->id, MUST_EXIST, true); } else { $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true); } if ($newparentcat->id != $this->parent) { $this->change_parent_raw($newparentcat); fix_course_sortorder(); cache_helper::purge_by_event('changesincoursecat'); $this->restore(); $event = \core\event\course_category_updated::create(array( 'objectid' => $this->id, 'context' => $this->get_context() )); $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id)); $event->trigger(); } }
[ "public", "function", "change_parent", "(", "$", "newparentcat", ")", "{", "// Make sure parent category exists but do not check capabilities here that it is visible to current user.", "if", "(", "is_object", "(", "$", "newparentcat", ")", ")", "{", "$", "newparentcat", "=", "self", "::", "get", "(", "$", "newparentcat", "->", "id", ",", "MUST_EXIST", ",", "true", ")", ";", "}", "else", "{", "$", "newparentcat", "=", "self", "::", "get", "(", "(", "int", ")", "$", "newparentcat", ",", "MUST_EXIST", ",", "true", ")", ";", "}", "if", "(", "$", "newparentcat", "->", "id", "!=", "$", "this", "->", "parent", ")", "{", "$", "this", "->", "change_parent_raw", "(", "$", "newparentcat", ")", ";", "fix_course_sortorder", "(", ")", ";", "cache_helper", "::", "purge_by_event", "(", "'changesincoursecat'", ")", ";", "$", "this", "->", "restore", "(", ")", ";", "$", "event", "=", "\\", "core", "\\", "event", "\\", "course_category_updated", "::", "create", "(", "array", "(", "'objectid'", "=>", "$", "this", "->", "id", ",", "'context'", "=>", "$", "this", "->", "get_context", "(", ")", ")", ")", ";", "$", "event", "->", "set_legacy_logdata", "(", "array", "(", "SITEID", ",", "'category'", ",", "'move'", ",", "'editcategory.php?id='", ".", "$", "this", "->", "id", ",", "$", "this", "->", "id", ")", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "}", "}" ]
Efficiently moves a category - NOTE that this can have a huge impact access-control-wise... Note that this function does not check capabilities. Example of usage: $coursecat = core_course_category::get($categoryid); if ($coursecat->can_change_parent($newparentcatid)) { $coursecat->change_parent($newparentcatid); } This function does not update field course_categories.timemodified If you want to update timemodified, use $coursecat->update(array('parent' => $newparentcat)); @param int|stdClass|core_course_category $newparentcat
[ "Efficiently", "moves", "a", "category", "-", "NOTE", "that", "this", "can", "have", "a", "huge", "impact", "access", "-", "control", "-", "wise", "..." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2242-L2262
216,827
moodle/moodle
course/classes/category.php
core_course_category.get_formatted_name
public function get_formatted_name($options = array()) { if ($this->id) { $context = $this->get_context(); return format_string($this->name, true, array('context' => $context) + $options); } else { return get_string('top'); } }
php
public function get_formatted_name($options = array()) { if ($this->id) { $context = $this->get_context(); return format_string($this->name, true, array('context' => $context) + $options); } else { return get_string('top'); } }
[ "public", "function", "get_formatted_name", "(", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "$", "this", "->", "id", ")", "{", "$", "context", "=", "$", "this", "->", "get_context", "(", ")", ";", "return", "format_string", "(", "$", "this", "->", "name", ",", "true", ",", "array", "(", "'context'", "=>", "$", "context", ")", "+", "$", "options", ")", ";", "}", "else", "{", "return", "get_string", "(", "'top'", ")", ";", "}", "}" ]
Returns name of the category formatted as a string @param array $options formatting options other than context @return string
[ "Returns", "name", "of", "the", "category", "formatted", "as", "a", "string" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2401-L2408
216,828
moodle/moodle
course/classes/category.php
core_course_category.get_nested_name
public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) { // Get the name of hierarchical name of this category. $parents = $this->get_parents(); $categories = static::get_many($parents); $categories[] = $this; $names = array_map(function($category) use ($options, $includelinks) { if ($includelinks) { return html_writer::link($category->get_view_link(), $category->get_formatted_name($options)); } else { return $category->get_formatted_name($options); } }, $categories); return implode($separator, $names); }
php
public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) { // Get the name of hierarchical name of this category. $parents = $this->get_parents(); $categories = static::get_many($parents); $categories[] = $this; $names = array_map(function($category) use ($options, $includelinks) { if ($includelinks) { return html_writer::link($category->get_view_link(), $category->get_formatted_name($options)); } else { return $category->get_formatted_name($options); } }, $categories); return implode($separator, $names); }
[ "public", "function", "get_nested_name", "(", "$", "includelinks", "=", "true", ",", "$", "separator", "=", "' / '", ",", "$", "options", "=", "[", "]", ")", "{", "// Get the name of hierarchical name of this category.", "$", "parents", "=", "$", "this", "->", "get_parents", "(", ")", ";", "$", "categories", "=", "static", "::", "get_many", "(", "$", "parents", ")", ";", "$", "categories", "[", "]", "=", "$", "this", ";", "$", "names", "=", "array_map", "(", "function", "(", "$", "category", ")", "use", "(", "$", "options", ",", "$", "includelinks", ")", "{", "if", "(", "$", "includelinks", ")", "{", "return", "html_writer", "::", "link", "(", "$", "category", "->", "get_view_link", "(", ")", ",", "$", "category", "->", "get_formatted_name", "(", "$", "options", ")", ")", ";", "}", "else", "{", "return", "$", "category", "->", "get_formatted_name", "(", "$", "options", ")", ";", "}", "}", ",", "$", "categories", ")", ";", "return", "implode", "(", "$", "separator", ",", "$", "names", ")", ";", "}" ]
Get the nested name of this category, with all of it's parents. @param bool $includelinks Whether to wrap each name in the view link for that category. @param string $separator The string between each name. @param array $options Formatting options. @return string
[ "Get", "the", "nested", "name", "of", "this", "category", "with", "all", "of", "it", "s", "parents", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2418-L2434
216,829
moodle/moodle
course/classes/category.php
core_course_category.wake_from_cache
public static function wake_from_cache($a) { $record = new stdClass; foreach (self::$coursecatfields as $property => $cachedirectives) { if ($cachedirectives !== null) { list($shortname, $defaultvalue) = $cachedirectives; if (array_key_exists($shortname, $a)) { $record->$property = $a[$shortname]; } else { $record->$property = $defaultvalue; } } } $record->ctxid = $a['xi']; $record->ctxpath = $a['xp']; $record->ctxdepth = $record->depth + 1; $record->ctxlevel = CONTEXT_COURSECAT; $record->ctxinstance = $record->id; $record->ctxlocked = $a['xl']; return new self($record, true); }
php
public static function wake_from_cache($a) { $record = new stdClass; foreach (self::$coursecatfields as $property => $cachedirectives) { if ($cachedirectives !== null) { list($shortname, $defaultvalue) = $cachedirectives; if (array_key_exists($shortname, $a)) { $record->$property = $a[$shortname]; } else { $record->$property = $defaultvalue; } } } $record->ctxid = $a['xi']; $record->ctxpath = $a['xp']; $record->ctxdepth = $record->depth + 1; $record->ctxlevel = CONTEXT_COURSECAT; $record->ctxinstance = $record->id; $record->ctxlocked = $a['xl']; return new self($record, true); }
[ "public", "static", "function", "wake_from_cache", "(", "$", "a", ")", "{", "$", "record", "=", "new", "stdClass", ";", "foreach", "(", "self", "::", "$", "coursecatfields", "as", "$", "property", "=>", "$", "cachedirectives", ")", "{", "if", "(", "$", "cachedirectives", "!==", "null", ")", "{", "list", "(", "$", "shortname", ",", "$", "defaultvalue", ")", "=", "$", "cachedirectives", ";", "if", "(", "array_key_exists", "(", "$", "shortname", ",", "$", "a", ")", ")", "{", "$", "record", "->", "$", "property", "=", "$", "a", "[", "$", "shortname", "]", ";", "}", "else", "{", "$", "record", "->", "$", "property", "=", "$", "defaultvalue", ";", "}", "}", "}", "$", "record", "->", "ctxid", "=", "$", "a", "[", "'xi'", "]", ";", "$", "record", "->", "ctxpath", "=", "$", "a", "[", "'xp'", "]", ";", "$", "record", "->", "ctxdepth", "=", "$", "record", "->", "depth", "+", "1", ";", "$", "record", "->", "ctxlevel", "=", "CONTEXT_COURSECAT", ";", "$", "record", "->", "ctxinstance", "=", "$", "record", "->", "id", ";", "$", "record", "->", "ctxlocked", "=", "$", "a", "[", "'xl'", "]", ";", "return", "new", "self", "(", "$", "record", ",", "true", ")", ";", "}" ]
Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it. implementing method from interface cacheable_object @param array $a @return core_course_category
[ "Takes", "the", "data", "provided", "by", "prepare_to_cache", "and", "reinitialises", "an", "instance", "of", "the", "associated", "from", "it", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2614-L2633
216,830
moodle/moodle
course/classes/category.php
core_course_category.can_review_filters
public function can_review_filters() { return $this->is_uservisible() && has_capability('moodle/filter:manage', $this->get_context()) && count(filter_get_available_in_context($this->get_context())) > 0; }
php
public function can_review_filters() { return $this->is_uservisible() && has_capability('moodle/filter:manage', $this->get_context()) && count(filter_get_available_in_context($this->get_context())) > 0; }
[ "public", "function", "can_review_filters", "(", ")", "{", "return", "$", "this", "->", "is_uservisible", "(", ")", "&&", "has_capability", "(", "'moodle/filter:manage'", ",", "$", "this", "->", "get_context", "(", ")", ")", "&&", "count", "(", "filter_get_available_in_context", "(", "$", "this", "->", "get_context", "(", ")", ")", ")", ">", "0", ";", "}" ]
Returns true if the current user can review filter settings for this category. @return bool
[ "Returns", "true", "if", "the", "current", "user", "can", "review", "filter", "settings", "for", "this", "category", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2760-L2764
216,831
moodle/moodle
course/classes/category.php
core_course_category.resort_subcategories
public function resort_subcategories($field, $cleanup = true) { global $DB; $desc = false; if (substr($field, -4) === "desc") { $desc = true; $field = substr($field, 0, -4); // Remove "desc" from field name. } if ($field !== 'name' && $field !== 'idnumber') { throw new coding_exception('Invalid field requested'); } $children = $this->get_children(); core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL); if (!empty($desc)) { $children = array_reverse($children); } $i = 1; foreach ($children as $cat) { $i++; $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id)); $i += $cat->coursecount; } if ($cleanup) { self::resort_categories_cleanup(); } return true; }
php
public function resort_subcategories($field, $cleanup = true) { global $DB; $desc = false; if (substr($field, -4) === "desc") { $desc = true; $field = substr($field, 0, -4); // Remove "desc" from field name. } if ($field !== 'name' && $field !== 'idnumber') { throw new coding_exception('Invalid field requested'); } $children = $this->get_children(); core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL); if (!empty($desc)) { $children = array_reverse($children); } $i = 1; foreach ($children as $cat) { $i++; $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id)); $i += $cat->coursecount; } if ($cleanup) { self::resort_categories_cleanup(); } return true; }
[ "public", "function", "resort_subcategories", "(", "$", "field", ",", "$", "cleanup", "=", "true", ")", "{", "global", "$", "DB", ";", "$", "desc", "=", "false", ";", "if", "(", "substr", "(", "$", "field", ",", "-", "4", ")", "===", "\"desc\"", ")", "{", "$", "desc", "=", "true", ";", "$", "field", "=", "substr", "(", "$", "field", ",", "0", ",", "-", "4", ")", ";", "// Remove \"desc\" from field name.", "}", "if", "(", "$", "field", "!==", "'name'", "&&", "$", "field", "!==", "'idnumber'", ")", "{", "throw", "new", "coding_exception", "(", "'Invalid field requested'", ")", ";", "}", "$", "children", "=", "$", "this", "->", "get_children", "(", ")", ";", "core_collator", "::", "asort_objects_by_property", "(", "$", "children", ",", "$", "field", ",", "core_collator", "::", "SORT_NATURAL", ")", ";", "if", "(", "!", "empty", "(", "$", "desc", ")", ")", "{", "$", "children", "=", "array_reverse", "(", "$", "children", ")", ";", "}", "$", "i", "=", "1", ";", "foreach", "(", "$", "children", "as", "$", "cat", ")", "{", "$", "i", "++", ";", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'sortorder'", ",", "$", "i", ",", "array", "(", "'id'", "=>", "$", "cat", "->", "id", ")", ")", ";", "$", "i", "+=", "$", "cat", "->", "coursecount", ";", "}", "if", "(", "$", "cleanup", ")", "{", "self", "::", "resort_categories_cleanup", "(", ")", ";", "}", "return", "true", ";", "}" ]
Resorts the sub categories of this category by the given field. @param string $field One of name, idnumber or descending values of each (appended desc) @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later. @return bool True on success. @throws coding_exception
[ "Resorts", "the", "sub", "categories", "of", "this", "category", "by", "the", "given", "field", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2806-L2831
216,832
moodle/moodle
course/classes/category.php
core_course_category.resort_courses
public function resort_courses($field, $cleanup = true) { global $DB; $desc = false; if (substr($field, -4) === "desc") { $desc = true; $field = substr($field, 0, -4); // Remove "desc" from field name. } if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') { // This is ultra important as we use $field in an SQL statement below this. throw new coding_exception('Invalid field requested'); } $ctxfields = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields FROM {course} c LEFT JOIN {context} ctx ON ctx.instanceid = c.id WHERE ctx.contextlevel = :ctxlevel AND c.category = :categoryid"; $params = array( 'ctxlevel' => CONTEXT_COURSE, 'categoryid' => $this->id ); $courses = $DB->get_records_sql($sql, $params); if (count($courses) > 0) { foreach ($courses as $courseid => $course) { context_helper::preload_from_record($course); if ($field === 'idnumber') { $course->sortby = $course->idnumber; } else { // It'll require formatting. $options = array( 'context' => context_course::instance($course->id) ); // We format the string first so that it appears as the user would see it. // This ensures the sorting makes sense to them. However it won't necessarily make // sense to everyone if things like multilang filters are enabled. // We then strip any tags as we don't want things such as image tags skewing the // sort results. $course->sortby = strip_tags(format_string($course->$field, true, $options)); } // We set it back here rather than using references as there is a bug with using // references in a foreach before passing as an arg by reference. $courses[$courseid] = $course; } // Sort the courses. core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL); if (!empty($desc)) { $courses = array_reverse($courses); } $i = 1; foreach ($courses as $course) { $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id)); $i++; } if ($cleanup) { // This should not be needed but we do it just to be safe. fix_course_sortorder(); cache_helper::purge_by_event('changesincourse'); } } return true; }
php
public function resort_courses($field, $cleanup = true) { global $DB; $desc = false; if (substr($field, -4) === "desc") { $desc = true; $field = substr($field, 0, -4); // Remove "desc" from field name. } if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') { // This is ultra important as we use $field in an SQL statement below this. throw new coding_exception('Invalid field requested'); } $ctxfields = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields FROM {course} c LEFT JOIN {context} ctx ON ctx.instanceid = c.id WHERE ctx.contextlevel = :ctxlevel AND c.category = :categoryid"; $params = array( 'ctxlevel' => CONTEXT_COURSE, 'categoryid' => $this->id ); $courses = $DB->get_records_sql($sql, $params); if (count($courses) > 0) { foreach ($courses as $courseid => $course) { context_helper::preload_from_record($course); if ($field === 'idnumber') { $course->sortby = $course->idnumber; } else { // It'll require formatting. $options = array( 'context' => context_course::instance($course->id) ); // We format the string first so that it appears as the user would see it. // This ensures the sorting makes sense to them. However it won't necessarily make // sense to everyone if things like multilang filters are enabled. // We then strip any tags as we don't want things such as image tags skewing the // sort results. $course->sortby = strip_tags(format_string($course->$field, true, $options)); } // We set it back here rather than using references as there is a bug with using // references in a foreach before passing as an arg by reference. $courses[$courseid] = $course; } // Sort the courses. core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL); if (!empty($desc)) { $courses = array_reverse($courses); } $i = 1; foreach ($courses as $course) { $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id)); $i++; } if ($cleanup) { // This should not be needed but we do it just to be safe. fix_course_sortorder(); cache_helper::purge_by_event('changesincourse'); } } return true; }
[ "public", "function", "resort_courses", "(", "$", "field", ",", "$", "cleanup", "=", "true", ")", "{", "global", "$", "DB", ";", "$", "desc", "=", "false", ";", "if", "(", "substr", "(", "$", "field", ",", "-", "4", ")", "===", "\"desc\"", ")", "{", "$", "desc", "=", "true", ";", "$", "field", "=", "substr", "(", "$", "field", ",", "0", ",", "-", "4", ")", ";", "// Remove \"desc\" from field name.", "}", "if", "(", "$", "field", "!==", "'fullname'", "&&", "$", "field", "!==", "'shortname'", "&&", "$", "field", "!==", "'idnumber'", "&&", "$", "field", "!==", "'timecreated'", ")", "{", "// This is ultra important as we use $field in an SQL statement below this.", "throw", "new", "coding_exception", "(", "'Invalid field requested'", ")", ";", "}", "$", "ctxfields", "=", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "sql", "=", "\"SELECT c.id, c.sortorder, c.{$field}, $ctxfields\n FROM {course} c\n LEFT JOIN {context} ctx ON ctx.instanceid = c.id\n WHERE ctx.contextlevel = :ctxlevel AND\n c.category = :categoryid\"", ";", "$", "params", "=", "array", "(", "'ctxlevel'", "=>", "CONTEXT_COURSE", ",", "'categoryid'", "=>", "$", "this", "->", "id", ")", ";", "$", "courses", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "if", "(", "count", "(", "$", "courses", ")", ">", "0", ")", "{", "foreach", "(", "$", "courses", "as", "$", "courseid", "=>", "$", "course", ")", "{", "context_helper", "::", "preload_from_record", "(", "$", "course", ")", ";", "if", "(", "$", "field", "===", "'idnumber'", ")", "{", "$", "course", "->", "sortby", "=", "$", "course", "->", "idnumber", ";", "}", "else", "{", "// It'll require formatting.", "$", "options", "=", "array", "(", "'context'", "=>", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ")", ";", "// We format the string first so that it appears as the user would see it.", "// This ensures the sorting makes sense to them. However it won't necessarily make", "// sense to everyone if things like multilang filters are enabled.", "// We then strip any tags as we don't want things such as image tags skewing the", "// sort results.", "$", "course", "->", "sortby", "=", "strip_tags", "(", "format_string", "(", "$", "course", "->", "$", "field", ",", "true", ",", "$", "options", ")", ")", ";", "}", "// We set it back here rather than using references as there is a bug with using", "// references in a foreach before passing as an arg by reference.", "$", "courses", "[", "$", "courseid", "]", "=", "$", "course", ";", "}", "// Sort the courses.", "core_collator", "::", "asort_objects_by_property", "(", "$", "courses", ",", "'sortby'", ",", "core_collator", "::", "SORT_NATURAL", ")", ";", "if", "(", "!", "empty", "(", "$", "desc", ")", ")", "{", "$", "courses", "=", "array_reverse", "(", "$", "courses", ")", ";", "}", "$", "i", "=", "1", ";", "foreach", "(", "$", "courses", "as", "$", "course", ")", "{", "$", "DB", "->", "set_field", "(", "'course'", ",", "'sortorder'", ",", "$", "this", "->", "sortorder", "+", "$", "i", ",", "array", "(", "'id'", "=>", "$", "course", "->", "id", ")", ")", ";", "$", "i", "++", ";", "}", "if", "(", "$", "cleanup", ")", "{", "// This should not be needed but we do it just to be safe.", "fix_course_sortorder", "(", ")", ";", "cache_helper", "::", "purge_by_event", "(", "'changesincourse'", ")", ";", "}", "}", "return", "true", ";", "}" ]
Resort the courses within this category by the given field. @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc) @param bool $cleanup @return bool True for success. @throws coding_exception
[ "Resort", "the", "courses", "within", "this", "category", "by", "the", "given", "field", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2854-L2914
216,833
moodle/moodle
course/classes/category.php
core_course_category.change_sortorder_by_one
public function change_sortorder_by_one($up) { global $DB; $params = array($this->sortorder, $this->parent); if ($up) { $select = 'sortorder < ? AND parent = ?'; $sort = 'sortorder DESC'; } else { $select = 'sortorder > ? AND parent = ?'; $sort = 'sortorder ASC'; } fix_course_sortorder(); $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1); $swapcategory = reset($swapcategory); if ($swapcategory) { $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id)); $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id)); $this->sortorder = $swapcategory->sortorder; $event = \core\event\course_category_updated::create(array( 'objectid' => $this->id, 'context' => $this->get_context() )); $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id, $this->id)); $event->trigger(); // Finally reorder courses. fix_course_sortorder(); cache_helper::purge_by_event('changesincoursecat'); return true; } return false; }
php
public function change_sortorder_by_one($up) { global $DB; $params = array($this->sortorder, $this->parent); if ($up) { $select = 'sortorder < ? AND parent = ?'; $sort = 'sortorder DESC'; } else { $select = 'sortorder > ? AND parent = ?'; $sort = 'sortorder ASC'; } fix_course_sortorder(); $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1); $swapcategory = reset($swapcategory); if ($swapcategory) { $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id)); $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id)); $this->sortorder = $swapcategory->sortorder; $event = \core\event\course_category_updated::create(array( 'objectid' => $this->id, 'context' => $this->get_context() )); $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id, $this->id)); $event->trigger(); // Finally reorder courses. fix_course_sortorder(); cache_helper::purge_by_event('changesincoursecat'); return true; } return false; }
[ "public", "function", "change_sortorder_by_one", "(", "$", "up", ")", "{", "global", "$", "DB", ";", "$", "params", "=", "array", "(", "$", "this", "->", "sortorder", ",", "$", "this", "->", "parent", ")", ";", "if", "(", "$", "up", ")", "{", "$", "select", "=", "'sortorder < ? AND parent = ?'", ";", "$", "sort", "=", "'sortorder DESC'", ";", "}", "else", "{", "$", "select", "=", "'sortorder > ? AND parent = ?'", ";", "$", "sort", "=", "'sortorder ASC'", ";", "}", "fix_course_sortorder", "(", ")", ";", "$", "swapcategory", "=", "$", "DB", "->", "get_records_select", "(", "'course_categories'", ",", "$", "select", ",", "$", "params", ",", "$", "sort", ",", "'*'", ",", "0", ",", "1", ")", ";", "$", "swapcategory", "=", "reset", "(", "$", "swapcategory", ")", ";", "if", "(", "$", "swapcategory", ")", "{", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'sortorder'", ",", "$", "swapcategory", "->", "sortorder", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ")", ")", ";", "$", "DB", "->", "set_field", "(", "'course_categories'", ",", "'sortorder'", ",", "$", "this", "->", "sortorder", ",", "array", "(", "'id'", "=>", "$", "swapcategory", "->", "id", ")", ")", ";", "$", "this", "->", "sortorder", "=", "$", "swapcategory", "->", "sortorder", ";", "$", "event", "=", "\\", "core", "\\", "event", "\\", "course_category_updated", "::", "create", "(", "array", "(", "'objectid'", "=>", "$", "this", "->", "id", ",", "'context'", "=>", "$", "this", "->", "get_context", "(", ")", ")", ")", ";", "$", "event", "->", "set_legacy_logdata", "(", "array", "(", "SITEID", ",", "'category'", ",", "'move'", ",", "'management.php?categoryid='", ".", "$", "this", "->", "id", ",", "$", "this", "->", "id", ")", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "// Finally reorder courses.", "fix_course_sortorder", "(", ")", ";", "cache_helper", "::", "purge_by_event", "(", "'changesincoursecat'", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Changes the sort order of this categories parent shifting this category up or down one. @param bool $up If set to true the category is shifted up one spot, else its moved down. @return bool True on success, false otherwise.
[ "Changes", "the", "sort", "order", "of", "this", "categories", "parent", "shifting", "this", "category", "up", "or", "down", "one", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2922-L2954
216,834
moodle/moodle
course/classes/category.php
core_course_category.can_request_course
public function can_request_course() { global $CFG; if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) { return false; } return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context()); }
php
public function can_request_course() { global $CFG; if (empty($CFG->enablecourserequests) || $this->id != $CFG->defaultrequestcategory) { return false; } return !$this->can_create_course() && has_capability('moodle/course:request', $this->get_context()); }
[ "public", "function", "can_request_course", "(", ")", "{", "global", "$", "CFG", ";", "if", "(", "empty", "(", "$", "CFG", "->", "enablecourserequests", ")", "||", "$", "this", "->", "id", "!=", "$", "CFG", "->", "defaultrequestcategory", ")", "{", "return", "false", ";", "}", "return", "!", "$", "this", "->", "can_create_course", "(", ")", "&&", "has_capability", "(", "'moodle/course:request'", ",", "$", "this", "->", "get_context", "(", ")", ")", ";", "}" ]
Returns true if the user is able to request a new course be created. @return bool
[ "Returns", "true", "if", "the", "user", "is", "able", "to", "request", "a", "new", "course", "be", "created", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2975-L2981
216,835
moodle/moodle
course/classes/category.php
core_course_category.can_approve_course_requests
public static function can_approve_course_requests() { global $CFG, $DB; if (empty($CFG->enablecourserequests)) { return false; } $context = context_system::instance(); if (!has_capability('moodle/site:approvecourse', $context)) { return false; } if (!$DB->record_exists('course_request', array())) { return false; } return true; }
php
public static function can_approve_course_requests() { global $CFG, $DB; if (empty($CFG->enablecourserequests)) { return false; } $context = context_system::instance(); if (!has_capability('moodle/site:approvecourse', $context)) { return false; } if (!$DB->record_exists('course_request', array())) { return false; } return true; }
[ "public", "static", "function", "can_approve_course_requests", "(", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "if", "(", "empty", "(", "$", "CFG", "->", "enablecourserequests", ")", ")", "{", "return", "false", ";", "}", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "if", "(", "!", "has_capability", "(", "'moodle/site:approvecourse'", ",", "$", "context", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "DB", "->", "record_exists", "(", "'course_request'", ",", "array", "(", ")", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if the user can approve course requests. @return bool
[ "Returns", "true", "if", "the", "user", "can", "approve", "course", "requests", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/course/classes/category.php#L2987-L3000
216,836
moodle/moodle
lib/oauthlib.php
oauth_helper.sign
public function sign($http_method, $url, $params, $secret) { $sig = array( strtoupper($http_method), preg_replace('/%7E/', '~', rawurlencode($url)), rawurlencode($this->get_signable_parameters($params)), ); $base_string = implode('&', $sig); $sig = base64_encode(hash_hmac('sha1', $base_string, $secret, true)); return $sig; }
php
public function sign($http_method, $url, $params, $secret) { $sig = array( strtoupper($http_method), preg_replace('/%7E/', '~', rawurlencode($url)), rawurlencode($this->get_signable_parameters($params)), ); $base_string = implode('&', $sig); $sig = base64_encode(hash_hmac('sha1', $base_string, $secret, true)); return $sig; }
[ "public", "function", "sign", "(", "$", "http_method", ",", "$", "url", ",", "$", "params", ",", "$", "secret", ")", "{", "$", "sig", "=", "array", "(", "strtoupper", "(", "$", "http_method", ")", ",", "preg_replace", "(", "'/%7E/'", ",", "'~'", ",", "rawurlencode", "(", "$", "url", ")", ")", ",", "rawurlencode", "(", "$", "this", "->", "get_signable_parameters", "(", "$", "params", ")", ")", ",", ")", ";", "$", "base_string", "=", "implode", "(", "'&'", ",", "$", "sig", ")", ";", "$", "sig", "=", "base64_encode", "(", "hash_hmac", "(", "'sha1'", ",", "$", "base_string", ",", "$", "secret", ",", "true", ")", ")", ";", "return", "$", "sig", ";", "}" ]
Create signature for oauth request @param string $url @param string $secret @param array $params @return string
[ "Create", "signature", "for", "oauth", "request" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L149-L159
216,837
moodle/moodle
lib/oauthlib.php
oauth_helper.request_token
public function request_token() { $this->sign_secret = $this->consumer_secret.'&'; if (empty($this->oauth_callback)) { $params = []; } else { $params = ['oauth_callback' => $this->oauth_callback->out(false)]; } $params = $this->prepare_oauth_parameters($this->request_token_api, $params, 'GET'); $content = $this->http->get($this->request_token_api, $params, $this->http_options); // Including: // oauth_token // oauth_token_secret $result = $this->parse_result($content); if (empty($result['oauth_token'])) { throw new moodle_exception('oauth1requesttoken', 'core_error', '', null, $content); } // Build oauth authorize url. $result['authorize_url'] = $this->authorize_url . '?oauth_token='.$result['oauth_token']; return $result; }
php
public function request_token() { $this->sign_secret = $this->consumer_secret.'&'; if (empty($this->oauth_callback)) { $params = []; } else { $params = ['oauth_callback' => $this->oauth_callback->out(false)]; } $params = $this->prepare_oauth_parameters($this->request_token_api, $params, 'GET'); $content = $this->http->get($this->request_token_api, $params, $this->http_options); // Including: // oauth_token // oauth_token_secret $result = $this->parse_result($content); if (empty($result['oauth_token'])) { throw new moodle_exception('oauth1requesttoken', 'core_error', '', null, $content); } // Build oauth authorize url. $result['authorize_url'] = $this->authorize_url . '?oauth_token='.$result['oauth_token']; return $result; }
[ "public", "function", "request_token", "(", ")", "{", "$", "this", "->", "sign_secret", "=", "$", "this", "->", "consumer_secret", ".", "'&'", ";", "if", "(", "empty", "(", "$", "this", "->", "oauth_callback", ")", ")", "{", "$", "params", "=", "[", "]", ";", "}", "else", "{", "$", "params", "=", "[", "'oauth_callback'", "=>", "$", "this", "->", "oauth_callback", "->", "out", "(", "false", ")", "]", ";", "}", "$", "params", "=", "$", "this", "->", "prepare_oauth_parameters", "(", "$", "this", "->", "request_token_api", ",", "$", "params", ",", "'GET'", ")", ";", "$", "content", "=", "$", "this", "->", "http", "->", "get", "(", "$", "this", "->", "request_token_api", ",", "$", "params", ",", "$", "this", "->", "http_options", ")", ";", "// Including:", "// oauth_token", "// oauth_token_secret", "$", "result", "=", "$", "this", "->", "parse_result", "(", "$", "content", ")", ";", "if", "(", "empty", "(", "$", "result", "[", "'oauth_token'", "]", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'oauth1requesttoken'", ",", "'core_error'", ",", "''", ",", "null", ",", "$", "content", ")", ";", "}", "// Build oauth authorize url.", "$", "result", "[", "'authorize_url'", "]", "=", "$", "this", "->", "authorize_url", ".", "'?oauth_token='", ".", "$", "result", "[", "'oauth_token'", "]", ";", "return", "$", "result", ";", "}" ]
Request token for authentication This is the first step to use OAuth, it will return oauth_token and oauth_token_secret @return array
[ "Request", "token", "for", "authentication", "This", "is", "the", "first", "step", "to", "use", "OAuth", "it", "will", "return", "oauth_token", "and", "oauth_token_secret" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L219-L241
216,838
moodle/moodle
lib/oauthlib.php
oauth_helper.get_access_token
public function get_access_token($token, $secret, $verifier='') { $this->sign_secret = $this->consumer_secret.'&'.$secret; $params = $this->prepare_oauth_parameters($this->access_token_api, array('oauth_token'=>$token, 'oauth_verifier'=>$verifier), 'POST'); $this->setup_oauth_http_header($params); // Should never send the callback in this request. unset($params['oauth_callback']); $content = $this->http->post($this->access_token_api, $params, $this->http_options); $keys = $this->parse_result($content); if (empty($keys['oauth_token']) || empty($keys['oauth_token_secret'])) { throw new moodle_exception('oauth1accesstoken', 'core_error', '', null, $content); } $this->set_access_token($keys['oauth_token'], $keys['oauth_token_secret']); return $keys; }
php
public function get_access_token($token, $secret, $verifier='') { $this->sign_secret = $this->consumer_secret.'&'.$secret; $params = $this->prepare_oauth_parameters($this->access_token_api, array('oauth_token'=>$token, 'oauth_verifier'=>$verifier), 'POST'); $this->setup_oauth_http_header($params); // Should never send the callback in this request. unset($params['oauth_callback']); $content = $this->http->post($this->access_token_api, $params, $this->http_options); $keys = $this->parse_result($content); if (empty($keys['oauth_token']) || empty($keys['oauth_token_secret'])) { throw new moodle_exception('oauth1accesstoken', 'core_error', '', null, $content); } $this->set_access_token($keys['oauth_token'], $keys['oauth_token_secret']); return $keys; }
[ "public", "function", "get_access_token", "(", "$", "token", ",", "$", "secret", ",", "$", "verifier", "=", "''", ")", "{", "$", "this", "->", "sign_secret", "=", "$", "this", "->", "consumer_secret", ".", "'&'", ".", "$", "secret", ";", "$", "params", "=", "$", "this", "->", "prepare_oauth_parameters", "(", "$", "this", "->", "access_token_api", ",", "array", "(", "'oauth_token'", "=>", "$", "token", ",", "'oauth_verifier'", "=>", "$", "verifier", ")", ",", "'POST'", ")", ";", "$", "this", "->", "setup_oauth_http_header", "(", "$", "params", ")", ";", "// Should never send the callback in this request.", "unset", "(", "$", "params", "[", "'oauth_callback'", "]", ")", ";", "$", "content", "=", "$", "this", "->", "http", "->", "post", "(", "$", "this", "->", "access_token_api", ",", "$", "params", ",", "$", "this", "->", "http_options", ")", ";", "$", "keys", "=", "$", "this", "->", "parse_result", "(", "$", "content", ")", ";", "if", "(", "empty", "(", "$", "keys", "[", "'oauth_token'", "]", ")", "||", "empty", "(", "$", "keys", "[", "'oauth_token_secret'", "]", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'oauth1accesstoken'", ",", "'core_error'", ",", "''", ",", "null", ",", "$", "content", ")", ";", "}", "$", "this", "->", "set_access_token", "(", "$", "keys", "[", "'oauth_token'", "]", ",", "$", "keys", "[", "'oauth_token_secret'", "]", ")", ";", "return", "$", "keys", ";", "}" ]
Request oauth access token from server @param string $method @param string $url @param string $token @param string $secret
[ "Request", "oauth", "access", "token", "from", "server" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L260-L275
216,839
moodle/moodle
lib/oauthlib.php
oauth_helper.request
public function request($method, $url, $params=array(), $token='', $secret='') { if (empty($token)) { $token = $this->access_token; } if (empty($secret)) { $secret = $this->access_token_secret; } // to access protected resource, sign_secret will alwasy be consumer_secret+token_secret $this->sign_secret = $this->consumer_secret.'&'.$secret; if (strtolower($method) === 'post' && !empty($params)) { $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token) + $params, $method); } else { $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token), $method); } $this->setup_oauth_http_header($oauth_params); $content = call_user_func_array(array($this->http, strtolower($method)), array($url, $params, $this->http_options)); // reset http header and options to prepare for the next request $this->http->resetHeader(); // return request return value return $content; }
php
public function request($method, $url, $params=array(), $token='', $secret='') { if (empty($token)) { $token = $this->access_token; } if (empty($secret)) { $secret = $this->access_token_secret; } // to access protected resource, sign_secret will alwasy be consumer_secret+token_secret $this->sign_secret = $this->consumer_secret.'&'.$secret; if (strtolower($method) === 'post' && !empty($params)) { $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token) + $params, $method); } else { $oauth_params = $this->prepare_oauth_parameters($url, array('oauth_token'=>$token), $method); } $this->setup_oauth_http_header($oauth_params); $content = call_user_func_array(array($this->http, strtolower($method)), array($url, $params, $this->http_options)); // reset http header and options to prepare for the next request $this->http->resetHeader(); // return request return value return $content; }
[ "public", "function", "request", "(", "$", "method", ",", "$", "url", ",", "$", "params", "=", "array", "(", ")", ",", "$", "token", "=", "''", ",", "$", "secret", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "token", ")", ")", "{", "$", "token", "=", "$", "this", "->", "access_token", ";", "}", "if", "(", "empty", "(", "$", "secret", ")", ")", "{", "$", "secret", "=", "$", "this", "->", "access_token_secret", ";", "}", "// to access protected resource, sign_secret will alwasy be consumer_secret+token_secret", "$", "this", "->", "sign_secret", "=", "$", "this", "->", "consumer_secret", ".", "'&'", ".", "$", "secret", ";", "if", "(", "strtolower", "(", "$", "method", ")", "===", "'post'", "&&", "!", "empty", "(", "$", "params", ")", ")", "{", "$", "oauth_params", "=", "$", "this", "->", "prepare_oauth_parameters", "(", "$", "url", ",", "array", "(", "'oauth_token'", "=>", "$", "token", ")", "+", "$", "params", ",", "$", "method", ")", ";", "}", "else", "{", "$", "oauth_params", "=", "$", "this", "->", "prepare_oauth_parameters", "(", "$", "url", ",", "array", "(", "'oauth_token'", "=>", "$", "token", ")", ",", "$", "method", ")", ";", "}", "$", "this", "->", "setup_oauth_http_header", "(", "$", "oauth_params", ")", ";", "$", "content", "=", "call_user_func_array", "(", "array", "(", "$", "this", "->", "http", ",", "strtolower", "(", "$", "method", ")", ")", ",", "array", "(", "$", "url", ",", "$", "params", ",", "$", "this", "->", "http_options", ")", ")", ";", "// reset http header and options to prepare for the next request", "$", "this", "->", "http", "->", "resetHeader", "(", ")", ";", "// return request return value", "return", "$", "content", ";", "}" ]
Request oauth protected resources @param string $method @param string $url @param string $token @param string $secret
[ "Request", "oauth", "protected", "resources" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L284-L304
216,840
moodle/moodle
lib/oauthlib.php
oauth_helper.get
public function get($url, $params=array(), $token='', $secret='') { return $this->request('GET', $url, $params, $token, $secret); }
php
public function get($url, $params=array(), $token='', $secret='') { return $this->request('GET', $url, $params, $token, $secret); }
[ "public", "function", "get", "(", "$", "url", ",", "$", "params", "=", "array", "(", ")", ",", "$", "token", "=", "''", ",", "$", "secret", "=", "''", ")", "{", "return", "$", "this", "->", "request", "(", "'GET'", ",", "$", "url", ",", "$", "params", ",", "$", "token", ",", "$", "secret", ")", ";", "}" ]
shortcut to start http get request
[ "shortcut", "to", "start", "http", "get", "request" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L309-L311
216,841
moodle/moodle
lib/oauthlib.php
oauth_helper.post
public function post($url, $params=array(), $token='', $secret='') { return $this->request('POST', $url, $params, $token, $secret); }
php
public function post($url, $params=array(), $token='', $secret='') { return $this->request('POST', $url, $params, $token, $secret); }
[ "public", "function", "post", "(", "$", "url", ",", "$", "params", "=", "array", "(", ")", ",", "$", "token", "=", "''", ",", "$", "secret", "=", "''", ")", "{", "return", "$", "this", "->", "request", "(", "'POST'", ",", "$", "url", ",", "$", "params", ",", "$", "token", ",", "$", "secret", ")", ";", "}" ]
shortcut to start http post request
[ "shortcut", "to", "start", "http", "post", "request" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L316-L318
216,842
moodle/moodle
lib/oauthlib.php
oauth_helper.parse_result
public function parse_result($str) { if (empty($str)) { throw new moodle_exception('error'); } $parts = explode('&', $str); $result = array(); foreach ($parts as $part){ list($k, $v) = explode('=', $part, 2); $result[urldecode($k)] = urldecode($v); } if (empty($result)) { throw new moodle_exception('error'); } return $result; }
php
public function parse_result($str) { if (empty($str)) { throw new moodle_exception('error'); } $parts = explode('&', $str); $result = array(); foreach ($parts as $part){ list($k, $v) = explode('=', $part, 2); $result[urldecode($k)] = urldecode($v); } if (empty($result)) { throw new moodle_exception('error'); } return $result; }
[ "public", "function", "parse_result", "(", "$", "str", ")", "{", "if", "(", "empty", "(", "$", "str", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'error'", ")", ";", "}", "$", "parts", "=", "explode", "(", "'&'", ",", "$", "str", ")", ";", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "list", "(", "$", "k", ",", "$", "v", ")", "=", "explode", "(", "'='", ",", "$", "part", ",", "2", ")", ";", "$", "result", "[", "urldecode", "(", "$", "k", ")", "]", "=", "urldecode", "(", "$", "v", ")", ";", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'error'", ")", ";", "}", "return", "$", "result", ";", "}" ]
A method to parse oauth response to get oauth_token and oauth_token_secret @param string $str @return array
[ "A", "method", "to", "parse", "oauth", "response", "to", "get", "oauth_token", "and", "oauth_token_secret" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L325-L339
216,843
moodle/moodle
lib/oauthlib.php
oauth_helper.get_nonce
function get_nonce() { if (!empty($this->nonce)) { $nonce = $this->nonce; unset($this->nonce); return $nonce; } $mt = microtime(); $rand = mt_rand(); return md5($mt . $rand); }
php
function get_nonce() { if (!empty($this->nonce)) { $nonce = $this->nonce; unset($this->nonce); return $nonce; } $mt = microtime(); $rand = mt_rand(); return md5($mt . $rand); }
[ "function", "get_nonce", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "nonce", ")", ")", "{", "$", "nonce", "=", "$", "this", "->", "nonce", ";", "unset", "(", "$", "this", "->", "nonce", ")", ";", "return", "$", "nonce", ";", "}", "$", "mt", "=", "microtime", "(", ")", ";", "$", "rand", "=", "mt_rand", "(", ")", ";", "return", "md5", "(", "$", "mt", ".", "$", "rand", ")", ";", "}" ]
Generate nonce for oauth request
[ "Generate", "nonce", "for", "oauth", "request" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L367-L377
216,844
moodle/moodle
lib/oauthlib.php
oauth2_client.is_logged_in
public function is_logged_in() { // Has the token expired? if (isset($this->accesstoken->expires) && time() >= $this->accesstoken->expires) { $this->log_out(); return false; } // We have a token so we are logged in. if (isset($this->accesstoken->token)) { // Check that the access token has all the requested scopes. $scopemissing = false; $scopecheck = ' ' . $this->accesstoken->scope . ' '; $requiredscopes = explode(' ', $this->scope); foreach ($requiredscopes as $requiredscope) { if (strpos($scopecheck, ' ' . $requiredscope . ' ') === false) { $scopemissing = true; break; } } if (!$scopemissing) { return true; } } // If we've been passed then authorization code generated by the // authorization server try and upgrade the token to an access token. $code = optional_param('oauth2code', null, PARAM_RAW); // Note - sometimes we may call is_logged_in twice in the same request - we don't want to attempt // to upgrade the same token twice. if ($code && !in_array($code, self::$upgradedcodes) && $this->upgrade_token($code)) { return true; } return false; }
php
public function is_logged_in() { // Has the token expired? if (isset($this->accesstoken->expires) && time() >= $this->accesstoken->expires) { $this->log_out(); return false; } // We have a token so we are logged in. if (isset($this->accesstoken->token)) { // Check that the access token has all the requested scopes. $scopemissing = false; $scopecheck = ' ' . $this->accesstoken->scope . ' '; $requiredscopes = explode(' ', $this->scope); foreach ($requiredscopes as $requiredscope) { if (strpos($scopecheck, ' ' . $requiredscope . ' ') === false) { $scopemissing = true; break; } } if (!$scopemissing) { return true; } } // If we've been passed then authorization code generated by the // authorization server try and upgrade the token to an access token. $code = optional_param('oauth2code', null, PARAM_RAW); // Note - sometimes we may call is_logged_in twice in the same request - we don't want to attempt // to upgrade the same token twice. if ($code && !in_array($code, self::$upgradedcodes) && $this->upgrade_token($code)) { return true; } return false; }
[ "public", "function", "is_logged_in", "(", ")", "{", "// Has the token expired?", "if", "(", "isset", "(", "$", "this", "->", "accesstoken", "->", "expires", ")", "&&", "time", "(", ")", ">=", "$", "this", "->", "accesstoken", "->", "expires", ")", "{", "$", "this", "->", "log_out", "(", ")", ";", "return", "false", ";", "}", "// We have a token so we are logged in.", "if", "(", "isset", "(", "$", "this", "->", "accesstoken", "->", "token", ")", ")", "{", "// Check that the access token has all the requested scopes.", "$", "scopemissing", "=", "false", ";", "$", "scopecheck", "=", "' '", ".", "$", "this", "->", "accesstoken", "->", "scope", ".", "' '", ";", "$", "requiredscopes", "=", "explode", "(", "' '", ",", "$", "this", "->", "scope", ")", ";", "foreach", "(", "$", "requiredscopes", "as", "$", "requiredscope", ")", "{", "if", "(", "strpos", "(", "$", "scopecheck", ",", "' '", ".", "$", "requiredscope", ".", "' '", ")", "===", "false", ")", "{", "$", "scopemissing", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "scopemissing", ")", "{", "return", "true", ";", "}", "}", "// If we've been passed then authorization code generated by the", "// authorization server try and upgrade the token to an access token.", "$", "code", "=", "optional_param", "(", "'oauth2code'", ",", "null", ",", "PARAM_RAW", ")", ";", "// Note - sometimes we may call is_logged_in twice in the same request - we don't want to attempt", "// to upgrade the same token twice.", "if", "(", "$", "code", "&&", "!", "in_array", "(", "$", "code", ",", "self", "::", "$", "upgradedcodes", ")", "&&", "$", "this", "->", "upgrade_token", "(", "$", "code", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Is the user logged in? Note that if this is called after the first part of the authorisation flow the token is upgraded to an accesstoken. @return boolean true if logged in
[ "Is", "the", "user", "logged", "in?", "Note", "that", "if", "this", "is", "called", "after", "the", "first", "part", "of", "the", "authorisation", "flow", "the", "token", "is", "upgraded", "to", "an", "accesstoken", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L445-L480
216,845
moodle/moodle
lib/oauthlib.php
oauth2_client.get_login_url
public function get_login_url() { $callbackurl = self::callback_url(); $params = array_merge( [ 'client_id' => $this->clientid, 'response_type' => 'code', 'redirect_uri' => $callbackurl->out(false), 'state' => $this->returnurl->out_as_local_url(false), 'scope' => $this->scope, ], $this->get_additional_login_parameters() ); return new moodle_url($this->auth_url(), $params); }
php
public function get_login_url() { $callbackurl = self::callback_url(); $params = array_merge( [ 'client_id' => $this->clientid, 'response_type' => 'code', 'redirect_uri' => $callbackurl->out(false), 'state' => $this->returnurl->out_as_local_url(false), 'scope' => $this->scope, ], $this->get_additional_login_parameters() ); return new moodle_url($this->auth_url(), $params); }
[ "public", "function", "get_login_url", "(", ")", "{", "$", "callbackurl", "=", "self", "::", "callback_url", "(", ")", ";", "$", "params", "=", "array_merge", "(", "[", "'client_id'", "=>", "$", "this", "->", "clientid", ",", "'response_type'", "=>", "'code'", ",", "'redirect_uri'", "=>", "$", "callbackurl", "->", "out", "(", "false", ")", ",", "'state'", "=>", "$", "this", "->", "returnurl", "->", "out_as_local_url", "(", "false", ")", ",", "'scope'", "=>", "$", "this", "->", "scope", ",", "]", ",", "$", "this", "->", "get_additional_login_parameters", "(", ")", ")", ";", "return", "new", "moodle_url", "(", "$", "this", "->", "auth_url", "(", ")", ",", "$", "params", ")", ";", "}" ]
Returns the login link for this oauth request @return moodle_url login url
[ "Returns", "the", "login", "link", "for", "this", "oauth", "request" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L507-L522
216,846
moodle/moodle
lib/oauthlib.php
oauth2_client.upgrade_token
public function upgrade_token($code) { $callbackurl = self::callback_url(); $params = array('code' => $code, 'grant_type' => 'authorization_code', 'redirect_uri' => $callbackurl->out(false), ); if ($this->basicauth) { $idsecret = urlencode($this->clientid) . ':' . urlencode($this->clientsecret); $this->setHeader('Authorization: Basic ' . base64_encode($idsecret)); } else { $params['client_id'] = $this->clientid; $params['client_secret'] = $this->clientsecret; } // Requests can either use http GET or POST. if ($this->use_http_get()) { $response = $this->get($this->token_url(), $params); } else { $response = $this->post($this->token_url(), $this->build_post_data($params)); } if ($this->info['http_code'] !== 200) { throw new moodle_exception('Could not upgrade oauth token'); } $r = json_decode($response); if (is_null($r)) { throw new moodle_exception("Could not decode JSON token response"); } if (!empty($r->error)) { throw new moodle_exception($r->error . ' ' . $r->error_description); } if (!isset($r->access_token)) { return false; } if (isset($r->refresh_token)) { $this->refreshtoken = $r->refresh_token; } // Store the token an expiry time. $accesstoken = new stdClass; $accesstoken->token = $r->access_token; if (isset($r->expires_in)) { // Expires 10 seconds before actual expiry. $accesstoken->expires = (time() + ($r->expires_in - 10)); } $accesstoken->scope = $this->scope; // Also add the scopes. self::$upgradedcodes[] = $code; $this->store_token($accesstoken); return true; }
php
public function upgrade_token($code) { $callbackurl = self::callback_url(); $params = array('code' => $code, 'grant_type' => 'authorization_code', 'redirect_uri' => $callbackurl->out(false), ); if ($this->basicauth) { $idsecret = urlencode($this->clientid) . ':' . urlencode($this->clientsecret); $this->setHeader('Authorization: Basic ' . base64_encode($idsecret)); } else { $params['client_id'] = $this->clientid; $params['client_secret'] = $this->clientsecret; } // Requests can either use http GET or POST. if ($this->use_http_get()) { $response = $this->get($this->token_url(), $params); } else { $response = $this->post($this->token_url(), $this->build_post_data($params)); } if ($this->info['http_code'] !== 200) { throw new moodle_exception('Could not upgrade oauth token'); } $r = json_decode($response); if (is_null($r)) { throw new moodle_exception("Could not decode JSON token response"); } if (!empty($r->error)) { throw new moodle_exception($r->error . ' ' . $r->error_description); } if (!isset($r->access_token)) { return false; } if (isset($r->refresh_token)) { $this->refreshtoken = $r->refresh_token; } // Store the token an expiry time. $accesstoken = new stdClass; $accesstoken->token = $r->access_token; if (isset($r->expires_in)) { // Expires 10 seconds before actual expiry. $accesstoken->expires = (time() + ($r->expires_in - 10)); } $accesstoken->scope = $this->scope; // Also add the scopes. self::$upgradedcodes[] = $code; $this->store_token($accesstoken); return true; }
[ "public", "function", "upgrade_token", "(", "$", "code", ")", "{", "$", "callbackurl", "=", "self", "::", "callback_url", "(", ")", ";", "$", "params", "=", "array", "(", "'code'", "=>", "$", "code", ",", "'grant_type'", "=>", "'authorization_code'", ",", "'redirect_uri'", "=>", "$", "callbackurl", "->", "out", "(", "false", ")", ",", ")", ";", "if", "(", "$", "this", "->", "basicauth", ")", "{", "$", "idsecret", "=", "urlencode", "(", "$", "this", "->", "clientid", ")", ".", "':'", ".", "urlencode", "(", "$", "this", "->", "clientsecret", ")", ";", "$", "this", "->", "setHeader", "(", "'Authorization: Basic '", ".", "base64_encode", "(", "$", "idsecret", ")", ")", ";", "}", "else", "{", "$", "params", "[", "'client_id'", "]", "=", "$", "this", "->", "clientid", ";", "$", "params", "[", "'client_secret'", "]", "=", "$", "this", "->", "clientsecret", ";", "}", "// Requests can either use http GET or POST.", "if", "(", "$", "this", "->", "use_http_get", "(", ")", ")", "{", "$", "response", "=", "$", "this", "->", "get", "(", "$", "this", "->", "token_url", "(", ")", ",", "$", "params", ")", ";", "}", "else", "{", "$", "response", "=", "$", "this", "->", "post", "(", "$", "this", "->", "token_url", "(", ")", ",", "$", "this", "->", "build_post_data", "(", "$", "params", ")", ")", ";", "}", "if", "(", "$", "this", "->", "info", "[", "'http_code'", "]", "!==", "200", ")", "{", "throw", "new", "moodle_exception", "(", "'Could not upgrade oauth token'", ")", ";", "}", "$", "r", "=", "json_decode", "(", "$", "response", ")", ";", "if", "(", "is_null", "(", "$", "r", ")", ")", "{", "throw", "new", "moodle_exception", "(", "\"Could not decode JSON token response\"", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "r", "->", "error", ")", ")", "{", "throw", "new", "moodle_exception", "(", "$", "r", "->", "error", ".", "' '", ".", "$", "r", "->", "error_description", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "r", "->", "access_token", ")", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "r", "->", "refresh_token", ")", ")", "{", "$", "this", "->", "refreshtoken", "=", "$", "r", "->", "refresh_token", ";", "}", "// Store the token an expiry time.", "$", "accesstoken", "=", "new", "stdClass", ";", "$", "accesstoken", "->", "token", "=", "$", "r", "->", "access_token", ";", "if", "(", "isset", "(", "$", "r", "->", "expires_in", ")", ")", "{", "// Expires 10 seconds before actual expiry.", "$", "accesstoken", "->", "expires", "=", "(", "time", "(", ")", "+", "(", "$", "r", "->", "expires_in", "-", "10", ")", ")", ";", "}", "$", "accesstoken", "->", "scope", "=", "$", "this", "->", "scope", ";", "// Also add the scopes.", "self", "::", "$", "upgradedcodes", "[", "]", "=", "$", "code", ";", "$", "this", "->", "store_token", "(", "$", "accesstoken", ")", ";", "return", "true", ";", "}" ]
Upgrade a authorization token from oauth 2.0 to an access token @param string $code the code returned from the oauth authenticaiton @return boolean true if token is upgraded succesfully
[ "Upgrade", "a", "authorization", "token", "from", "oauth", "2", ".", "0", "to", "an", "access", "token" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L544-L601
216,847
moodle/moodle
lib/oauthlib.php
oauth2_client.request
protected function request($url, $options = array(), $acceptheader = 'application/json') { $murl = new moodle_url($url); if ($this->accesstoken) { if ($this->use_http_get()) { // If using HTTP GET add as a parameter. $murl->param('access_token', $this->accesstoken->token); } else { $this->setHeader('Authorization: Bearer '.$this->accesstoken->token); } } if ($acceptheader) { $this->setHeader('Accept: ' . $acceptheader); } $response = parent::request($murl->out(false), $options); $this->resetHeader(); return $response; }
php
protected function request($url, $options = array(), $acceptheader = 'application/json') { $murl = new moodle_url($url); if ($this->accesstoken) { if ($this->use_http_get()) { // If using HTTP GET add as a parameter. $murl->param('access_token', $this->accesstoken->token); } else { $this->setHeader('Authorization: Bearer '.$this->accesstoken->token); } } if ($acceptheader) { $this->setHeader('Accept: ' . $acceptheader); } $response = parent::request($murl->out(false), $options); $this->resetHeader(); return $response; }
[ "protected", "function", "request", "(", "$", "url", ",", "$", "options", "=", "array", "(", ")", ",", "$", "acceptheader", "=", "'application/json'", ")", "{", "$", "murl", "=", "new", "moodle_url", "(", "$", "url", ")", ";", "if", "(", "$", "this", "->", "accesstoken", ")", "{", "if", "(", "$", "this", "->", "use_http_get", "(", ")", ")", "{", "// If using HTTP GET add as a parameter.", "$", "murl", "->", "param", "(", "'access_token'", ",", "$", "this", "->", "accesstoken", "->", "token", ")", ";", "}", "else", "{", "$", "this", "->", "setHeader", "(", "'Authorization: Bearer '", ".", "$", "this", "->", "accesstoken", "->", "token", ")", ";", "}", "}", "if", "(", "$", "acceptheader", ")", "{", "$", "this", "->", "setHeader", "(", "'Accept: '", ".", "$", "acceptheader", ")", ";", "}", "$", "response", "=", "parent", "::", "request", "(", "$", "murl", "->", "out", "(", "false", ")", ",", "$", "options", ")", ";", "$", "this", "->", "resetHeader", "(", ")", ";", "return", "$", "response", ";", "}" ]
Make a HTTP request, adding the access token we have @param string $url The URL to request @param array $options @param mixed $acceptheader mimetype (as string) or false to skip sending an accept header. @return bool
[ "Make", "a", "HTTP", "request", "adding", "the", "access", "token", "we", "have" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L618-L639
216,848
moodle/moodle
lib/oauthlib.php
oauth2_client.multi
protected function multi($requests, $options = array()) { if ($this->accesstoken) { $this->setHeader('Authorization: Bearer '.$this->accesstoken->token); } return parent::multi($requests, $options); }
php
protected function multi($requests, $options = array()) { if ($this->accesstoken) { $this->setHeader('Authorization: Bearer '.$this->accesstoken->token); } return parent::multi($requests, $options); }
[ "protected", "function", "multi", "(", "$", "requests", ",", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "$", "this", "->", "accesstoken", ")", "{", "$", "this", "->", "setHeader", "(", "'Authorization: Bearer '", ".", "$", "this", "->", "accesstoken", "->", "token", ")", ";", "}", "return", "parent", "::", "multi", "(", "$", "requests", ",", "$", "options", ")", ";", "}" ]
Multiple HTTP Requests This function could run multi-requests in parallel. @param array $requests An array of files to request @param array $options An array of options to set @return array An array of results
[ "Multiple", "HTTP", "Requests", "This", "function", "could", "run", "multi", "-", "requests", "in", "parallel", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L649-L654
216,849
moodle/moodle
lib/oauthlib.php
oauth2_client.store_token
protected function store_token($token) { global $SESSION; $this->accesstoken = $token; $name = $this->get_tokenname(); if ($token !== null) { $SESSION->{$name} = $token; } else { unset($SESSION->{$name}); } }
php
protected function store_token($token) { global $SESSION; $this->accesstoken = $token; $name = $this->get_tokenname(); if ($token !== null) { $SESSION->{$name} = $token; } else { unset($SESSION->{$name}); } }
[ "protected", "function", "store_token", "(", "$", "token", ")", "{", "global", "$", "SESSION", ";", "$", "this", "->", "accesstoken", "=", "$", "token", ";", "$", "name", "=", "$", "this", "->", "get_tokenname", "(", ")", ";", "if", "(", "$", "token", "!==", "null", ")", "{", "$", "SESSION", "->", "{", "$", "name", "}", "=", "$", "token", ";", "}", "else", "{", "unset", "(", "$", "SESSION", "->", "{", "$", "name", "}", ")", ";", "}", "}" ]
Store a token between requests. Currently uses session named by get_tokenname @param stdClass|null $token token object to store or null to clear
[ "Store", "a", "token", "between", "requests", ".", "Currently", "uses", "session", "named", "by", "get_tokenname" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L676-L687
216,850
moodle/moodle
lib/oauthlib.php
oauth2_client.get_stored_token
protected function get_stored_token() { global $SESSION; $name = $this->get_tokenname(); if (isset($SESSION->{$name})) { return $SESSION->{$name}; } return null; }
php
protected function get_stored_token() { global $SESSION; $name = $this->get_tokenname(); if (isset($SESSION->{$name})) { return $SESSION->{$name}; } return null; }
[ "protected", "function", "get_stored_token", "(", ")", "{", "global", "$", "SESSION", ";", "$", "name", "=", "$", "this", "->", "get_tokenname", "(", ")", ";", "if", "(", "isset", "(", "$", "SESSION", "->", "{", "$", "name", "}", ")", ")", "{", "return", "$", "SESSION", "->", "{", "$", "name", "}", ";", "}", "return", "null", ";", "}" ]
Retrieve a token stored. @return stdClass|null token object
[ "Retrieve", "a", "token", "stored", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/oauthlib.php#L703-L713
216,851
moodle/moodle
lib/horde/framework/Horde/Mail/Transport/Smtp.php
Horde_Mail_Transport_Smtp.disconnect
public function disconnect() { /* If we have an SMTP object, disconnect and destroy it. */ if (is_object($this->_smtp) && $this->_smtp->disconnect()) { $this->_smtp = null; } /* We are disconnected if we no longer have an SMTP object. */ return ($this->_smtp === null); }
php
public function disconnect() { /* If we have an SMTP object, disconnect and destroy it. */ if (is_object($this->_smtp) && $this->_smtp->disconnect()) { $this->_smtp = null; } /* We are disconnected if we no longer have an SMTP object. */ return ($this->_smtp === null); }
[ "public", "function", "disconnect", "(", ")", "{", "/* If we have an SMTP object, disconnect and destroy it. */", "if", "(", "is_object", "(", "$", "this", "->", "_smtp", ")", "&&", "$", "this", "->", "_smtp", "->", "disconnect", "(", ")", ")", "{", "$", "this", "->", "_smtp", "=", "null", ";", "}", "/* We are disconnected if we no longer have an SMTP object. */", "return", "(", "$", "this", "->", "_smtp", "===", "null", ")", ";", "}" ]
Disconnect and destroy the current SMTP connection. @return boolean True if the SMTP connection no longer exists.
[ "Disconnect", "and", "destroy", "the", "current", "SMTP", "connection", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Mail/Transport/Smtp.php#L318-L327
216,852
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.print_login
public function print_login() { $client = $this->get_user_oauth_client(); $url = $client->get_login_url(); if ($this->options['ajax']) { $popup = new stdClass(); $popup->type = 'popup'; $popup->url = $url->out(false); return array('login' => array($popup)); } else { echo '<a target="_blank" href="'.$url->out(false).'">'.get_string('login', 'repository').'</a>'; } }
php
public function print_login() { $client = $this->get_user_oauth_client(); $url = $client->get_login_url(); if ($this->options['ajax']) { $popup = new stdClass(); $popup->type = 'popup'; $popup->url = $url->out(false); return array('login' => array($popup)); } else { echo '<a target="_blank" href="'.$url->out(false).'">'.get_string('login', 'repository').'</a>'; } }
[ "public", "function", "print_login", "(", ")", "{", "$", "client", "=", "$", "this", "->", "get_user_oauth_client", "(", ")", ";", "$", "url", "=", "$", "client", "->", "get_login_url", "(", ")", ";", "if", "(", "$", "this", "->", "options", "[", "'ajax'", "]", ")", "{", "$", "popup", "=", "new", "stdClass", "(", ")", ";", "$", "popup", "->", "type", "=", "'popup'", ";", "$", "popup", "->", "url", "=", "$", "url", "->", "out", "(", "false", ")", ";", "return", "array", "(", "'login'", "=>", "array", "(", "$", "popup", ")", ")", ";", "}", "else", "{", "echo", "'<a target=\"_blank\" href=\"'", ".", "$", "url", "->", "out", "(", "false", ")", ".", "'\">'", ".", "get_string", "(", "'login'", ",", "'repository'", ")", ".", "'</a>'", ";", "}", "}" ]
Print or return the login form. @return void|array for ajax.
[ "Print", "or", "return", "the", "login", "form", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L116-L128
216,853
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.print_login_popup
public function print_login_popup($attr = null) { global $OUTPUT, $PAGE; $client = $this->get_user_oauth_client(false); $url = new moodle_url($client->get_login_url()); $state = $url->get_param('state') . '&reloadparent=true'; $url->param('state', $state); $PAGE->set_pagelayout('embedded'); echo $OUTPUT->header(); $repositoryname = get_string('pluginname', 'repository_onedrive'); $button = new single_button($url, get_string('logintoaccount', 'repository', $repositoryname), 'post', true); $button->add_action(new popup_action('click', $url, 'Login')); $button->class = 'mdl-align'; $button = $OUTPUT->render($button); echo html_writer::div($button, '', $attr); echo $OUTPUT->footer(); }
php
public function print_login_popup($attr = null) { global $OUTPUT, $PAGE; $client = $this->get_user_oauth_client(false); $url = new moodle_url($client->get_login_url()); $state = $url->get_param('state') . '&reloadparent=true'; $url->param('state', $state); $PAGE->set_pagelayout('embedded'); echo $OUTPUT->header(); $repositoryname = get_string('pluginname', 'repository_onedrive'); $button = new single_button($url, get_string('logintoaccount', 'repository', $repositoryname), 'post', true); $button->add_action(new popup_action('click', $url, 'Login')); $button->class = 'mdl-align'; $button = $OUTPUT->render($button); echo html_writer::div($button, '', $attr); echo $OUTPUT->footer(); }
[ "public", "function", "print_login_popup", "(", "$", "attr", "=", "null", ")", "{", "global", "$", "OUTPUT", ",", "$", "PAGE", ";", "$", "client", "=", "$", "this", "->", "get_user_oauth_client", "(", "false", ")", ";", "$", "url", "=", "new", "moodle_url", "(", "$", "client", "->", "get_login_url", "(", ")", ")", ";", "$", "state", "=", "$", "url", "->", "get_param", "(", "'state'", ")", ".", "'&reloadparent=true'", ";", "$", "url", "->", "param", "(", "'state'", ",", "$", "state", ")", ";", "$", "PAGE", "->", "set_pagelayout", "(", "'embedded'", ")", ";", "echo", "$", "OUTPUT", "->", "header", "(", ")", ";", "$", "repositoryname", "=", "get_string", "(", "'pluginname'", ",", "'repository_onedrive'", ")", ";", "$", "button", "=", "new", "single_button", "(", "$", "url", ",", "get_string", "(", "'logintoaccount'", ",", "'repository'", ",", "$", "repositoryname", ")", ",", "'post'", ",", "true", ")", ";", "$", "button", "->", "add_action", "(", "new", "popup_action", "(", "'click'", ",", "$", "url", ",", "'Login'", ")", ")", ";", "$", "button", "->", "class", "=", "'mdl-align'", ";", "$", "button", "=", "$", "OUTPUT", "->", "render", "(", "$", "button", ")", ";", "echo", "html_writer", "::", "div", "(", "$", "button", ",", "''", ",", "$", "attr", ")", ";", "echo", "$", "OUTPUT", "->", "footer", "(", ")", ";", "}" ]
Print the login in a popup. @param array|null $attr Custom attributes to be applied to popup div.
[ "Print", "the", "login", "in", "a", "popup", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L135-L155
216,854
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.build_breadcrumb
protected function build_breadcrumb($path) { $bread = explode('/', $path); $crumbtrail = ''; foreach ($bread as $crumb) { list($id, $name) = $this->explode_node_path($crumb); $name = empty($name) ? $id : $name; $breadcrumb[] = array( 'name' => $name, 'path' => $this->build_node_path($id, $name, $crumbtrail) ); $tmp = end($breadcrumb); $crumbtrail = $tmp['path']; } return $breadcrumb; }
php
protected function build_breadcrumb($path) { $bread = explode('/', $path); $crumbtrail = ''; foreach ($bread as $crumb) { list($id, $name) = $this->explode_node_path($crumb); $name = empty($name) ? $id : $name; $breadcrumb[] = array( 'name' => $name, 'path' => $this->build_node_path($id, $name, $crumbtrail) ); $tmp = end($breadcrumb); $crumbtrail = $tmp['path']; } return $breadcrumb; }
[ "protected", "function", "build_breadcrumb", "(", "$", "path", ")", "{", "$", "bread", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "$", "crumbtrail", "=", "''", ";", "foreach", "(", "$", "bread", "as", "$", "crumb", ")", "{", "list", "(", "$", "id", ",", "$", "name", ")", "=", "$", "this", "->", "explode_node_path", "(", "$", "crumb", ")", ";", "$", "name", "=", "empty", "(", "$", "name", ")", "?", "$", "id", ":", "$", "name", ";", "$", "breadcrumb", "[", "]", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'path'", "=>", "$", "this", "->", "build_node_path", "(", "$", "id", ",", "$", "name", ",", "$", "crumbtrail", ")", ")", ";", "$", "tmp", "=", "end", "(", "$", "breadcrumb", ")", ";", "$", "crumbtrail", "=", "$", "tmp", "[", "'path'", "]", ";", "}", "return", "$", "breadcrumb", ";", "}" ]
Build the breadcrumb from a path. @param string $path to create a breadcrumb from. @return array containing name and path of each crumb.
[ "Build", "the", "breadcrumb", "from", "a", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L163-L177
216,855
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.build_node_path
protected function build_node_path($id, $name = '', $root = '') { $path = $id; if (!empty($name)) { $path .= '|' . urlencode($name); } if (!empty($root)) { $path = trim($root, '/') . '/' . $path; } return $path; }
php
protected function build_node_path($id, $name = '', $root = '') { $path = $id; if (!empty($name)) { $path .= '|' . urlencode($name); } if (!empty($root)) { $path = trim($root, '/') . '/' . $path; } return $path; }
[ "protected", "function", "build_node_path", "(", "$", "id", ",", "$", "name", "=", "''", ",", "$", "root", "=", "''", ")", "{", "$", "path", "=", "$", "id", ";", "if", "(", "!", "empty", "(", "$", "name", ")", ")", "{", "$", "path", ".=", "'|'", ".", "urlencode", "(", "$", "name", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "root", ")", ")", "{", "$", "path", "=", "trim", "(", "$", "root", ",", "'/'", ")", ".", "'/'", ".", "$", "path", ";", "}", "return", "$", "path", ";", "}" ]
Generates a safe path to a node. Typically, a node will be id|Name of the node. @param string $id of the node. @param string $name of the node, will be URL encoded. @param string $root to append the node on, must be a result of this function. @return string path to the node.
[ "Generates", "a", "safe", "path", "to", "a", "node", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L189-L198
216,856
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.explode_node_path
protected function explode_node_path($node) { if (strpos($node, '|') !== false) { list($id, $name) = explode('|', $node, 2); $name = urldecode($name); } else { $id = $node; $name = ''; } $id = urldecode($id); return array( 0 => $id, 1 => $name, 'id' => $id, 'name' => $name ); }
php
protected function explode_node_path($node) { if (strpos($node, '|') !== false) { list($id, $name) = explode('|', $node, 2); $name = urldecode($name); } else { $id = $node; $name = ''; } $id = urldecode($id); return array( 0 => $id, 1 => $name, 'id' => $id, 'name' => $name ); }
[ "protected", "function", "explode_node_path", "(", "$", "node", ")", "{", "if", "(", "strpos", "(", "$", "node", ",", "'|'", ")", "!==", "false", ")", "{", "list", "(", "$", "id", ",", "$", "name", ")", "=", "explode", "(", "'|'", ",", "$", "node", ",", "2", ")", ";", "$", "name", "=", "urldecode", "(", "$", "name", ")", ";", "}", "else", "{", "$", "id", "=", "$", "node", ";", "$", "name", "=", "''", ";", "}", "$", "id", "=", "urldecode", "(", "$", "id", ")", ";", "return", "array", "(", "0", "=>", "$", "id", ",", "1", "=>", "$", "name", ",", "'id'", "=>", "$", "id", ",", "'name'", "=>", "$", "name", ")", ";", "}" ]
Returns information about a node in a path. @see self::build_node_path() @param string $node to extrat information from. @return array about the node.
[ "Returns", "information", "about", "a", "node", "in", "a", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L207-L222
216,857
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.delete_file_by_path
protected function delete_file_by_path(\repository_onedrive\rest $client, $fullpath) { try { $response = $client->call('delete_file_by_path', ['fullpath' => $fullpath]); } catch (\core\oauth2\rest_exception $re) { return false; } return true; }
php
protected function delete_file_by_path(\repository_onedrive\rest $client, $fullpath) { try { $response = $client->call('delete_file_by_path', ['fullpath' => $fullpath]); } catch (\core\oauth2\rest_exception $re) { return false; } return true; }
[ "protected", "function", "delete_file_by_path", "(", "\\", "repository_onedrive", "\\", "rest", "$", "client", ",", "$", "fullpath", ")", "{", "try", "{", "$", "response", "=", "$", "client", "->", "call", "(", "'delete_file_by_path'", ",", "[", "'fullpath'", "=>", "$", "fullpath", "]", ")", ";", "}", "catch", "(", "\\", "core", "\\", "oauth2", "\\", "rest_exception", "$", "re", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Delete a file by full path. @param \repository_onedrive\rest $client Authenticated client. @param string $fullpath @return boolean
[ "Delete", "a", "file", "by", "full", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L653-L660
216,858
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.create_folder_in_folder
protected function create_folder_in_folder(\repository_onedrive\rest $client, $foldername, $parentid) { $params = ['parentid' => $parentid]; $folder = [ 'name' => $foldername, 'folder' => [ 'childCount' => 0 ]]; $created = $client->call('create_folder', $params, json_encode($folder)); if (empty($created->id)) { $details = 'Cannot create folder:' . $foldername; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } return $created->id; }
php
protected function create_folder_in_folder(\repository_onedrive\rest $client, $foldername, $parentid) { $params = ['parentid' => $parentid]; $folder = [ 'name' => $foldername, 'folder' => [ 'childCount' => 0 ]]; $created = $client->call('create_folder', $params, json_encode($folder)); if (empty($created->id)) { $details = 'Cannot create folder:' . $foldername; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } return $created->id; }
[ "protected", "function", "create_folder_in_folder", "(", "\\", "repository_onedrive", "\\", "rest", "$", "client", ",", "$", "foldername", ",", "$", "parentid", ")", "{", "$", "params", "=", "[", "'parentid'", "=>", "$", "parentid", "]", ";", "$", "folder", "=", "[", "'name'", "=>", "$", "foldername", ",", "'folder'", "=>", "[", "'childCount'", "=>", "0", "]", "]", ";", "$", "created", "=", "$", "client", "->", "call", "(", "'create_folder'", ",", "$", "params", ",", "json_encode", "(", "$", "folder", ")", ")", ";", "if", "(", "empty", "(", "$", "created", "->", "id", ")", ")", "{", "$", "details", "=", "'Cannot create folder:'", ".", "$", "foldername", ";", "throw", "new", "repository_exception", "(", "'errorwhilecommunicatingwith'", ",", "'repository'", ",", "''", ",", "$", "details", ")", ";", "}", "return", "$", "created", "->", "id", ";", "}" ]
Create a folder within a folder @param \repository_onedrive\rest $client Authenticated client. @param string $foldername The folder we are creating. @param string $parentid The parent folder we are creating in. @return string The file id of the new folder.
[ "Create", "a", "folder", "within", "a", "folder" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L671-L680
216,859
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.get_mimetype_from_filename
protected function get_mimetype_from_filename($filename) { $mimetype = 'application/unknown'; $types = core_filetypes::get_types(); $fileextension = '.bin'; if (strpos($filename, '.') !== false) { $fileextension = substr($filename, strrpos($filename, '.') + 1); } if (isset($types[$fileextension])) { $mimetype = $types[$fileextension]['type']; } return $mimetype; }
php
protected function get_mimetype_from_filename($filename) { $mimetype = 'application/unknown'; $types = core_filetypes::get_types(); $fileextension = '.bin'; if (strpos($filename, '.') !== false) { $fileextension = substr($filename, strrpos($filename, '.') + 1); } if (isset($types[$fileextension])) { $mimetype = $types[$fileextension]['type']; } return $mimetype; }
[ "protected", "function", "get_mimetype_from_filename", "(", "$", "filename", ")", "{", "$", "mimetype", "=", "'application/unknown'", ";", "$", "types", "=", "core_filetypes", "::", "get_types", "(", ")", ";", "$", "fileextension", "=", "'.bin'", ";", "if", "(", "strpos", "(", "$", "filename", ",", "'.'", ")", "!==", "false", ")", "{", "$", "fileextension", "=", "substr", "(", "$", "filename", ",", "strrpos", "(", "$", "filename", ",", "'.'", ")", "+", "1", ")", ";", "}", "if", "(", "isset", "(", "$", "types", "[", "$", "fileextension", "]", ")", ")", "{", "$", "mimetype", "=", "$", "types", "[", "$", "fileextension", "]", "[", "'type'", "]", ";", "}", "return", "$", "mimetype", ";", "}" ]
Given a filename, use the core_filetypes registered types to guess a mimetype. If no mimetype is known, return 'application/unknown'; @param string $filename @return string $mimetype
[ "Given", "a", "filename", "use", "the", "core_filetypes", "registered", "types", "to", "guess", "a", "mimetype", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L764-L776
216,860
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.upload_file
protected function upload_file(\repository_onedrive\rest $service, \curl $curl, \curl $authcurl, $filepath, $mimetype, $parentid, $filename) { // Start an upload session. // Docs https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession link. $params = ['parentid' => $parentid, 'filename' => urlencode($filename)]; $behaviour = [ 'item' => [ "@microsoft.graph.conflictBehavior" => "rename" ] ]; $created = $service->call('create_upload', $params, json_encode($behaviour)); if (empty($created->uploadUrl)) { $details = 'Cannot begin upload session:' . $parentid; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } $options = ['file' => $filepath]; // Try each curl class in turn until we succeed. // First attempt an upload with no auth headers (will work for personal onedrive accounts). // If that fails, try an upload with the auth headers (will work for work onedrive accounts). $curls = [$curl, $authcurl]; $response = null; foreach ($curls as $curlinstance) { $curlinstance->setHeader('Content-type: ' . $mimetype); $size = filesize($filepath); $curlinstance->setHeader('Content-Range: bytes 0-' . ($size - 1) . '/' . $size); $response = $curlinstance->put($created->uploadUrl, $options); if ($curlinstance->errno == 0) { $response = json_decode($response); } if (!empty($response->id)) { // We can stop now - there is a valid file returned. break; } } if (empty($response->id)) { $details = 'File not created'; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } return $response->id; }
php
protected function upload_file(\repository_onedrive\rest $service, \curl $curl, \curl $authcurl, $filepath, $mimetype, $parentid, $filename) { // Start an upload session. // Docs https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession link. $params = ['parentid' => $parentid, 'filename' => urlencode($filename)]; $behaviour = [ 'item' => [ "@microsoft.graph.conflictBehavior" => "rename" ] ]; $created = $service->call('create_upload', $params, json_encode($behaviour)); if (empty($created->uploadUrl)) { $details = 'Cannot begin upload session:' . $parentid; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } $options = ['file' => $filepath]; // Try each curl class in turn until we succeed. // First attempt an upload with no auth headers (will work for personal onedrive accounts). // If that fails, try an upload with the auth headers (will work for work onedrive accounts). $curls = [$curl, $authcurl]; $response = null; foreach ($curls as $curlinstance) { $curlinstance->setHeader('Content-type: ' . $mimetype); $size = filesize($filepath); $curlinstance->setHeader('Content-Range: bytes 0-' . ($size - 1) . '/' . $size); $response = $curlinstance->put($created->uploadUrl, $options); if ($curlinstance->errno == 0) { $response = json_decode($response); } if (!empty($response->id)) { // We can stop now - there is a valid file returned. break; } } if (empty($response->id)) { $details = 'File not created'; throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details); } return $response->id; }
[ "protected", "function", "upload_file", "(", "\\", "repository_onedrive", "\\", "rest", "$", "service", ",", "\\", "curl", "$", "curl", ",", "\\", "curl", "$", "authcurl", ",", "$", "filepath", ",", "$", "mimetype", ",", "$", "parentid", ",", "$", "filename", ")", "{", "// Start an upload session.", "// Docs https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession link.", "$", "params", "=", "[", "'parentid'", "=>", "$", "parentid", ",", "'filename'", "=>", "urlencode", "(", "$", "filename", ")", "]", ";", "$", "behaviour", "=", "[", "'item'", "=>", "[", "\"@microsoft.graph.conflictBehavior\"", "=>", "\"rename\"", "]", "]", ";", "$", "created", "=", "$", "service", "->", "call", "(", "'create_upload'", ",", "$", "params", ",", "json_encode", "(", "$", "behaviour", ")", ")", ";", "if", "(", "empty", "(", "$", "created", "->", "uploadUrl", ")", ")", "{", "$", "details", "=", "'Cannot begin upload session:'", ".", "$", "parentid", ";", "throw", "new", "repository_exception", "(", "'errorwhilecommunicatingwith'", ",", "'repository'", ",", "''", ",", "$", "details", ")", ";", "}", "$", "options", "=", "[", "'file'", "=>", "$", "filepath", "]", ";", "// Try each curl class in turn until we succeed.", "// First attempt an upload with no auth headers (will work for personal onedrive accounts).", "// If that fails, try an upload with the auth headers (will work for work onedrive accounts).", "$", "curls", "=", "[", "$", "curl", ",", "$", "authcurl", "]", ";", "$", "response", "=", "null", ";", "foreach", "(", "$", "curls", "as", "$", "curlinstance", ")", "{", "$", "curlinstance", "->", "setHeader", "(", "'Content-type: '", ".", "$", "mimetype", ")", ";", "$", "size", "=", "filesize", "(", "$", "filepath", ")", ";", "$", "curlinstance", "->", "setHeader", "(", "'Content-Range: bytes 0-'", ".", "(", "$", "size", "-", "1", ")", ".", "'/'", ".", "$", "size", ")", ";", "$", "response", "=", "$", "curlinstance", "->", "put", "(", "$", "created", "->", "uploadUrl", ",", "$", "options", ")", ";", "if", "(", "$", "curlinstance", "->", "errno", "==", "0", ")", "{", "$", "response", "=", "json_decode", "(", "$", "response", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "response", "->", "id", ")", ")", "{", "// We can stop now - there is a valid file returned.", "break", ";", "}", "}", "if", "(", "empty", "(", "$", "response", "->", "id", ")", ")", "{", "$", "details", "=", "'File not created'", ";", "throw", "new", "repository_exception", "(", "'errorwhilecommunicatingwith'", ",", "'repository'", ",", "''", ",", "$", "details", ")", ";", "}", "return", "$", "response", "->", "id", ";", "}" ]
Upload a file to onedrive. @param \repository_onedrive\rest $service Authenticated client. @param \curl $curl Curl client to perform the put operation (with no auth headers). @param \curl $authcurl Curl client that will send authentication headers @param string $filepath The local path to the file to upload @param string $mimetype The new mimetype @param string $parentid The folder to put it. @param string $filename The name of the new file @return string $fileid
[ "Upload", "a", "file", "to", "onedrive", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L790-L830
216,861
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.get_reference_details
public function get_reference_details($reference, $filestatus = 0) { if (empty($reference)) { return get_string('unknownsource', 'repository'); } $source = json_decode($reference); if (empty($source->usesystem)) { return ''; } $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer); if ($systemauth === false) { return ''; } $systemservice = new repository_onedrive\rest($systemauth); $info = $this->get_file_summary($systemservice, $source->id); $owner = ''; if (!empty($info->createdByUser->displayName)) { $owner = $info->createdByUser->displayName; } if ($owner) { return get_string('owner', 'repository_onedrive', $owner); } else { return $info->name; } }
php
public function get_reference_details($reference, $filestatus = 0) { if (empty($reference)) { return get_string('unknownsource', 'repository'); } $source = json_decode($reference); if (empty($source->usesystem)) { return ''; } $systemauth = \core\oauth2\api::get_system_oauth_client($this->issuer); if ($systemauth === false) { return ''; } $systemservice = new repository_onedrive\rest($systemauth); $info = $this->get_file_summary($systemservice, $source->id); $owner = ''; if (!empty($info->createdByUser->displayName)) { $owner = $info->createdByUser->displayName; } if ($owner) { return get_string('owner', 'repository_onedrive', $owner); } else { return $info->name; } }
[ "public", "function", "get_reference_details", "(", "$", "reference", ",", "$", "filestatus", "=", "0", ")", "{", "if", "(", "empty", "(", "$", "reference", ")", ")", "{", "return", "get_string", "(", "'unknownsource'", ",", "'repository'", ")", ";", "}", "$", "source", "=", "json_decode", "(", "$", "reference", ")", ";", "if", "(", "empty", "(", "$", "source", "->", "usesystem", ")", ")", "{", "return", "''", ";", "}", "$", "systemauth", "=", "\\", "core", "\\", "oauth2", "\\", "api", "::", "get_system_oauth_client", "(", "$", "this", "->", "issuer", ")", ";", "if", "(", "$", "systemauth", "===", "false", ")", "{", "return", "''", ";", "}", "$", "systemservice", "=", "new", "repository_onedrive", "\\", "rest", "(", "$", "systemauth", ")", ";", "$", "info", "=", "$", "this", "->", "get_file_summary", "(", "$", "systemservice", ",", "$", "source", "->", "id", ")", ";", "$", "owner", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "info", "->", "createdByUser", "->", "displayName", ")", ")", "{", "$", "owner", "=", "$", "info", "->", "createdByUser", "->", "displayName", ";", "}", "if", "(", "$", "owner", ")", "{", "return", "get_string", "(", "'owner'", ",", "'repository_onedrive'", ",", "$", "owner", ")", ";", "}", "else", "{", "return", "$", "info", "->", "name", ";", "}", "}" ]
Get human readable file info from the reference. @param string $reference @param int $filestatus
[ "Get", "human", "readable", "file", "info", "from", "the", "reference", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L980-L1005
216,862
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.can_import_skydrive_files
public static function can_import_skydrive_files() { global $DB; $skydrive = $DB->get_record('repository', ['type' => 'skydrive'], 'id', IGNORE_MISSING); $onedrive = $DB->get_record('repository', ['type' => 'onedrive'], 'id', IGNORE_MISSING); if (empty($skydrive) || empty($onedrive)) { return false; } $ready = true; try { $issuer = \core\oauth2\api::get_issuer(get_config('onedrive', 'issuerid')); if (!$issuer->get('enabled')) { $ready = false; } if (!$issuer->is_configured()) { $ready = false; } } catch (dml_missing_record_exception $e) { $ready = false; } if (!$ready) { return false; } $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid"; $params = array('plugin' => 'skydrive'); return $DB->count_records_sql($sql, $params) > 0; }
php
public static function can_import_skydrive_files() { global $DB; $skydrive = $DB->get_record('repository', ['type' => 'skydrive'], 'id', IGNORE_MISSING); $onedrive = $DB->get_record('repository', ['type' => 'onedrive'], 'id', IGNORE_MISSING); if (empty($skydrive) || empty($onedrive)) { return false; } $ready = true; try { $issuer = \core\oauth2\api::get_issuer(get_config('onedrive', 'issuerid')); if (!$issuer->get('enabled')) { $ready = false; } if (!$issuer->is_configured()) { $ready = false; } } catch (dml_missing_record_exception $e) { $ready = false; } if (!$ready) { return false; } $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid"; $params = array('plugin' => 'skydrive'); return $DB->count_records_sql($sql, $params) > 0; }
[ "public", "static", "function", "can_import_skydrive_files", "(", ")", "{", "global", "$", "DB", ";", "$", "skydrive", "=", "$", "DB", "->", "get_record", "(", "'repository'", ",", "[", "'type'", "=>", "'skydrive'", "]", ",", "'id'", ",", "IGNORE_MISSING", ")", ";", "$", "onedrive", "=", "$", "DB", "->", "get_record", "(", "'repository'", ",", "[", "'type'", "=>", "'onedrive'", "]", ",", "'id'", ",", "IGNORE_MISSING", ")", ";", "if", "(", "empty", "(", "$", "skydrive", ")", "||", "empty", "(", "$", "onedrive", ")", ")", "{", "return", "false", ";", "}", "$", "ready", "=", "true", ";", "try", "{", "$", "issuer", "=", "\\", "core", "\\", "oauth2", "\\", "api", "::", "get_issuer", "(", "get_config", "(", "'onedrive'", ",", "'issuerid'", ")", ")", ";", "if", "(", "!", "$", "issuer", "->", "get", "(", "'enabled'", ")", ")", "{", "$", "ready", "=", "false", ";", "}", "if", "(", "!", "$", "issuer", "->", "is_configured", "(", ")", ")", "{", "$", "ready", "=", "false", ";", "}", "}", "catch", "(", "dml_missing_record_exception", "$", "e", ")", "{", "$", "ready", "=", "false", ";", "}", "if", "(", "!", "$", "ready", ")", "{", "return", "false", ";", "}", "$", "sql", "=", "\"SELECT count('x')\n FROM {repository_instances} i, {repository} r\n WHERE r.type=:plugin AND r.id=i.typeid\"", ";", "$", "params", "=", "array", "(", "'plugin'", "=>", "'skydrive'", ")", ";", "return", "$", "DB", "->", "count_records_sql", "(", "$", "sql", ",", "$", "params", ")", ">", "0", ";", "}" ]
Return true if any instances of the skydrive repo exist - and we can import them. @return bool
[ "Return", "true", "if", "any", "instances", "of", "the", "skydrive", "repo", "exist", "-", "and", "we", "can", "import", "them", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L1012-L1043
216,863
moodle/moodle
repository/onedrive/lib.php
repository_onedrive.import_skydrive_files
public static function import_skydrive_files() { global $DB; if (!self::can_import_skydrive_files()) { return false; } // Should only be one of each. $skydrivetype = repository::get_type_by_typename('skydrive'); $skydriveinstances = repository::get_instances(['type' => 'skydrive']); $skydriveinstance = reset($skydriveinstances); $onedriveinstances = repository::get_instances(['type' => 'onedrive']); $onedriveinstance = reset($onedriveinstances); // Update all file references. $DB->set_field('files_reference', 'repositoryid', $onedriveinstance->id, ['repositoryid' => $skydriveinstance->id]); // Delete and disable the skydrive repo. $skydrivetype->delete(); core_plugin_manager::reset_caches(); $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid"; $params = array('plugin' => 'skydrive'); return $DB->count_records_sql($sql, $params) == 0; }
php
public static function import_skydrive_files() { global $DB; if (!self::can_import_skydrive_files()) { return false; } // Should only be one of each. $skydrivetype = repository::get_type_by_typename('skydrive'); $skydriveinstances = repository::get_instances(['type' => 'skydrive']); $skydriveinstance = reset($skydriveinstances); $onedriveinstances = repository::get_instances(['type' => 'onedrive']); $onedriveinstance = reset($onedriveinstances); // Update all file references. $DB->set_field('files_reference', 'repositoryid', $onedriveinstance->id, ['repositoryid' => $skydriveinstance->id]); // Delete and disable the skydrive repo. $skydrivetype->delete(); core_plugin_manager::reset_caches(); $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid"; $params = array('plugin' => 'skydrive'); return $DB->count_records_sql($sql, $params) == 0; }
[ "public", "static", "function", "import_skydrive_files", "(", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "self", "::", "can_import_skydrive_files", "(", ")", ")", "{", "return", "false", ";", "}", "// Should only be one of each.", "$", "skydrivetype", "=", "repository", "::", "get_type_by_typename", "(", "'skydrive'", ")", ";", "$", "skydriveinstances", "=", "repository", "::", "get_instances", "(", "[", "'type'", "=>", "'skydrive'", "]", ")", ";", "$", "skydriveinstance", "=", "reset", "(", "$", "skydriveinstances", ")", ";", "$", "onedriveinstances", "=", "repository", "::", "get_instances", "(", "[", "'type'", "=>", "'onedrive'", "]", ")", ";", "$", "onedriveinstance", "=", "reset", "(", "$", "onedriveinstances", ")", ";", "// Update all file references.", "$", "DB", "->", "set_field", "(", "'files_reference'", ",", "'repositoryid'", ",", "$", "onedriveinstance", "->", "id", ",", "[", "'repositoryid'", "=>", "$", "skydriveinstance", "->", "id", "]", ")", ";", "// Delete and disable the skydrive repo.", "$", "skydrivetype", "->", "delete", "(", ")", ";", "core_plugin_manager", "::", "reset_caches", "(", ")", ";", "$", "sql", "=", "\"SELECT count('x')\n FROM {repository_instances} i, {repository} r\n WHERE r.type=:plugin AND r.id=i.typeid\"", ";", "$", "params", "=", "array", "(", "'plugin'", "=>", "'skydrive'", ")", ";", "return", "$", "DB", "->", "count_records_sql", "(", "$", "sql", ",", "$", "params", ")", "==", "0", ";", "}" ]
Import all the files that were created with the skydrive repo to this repo. @return bool
[ "Import", "all", "the", "files", "that", "were", "created", "with", "the", "skydrive", "repo", "to", "this", "repo", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/repository/onedrive/lib.php#L1050-L1076
216,864
moodle/moodle
blocks/activity_results/backup/moodle2/restore_activity_results_block_task.class.php
restore_activity_results_block_task.after_restore
public function after_restore() { global $DB; // Get the blockid. $blockid = $this->get_blockid(); if ($configdata = $DB->get_field('block_instances', 'configdata', array('id' => $blockid))) { $config = unserialize(base64_decode($configdata)); if (!empty($config->activityparentid)) { // Get the mapping and replace it in config. if ($mapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), $config->activityparent, $config->activityparentid)) { // Update the parent module id (the id from mdl_quiz etc...) $config->activityparentid = $mapping->newitemid; // Get the grade_items record to update the activitygradeitemid. $info = $DB->get_record('grade_items', array('iteminstance' => $config->activityparentid, 'itemmodule' => $config->activityparent)); // Update the activitygradeitemid the id from the grade_items table. $config->activitygradeitemid = $info->id; // Encode and save the config. $configdata = base64_encode(serialize($config)); $DB->set_field('block_instances', 'configdata', $configdata, array('id' => $blockid)); } } } }
php
public function after_restore() { global $DB; // Get the blockid. $blockid = $this->get_blockid(); if ($configdata = $DB->get_field('block_instances', 'configdata', array('id' => $blockid))) { $config = unserialize(base64_decode($configdata)); if (!empty($config->activityparentid)) { // Get the mapping and replace it in config. if ($mapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), $config->activityparent, $config->activityparentid)) { // Update the parent module id (the id from mdl_quiz etc...) $config->activityparentid = $mapping->newitemid; // Get the grade_items record to update the activitygradeitemid. $info = $DB->get_record('grade_items', array('iteminstance' => $config->activityparentid, 'itemmodule' => $config->activityparent)); // Update the activitygradeitemid the id from the grade_items table. $config->activitygradeitemid = $info->id; // Encode and save the config. $configdata = base64_encode(serialize($config)); $DB->set_field('block_instances', 'configdata', $configdata, array('id' => $blockid)); } } } }
[ "public", "function", "after_restore", "(", ")", "{", "global", "$", "DB", ";", "// Get the blockid.", "$", "blockid", "=", "$", "this", "->", "get_blockid", "(", ")", ";", "if", "(", "$", "configdata", "=", "$", "DB", "->", "get_field", "(", "'block_instances'", ",", "'configdata'", ",", "array", "(", "'id'", "=>", "$", "blockid", ")", ")", ")", "{", "$", "config", "=", "unserialize", "(", "base64_decode", "(", "$", "configdata", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "config", "->", "activityparentid", ")", ")", "{", "// Get the mapping and replace it in config.", "if", "(", "$", "mapping", "=", "restore_dbops", "::", "get_backup_ids_record", "(", "$", "this", "->", "get_restoreid", "(", ")", ",", "$", "config", "->", "activityparent", ",", "$", "config", "->", "activityparentid", ")", ")", "{", "// Update the parent module id (the id from mdl_quiz etc...)", "$", "config", "->", "activityparentid", "=", "$", "mapping", "->", "newitemid", ";", "// Get the grade_items record to update the activitygradeitemid.", "$", "info", "=", "$", "DB", "->", "get_record", "(", "'grade_items'", ",", "array", "(", "'iteminstance'", "=>", "$", "config", "->", "activityparentid", ",", "'itemmodule'", "=>", "$", "config", "->", "activityparent", ")", ")", ";", "// Update the activitygradeitemid the id from the grade_items table.", "$", "config", "->", "activitygradeitemid", "=", "$", "info", "->", "id", ";", "// Encode and save the config.", "$", "configdata", "=", "base64_encode", "(", "serialize", "(", "$", "config", ")", ")", ";", "$", "DB", "->", "set_field", "(", "'block_instances'", ",", "'configdata'", ",", "$", "configdata", ",", "array", "(", "'id'", "=>", "$", "blockid", ")", ")", ";", "}", "}", "}", "}" ]
This function, executed after all the tasks in the plan have been executed, will perform the recode of the target activity for the block. This must be done here and not in normal execution steps because the activity can be restored after the block.
[ "This", "function", "executed", "after", "all", "the", "tasks", "in", "the", "plan", "have", "been", "executed", "will", "perform", "the", "recode", "of", "the", "target", "activity", "for", "the", "block", ".", "This", "must", "be", "done", "here", "and", "not", "in", "normal", "execution", "steps", "because", "the", "activity", "can", "be", "restored", "after", "the", "block", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/activity_results/backup/moodle2/restore_activity_results_block_task.class.php#L69-L98
216,865
moodle/moodle
admin/tool/usertours/classes/local/filter/base.php
base.save_filter_values_from_form
public static function save_filter_values_from_form(tour $tour, \stdClass $data) { $filtername = static::get_filter_name(); $key = "filter_{$filtername}"; $newvalue = $data->$key; foreach ($data->$key as $value) { if ($value === static::ANYVALUE) { $newvalue = []; break; } } $tour->set_filter_values($filtername, $newvalue); }
php
public static function save_filter_values_from_form(tour $tour, \stdClass $data) { $filtername = static::get_filter_name(); $key = "filter_{$filtername}"; $newvalue = $data->$key; foreach ($data->$key as $value) { if ($value === static::ANYVALUE) { $newvalue = []; break; } } $tour->set_filter_values($filtername, $newvalue); }
[ "public", "static", "function", "save_filter_values_from_form", "(", "tour", "$", "tour", ",", "\\", "stdClass", "$", "data", ")", "{", "$", "filtername", "=", "static", "::", "get_filter_name", "(", ")", ";", "$", "key", "=", "\"filter_{$filtername}\"", ";", "$", "newvalue", "=", "$", "data", "->", "$", "key", ";", "foreach", "(", "$", "data", "->", "$", "key", "as", "$", "value", ")", "{", "if", "(", "$", "value", "===", "static", "::", "ANYVALUE", ")", "{", "$", "newvalue", "=", "[", "]", ";", "break", ";", "}", "}", "$", "tour", "->", "set_filter_values", "(", "$", "filtername", ",", "$", "newvalue", ")", ";", "}" ]
Save the filter values from the form to the tour. @param tour $tour The tour to save values to @param stdClass $data The data submitted in the form
[ "Save", "the", "filter", "values", "from", "the", "form", "to", "the", "tour", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/usertours/classes/local/filter/base.php#L120-L134
216,866
moodle/moodle
customfield/classes/handler.php
handler.get_field_config_form
public function get_field_config_form(field_controller $field) : field_config_form { $form = new field_config_form(null, ['field' => $field]); $form->set_data(api::prepare_field_for_config_form($field)); return $form; }
php
public function get_field_config_form(field_controller $field) : field_config_form { $form = new field_config_form(null, ['field' => $field]); $form->set_data(api::prepare_field_for_config_form($field)); return $form; }
[ "public", "function", "get_field_config_form", "(", "field_controller", "$", "field", ")", ":", "field_config_form", "{", "$", "form", "=", "new", "field_config_form", "(", "null", ",", "[", "'field'", "=>", "$", "field", "]", ")", ";", "$", "form", "->", "set_data", "(", "api", "::", "prepare_field_for_config_form", "(", "$", "field", ")", ")", ";", "return", "$", "form", ";", "}" ]
The form to create or edit a field @param field_controller $field @return field_config_form
[ "The", "form", "to", "create", "or", "edit", "a", "field" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L187-L191
216,867
moodle/moodle
customfield/classes/handler.php
handler.create_category
public function create_category(string $name = null) : int { global $DB; $params = ['component' => $this->get_component(), 'area' => $this->get_area(), 'itemid' => $this->get_itemid()]; if (empty($name)) { for ($suffix = 0; $suffix < 100; $suffix++) { $name = $this->generate_category_name($suffix); if (!$DB->record_exists(category::TABLE, $params + ['name' => $name])) { break; } } } $category = category_controller::create(0, (object)['name' => $name], $this); api::save_category($category); $this->clear_configuration_cache(); return $category->get('id'); }
php
public function create_category(string $name = null) : int { global $DB; $params = ['component' => $this->get_component(), 'area' => $this->get_area(), 'itemid' => $this->get_itemid()]; if (empty($name)) { for ($suffix = 0; $suffix < 100; $suffix++) { $name = $this->generate_category_name($suffix); if (!$DB->record_exists(category::TABLE, $params + ['name' => $name])) { break; } } } $category = category_controller::create(0, (object)['name' => $name], $this); api::save_category($category); $this->clear_configuration_cache(); return $category->get('id'); }
[ "public", "function", "create_category", "(", "string", "$", "name", "=", "null", ")", ":", "int", "{", "global", "$", "DB", ";", "$", "params", "=", "[", "'component'", "=>", "$", "this", "->", "get_component", "(", ")", ",", "'area'", "=>", "$", "this", "->", "get_area", "(", ")", ",", "'itemid'", "=>", "$", "this", "->", "get_itemid", "(", ")", "]", ";", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "for", "(", "$", "suffix", "=", "0", ";", "$", "suffix", "<", "100", ";", "$", "suffix", "++", ")", "{", "$", "name", "=", "$", "this", "->", "generate_category_name", "(", "$", "suffix", ")", ";", "if", "(", "!", "$", "DB", "->", "record_exists", "(", "category", "::", "TABLE", ",", "$", "params", "+", "[", "'name'", "=>", "$", "name", "]", ")", ")", "{", "break", ";", "}", "}", "}", "$", "category", "=", "category_controller", "::", "create", "(", "0", ",", "(", "object", ")", "[", "'name'", "=>", "$", "name", "]", ",", "$", "this", ")", ";", "api", "::", "save_category", "(", "$", "category", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "return", "$", "category", "->", "get", "(", "'id'", ")", ";", "}" ]
Creates a new category and inserts it to the database @param string $name name of the category, null to generate automatically @return int id of the new category
[ "Creates", "a", "new", "category", "and", "inserts", "it", "to", "the", "database" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L213-L230
216,868
moodle/moodle
customfield/classes/handler.php
handler.validate_category
protected function validate_category(category_controller $category) : category_controller { $categories = $this->get_categories_with_fields(); if (!array_key_exists($category->get('id'), $categories)) { throw new \moodle_exception('categorynotfound', 'core_customfield'); } return $categories[$category->get('id')]; }
php
protected function validate_category(category_controller $category) : category_controller { $categories = $this->get_categories_with_fields(); if (!array_key_exists($category->get('id'), $categories)) { throw new \moodle_exception('categorynotfound', 'core_customfield'); } return $categories[$category->get('id')]; }
[ "protected", "function", "validate_category", "(", "category_controller", "$", "category", ")", ":", "category_controller", "{", "$", "categories", "=", "$", "this", "->", "get_categories_with_fields", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "category", "->", "get", "(", "'id'", ")", ",", "$", "categories", ")", ")", "{", "throw", "new", "\\", "moodle_exception", "(", "'categorynotfound'", ",", "'core_customfield'", ")", ";", "}", "return", "$", "categories", "[", "$", "category", "->", "get", "(", "'id'", ")", "]", ";", "}" ]
Validate that the given category belongs to this handler @param category_controller $category @return category_controller @throws \moodle_exception
[ "Validate", "that", "the", "given", "category", "belongs", "to", "this", "handler" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L239-L245
216,869
moodle/moodle
customfield/classes/handler.php
handler.validate_field
protected function validate_field(field_controller $field) : field_controller { if (!array_key_exists($field->get('categoryid'), $this->get_categories_with_fields())) { throw new \moodle_exception('fieldnotfound', 'core_customfield'); } $category = $this->get_categories_with_fields()[$field->get('categoryid')]; if (!array_key_exists($field->get('id'), $category->get_fields())) { throw new \moodle_exception('fieldnotfound', 'core_customfield'); } return $category->get_fields()[$field->get('id')]; }
php
protected function validate_field(field_controller $field) : field_controller { if (!array_key_exists($field->get('categoryid'), $this->get_categories_with_fields())) { throw new \moodle_exception('fieldnotfound', 'core_customfield'); } $category = $this->get_categories_with_fields()[$field->get('categoryid')]; if (!array_key_exists($field->get('id'), $category->get_fields())) { throw new \moodle_exception('fieldnotfound', 'core_customfield'); } return $category->get_fields()[$field->get('id')]; }
[ "protected", "function", "validate_field", "(", "field_controller", "$", "field", ")", ":", "field_controller", "{", "if", "(", "!", "array_key_exists", "(", "$", "field", "->", "get", "(", "'categoryid'", ")", ",", "$", "this", "->", "get_categories_with_fields", "(", ")", ")", ")", "{", "throw", "new", "\\", "moodle_exception", "(", "'fieldnotfound'", ",", "'core_customfield'", ")", ";", "}", "$", "category", "=", "$", "this", "->", "get_categories_with_fields", "(", ")", "[", "$", "field", "->", "get", "(", "'categoryid'", ")", "]", ";", "if", "(", "!", "array_key_exists", "(", "$", "field", "->", "get", "(", "'id'", ")", ",", "$", "category", "->", "get_fields", "(", ")", ")", ")", "{", "throw", "new", "\\", "moodle_exception", "(", "'fieldnotfound'", ",", "'core_customfield'", ")", ";", "}", "return", "$", "category", "->", "get_fields", "(", ")", "[", "$", "field", "->", "get", "(", "'id'", ")", "]", ";", "}" ]
Validate that the given field belongs to this handler @param field_controller $field @return field_controller @throws \moodle_exception
[ "Validate", "that", "the", "given", "field", "belongs", "to", "this", "handler" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L254-L263
216,870
moodle/moodle
customfield/classes/handler.php
handler.rename_category
public function rename_category(category_controller $category, string $name) { $this->validate_category($category); $category->set('name', $name); api::save_category($category); $this->clear_configuration_cache(); }
php
public function rename_category(category_controller $category, string $name) { $this->validate_category($category); $category->set('name', $name); api::save_category($category); $this->clear_configuration_cache(); }
[ "public", "function", "rename_category", "(", "category_controller", "$", "category", ",", "string", "$", "name", ")", "{", "$", "this", "->", "validate_category", "(", "$", "category", ")", ";", "$", "category", "->", "set", "(", "'name'", ",", "$", "name", ")", ";", "api", "::", "save_category", "(", "$", "category", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "}" ]
Change name for a field category @param category_controller $category @param string $name
[ "Change", "name", "for", "a", "field", "category" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L271-L276
216,871
moodle/moodle
customfield/classes/handler.php
handler.move_category
public function move_category(category_controller $category, int $beforeid = 0) { $category = $this->validate_category($category); api::move_category($category, $beforeid); $this->clear_configuration_cache(); }
php
public function move_category(category_controller $category, int $beforeid = 0) { $category = $this->validate_category($category); api::move_category($category, $beforeid); $this->clear_configuration_cache(); }
[ "public", "function", "move_category", "(", "category_controller", "$", "category", ",", "int", "$", "beforeid", "=", "0", ")", "{", "$", "category", "=", "$", "this", "->", "validate_category", "(", "$", "category", ")", ";", "api", "::", "move_category", "(", "$", "category", ",", "$", "beforeid", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "}" ]
Change sort order of the categories @param category_controller $category category that needs to be moved @param int $beforeid id of the category this category needs to be moved before, 0 to move to the end
[ "Change", "sort", "order", "of", "the", "categories" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L284-L288
216,872
moodle/moodle
customfield/classes/handler.php
handler.delete_category
public function delete_category(category_controller $category) : bool { $category = $this->validate_category($category); $result = api::delete_category($category); $this->clear_configuration_cache(); return $result; }
php
public function delete_category(category_controller $category) : bool { $category = $this->validate_category($category); $result = api::delete_category($category); $this->clear_configuration_cache(); return $result; }
[ "public", "function", "delete_category", "(", "category_controller", "$", "category", ")", ":", "bool", "{", "$", "category", "=", "$", "this", "->", "validate_category", "(", "$", "category", ")", ";", "$", "result", "=", "api", "::", "delete_category", "(", "$", "category", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "return", "$", "result", ";", "}" ]
Permanently delete category, all fields in it and all associated data @param category_controller $category @return bool
[ "Permanently", "delete", "category", "all", "fields", "in", "it", "and", "all", "associated", "data" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L296-L301
216,873
moodle/moodle
customfield/classes/handler.php
handler.delete_all
public function delete_all() { $categories = $this->get_categories_with_fields(); foreach ($categories as $category) { api::delete_category($category); } $this->clear_configuration_cache(); }
php
public function delete_all() { $categories = $this->get_categories_with_fields(); foreach ($categories as $category) { api::delete_category($category); } $this->clear_configuration_cache(); }
[ "public", "function", "delete_all", "(", ")", "{", "$", "categories", "=", "$", "this", "->", "get_categories_with_fields", "(", ")", ";", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "api", "::", "delete_category", "(", "$", "category", ")", ";", "}", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "}" ]
Deletes all data and all fields and categories defined in this handler
[ "Deletes", "all", "data", "and", "all", "fields", "and", "categories", "defined", "in", "this", "handler" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L306-L312
216,874
moodle/moodle
customfield/classes/handler.php
handler.delete_field_configuration
public function delete_field_configuration(field_controller $field) : bool { $field = $this->validate_field($field); $result = api::delete_field_configuration($field); $this->clear_configuration_cache(); return $result; }
php
public function delete_field_configuration(field_controller $field) : bool { $field = $this->validate_field($field); $result = api::delete_field_configuration($field); $this->clear_configuration_cache(); return $result; }
[ "public", "function", "delete_field_configuration", "(", "field_controller", "$", "field", ")", ":", "bool", "{", "$", "field", "=", "$", "this", "->", "validate_field", "(", "$", "field", ")", ";", "$", "result", "=", "api", "::", "delete_field_configuration", "(", "$", "field", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "return", "$", "result", ";", "}" ]
Permanently delete a custom field configuration and all associated data @param field_controller $field @return bool
[ "Permanently", "delete", "a", "custom", "field", "configuration", "and", "all", "associated", "data" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L320-L325
216,875
moodle/moodle
customfield/classes/handler.php
handler.get_instance_data
public function get_instance_data(int $instanceid, bool $returnall = false) : array { $fields = $returnall ? $this->get_fields() : $this->get_visible_fields($instanceid); return api::get_instance_fields_data($fields, $instanceid); }
php
public function get_instance_data(int $instanceid, bool $returnall = false) : array { $fields = $returnall ? $this->get_fields() : $this->get_visible_fields($instanceid); return api::get_instance_fields_data($fields, $instanceid); }
[ "public", "function", "get_instance_data", "(", "int", "$", "instanceid", ",", "bool", "$", "returnall", "=", "false", ")", ":", "array", "{", "$", "fields", "=", "$", "returnall", "?", "$", "this", "->", "get_fields", "(", ")", ":", "$", "this", "->", "get_visible_fields", "(", "$", "instanceid", ")", ";", "return", "api", "::", "get_instance_fields_data", "(", "$", "fields", ",", "$", "instanceid", ")", ";", "}" ]
Returns the custom field values for an individual instance The caller must check access to the instance itself before invoking this method The result is an array of data_controller objects @param int $instanceid @param bool $returnall return data for all fields (by default only visible fields) @return data_controller[] array of data_controller objects indexed by fieldid. All fields are present, some data_controller objects may have 'id', some not In the last case data_controller::get_value() and export_value() functions will return default values.
[ "Returns", "the", "custom", "field", "values", "for", "an", "individual", "instance" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L387-L390
216,876
moodle/moodle
customfield/classes/handler.php
handler.get_instances_data
public function get_instances_data(array $instanceids, bool $returnall = false) : array { $result = api::get_instances_fields_data($this->get_fields(), $instanceids); if (!$returnall) { // Filter only by visible fields (list of visible fields may be different for each instance). $handler = $this; foreach ($instanceids as $instanceid) { $result[$instanceid] = array_filter($result[$instanceid], function(data_controller $d) use ($handler) { return $handler->can_view($d->get_field(), $d->get('instanceid')); }); } } return $result; }
php
public function get_instances_data(array $instanceids, bool $returnall = false) : array { $result = api::get_instances_fields_data($this->get_fields(), $instanceids); if (!$returnall) { // Filter only by visible fields (list of visible fields may be different for each instance). $handler = $this; foreach ($instanceids as $instanceid) { $result[$instanceid] = array_filter($result[$instanceid], function(data_controller $d) use ($handler) { return $handler->can_view($d->get_field(), $d->get('instanceid')); }); } } return $result; }
[ "public", "function", "get_instances_data", "(", "array", "$", "instanceids", ",", "bool", "$", "returnall", "=", "false", ")", ":", "array", "{", "$", "result", "=", "api", "::", "get_instances_fields_data", "(", "$", "this", "->", "get_fields", "(", ")", ",", "$", "instanceids", ")", ";", "if", "(", "!", "$", "returnall", ")", "{", "// Filter only by visible fields (list of visible fields may be different for each instance).", "$", "handler", "=", "$", "this", ";", "foreach", "(", "$", "instanceids", "as", "$", "instanceid", ")", "{", "$", "result", "[", "$", "instanceid", "]", "=", "array_filter", "(", "$", "result", "[", "$", "instanceid", "]", ",", "function", "(", "data_controller", "$", "d", ")", "use", "(", "$", "handler", ")", "{", "return", "$", "handler", "->", "can_view", "(", "$", "d", "->", "get_field", "(", ")", ",", "$", "d", "->", "get", "(", "'instanceid'", ")", ")", ";", "}", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns the custom fields values for multiple instances The caller must check access to the instance itself before invoking this method The result is an array of data_controller objects @param int[] $instanceids @param bool $returnall return data for all fields (by default only visible fields) @return data_controller[][] 2-dimension array, first index is instanceid, second index is fieldid. All instanceids and all fieldids are present, some data_controller objects may have 'id', some not. In the last case data_controller::get_value() and export_value() functions will return default values.
[ "Returns", "the", "custom", "fields", "values", "for", "multiple", "instances" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L405-L418
216,877
moodle/moodle
customfield/classes/handler.php
handler.display_custom_fields_data
public function display_custom_fields_data(array $fieldsdata) : string { global $PAGE; $output = $PAGE->get_renderer('core_customfield'); $content = ''; foreach ($fieldsdata as $data) { $fd = new field_data($data); $content .= $output->render($fd); } return $content; }
php
public function display_custom_fields_data(array $fieldsdata) : string { global $PAGE; $output = $PAGE->get_renderer('core_customfield'); $content = ''; foreach ($fieldsdata as $data) { $fd = new field_data($data); $content .= $output->render($fd); } return $content; }
[ "public", "function", "display_custom_fields_data", "(", "array", "$", "fieldsdata", ")", ":", "string", "{", "global", "$", "PAGE", ";", "$", "output", "=", "$", "PAGE", "->", "get_renderer", "(", "'core_customfield'", ")", ";", "$", "content", "=", "''", ";", "foreach", "(", "$", "fieldsdata", "as", "$", "data", ")", "{", "$", "fd", "=", "new", "field_data", "(", "$", "data", ")", ";", "$", "content", ".=", "$", "output", "->", "render", "(", "$", "fd", ")", ";", "}", "return", "$", "content", ";", "}" ]
Display visible custom fields. This is a sample implementation that can be overridden in each handler. @param data_controller[] $fieldsdata @return string
[ "Display", "visible", "custom", "fields", ".", "This", "is", "a", "sample", "implementation", "that", "can", "be", "overridden", "in", "each", "handler", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L463-L473
216,878
moodle/moodle
customfield/classes/handler.php
handler.get_categories_with_fields
public function get_categories_with_fields() : array { if ($this->categories === null) { $this->categories = api::get_categories_with_fields($this->get_component(), $this->get_area(), $this->get_itemid()); } $handler = $this; array_walk($this->categories, function(category_controller $c) use ($handler) { $c->set_handler($handler); }); return $this->categories; }
php
public function get_categories_with_fields() : array { if ($this->categories === null) { $this->categories = api::get_categories_with_fields($this->get_component(), $this->get_area(), $this->get_itemid()); } $handler = $this; array_walk($this->categories, function(category_controller $c) use ($handler) { $c->set_handler($handler); }); return $this->categories; }
[ "public", "function", "get_categories_with_fields", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "categories", "===", "null", ")", "{", "$", "this", "->", "categories", "=", "api", "::", "get_categories_with_fields", "(", "$", "this", "->", "get_component", "(", ")", ",", "$", "this", "->", "get_area", "(", ")", ",", "$", "this", "->", "get_itemid", "(", ")", ")", ";", "}", "$", "handler", "=", "$", "this", ";", "array_walk", "(", "$", "this", "->", "categories", ",", "function", "(", "category_controller", "$", "c", ")", "use", "(", "$", "handler", ")", "{", "$", "c", "->", "set_handler", "(", "$", "handler", ")", ";", "}", ")", ";", "return", "$", "this", "->", "categories", ";", "}" ]
Returns array of categories, each of them contains a list of fields definitions. @return category_controller[]
[ "Returns", "array", "of", "categories", "each", "of", "them", "contains", "a", "list", "of", "fields", "definitions", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L480-L489
216,879
moodle/moodle
customfield/classes/handler.php
handler.can_backup
protected function can_backup(field_controller $field, int $instanceid) : bool { return $this->can_view($field, $instanceid) || $this->can_edit($field, $instanceid); }
php
protected function can_backup(field_controller $field, int $instanceid) : bool { return $this->can_view($field, $instanceid) || $this->can_edit($field, $instanceid); }
[ "protected", "function", "can_backup", "(", "field_controller", "$", "field", ",", "int", "$", "instanceid", ")", ":", "bool", "{", "return", "$", "this", "->", "can_view", "(", "$", "field", ",", "$", "instanceid", ")", "||", "$", "this", "->", "can_edit", "(", "$", "field", ",", "$", "instanceid", ")", ";", "}" ]
Checks if current user can backup a given field Capability to backup the instance does not need to be checked here @param field_controller $field @param int $instanceid @return bool
[ "Checks", "if", "current", "user", "can", "backup", "a", "given", "field" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L507-L509
216,880
moodle/moodle
customfield/classes/handler.php
handler.get_instance_data_for_backup
public function get_instance_data_for_backup(int $instanceid) : array { $finalfields = []; $data = $this->get_instance_data($instanceid, true); foreach ($data as $d) { if ($d->get('id') && $this->can_backup($d->get_field(), $instanceid)) { $finalfields[] = [ 'id' => $d->get('id'), 'shortname' => $d->get_field()->get('shortname'), 'type' => $d->get_field()->get('type'), 'value' => $d->get_value(), 'valueformat' => $d->get('valueformat')]; } } return $finalfields; }
php
public function get_instance_data_for_backup(int $instanceid) : array { $finalfields = []; $data = $this->get_instance_data($instanceid, true); foreach ($data as $d) { if ($d->get('id') && $this->can_backup($d->get_field(), $instanceid)) { $finalfields[] = [ 'id' => $d->get('id'), 'shortname' => $d->get_field()->get('shortname'), 'type' => $d->get_field()->get('type'), 'value' => $d->get_value(), 'valueformat' => $d->get('valueformat')]; } } return $finalfields; }
[ "public", "function", "get_instance_data_for_backup", "(", "int", "$", "instanceid", ")", ":", "array", "{", "$", "finalfields", "=", "[", "]", ";", "$", "data", "=", "$", "this", "->", "get_instance_data", "(", "$", "instanceid", ",", "true", ")", ";", "foreach", "(", "$", "data", "as", "$", "d", ")", "{", "if", "(", "$", "d", "->", "get", "(", "'id'", ")", "&&", "$", "this", "->", "can_backup", "(", "$", "d", "->", "get_field", "(", ")", ",", "$", "instanceid", ")", ")", "{", "$", "finalfields", "[", "]", "=", "[", "'id'", "=>", "$", "d", "->", "get", "(", "'id'", ")", ",", "'shortname'", "=>", "$", "d", "->", "get_field", "(", ")", "->", "get", "(", "'shortname'", ")", ",", "'type'", "=>", "$", "d", "->", "get_field", "(", ")", "->", "get", "(", "'type'", ")", ",", "'value'", "=>", "$", "d", "->", "get_value", "(", ")", ",", "'valueformat'", "=>", "$", "d", "->", "get", "(", "'valueformat'", ")", "]", ";", "}", "}", "return", "$", "finalfields", ";", "}" ]
Get raw data associated with all fields current user can view or edit @param int $instanceid @return array
[ "Get", "raw", "data", "associated", "with", "all", "fields", "current", "user", "can", "view", "or", "edit" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L517-L531
216,881
moodle/moodle
customfield/classes/handler.php
handler.instance_form_definition_after_data
public function instance_form_definition_after_data(\MoodleQuickForm $mform, int $instanceid = 0) { $editablefields = $this->get_editable_fields($instanceid); $fields = api::get_instance_fields_data($editablefields, $instanceid); foreach ($fields as $formfield) { $formfield->instance_form_definition_after_data($mform); } }
php
public function instance_form_definition_after_data(\MoodleQuickForm $mform, int $instanceid = 0) { $editablefields = $this->get_editable_fields($instanceid); $fields = api::get_instance_fields_data($editablefields, $instanceid); foreach ($fields as $formfield) { $formfield->instance_form_definition_after_data($mform); } }
[ "public", "function", "instance_form_definition_after_data", "(", "\\", "MoodleQuickForm", "$", "mform", ",", "int", "$", "instanceid", "=", "0", ")", "{", "$", "editablefields", "=", "$", "this", "->", "get_editable_fields", "(", "$", "instanceid", ")", ";", "$", "fields", "=", "api", "::", "get_instance_fields_data", "(", "$", "editablefields", ",", "$", "instanceid", ")", ";", "foreach", "(", "$", "fields", "as", "$", "formfield", ")", "{", "$", "formfield", "->", "instance_form_definition_after_data", "(", "$", "mform", ")", ";", "}", "}" ]
Form data definition callback. This method is called from moodleform::definition_after_data and allows to tweak mform with some data coming directly from the field plugin data controller. @param \MoodleQuickForm $mform @param int $instanceid
[ "Form", "data", "definition", "callback", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L542-L549
216,882
moodle/moodle
customfield/classes/handler.php
handler.instance_form_save
public function instance_form_save(stdClass $instance, bool $isnewinstance = false) { if (empty($instance->id)) { throw new \coding_exception('Caller must ensure that id is already set in data before calling this method'); } if (!preg_grep('/^customfield_/', array_keys((array)$instance))) { // For performance. return; } $editablefields = $this->get_editable_fields($isnewinstance ? 0 : $instance->id); $fields = api::get_instance_fields_data($editablefields, $instance->id); foreach ($fields as $data) { if (!$data->get('id')) { $data->set('contextid', $this->get_instance_context($instance->id)->id); } $data->instance_form_save($instance); } }
php
public function instance_form_save(stdClass $instance, bool $isnewinstance = false) { if (empty($instance->id)) { throw new \coding_exception('Caller must ensure that id is already set in data before calling this method'); } if (!preg_grep('/^customfield_/', array_keys((array)$instance))) { // For performance. return; } $editablefields = $this->get_editable_fields($isnewinstance ? 0 : $instance->id); $fields = api::get_instance_fields_data($editablefields, $instance->id); foreach ($fields as $data) { if (!$data->get('id')) { $data->set('contextid', $this->get_instance_context($instance->id)->id); } $data->instance_form_save($instance); } }
[ "public", "function", "instance_form_save", "(", "stdClass", "$", "instance", ",", "bool", "$", "isnewinstance", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "instance", "->", "id", ")", ")", "{", "throw", "new", "\\", "coding_exception", "(", "'Caller must ensure that id is already set in data before calling this method'", ")", ";", "}", "if", "(", "!", "preg_grep", "(", "'/^customfield_/'", ",", "array_keys", "(", "(", "array", ")", "$", "instance", ")", ")", ")", "{", "// For performance.", "return", ";", "}", "$", "editablefields", "=", "$", "this", "->", "get_editable_fields", "(", "$", "isnewinstance", "?", "0", ":", "$", "instance", "->", "id", ")", ";", "$", "fields", "=", "api", "::", "get_instance_fields_data", "(", "$", "editablefields", ",", "$", "instance", "->", "id", ")", ";", "foreach", "(", "$", "fields", "as", "$", "data", ")", "{", "if", "(", "!", "$", "data", "->", "get", "(", "'id'", ")", ")", "{", "$", "data", "->", "set", "(", "'contextid'", ",", "$", "this", "->", "get_instance_context", "(", "$", "instance", "->", "id", ")", "->", "id", ")", ";", "}", "$", "data", "->", "instance_form_save", "(", "$", "instance", ")", ";", "}", "}" ]
Saves the given data for custom fields, must be called after the instance is saved and id is present Example: if ($data = $form->get_data()) { // ... save main instance, set $data->id if instance was created. $handler->instance_form_save($data); redirect(...); } @param stdClass $instance data received from a form @param bool $isnewinstance if this is call is made during instance creation
[ "Saves", "the", "given", "data", "for", "custom", "fields", "must", "be", "called", "after", "the", "instance", "is", "saved", "and", "id", "is", "present" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L585-L601
216,883
moodle/moodle
customfield/classes/handler.php
handler.instance_form_definition
public function instance_form_definition(\MoodleQuickForm $mform, int $instanceid = 0) { $editablefields = $this->get_editable_fields($instanceid); $fieldswithdata = api::get_instance_fields_data($editablefields, $instanceid); $lastcategoryid = null; foreach ($fieldswithdata as $data) { $categoryid = $data->get_field()->get_category()->get('id'); if ($categoryid != $lastcategoryid) { $mform->addElement('header', 'category_' . $categoryid, format_string($data->get_field()->get_category()->get('name'))); $lastcategoryid = $categoryid; } $data->instance_form_definition($mform); $field = $data->get_field()->to_record(); if (strlen($field->description)) { // Add field description. $context = $this->get_configuration_context(); $value = file_rewrite_pluginfile_urls($field->description, 'pluginfile.php', $context->id, 'core_customfield', 'description', $field->id); $value = format_text($value, $field->descriptionformat, ['context' => $context]); $mform->addElement('static', 'customfield_' . $field->shortname . '_static', '', $value); } } }
php
public function instance_form_definition(\MoodleQuickForm $mform, int $instanceid = 0) { $editablefields = $this->get_editable_fields($instanceid); $fieldswithdata = api::get_instance_fields_data($editablefields, $instanceid); $lastcategoryid = null; foreach ($fieldswithdata as $data) { $categoryid = $data->get_field()->get_category()->get('id'); if ($categoryid != $lastcategoryid) { $mform->addElement('header', 'category_' . $categoryid, format_string($data->get_field()->get_category()->get('name'))); $lastcategoryid = $categoryid; } $data->instance_form_definition($mform); $field = $data->get_field()->to_record(); if (strlen($field->description)) { // Add field description. $context = $this->get_configuration_context(); $value = file_rewrite_pluginfile_urls($field->description, 'pluginfile.php', $context->id, 'core_customfield', 'description', $field->id); $value = format_text($value, $field->descriptionformat, ['context' => $context]); $mform->addElement('static', 'customfield_' . $field->shortname . '_static', '', $value); } } }
[ "public", "function", "instance_form_definition", "(", "\\", "MoodleQuickForm", "$", "mform", ",", "int", "$", "instanceid", "=", "0", ")", "{", "$", "editablefields", "=", "$", "this", "->", "get_editable_fields", "(", "$", "instanceid", ")", ";", "$", "fieldswithdata", "=", "api", "::", "get_instance_fields_data", "(", "$", "editablefields", ",", "$", "instanceid", ")", ";", "$", "lastcategoryid", "=", "null", ";", "foreach", "(", "$", "fieldswithdata", "as", "$", "data", ")", "{", "$", "categoryid", "=", "$", "data", "->", "get_field", "(", ")", "->", "get_category", "(", ")", "->", "get", "(", "'id'", ")", ";", "if", "(", "$", "categoryid", "!=", "$", "lastcategoryid", ")", "{", "$", "mform", "->", "addElement", "(", "'header'", ",", "'category_'", ".", "$", "categoryid", ",", "format_string", "(", "$", "data", "->", "get_field", "(", ")", "->", "get_category", "(", ")", "->", "get", "(", "'name'", ")", ")", ")", ";", "$", "lastcategoryid", "=", "$", "categoryid", ";", "}", "$", "data", "->", "instance_form_definition", "(", "$", "mform", ")", ";", "$", "field", "=", "$", "data", "->", "get_field", "(", ")", "->", "to_record", "(", ")", ";", "if", "(", "strlen", "(", "$", "field", "->", "description", ")", ")", "{", "// Add field description.", "$", "context", "=", "$", "this", "->", "get_configuration_context", "(", ")", ";", "$", "value", "=", "file_rewrite_pluginfile_urls", "(", "$", "field", "->", "description", ",", "'pluginfile.php'", ",", "$", "context", "->", "id", ",", "'core_customfield'", ",", "'description'", ",", "$", "field", "->", "id", ")", ";", "$", "value", "=", "format_text", "(", "$", "value", ",", "$", "field", "->", "descriptionformat", ",", "[", "'context'", "=>", "$", "context", "]", ")", ";", "$", "mform", "->", "addElement", "(", "'static'", ",", "'customfield_'", ".", "$", "field", "->", "shortname", ".", "'_static'", ",", "''", ",", "$", "value", ")", ";", "}", "}", "}" ]
Adds custom fields to instance editing form Example: public function definition() { // ... normal instance definition, including hidden 'id' field. $handler->instance_form_definition($this->_form, $instanceid); $this->add_action_buttons(); } @param \MoodleQuickForm $mform @param int $instanceid id of the instance, can be null when instance is being created
[ "Adds", "custom", "fields", "to", "instance", "editing", "form" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L642-L665
216,884
moodle/moodle
customfield/classes/handler.php
handler.save_field_configuration
public function save_field_configuration(field_controller $field, stdClass $data) { if ($field->get('id')) { $field = $this->validate_field($field); } else { $this->validate_category($field->get_category()); } api::save_field_configuration($field, $data); $this->clear_configuration_cache(); }
php
public function save_field_configuration(field_controller $field, stdClass $data) { if ($field->get('id')) { $field = $this->validate_field($field); } else { $this->validate_category($field->get_category()); } api::save_field_configuration($field, $data); $this->clear_configuration_cache(); }
[ "public", "function", "save_field_configuration", "(", "field_controller", "$", "field", ",", "stdClass", "$", "data", ")", "{", "if", "(", "$", "field", "->", "get", "(", "'id'", ")", ")", "{", "$", "field", "=", "$", "this", "->", "validate_field", "(", "$", "field", ")", ";", "}", "else", "{", "$", "this", "->", "validate_category", "(", "$", "field", "->", "get_category", "(", ")", ")", ";", "}", "api", "::", "save_field_configuration", "(", "$", "field", ",", "$", "data", ")", ";", "$", "this", "->", "clear_configuration_cache", "(", ")", ";", "}" ]
Save the field configuration with the data from the form @param field_controller $field @param stdClass $data data from the form
[ "Save", "the", "field", "configuration", "with", "the", "data", "from", "the", "form" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L700-L708
216,885
moodle/moodle
customfield/classes/handler.php
handler.get_visible_fields
protected function get_visible_fields(int $instanceid) : array { $handler = $this; return array_filter($this->get_fields(), function($field) use($handler, $instanceid) { return $handler->can_view($field, $instanceid); } ); }
php
protected function get_visible_fields(int $instanceid) : array { $handler = $this; return array_filter($this->get_fields(), function($field) use($handler, $instanceid) { return $handler->can_view($field, $instanceid); } ); }
[ "protected", "function", "get_visible_fields", "(", "int", "$", "instanceid", ")", ":", "array", "{", "$", "handler", "=", "$", "this", ";", "return", "array_filter", "(", "$", "this", "->", "get_fields", "(", ")", ",", "function", "(", "$", "field", ")", "use", "(", "$", "handler", ",", "$", "instanceid", ")", "{", "return", "$", "handler", "->", "can_view", "(", "$", "field", ",", "$", "instanceid", ")", ";", "}", ")", ";", "}" ]
Get visible fields @param int $instanceid @return field_controller[]
[ "Get", "visible", "fields" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L749-L756
216,886
moodle/moodle
customfield/classes/handler.php
handler.get_editable_fields
public function get_editable_fields(int $instanceid) : array { $handler = $this; return array_filter($this->get_fields(), function($field) use($handler, $instanceid) { return $handler->can_edit($field, $instanceid); } ); }
php
public function get_editable_fields(int $instanceid) : array { $handler = $this; return array_filter($this->get_fields(), function($field) use($handler, $instanceid) { return $handler->can_edit($field, $instanceid); } ); }
[ "public", "function", "get_editable_fields", "(", "int", "$", "instanceid", ")", ":", "array", "{", "$", "handler", "=", "$", "this", ";", "return", "array_filter", "(", "$", "this", "->", "get_fields", "(", ")", ",", "function", "(", "$", "field", ")", "use", "(", "$", "handler", ",", "$", "instanceid", ")", "{", "return", "$", "handler", "->", "can_edit", "(", "$", "field", ",", "$", "instanceid", ")", ";", "}", ")", ";", "}" ]
Get editable fields @param int $instanceid @return field_controller[]
[ "Get", "editable", "fields" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L764-L771
216,887
moodle/moodle
customfield/classes/handler.php
handler.delete_instance
public function delete_instance(int $instanceid) { $fielddata = api::get_instance_fields_data($this->get_fields(), $instanceid, false); foreach ($fielddata as $data) { $data->delete(); } }
php
public function delete_instance(int $instanceid) { $fielddata = api::get_instance_fields_data($this->get_fields(), $instanceid, false); foreach ($fielddata as $data) { $data->delete(); } }
[ "public", "function", "delete_instance", "(", "int", "$", "instanceid", ")", "{", "$", "fielddata", "=", "api", "::", "get_instance_fields_data", "(", "$", "this", "->", "get_fields", "(", ")", ",", "$", "instanceid", ",", "false", ")", ";", "foreach", "(", "$", "fielddata", "as", "$", "data", ")", "{", "$", "data", "->", "delete", "(", ")", ";", "}", "}" ]
Deletes all data related to all fields of an instance. @param int $instanceid
[ "Deletes", "all", "data", "related", "to", "all", "fields", "of", "an", "instance", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/handler.php#L786-L791
216,888
moodle/moodle
customfield/classes/output/field_data.php
field_data.export_for_template
public function export_for_template(\renderer_base $output) { $value = $this->get_value(); return (object)[ 'value' => $value, 'type' => $this->get_type(), 'shortname' => $this->get_shortname(), 'name' => $this->get_name(), 'hasvalue' => ($value !== null), 'instanceid' => $this->data->get('instanceid') ]; }
php
public function export_for_template(\renderer_base $output) { $value = $this->get_value(); return (object)[ 'value' => $value, 'type' => $this->get_type(), 'shortname' => $this->get_shortname(), 'name' => $this->get_name(), 'hasvalue' => ($value !== null), 'instanceid' => $this->data->get('instanceid') ]; }
[ "public", "function", "export_for_template", "(", "\\", "renderer_base", "$", "output", ")", "{", "$", "value", "=", "$", "this", "->", "get_value", "(", ")", ";", "return", "(", "object", ")", "[", "'value'", "=>", "$", "value", ",", "'type'", "=>", "$", "this", "->", "get_type", "(", ")", ",", "'shortname'", "=>", "$", "this", "->", "get_shortname", "(", ")", ",", "'name'", "=>", "$", "this", "->", "get_name", "(", ")", ",", "'hasvalue'", "=>", "(", "$", "value", "!==", "null", ")", ",", "'instanceid'", "=>", "$", "this", "->", "data", "->", "get", "(", "'instanceid'", ")", "]", ";", "}" ]
Export data for using as template context. @param \renderer_base $output @return \stdClass
[ "Export", "data", "for", "using", "as", "template", "context", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/customfield/classes/output/field_data.php#L103-L113
216,889
moodle/moodle
auth/mnet/classes/privacy/provider.php
provider.export_user_data
public static function export_user_data(approved_contextlist $contextlist) { global $DB; $context = \context_user::instance($contextlist->get_user()->id); $sql = "SELECT ml.id, mh.wwwroot, mh.name, ml.remoteid, ml.time, ml.userid, ml.ip, ml.course, ml.coursename, ml.module, ml.cmid, ml.action, ml.url, ml.info FROM {mnet_log} ml JOIN {mnet_host} mh ON mh.id = ml.hostid WHERE ml.userid = :userid ORDER BY mh.name, ml.coursename"; $params = ['userid' => $contextlist->get_user()->id]; $data = []; $lastcourseid = null; $logentries = $DB->get_recordset_sql($sql, $params); foreach ($logentries as $logentry) { $item = (object) [ 'time' => transform::datetime($logentry->time), 'remoteid' => $logentry->remoteid, 'ip' => $logentry->ip, 'course' => $logentry->course, 'coursename' => format_string($logentry->coursename), 'module' => $logentry->module, 'cmid' => $logentry->cmid, 'action' => $logentry->action, 'url' => $logentry->url, 'info' => format_string($logentry->info) ]; $item->externalhost = ($logentry->name == '') ? preg_replace('#^https?://#', '', $logentry->wwwroot) : preg_replace('#^https?://#', '', $logentry->name); if ($lastcourseid && $lastcourseid != $logentry->course) { $path = [get_string('pluginname', 'auth_mnet'), $data[0]->externalhost, $data[0]->coursename]; writer::with_context($context)->export_data($path, (object) $data); $data = []; } $data[] = $item; $lastcourseid = $logentry->course; } $logentries->close(); $path = [get_string('pluginname', 'auth_mnet'), $item->externalhost, $item->coursename]; writer::with_context($context)->export_data($path, (object) $data); }
php
public static function export_user_data(approved_contextlist $contextlist) { global $DB; $context = \context_user::instance($contextlist->get_user()->id); $sql = "SELECT ml.id, mh.wwwroot, mh.name, ml.remoteid, ml.time, ml.userid, ml.ip, ml.course, ml.coursename, ml.module, ml.cmid, ml.action, ml.url, ml.info FROM {mnet_log} ml JOIN {mnet_host} mh ON mh.id = ml.hostid WHERE ml.userid = :userid ORDER BY mh.name, ml.coursename"; $params = ['userid' => $contextlist->get_user()->id]; $data = []; $lastcourseid = null; $logentries = $DB->get_recordset_sql($sql, $params); foreach ($logentries as $logentry) { $item = (object) [ 'time' => transform::datetime($logentry->time), 'remoteid' => $logentry->remoteid, 'ip' => $logentry->ip, 'course' => $logentry->course, 'coursename' => format_string($logentry->coursename), 'module' => $logentry->module, 'cmid' => $logentry->cmid, 'action' => $logentry->action, 'url' => $logentry->url, 'info' => format_string($logentry->info) ]; $item->externalhost = ($logentry->name == '') ? preg_replace('#^https?://#', '', $logentry->wwwroot) : preg_replace('#^https?://#', '', $logentry->name); if ($lastcourseid && $lastcourseid != $logentry->course) { $path = [get_string('pluginname', 'auth_mnet'), $data[0]->externalhost, $data[0]->coursename]; writer::with_context($context)->export_data($path, (object) $data); $data = []; } $data[] = $item; $lastcourseid = $logentry->course; } $logentries->close(); $path = [get_string('pluginname', 'auth_mnet'), $item->externalhost, $item->coursename]; writer::with_context($context)->export_data($path, (object) $data); }
[ "public", "static", "function", "export_user_data", "(", "approved_contextlist", "$", "contextlist", ")", "{", "global", "$", "DB", ";", "$", "context", "=", "\\", "context_user", "::", "instance", "(", "$", "contextlist", "->", "get_user", "(", ")", "->", "id", ")", ";", "$", "sql", "=", "\"SELECT ml.id, mh.wwwroot, mh.name, ml.remoteid, ml.time, ml.userid, ml.ip, ml.course,\n ml.coursename, ml.module, ml.cmid, ml.action, ml.url, ml.info\n FROM {mnet_log} ml\n JOIN {mnet_host} mh ON mh.id = ml.hostid\n WHERE ml.userid = :userid\n ORDER BY mh.name, ml.coursename\"", ";", "$", "params", "=", "[", "'userid'", "=>", "$", "contextlist", "->", "get_user", "(", ")", "->", "id", "]", ";", "$", "data", "=", "[", "]", ";", "$", "lastcourseid", "=", "null", ";", "$", "logentries", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "foreach", "(", "$", "logentries", "as", "$", "logentry", ")", "{", "$", "item", "=", "(", "object", ")", "[", "'time'", "=>", "transform", "::", "datetime", "(", "$", "logentry", "->", "time", ")", ",", "'remoteid'", "=>", "$", "logentry", "->", "remoteid", ",", "'ip'", "=>", "$", "logentry", "->", "ip", ",", "'course'", "=>", "$", "logentry", "->", "course", ",", "'coursename'", "=>", "format_string", "(", "$", "logentry", "->", "coursename", ")", ",", "'module'", "=>", "$", "logentry", "->", "module", ",", "'cmid'", "=>", "$", "logentry", "->", "cmid", ",", "'action'", "=>", "$", "logentry", "->", "action", ",", "'url'", "=>", "$", "logentry", "->", "url", ",", "'info'", "=>", "format_string", "(", "$", "logentry", "->", "info", ")", "]", ";", "$", "item", "->", "externalhost", "=", "(", "$", "logentry", "->", "name", "==", "''", ")", "?", "preg_replace", "(", "'#^https?://#'", ",", "''", ",", "$", "logentry", "->", "wwwroot", ")", ":", "preg_replace", "(", "'#^https?://#'", ",", "''", ",", "$", "logentry", "->", "name", ")", ";", "if", "(", "$", "lastcourseid", "&&", "$", "lastcourseid", "!=", "$", "logentry", "->", "course", ")", "{", "$", "path", "=", "[", "get_string", "(", "'pluginname'", ",", "'auth_mnet'", ")", ",", "$", "data", "[", "0", "]", "->", "externalhost", ",", "$", "data", "[", "0", "]", "->", "coursename", "]", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "$", "path", ",", "(", "object", ")", "$", "data", ")", ";", "$", "data", "=", "[", "]", ";", "}", "$", "data", "[", "]", "=", "$", "item", ";", "$", "lastcourseid", "=", "$", "logentry", "->", "course", ";", "}", "$", "logentries", "->", "close", "(", ")", ";", "$", "path", "=", "[", "get_string", "(", "'pluginname'", ",", "'auth_mnet'", ")", ",", "$", "item", "->", "externalhost", ",", "$", "item", "->", "coursename", "]", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "$", "path", ",", "(", "object", ")", "$", "data", ")", ";", "}" ]
Export all user data for the specified user, in the specified contexts, using the supplied exporter instance. @param approved_contextlist $contextlist The approved contexts to export information for.
[ "Export", "all", "user", "data", "for", "the", "specified", "user", "in", "the", "specified", "contexts", "using", "the", "supplied", "exporter", "instance", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/auth/mnet/classes/privacy/provider.php#L176-L224
216,890
moodle/moodle
user/externallib.php
core_user_external.update_user_preferences
public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) { global $USER, $CFG; require_once($CFG->dirroot . '/user/lib.php'); require_once($CFG->dirroot . '/user/editlib.php'); require_once($CFG->dirroot . '/message/lib.php'); if (empty($userid)) { $userid = $USER->id; } $systemcontext = context_system::instance(); self::validate_context($systemcontext); $params = array( 'userid' => $userid, 'emailstop' => $emailstop, 'preferences' => $preferences ); $params = self::validate_parameters(self::update_user_preferences_parameters(), $params); $preferences = $params['preferences']; // Preferences. if (!empty($preferences)) { $userpref = ['id' => $userid]; foreach ($preferences as $preference) { $userpref['preference_' . $preference['type']] = $preference['value']; } useredit_update_user_preference($userpref); } // Check if they want to update the email. if ($emailstop !== null) { $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST); core_user::require_active_user($otheruser); if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) { $user = new stdClass(); $user->id = $userid; $user->emailstop = $emailstop; user_update_user($user); // Update the $USER if we should. if ($userid == $USER->id) { $USER->emailstop = $emailstop; } } } return null; }
php
public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) { global $USER, $CFG; require_once($CFG->dirroot . '/user/lib.php'); require_once($CFG->dirroot . '/user/editlib.php'); require_once($CFG->dirroot . '/message/lib.php'); if (empty($userid)) { $userid = $USER->id; } $systemcontext = context_system::instance(); self::validate_context($systemcontext); $params = array( 'userid' => $userid, 'emailstop' => $emailstop, 'preferences' => $preferences ); $params = self::validate_parameters(self::update_user_preferences_parameters(), $params); $preferences = $params['preferences']; // Preferences. if (!empty($preferences)) { $userpref = ['id' => $userid]; foreach ($preferences as $preference) { $userpref['preference_' . $preference['type']] = $preference['value']; } useredit_update_user_preference($userpref); } // Check if they want to update the email. if ($emailstop !== null) { $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST); core_user::require_active_user($otheruser); if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) { $user = new stdClass(); $user->id = $userid; $user->emailstop = $emailstop; user_update_user($user); // Update the $USER if we should. if ($userid == $USER->id) { $USER->emailstop = $emailstop; } } } return null; }
[ "public", "static", "function", "update_user_preferences", "(", "$", "userid", "=", "0", ",", "$", "emailstop", "=", "null", ",", "$", "preferences", "=", "array", "(", ")", ")", "{", "global", "$", "USER", ",", "$", "CFG", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/user/lib.php'", ")", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/user/editlib.php'", ")", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/message/lib.php'", ")", ";", "if", "(", "empty", "(", "$", "userid", ")", ")", "{", "$", "userid", "=", "$", "USER", "->", "id", ";", "}", "$", "systemcontext", "=", "context_system", "::", "instance", "(", ")", ";", "self", "::", "validate_context", "(", "$", "systemcontext", ")", ";", "$", "params", "=", "array", "(", "'userid'", "=>", "$", "userid", ",", "'emailstop'", "=>", "$", "emailstop", ",", "'preferences'", "=>", "$", "preferences", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "update_user_preferences_parameters", "(", ")", ",", "$", "params", ")", ";", "$", "preferences", "=", "$", "params", "[", "'preferences'", "]", ";", "// Preferences.", "if", "(", "!", "empty", "(", "$", "preferences", ")", ")", "{", "$", "userpref", "=", "[", "'id'", "=>", "$", "userid", "]", ";", "foreach", "(", "$", "preferences", "as", "$", "preference", ")", "{", "$", "userpref", "[", "'preference_'", ".", "$", "preference", "[", "'type'", "]", "]", "=", "$", "preference", "[", "'value'", "]", ";", "}", "useredit_update_user_preference", "(", "$", "userpref", ")", ";", "}", "// Check if they want to update the email.", "if", "(", "$", "emailstop", "!==", "null", ")", "{", "$", "otheruser", "=", "(", "$", "userid", "==", "$", "USER", "->", "id", ")", "?", "$", "USER", ":", "core_user", "::", "get_user", "(", "$", "userid", ",", "'*'", ",", "MUST_EXIST", ")", ";", "core_user", "::", "require_active_user", "(", "$", "otheruser", ")", ";", "if", "(", "core_message_can_edit_message_profile", "(", "$", "otheruser", ")", "&&", "$", "otheruser", "->", "emailstop", "!=", "$", "emailstop", ")", "{", "$", "user", "=", "new", "stdClass", "(", ")", ";", "$", "user", "->", "id", "=", "$", "userid", ";", "$", "user", "->", "emailstop", "=", "$", "emailstop", ";", "user_update_user", "(", "$", "user", ")", ";", "// Update the $USER if we should.", "if", "(", "$", "userid", "==", "$", "USER", "->", "id", ")", "{", "$", "USER", "->", "emailstop", "=", "$", "emailstop", ";", "}", "}", "}", "return", "null", ";", "}" ]
Update the user's preferences. @param int $userid @param bool|null $emailstop @param array $preferences @return null @since Moodle 3.2
[ "Update", "the", "user", "s", "preferences", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L399-L447
216,891
moodle/moodle
user/externallib.php
core_user_external.get_users_by_field
public static function get_users_by_field($field, $values) { global $CFG, $USER, $DB; require_once($CFG->dirroot . "/user/lib.php"); $params = self::validate_parameters(self::get_users_by_field_parameters(), array('field' => $field, 'values' => $values)); // This array will keep all the users that are allowed to be searched, // according to the current user's privileges. $cleanedvalues = array(); switch ($field) { case 'id': $paramtype = core_user::get_property_type('id'); break; case 'idnumber': $paramtype = core_user::get_property_type('idnumber'); break; case 'username': $paramtype = core_user::get_property_type('username'); break; case 'email': $paramtype = core_user::get_property_type('email'); break; default: throw new coding_exception('invalid field parameter', 'The search field \'' . $field . '\' is not supported, look at the web service documentation'); } // Clean the values. foreach ($values as $value) { $cleanedvalue = clean_param($value, $paramtype); if ( $value != $cleanedvalue) { throw new invalid_parameter_exception('The field \'' . $field . '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')'); } $cleanedvalues[] = $cleanedvalue; } // Retrieve the users. $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id'); $context = context_system::instance(); self::validate_context($context); // Finally retrieve each users information. $returnedusers = array(); foreach ($users as $user) { $userdetails = user_get_user_details_courses($user); // Return the user only if the searched field is returned. // Otherwise it means that the $USER was not allowed to search the returned user. if (!empty($userdetails) and !empty($userdetails[$field])) { $returnedusers[] = $userdetails; } } return $returnedusers; }
php
public static function get_users_by_field($field, $values) { global $CFG, $USER, $DB; require_once($CFG->dirroot . "/user/lib.php"); $params = self::validate_parameters(self::get_users_by_field_parameters(), array('field' => $field, 'values' => $values)); // This array will keep all the users that are allowed to be searched, // according to the current user's privileges. $cleanedvalues = array(); switch ($field) { case 'id': $paramtype = core_user::get_property_type('id'); break; case 'idnumber': $paramtype = core_user::get_property_type('idnumber'); break; case 'username': $paramtype = core_user::get_property_type('username'); break; case 'email': $paramtype = core_user::get_property_type('email'); break; default: throw new coding_exception('invalid field parameter', 'The search field \'' . $field . '\' is not supported, look at the web service documentation'); } // Clean the values. foreach ($values as $value) { $cleanedvalue = clean_param($value, $paramtype); if ( $value != $cleanedvalue) { throw new invalid_parameter_exception('The field \'' . $field . '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')'); } $cleanedvalues[] = $cleanedvalue; } // Retrieve the users. $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id'); $context = context_system::instance(); self::validate_context($context); // Finally retrieve each users information. $returnedusers = array(); foreach ($users as $user) { $userdetails = user_get_user_details_courses($user); // Return the user only if the searched field is returned. // Otherwise it means that the $USER was not allowed to search the returned user. if (!empty($userdetails) and !empty($userdetails[$field])) { $returnedusers[] = $userdetails; } } return $returnedusers; }
[ "public", "static", "function", "get_users_by_field", "(", "$", "field", ",", "$", "values", ")", "{", "global", "$", "CFG", ",", "$", "USER", ",", "$", "DB", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "\"/user/lib.php\"", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "get_users_by_field_parameters", "(", ")", ",", "array", "(", "'field'", "=>", "$", "field", ",", "'values'", "=>", "$", "values", ")", ")", ";", "// This array will keep all the users that are allowed to be searched,", "// according to the current user's privileges.", "$", "cleanedvalues", "=", "array", "(", ")", ";", "switch", "(", "$", "field", ")", "{", "case", "'id'", ":", "$", "paramtype", "=", "core_user", "::", "get_property_type", "(", "'id'", ")", ";", "break", ";", "case", "'idnumber'", ":", "$", "paramtype", "=", "core_user", "::", "get_property_type", "(", "'idnumber'", ")", ";", "break", ";", "case", "'username'", ":", "$", "paramtype", "=", "core_user", "::", "get_property_type", "(", "'username'", ")", ";", "break", ";", "case", "'email'", ":", "$", "paramtype", "=", "core_user", "::", "get_property_type", "(", "'email'", ")", ";", "break", ";", "default", ":", "throw", "new", "coding_exception", "(", "'invalid field parameter'", ",", "'The search field \\''", ".", "$", "field", ".", "'\\' is not supported, look at the web service documentation'", ")", ";", "}", "// Clean the values.", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$", "cleanedvalue", "=", "clean_param", "(", "$", "value", ",", "$", "paramtype", ")", ";", "if", "(", "$", "value", "!=", "$", "cleanedvalue", ")", "{", "throw", "new", "invalid_parameter_exception", "(", "'The field \\''", ".", "$", "field", ".", "'\\' value is invalid: '", ".", "$", "value", ".", "'(cleaned value: '", ".", "$", "cleanedvalue", ".", "')'", ")", ";", "}", "$", "cleanedvalues", "[", "]", "=", "$", "cleanedvalue", ";", "}", "// Retrieve the users.", "$", "users", "=", "$", "DB", "->", "get_records_list", "(", "'user'", ",", "$", "field", ",", "$", "cleanedvalues", ",", "'id'", ")", ";", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "self", "::", "validate_context", "(", "$", "context", ")", ";", "// Finally retrieve each users information.", "$", "returnedusers", "=", "array", "(", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "userdetails", "=", "user_get_user_details_courses", "(", "$", "user", ")", ";", "// Return the user only if the searched field is returned.", "// Otherwise it means that the $USER was not allowed to search the returned user.", "if", "(", "!", "empty", "(", "$", "userdetails", ")", "and", "!", "empty", "(", "$", "userdetails", "[", "$", "field", "]", ")", ")", "{", "$", "returnedusers", "[", "]", "=", "$", "userdetails", ";", "}", "}", "return", "$", "returnedusers", ";", "}" ]
Get user information for a unique field. @throws coding_exception @throws invalid_parameter_exception @param string $field @param array $values @return array An array of arrays containg user profiles. @since Moodle 2.4
[ "Get", "user", "information", "for", "a", "unique", "field", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L708-L766
216,892
moodle/moodle
user/externallib.php
core_user_external.get_course_user_profiles
public static function get_course_user_profiles($userlist) { global $CFG, $USER, $DB; require_once($CFG->dirroot . "/user/lib.php"); $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist)); $userids = array(); $courseids = array(); foreach ($params['userlist'] as $value) { $userids[] = $value['userid']; $courseids[$value['userid']] = $value['courseid']; } // Cache all courses. $courses = array(); list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED); $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; $params['contextlevel'] = CONTEXT_COURSE; $coursesql = "SELECT c.* $cselect FROM {course} c $cjoin WHERE c.id $sqlcourseids"; $rs = $DB->get_recordset_sql($coursesql, $params); foreach ($rs as $course) { // Adding course contexts to cache. context_helper::preload_from_record($course); // Cache courses. $courses[$course->id] = $course; } $rs->close(); list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED); $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)"; $params['contextlevel'] = CONTEXT_USER; $usersql = "SELECT u.* $uselect FROM {user} u $ujoin WHERE u.id $sqluserids"; $users = $DB->get_recordset_sql($usersql, $params); $result = array(); foreach ($users as $user) { if (!empty($user->deleted)) { continue; } context_helper::preload_from_record($user); $course = $courses[$courseids[$user->id]]; $context = context_course::instance($courseids[$user->id], IGNORE_MISSING); self::validate_context($context); if ($userarray = user_get_user_details($user, $course)) { $result[] = $userarray; } } $users->close(); return $result; }
php
public static function get_course_user_profiles($userlist) { global $CFG, $USER, $DB; require_once($CFG->dirroot . "/user/lib.php"); $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist)); $userids = array(); $courseids = array(); foreach ($params['userlist'] as $value) { $userids[] = $value['userid']; $courseids[$value['userid']] = $value['courseid']; } // Cache all courses. $courses = array(); list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED); $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; $params['contextlevel'] = CONTEXT_COURSE; $coursesql = "SELECT c.* $cselect FROM {course} c $cjoin WHERE c.id $sqlcourseids"; $rs = $DB->get_recordset_sql($coursesql, $params); foreach ($rs as $course) { // Adding course contexts to cache. context_helper::preload_from_record($course); // Cache courses. $courses[$course->id] = $course; } $rs->close(); list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED); $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)"; $params['contextlevel'] = CONTEXT_USER; $usersql = "SELECT u.* $uselect FROM {user} u $ujoin WHERE u.id $sqluserids"; $users = $DB->get_recordset_sql($usersql, $params); $result = array(); foreach ($users as $user) { if (!empty($user->deleted)) { continue; } context_helper::preload_from_record($user); $course = $courses[$courseids[$user->id]]; $context = context_course::instance($courseids[$user->id], IGNORE_MISSING); self::validate_context($context); if ($userarray = user_get_user_details($user, $course)) { $result[] = $userarray; } } $users->close(); return $result; }
[ "public", "static", "function", "get_course_user_profiles", "(", "$", "userlist", ")", "{", "global", "$", "CFG", ",", "$", "USER", ",", "$", "DB", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "\"/user/lib.php\"", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "get_course_user_profiles_parameters", "(", ")", ",", "array", "(", "'userlist'", "=>", "$", "userlist", ")", ")", ";", "$", "userids", "=", "array", "(", ")", ";", "$", "courseids", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "[", "'userlist'", "]", "as", "$", "value", ")", "{", "$", "userids", "[", "]", "=", "$", "value", "[", "'userid'", "]", ";", "$", "courseids", "[", "$", "value", "[", "'userid'", "]", "]", "=", "$", "value", "[", "'courseid'", "]", ";", "}", "// Cache all courses.", "$", "courses", "=", "array", "(", ")", ";", "list", "(", "$", "sqlcourseids", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "array_unique", "(", "$", "courseids", ")", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "cselect", "=", "', '", ".", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "cjoin", "=", "\"LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)\"", ";", "$", "params", "[", "'contextlevel'", "]", "=", "CONTEXT_COURSE", ";", "$", "coursesql", "=", "\"SELECT c.* $cselect\n FROM {course} c $cjoin\n WHERE c.id $sqlcourseids\"", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "coursesql", ",", "$", "params", ")", ";", "foreach", "(", "$", "rs", "as", "$", "course", ")", "{", "// Adding course contexts to cache.", "context_helper", "::", "preload_from_record", "(", "$", "course", ")", ";", "// Cache courses.", "$", "courses", "[", "$", "course", "->", "id", "]", "=", "$", "course", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "list", "(", "$", "sqluserids", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "userids", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "uselect", "=", "', '", ".", "context_helper", "::", "get_preload_record_columns_sql", "(", "'ctx'", ")", ";", "$", "ujoin", "=", "\"LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)\"", ";", "$", "params", "[", "'contextlevel'", "]", "=", "CONTEXT_USER", ";", "$", "usersql", "=", "\"SELECT u.* $uselect\n FROM {user} u $ujoin\n WHERE u.id $sqluserids\"", ";", "$", "users", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "usersql", ",", "$", "params", ")", ";", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "if", "(", "!", "empty", "(", "$", "user", "->", "deleted", ")", ")", "{", "continue", ";", "}", "context_helper", "::", "preload_from_record", "(", "$", "user", ")", ";", "$", "course", "=", "$", "courses", "[", "$", "courseids", "[", "$", "user", "->", "id", "]", "]", ";", "$", "context", "=", "context_course", "::", "instance", "(", "$", "courseids", "[", "$", "user", "->", "id", "]", ",", "IGNORE_MISSING", ")", ";", "self", "::", "validate_context", "(", "$", "context", ")", ";", "if", "(", "$", "userarray", "=", "user_get_user_details", "(", "$", "user", ",", "$", "course", ")", ")", "{", "$", "result", "[", "]", "=", "$", "userarray", ";", "}", "}", "$", "users", "->", "close", "(", ")", ";", "return", "$", "result", ";", "}" ]
Get course participant's details @param array $userlist array of user ids and according course ids @return array An array of arrays describing course participants @since Moodle 2.2
[ "Get", "course", "participant", "s", "details" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L983-L1038
216,893
moodle/moodle
user/externallib.php
core_user_external.add_user_private_files
public static function add_user_private_files($draftid) { global $CFG, $USER; require_once($CFG->libdir . "/filelib.php"); $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid)); if (isguestuser()) { throw new invalid_parameter_exception('Guest users cannot upload files'); } $context = context_user::instance($USER->id); require_capability('moodle/user:manageownfiles', $context); $maxbytes = $CFG->userquota; $maxareabytes = $CFG->userquota; if (has_capability('moodle/user:ignoreuserquota', $context)) { $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS; $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED; } $options = array('subdirs' => 1, 'maxbytes' => $maxbytes, 'maxfiles' => -1, 'areamaxbytes' => $maxareabytes); file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options); return null; }
php
public static function add_user_private_files($draftid) { global $CFG, $USER; require_once($CFG->libdir . "/filelib.php"); $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid)); if (isguestuser()) { throw new invalid_parameter_exception('Guest users cannot upload files'); } $context = context_user::instance($USER->id); require_capability('moodle/user:manageownfiles', $context); $maxbytes = $CFG->userquota; $maxareabytes = $CFG->userquota; if (has_capability('moodle/user:ignoreuserquota', $context)) { $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS; $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED; } $options = array('subdirs' => 1, 'maxbytes' => $maxbytes, 'maxfiles' => -1, 'areamaxbytes' => $maxareabytes); file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options); return null; }
[ "public", "static", "function", "add_user_private_files", "(", "$", "draftid", ")", "{", "global", "$", "CFG", ",", "$", "USER", ";", "require_once", "(", "$", "CFG", "->", "libdir", ".", "\"/filelib.php\"", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "add_user_private_files_parameters", "(", ")", ",", "array", "(", "'draftid'", "=>", "$", "draftid", ")", ")", ";", "if", "(", "isguestuser", "(", ")", ")", "{", "throw", "new", "invalid_parameter_exception", "(", "'Guest users cannot upload files'", ")", ";", "}", "$", "context", "=", "context_user", "::", "instance", "(", "$", "USER", "->", "id", ")", ";", "require_capability", "(", "'moodle/user:manageownfiles'", ",", "$", "context", ")", ";", "$", "maxbytes", "=", "$", "CFG", "->", "userquota", ";", "$", "maxareabytes", "=", "$", "CFG", "->", "userquota", ";", "if", "(", "has_capability", "(", "'moodle/user:ignoreuserquota'", ",", "$", "context", ")", ")", "{", "$", "maxbytes", "=", "USER_CAN_IGNORE_FILE_SIZE_LIMITS", ";", "$", "maxareabytes", "=", "FILE_AREA_MAX_BYTES_UNLIMITED", ";", "}", "$", "options", "=", "array", "(", "'subdirs'", "=>", "1", ",", "'maxbytes'", "=>", "$", "maxbytes", ",", "'maxfiles'", "=>", "-", "1", ",", "'areamaxbytes'", "=>", "$", "maxareabytes", ")", ";", "file_merge_files_from_draft_area_into_filearea", "(", "$", "draftid", ",", "$", "context", "->", "id", ",", "'user'", ",", "'private'", ",", "0", ",", "$", "options", ")", ";", "return", "null", ";", "}" ]
Copy files from a draft area to users private files area. @throws invalid_parameter_exception @param int $draftid Id of a draft area containing files. @return array An array of warnings @since Moodle 2.6
[ "Copy", "files", "from", "a", "draft", "area", "to", "users", "private", "files", "area", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1167-L1195
216,894
moodle/moodle
user/externallib.php
core_user_external.view_user_list
public static function view_user_list($courseid) { global $CFG; require_once($CFG->dirroot . "/user/lib.php"); require_once($CFG->dirroot . '/course/lib.php'); $params = self::validate_parameters(self::view_user_list_parameters(), array( 'courseid' => $courseid )); $warnings = array(); if (empty($params['courseid'])) { $params['courseid'] = SITEID; } $course = get_course($params['courseid']); if ($course->id == SITEID) { $context = context_system::instance(); } else { $context = context_course::instance($course->id); } self::validate_context($context); course_require_view_participants($context); user_list_view($course, $context); $result = array(); $result['status'] = true; $result['warnings'] = $warnings; return $result; }
php
public static function view_user_list($courseid) { global $CFG; require_once($CFG->dirroot . "/user/lib.php"); require_once($CFG->dirroot . '/course/lib.php'); $params = self::validate_parameters(self::view_user_list_parameters(), array( 'courseid' => $courseid )); $warnings = array(); if (empty($params['courseid'])) { $params['courseid'] = SITEID; } $course = get_course($params['courseid']); if ($course->id == SITEID) { $context = context_system::instance(); } else { $context = context_course::instance($course->id); } self::validate_context($context); course_require_view_participants($context); user_list_view($course, $context); $result = array(); $result['status'] = true; $result['warnings'] = $warnings; return $result; }
[ "public", "static", "function", "view_user_list", "(", "$", "courseid", ")", "{", "global", "$", "CFG", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "\"/user/lib.php\"", ")", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/course/lib.php'", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "view_user_list_parameters", "(", ")", ",", "array", "(", "'courseid'", "=>", "$", "courseid", ")", ")", ";", "$", "warnings", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "'courseid'", "]", ")", ")", "{", "$", "params", "[", "'courseid'", "]", "=", "SITEID", ";", "}", "$", "course", "=", "get_course", "(", "$", "params", "[", "'courseid'", "]", ")", ";", "if", "(", "$", "course", "->", "id", "==", "SITEID", ")", "{", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "}", "else", "{", "$", "context", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "}", "self", "::", "validate_context", "(", "$", "context", ")", ";", "course_require_view_participants", "(", "$", "context", ")", ";", "user_list_view", "(", "$", "course", ",", "$", "context", ")", ";", "$", "result", "=", "array", "(", ")", ";", "$", "result", "[", "'status'", "]", "=", "true", ";", "$", "result", "[", "'warnings'", "]", "=", "$", "warnings", ";", "return", "$", "result", ";", "}" ]
Trigger the user_list_viewed event. @param int $courseid id of course @return array of warnings and status result @since Moodle 2.9 @throws moodle_exception
[ "Trigger", "the", "user_list_viewed", "event", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1404-L1437
216,895
moodle/moodle
user/externallib.php
core_user_external.view_user_profile
public static function view_user_profile($userid, $courseid = 0) { global $CFG, $USER; require_once($CFG->dirroot . "/user/profile/lib.php"); $params = self::validate_parameters(self::view_user_profile_parameters(), array( 'userid' => $userid, 'courseid' => $courseid )); $warnings = array(); if (empty($params['userid'])) { $params['userid'] = $USER->id; } if (empty($params['courseid'])) { $params['courseid'] = SITEID; } $course = get_course($params['courseid']); $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); if ($course->id == SITEID) { $coursecontext = context_system::instance();; } else { $coursecontext = context_course::instance($course->id); } self::validate_context($coursecontext); $currentuser = $USER->id == $user->id; $usercontext = context_user::instance($user->id); if (!$currentuser and !has_capability('moodle/user:viewdetails', $coursecontext) and !has_capability('moodle/user:viewdetails', $usercontext)) { throw new moodle_exception('cannotviewprofile'); } // Case like user/profile.php. if ($course->id == SITEID) { profile_view($user, $usercontext); } else { // Case like user/view.php. if (!$currentuser and !can_access_course($course, $user, '', true)) { throw new moodle_exception('notenrolledprofile'); } profile_view($user, $coursecontext, $course); } $result = array(); $result['status'] = true; $result['warnings'] = $warnings; return $result; }
php
public static function view_user_profile($userid, $courseid = 0) { global $CFG, $USER; require_once($CFG->dirroot . "/user/profile/lib.php"); $params = self::validate_parameters(self::view_user_profile_parameters(), array( 'userid' => $userid, 'courseid' => $courseid )); $warnings = array(); if (empty($params['userid'])) { $params['userid'] = $USER->id; } if (empty($params['courseid'])) { $params['courseid'] = SITEID; } $course = get_course($params['courseid']); $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); if ($course->id == SITEID) { $coursecontext = context_system::instance();; } else { $coursecontext = context_course::instance($course->id); } self::validate_context($coursecontext); $currentuser = $USER->id == $user->id; $usercontext = context_user::instance($user->id); if (!$currentuser and !has_capability('moodle/user:viewdetails', $coursecontext) and !has_capability('moodle/user:viewdetails', $usercontext)) { throw new moodle_exception('cannotviewprofile'); } // Case like user/profile.php. if ($course->id == SITEID) { profile_view($user, $usercontext); } else { // Case like user/view.php. if (!$currentuser and !can_access_course($course, $user, '', true)) { throw new moodle_exception('notenrolledprofile'); } profile_view($user, $coursecontext, $course); } $result = array(); $result['status'] = true; $result['warnings'] = $warnings; return $result; }
[ "public", "static", "function", "view_user_profile", "(", "$", "userid", ",", "$", "courseid", "=", "0", ")", "{", "global", "$", "CFG", ",", "$", "USER", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "\"/user/profile/lib.php\"", ")", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "view_user_profile_parameters", "(", ")", ",", "array", "(", "'userid'", "=>", "$", "userid", ",", "'courseid'", "=>", "$", "courseid", ")", ")", ";", "$", "warnings", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "'userid'", "]", ")", ")", "{", "$", "params", "[", "'userid'", "]", "=", "$", "USER", "->", "id", ";", "}", "if", "(", "empty", "(", "$", "params", "[", "'courseid'", "]", ")", ")", "{", "$", "params", "[", "'courseid'", "]", "=", "SITEID", ";", "}", "$", "course", "=", "get_course", "(", "$", "params", "[", "'courseid'", "]", ")", ";", "$", "user", "=", "core_user", "::", "get_user", "(", "$", "params", "[", "'userid'", "]", ",", "'*'", ",", "MUST_EXIST", ")", ";", "core_user", "::", "require_active_user", "(", "$", "user", ")", ";", "if", "(", "$", "course", "->", "id", "==", "SITEID", ")", "{", "$", "coursecontext", "=", "context_system", "::", "instance", "(", ")", ";", ";", "}", "else", "{", "$", "coursecontext", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "}", "self", "::", "validate_context", "(", "$", "coursecontext", ")", ";", "$", "currentuser", "=", "$", "USER", "->", "id", "==", "$", "user", "->", "id", ";", "$", "usercontext", "=", "context_user", "::", "instance", "(", "$", "user", "->", "id", ")", ";", "if", "(", "!", "$", "currentuser", "and", "!", "has_capability", "(", "'moodle/user:viewdetails'", ",", "$", "coursecontext", ")", "and", "!", "has_capability", "(", "'moodle/user:viewdetails'", ",", "$", "usercontext", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'cannotviewprofile'", ")", ";", "}", "// Case like user/profile.php.", "if", "(", "$", "course", "->", "id", "==", "SITEID", ")", "{", "profile_view", "(", "$", "user", ",", "$", "usercontext", ")", ";", "}", "else", "{", "// Case like user/view.php.", "if", "(", "!", "$", "currentuser", "and", "!", "can_access_course", "(", "$", "course", ",", "$", "user", ",", "''", ",", "true", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'notenrolledprofile'", ")", ";", "}", "profile_view", "(", "$", "user", ",", "$", "coursecontext", ",", "$", "course", ")", ";", "}", "$", "result", "=", "array", "(", ")", ";", "$", "result", "[", "'status'", "]", "=", "true", ";", "$", "result", "[", "'warnings'", "]", "=", "$", "warnings", ";", "return", "$", "result", ";", "}" ]
Trigger the user profile viewed event. @param int $userid id of user @param int $courseid id of course @return array of warnings and status result @since Moodle 2.9 @throws moodle_exception
[ "Trigger", "the", "user", "profile", "viewed", "event", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1478-L1534
216,896
moodle/moodle
user/externallib.php
core_user_external.get_user_preferences
public static function get_user_preferences($name = '', $userid = 0) { global $USER; $params = self::validate_parameters(self::get_user_preferences_parameters(), array( 'name' => $name, 'userid' => $userid )); $preferences = array(); $warnings = array(); $context = context_system::instance(); self::validate_context($context); if (empty($params['name'])) { $name = null; } if (empty($params['userid'])) { $user = null; } else { $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); if ($user->id != $USER->id) { // Only admins can retrieve other users preferences. require_capability('moodle/site:config', $context); } } $userpreferences = get_user_preferences($name, null, $user); // Check if we received just one preference. if (!is_array($userpreferences)) { $userpreferences = array($name => $userpreferences); } foreach ($userpreferences as $name => $value) { $preferences[] = array( 'name' => $name, 'value' => $value, ); } $result = array(); $result['preferences'] = $preferences; $result['warnings'] = $warnings; return $result; }
php
public static function get_user_preferences($name = '', $userid = 0) { global $USER; $params = self::validate_parameters(self::get_user_preferences_parameters(), array( 'name' => $name, 'userid' => $userid )); $preferences = array(); $warnings = array(); $context = context_system::instance(); self::validate_context($context); if (empty($params['name'])) { $name = null; } if (empty($params['userid'])) { $user = null; } else { $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); if ($user->id != $USER->id) { // Only admins can retrieve other users preferences. require_capability('moodle/site:config', $context); } } $userpreferences = get_user_preferences($name, null, $user); // Check if we received just one preference. if (!is_array($userpreferences)) { $userpreferences = array($name => $userpreferences); } foreach ($userpreferences as $name => $value) { $preferences[] = array( 'name' => $name, 'value' => $value, ); } $result = array(); $result['preferences'] = $preferences; $result['warnings'] = $warnings; return $result; }
[ "public", "static", "function", "get_user_preferences", "(", "$", "name", "=", "''", ",", "$", "userid", "=", "0", ")", "{", "global", "$", "USER", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "get_user_preferences_parameters", "(", ")", ",", "array", "(", "'name'", "=>", "$", "name", ",", "'userid'", "=>", "$", "userid", ")", ")", ";", "$", "preferences", "=", "array", "(", ")", ";", "$", "warnings", "=", "array", "(", ")", ";", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "self", "::", "validate_context", "(", "$", "context", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "'name'", "]", ")", ")", "{", "$", "name", "=", "null", ";", "}", "if", "(", "empty", "(", "$", "params", "[", "'userid'", "]", ")", ")", "{", "$", "user", "=", "null", ";", "}", "else", "{", "$", "user", "=", "core_user", "::", "get_user", "(", "$", "params", "[", "'userid'", "]", ",", "'*'", ",", "MUST_EXIST", ")", ";", "core_user", "::", "require_active_user", "(", "$", "user", ")", ";", "if", "(", "$", "user", "->", "id", "!=", "$", "USER", "->", "id", ")", "{", "// Only admins can retrieve other users preferences.", "require_capability", "(", "'moodle/site:config'", ",", "$", "context", ")", ";", "}", "}", "$", "userpreferences", "=", "get_user_preferences", "(", "$", "name", ",", "null", ",", "$", "user", ")", ";", "// Check if we received just one preference.", "if", "(", "!", "is_array", "(", "$", "userpreferences", ")", ")", "{", "$", "userpreferences", "=", "array", "(", "$", "name", "=>", "$", "userpreferences", ")", ";", "}", "foreach", "(", "$", "userpreferences", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "preferences", "[", "]", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'value'", "=>", "$", "value", ",", ")", ";", "}", "$", "result", "=", "array", "(", ")", ";", "$", "result", "[", "'preferences'", "]", "=", "$", "preferences", ";", "$", "result", "[", "'warnings'", "]", "=", "$", "warnings", ";", "return", "$", "result", ";", "}" ]
Return user preferences. @param string $name preference name, empty for all @param int $userid id of the user, 0 for current user @return array of warnings and preferences @since Moodle 3.2 @throws moodle_exception
[ "Return", "user", "preferences", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1575-L1620
216,897
moodle/moodle
user/externallib.php
core_user_external.update_picture
public static function update_picture($draftitemid, $delete = false, $userid = 0) { global $CFG, $USER, $PAGE; $params = self::validate_parameters( self::update_picture_parameters(), array( 'draftitemid' => $draftitemid, 'delete' => $delete, 'userid' => $userid ) ); $context = context_system::instance(); self::validate_context($context); if (!empty($CFG->disableuserimages)) { throw new moodle_exception('userimagesdisabled', 'admin'); } if (empty($params['userid']) or $params['userid'] == $USER->id) { $user = $USER; require_capability('moodle/user:editownprofile', $context); } else { $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); $personalcontext = context_user::instance($user->id); require_capability('moodle/user:editprofile', $personalcontext); if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins. throw new moodle_exception('useradmineditadmin'); } } // Load the appropriate auth plugin. $userauth = get_auth_plugin($user->auth); if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) { throw new moodle_exception('noprofileedit', 'auth'); } $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image'); $user->deletepicture = $params['delete']; $user->imagefile = $params['draftitemid']; $success = core_user::update_picture($user, $filemanageroptions); $result = array( 'success' => $success, 'warnings' => array(), ); if ($success) { $userpicture = new user_picture(core_user::get_user($user->id)); $userpicture->size = 1; // Size f1. $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); } return $result; }
php
public static function update_picture($draftitemid, $delete = false, $userid = 0) { global $CFG, $USER, $PAGE; $params = self::validate_parameters( self::update_picture_parameters(), array( 'draftitemid' => $draftitemid, 'delete' => $delete, 'userid' => $userid ) ); $context = context_system::instance(); self::validate_context($context); if (!empty($CFG->disableuserimages)) { throw new moodle_exception('userimagesdisabled', 'admin'); } if (empty($params['userid']) or $params['userid'] == $USER->id) { $user = $USER; require_capability('moodle/user:editownprofile', $context); } else { $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); $personalcontext = context_user::instance($user->id); require_capability('moodle/user:editprofile', $personalcontext); if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins. throw new moodle_exception('useradmineditadmin'); } } // Load the appropriate auth plugin. $userauth = get_auth_plugin($user->auth); if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) { throw new moodle_exception('noprofileedit', 'auth'); } $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image'); $user->deletepicture = $params['delete']; $user->imagefile = $params['draftitemid']; $success = core_user::update_picture($user, $filemanageroptions); $result = array( 'success' => $success, 'warnings' => array(), ); if ($success) { $userpicture = new user_picture(core_user::get_user($user->id)); $userpicture->size = 1; // Size f1. $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); } return $result; }
[ "public", "static", "function", "update_picture", "(", "$", "draftitemid", ",", "$", "delete", "=", "false", ",", "$", "userid", "=", "0", ")", "{", "global", "$", "CFG", ",", "$", "USER", ",", "$", "PAGE", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "update_picture_parameters", "(", ")", ",", "array", "(", "'draftitemid'", "=>", "$", "draftitemid", ",", "'delete'", "=>", "$", "delete", ",", "'userid'", "=>", "$", "userid", ")", ")", ";", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "self", "::", "validate_context", "(", "$", "context", ")", ";", "if", "(", "!", "empty", "(", "$", "CFG", "->", "disableuserimages", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'userimagesdisabled'", ",", "'admin'", ")", ";", "}", "if", "(", "empty", "(", "$", "params", "[", "'userid'", "]", ")", "or", "$", "params", "[", "'userid'", "]", "==", "$", "USER", "->", "id", ")", "{", "$", "user", "=", "$", "USER", ";", "require_capability", "(", "'moodle/user:editownprofile'", ",", "$", "context", ")", ";", "}", "else", "{", "$", "user", "=", "core_user", "::", "get_user", "(", "$", "params", "[", "'userid'", "]", ",", "'*'", ",", "MUST_EXIST", ")", ";", "core_user", "::", "require_active_user", "(", "$", "user", ")", ";", "$", "personalcontext", "=", "context_user", "::", "instance", "(", "$", "user", "->", "id", ")", ";", "require_capability", "(", "'moodle/user:editprofile'", ",", "$", "personalcontext", ")", ";", "if", "(", "is_siteadmin", "(", "$", "user", ")", "and", "!", "is_siteadmin", "(", "$", "USER", ")", ")", "{", "// Only admins may edit other admins.", "throw", "new", "moodle_exception", "(", "'useradmineditadmin'", ")", ";", "}", "}", "// Load the appropriate auth plugin.", "$", "userauth", "=", "get_auth_plugin", "(", "$", "user", "->", "auth", ")", ";", "if", "(", "is_mnet_remote_user", "(", "$", "user", ")", "or", "!", "$", "userauth", "->", "can_edit_profile", "(", ")", "or", "$", "userauth", "->", "edit_profile_url", "(", ")", ")", "{", "throw", "new", "moodle_exception", "(", "'noprofileedit'", ",", "'auth'", ")", ";", "}", "$", "filemanageroptions", "=", "array", "(", "'maxbytes'", "=>", "$", "CFG", "->", "maxbytes", ",", "'subdirs'", "=>", "0", ",", "'maxfiles'", "=>", "1", ",", "'accepted_types'", "=>", "'web_image'", ")", ";", "$", "user", "->", "deletepicture", "=", "$", "params", "[", "'delete'", "]", ";", "$", "user", "->", "imagefile", "=", "$", "params", "[", "'draftitemid'", "]", ";", "$", "success", "=", "core_user", "::", "update_picture", "(", "$", "user", ",", "$", "filemanageroptions", ")", ";", "$", "result", "=", "array", "(", "'success'", "=>", "$", "success", ",", "'warnings'", "=>", "array", "(", ")", ",", ")", ";", "if", "(", "$", "success", ")", "{", "$", "userpicture", "=", "new", "user_picture", "(", "core_user", "::", "get_user", "(", "$", "user", "->", "id", ")", ")", ";", "$", "userpicture", "->", "size", "=", "1", ";", "// Size f1.", "$", "result", "[", "'profileimageurl'", "]", "=", "$", "userpicture", "->", "get_url", "(", "$", "PAGE", ")", "->", "out", "(", "false", ")", ";", "}", "return", "$", "result", ";", "}" ]
Update or delete the user picture in the site @param int $draftitemid id of the user draft file to use as image @param bool $delete if we should delete the user picture @param int $userid id of the user, 0 for current user @return array warnings and success status @since Moodle 3.2 @throws moodle_exception
[ "Update", "or", "delete", "the", "user", "picture", "in", "the", "site" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1671-L1725
216,898
moodle/moodle
user/externallib.php
core_user_external.set_user_preferences
public static function set_user_preferences($preferences) { global $USER; $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences)); $warnings = array(); $saved = array(); $context = context_system::instance(); self::validate_context($context); $userscache = array(); foreach ($params['preferences'] as $pref) { // Check to which user set the preference. if (!empty($userscache[$pref['userid']])) { $user = $userscache[$pref['userid']]; } else { try { $user = core_user::get_user($pref['userid'], '*', MUST_EXIST); core_user::require_active_user($user); $userscache[$pref['userid']] = $user; } catch (Exception $e) { $warnings[] = array( 'item' => 'user', 'itemid' => $pref['userid'], 'warningcode' => 'invaliduser', 'message' => $e->getMessage() ); continue; } } try { if (core_user::can_edit_preference($pref['name'], $user)) { $value = core_user::clean_preference($pref['value'], $pref['name']); set_user_preference($pref['name'], $value, $user->id); $saved[] = array( 'name' => $pref['name'], 'userid' => $user->id, ); } else { $warnings[] = array( 'item' => 'user', 'itemid' => $user->id, 'warningcode' => 'nopermission', 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id ); } } catch (Exception $e) { $warnings[] = array( 'item' => 'user', 'itemid' => $user->id, 'warningcode' => 'errorsavingpreference', 'message' => $e->getMessage() ); } } $result = array(); $result['saved'] = $saved; $result['warnings'] = $warnings; return $result; }
php
public static function set_user_preferences($preferences) { global $USER; $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences)); $warnings = array(); $saved = array(); $context = context_system::instance(); self::validate_context($context); $userscache = array(); foreach ($params['preferences'] as $pref) { // Check to which user set the preference. if (!empty($userscache[$pref['userid']])) { $user = $userscache[$pref['userid']]; } else { try { $user = core_user::get_user($pref['userid'], '*', MUST_EXIST); core_user::require_active_user($user); $userscache[$pref['userid']] = $user; } catch (Exception $e) { $warnings[] = array( 'item' => 'user', 'itemid' => $pref['userid'], 'warningcode' => 'invaliduser', 'message' => $e->getMessage() ); continue; } } try { if (core_user::can_edit_preference($pref['name'], $user)) { $value = core_user::clean_preference($pref['value'], $pref['name']); set_user_preference($pref['name'], $value, $user->id); $saved[] = array( 'name' => $pref['name'], 'userid' => $user->id, ); } else { $warnings[] = array( 'item' => 'user', 'itemid' => $user->id, 'warningcode' => 'nopermission', 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id ); } } catch (Exception $e) { $warnings[] = array( 'item' => 'user', 'itemid' => $user->id, 'warningcode' => 'errorsavingpreference', 'message' => $e->getMessage() ); } } $result = array(); $result['saved'] = $saved; $result['warnings'] = $warnings; return $result; }
[ "public", "static", "function", "set_user_preferences", "(", "$", "preferences", ")", "{", "global", "$", "USER", ";", "$", "params", "=", "self", "::", "validate_parameters", "(", "self", "::", "set_user_preferences_parameters", "(", ")", ",", "array", "(", "'preferences'", "=>", "$", "preferences", ")", ")", ";", "$", "warnings", "=", "array", "(", ")", ";", "$", "saved", "=", "array", "(", ")", ";", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "self", "::", "validate_context", "(", "$", "context", ")", ";", "$", "userscache", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "[", "'preferences'", "]", "as", "$", "pref", ")", "{", "// Check to which user set the preference.", "if", "(", "!", "empty", "(", "$", "userscache", "[", "$", "pref", "[", "'userid'", "]", "]", ")", ")", "{", "$", "user", "=", "$", "userscache", "[", "$", "pref", "[", "'userid'", "]", "]", ";", "}", "else", "{", "try", "{", "$", "user", "=", "core_user", "::", "get_user", "(", "$", "pref", "[", "'userid'", "]", ",", "'*'", ",", "MUST_EXIST", ")", ";", "core_user", "::", "require_active_user", "(", "$", "user", ")", ";", "$", "userscache", "[", "$", "pref", "[", "'userid'", "]", "]", "=", "$", "user", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "warnings", "[", "]", "=", "array", "(", "'item'", "=>", "'user'", ",", "'itemid'", "=>", "$", "pref", "[", "'userid'", "]", ",", "'warningcode'", "=>", "'invaliduser'", ",", "'message'", "=>", "$", "e", "->", "getMessage", "(", ")", ")", ";", "continue", ";", "}", "}", "try", "{", "if", "(", "core_user", "::", "can_edit_preference", "(", "$", "pref", "[", "'name'", "]", ",", "$", "user", ")", ")", "{", "$", "value", "=", "core_user", "::", "clean_preference", "(", "$", "pref", "[", "'value'", "]", ",", "$", "pref", "[", "'name'", "]", ")", ";", "set_user_preference", "(", "$", "pref", "[", "'name'", "]", ",", "$", "value", ",", "$", "user", "->", "id", ")", ";", "$", "saved", "[", "]", "=", "array", "(", "'name'", "=>", "$", "pref", "[", "'name'", "]", ",", "'userid'", "=>", "$", "user", "->", "id", ",", ")", ";", "}", "else", "{", "$", "warnings", "[", "]", "=", "array", "(", "'item'", "=>", "'user'", ",", "'itemid'", "=>", "$", "user", "->", "id", ",", "'warningcode'", "=>", "'nopermission'", ",", "'message'", "=>", "'You are not allowed to change the preference '", ".", "s", "(", "$", "pref", "[", "'name'", "]", ")", ".", "' for user '", ".", "$", "user", "->", "id", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "warnings", "[", "]", "=", "array", "(", "'item'", "=>", "'user'", ",", "'itemid'", "=>", "$", "user", "->", "id", ",", "'warningcode'", "=>", "'errorsavingpreference'", ",", "'message'", "=>", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}", "$", "result", "=", "array", "(", ")", ";", "$", "result", "[", "'saved'", "]", "=", "$", "saved", ";", "$", "result", "[", "'warnings'", "]", "=", "$", "warnings", ";", "return", "$", "result", ";", "}" ]
Set user preferences. @param array $preferences list of preferences including name, value and userid @return array of warnings and preferences saved @since Moodle 3.2 @throws moodle_exception
[ "Set", "user", "preferences", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1773-L1834
216,899
moodle/moodle
user/externallib.php
core_user_external.agree_site_policy
public static function agree_site_policy() { global $CFG, $DB, $USER; $warnings = array(); $context = context_system::instance(); try { // We expect an exception here since the user didn't agree the site policy yet. self::validate_context($context); } catch (Exception $e) { // We are expecting only a sitepolicynotagreed exception. if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') { // In case we receive a different exception, throw it. throw $e; } } $manager = new \core_privacy\local\sitepolicy\manager(); if (!empty($USER->policyagreed)) { $status = false; $warnings[] = array( 'item' => 'user', 'itemid' => $USER->id, 'warningcode' => 'alreadyagreed', 'message' => 'The user already agreed the site policy.' ); } else if (!$manager->is_defined()) { $status = false; $warnings[] = array( 'item' => 'user', 'itemid' => $USER->id, 'warningcode' => 'nositepolicy', 'message' => 'The site does not have a site policy configured.' ); } else { $status = $manager->accept(); } $result = array(); $result['status'] = $status; $result['warnings'] = $warnings; return $result; }
php
public static function agree_site_policy() { global $CFG, $DB, $USER; $warnings = array(); $context = context_system::instance(); try { // We expect an exception here since the user didn't agree the site policy yet. self::validate_context($context); } catch (Exception $e) { // We are expecting only a sitepolicynotagreed exception. if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') { // In case we receive a different exception, throw it. throw $e; } } $manager = new \core_privacy\local\sitepolicy\manager(); if (!empty($USER->policyagreed)) { $status = false; $warnings[] = array( 'item' => 'user', 'itemid' => $USER->id, 'warningcode' => 'alreadyagreed', 'message' => 'The user already agreed the site policy.' ); } else if (!$manager->is_defined()) { $status = false; $warnings[] = array( 'item' => 'user', 'itemid' => $USER->id, 'warningcode' => 'nositepolicy', 'message' => 'The site does not have a site policy configured.' ); } else { $status = $manager->accept(); } $result = array(); $result['status'] = $status; $result['warnings'] = $warnings; return $result; }
[ "public", "static", "function", "agree_site_policy", "(", ")", "{", "global", "$", "CFG", ",", "$", "DB", ",", "$", "USER", ";", "$", "warnings", "=", "array", "(", ")", ";", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "try", "{", "// We expect an exception here since the user didn't agree the site policy yet.", "self", "::", "validate_context", "(", "$", "context", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// We are expecting only a sitepolicynotagreed exception.", "if", "(", "!", "(", "$", "e", "instanceof", "moodle_exception", ")", "or", "$", "e", "->", "errorcode", "!=", "'sitepolicynotagreed'", ")", "{", "// In case we receive a different exception, throw it.", "throw", "$", "e", ";", "}", "}", "$", "manager", "=", "new", "\\", "core_privacy", "\\", "local", "\\", "sitepolicy", "\\", "manager", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "USER", "->", "policyagreed", ")", ")", "{", "$", "status", "=", "false", ";", "$", "warnings", "[", "]", "=", "array", "(", "'item'", "=>", "'user'", ",", "'itemid'", "=>", "$", "USER", "->", "id", ",", "'warningcode'", "=>", "'alreadyagreed'", ",", "'message'", "=>", "'The user already agreed the site policy.'", ")", ";", "}", "else", "if", "(", "!", "$", "manager", "->", "is_defined", "(", ")", ")", "{", "$", "status", "=", "false", ";", "$", "warnings", "[", "]", "=", "array", "(", "'item'", "=>", "'user'", ",", "'itemid'", "=>", "$", "USER", "->", "id", ",", "'warningcode'", "=>", "'nositepolicy'", ",", "'message'", "=>", "'The site does not have a site policy configured.'", ")", ";", "}", "else", "{", "$", "status", "=", "$", "manager", "->", "accept", "(", ")", ";", "}", "$", "result", "=", "array", "(", ")", ";", "$", "result", "[", "'status'", "]", "=", "$", "status", ";", "$", "result", "[", "'warnings'", "]", "=", "$", "warnings", ";", "return", "$", "result", ";", "}" ]
Agree the site policy for the current user. @return array of warnings and status result @since Moodle 3.2 @throws moodle_exception
[ "Agree", "the", "site", "policy", "for", "the", "current", "user", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/externallib.php#L1875-L1917