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
218,900
moodle/moodle
user/profile/field/menu/field.class.php
profile_field_menu.edit_field_add
public function edit_field_add($mform) { $mform->addElement('select', $this->inputname, format_string($this->field->name), $this->options); }
php
public function edit_field_add($mform) { $mform->addElement('select', $this->inputname, format_string($this->field->name), $this->options); }
[ "public", "function", "edit_field_add", "(", "$", "mform", ")", "{", "$", "mform", "->", "addElement", "(", "'select'", ",", "$", "this", "->", "inputname", ",", "format_string", "(", "$", "this", "->", "field", "->", "name", ")", ",", "$", "this", "->", "options", ")", ";", "}" ]
Create the code snippet for this field instance Overwrites the base class method @param moodleform $mform Moodle form instance
[ "Create", "the", "code", "snippet", "for", "this", "field", "instance", "Overwrites", "the", "base", "class", "method" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/profile/field/menu/field.class.php#L82-L84
218,901
moodle/moodle
user/profile/field/menu/field.class.php
profile_field_menu.edit_field_set_default
public function edit_field_set_default($mform) { $key = $this->field->defaultdata; if (isset($this->options[$key]) || ($key = array_search($key, $this->options)) !== false){ $defaultkey = $key; } else { $defaultkey = ''; } $mform->setDefault($this->inputname, $defaultkey); }
php
public function edit_field_set_default($mform) { $key = $this->field->defaultdata; if (isset($this->options[$key]) || ($key = array_search($key, $this->options)) !== false){ $defaultkey = $key; } else { $defaultkey = ''; } $mform->setDefault($this->inputname, $defaultkey); }
[ "public", "function", "edit_field_set_default", "(", "$", "mform", ")", "{", "$", "key", "=", "$", "this", "->", "field", "->", "defaultdata", ";", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "$", "key", "]", ")", "||", "(", "$", "key", "=", "array_search", "(", "$", "key", ",", "$", "this", "->", "options", ")", ")", "!==", "false", ")", "{", "$", "defaultkey", "=", "$", "key", ";", "}", "else", "{", "$", "defaultkey", "=", "''", ";", "}", "$", "mform", "->", "setDefault", "(", "$", "this", "->", "inputname", ",", "$", "defaultkey", ")", ";", "}" ]
Set the default value for this field instance Overwrites the base class method. @param moodleform $mform Moodle form instance
[ "Set", "the", "default", "value", "for", "this", "field", "instance", "Overwrites", "the", "base", "class", "method", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/profile/field/menu/field.class.php#L91-L99
218,902
moodle/moodle
blocks/recent_activity/block_recent_activity.php
block_recent_activity.get_content
function get_content() { if ($this->content !== NULL) { return $this->content; } if (empty($this->instance)) { $this->content = ''; return $this->content; } $this->content = new stdClass; $this->content->text = ''; $this->content->footer = ''; $renderer = $this->page->get_renderer('block_recent_activity'); $this->content->text = $renderer->recent_activity($this->page->course, $this->get_timestart(), $this->get_recent_enrolments(), $this->get_structural_changes(), $this->get_modules_recent_activity()); return $this->content; }
php
function get_content() { if ($this->content !== NULL) { return $this->content; } if (empty($this->instance)) { $this->content = ''; return $this->content; } $this->content = new stdClass; $this->content->text = ''; $this->content->footer = ''; $renderer = $this->page->get_renderer('block_recent_activity'); $this->content->text = $renderer->recent_activity($this->page->course, $this->get_timestart(), $this->get_recent_enrolments(), $this->get_structural_changes(), $this->get_modules_recent_activity()); return $this->content; }
[ "function", "get_content", "(", ")", "{", "if", "(", "$", "this", "->", "content", "!==", "NULL", ")", "{", "return", "$", "this", "->", "content", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "instance", ")", ")", "{", "$", "this", "->", "content", "=", "''", ";", "return", "$", "this", "->", "content", ";", "}", "$", "this", "->", "content", "=", "new", "stdClass", ";", "$", "this", "->", "content", "->", "text", "=", "''", ";", "$", "this", "->", "content", "->", "footer", "=", "''", ";", "$", "renderer", "=", "$", "this", "->", "page", "->", "get_renderer", "(", "'block_recent_activity'", ")", ";", "$", "this", "->", "content", "->", "text", "=", "$", "renderer", "->", "recent_activity", "(", "$", "this", "->", "page", "->", "course", ",", "$", "this", "->", "get_timestart", "(", ")", ",", "$", "this", "->", "get_recent_enrolments", "(", ")", ",", "$", "this", "->", "get_structural_changes", "(", ")", ",", "$", "this", "->", "get_modules_recent_activity", "(", ")", ")", ";", "return", "$", "this", "->", "content", ";", "}" ]
Returns the content object @return stdObject
[ "Returns", "the", "content", "object" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/recent_activity/block_recent_activity.php#L55-L77
218,903
moodle/moodle
blocks/recent_activity/block_recent_activity.php
block_recent_activity.get_timestart
protected function get_timestart() { global $USER; if ($this->timestart === null) { $this->timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds if (!isguestuser()) { if (!empty($USER->lastcourseaccess[$this->page->course->id])) { if ($USER->lastcourseaccess[$this->page->course->id] > $this->timestart) { $this->timestart = $USER->lastcourseaccess[$this->page->course->id]; } } } } return $this->timestart; }
php
protected function get_timestart() { global $USER; if ($this->timestart === null) { $this->timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds if (!isguestuser()) { if (!empty($USER->lastcourseaccess[$this->page->course->id])) { if ($USER->lastcourseaccess[$this->page->course->id] > $this->timestart) { $this->timestart = $USER->lastcourseaccess[$this->page->course->id]; } } } } return $this->timestart; }
[ "protected", "function", "get_timestart", "(", ")", "{", "global", "$", "USER", ";", "if", "(", "$", "this", "->", "timestart", "===", "null", ")", "{", "$", "this", "->", "timestart", "=", "round", "(", "time", "(", ")", "-", "COURSE_MAX_RECENT_PERIOD", ",", "-", "2", ")", ";", "// better db caching for guests - 100 seconds", "if", "(", "!", "isguestuser", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "USER", "->", "lastcourseaccess", "[", "$", "this", "->", "page", "->", "course", "->", "id", "]", ")", ")", "{", "if", "(", "$", "USER", "->", "lastcourseaccess", "[", "$", "this", "->", "page", "->", "course", "->", "id", "]", ">", "$", "this", "->", "timestart", ")", "{", "$", "this", "->", "timestart", "=", "$", "USER", "->", "lastcourseaccess", "[", "$", "this", "->", "page", "->", "course", "->", "id", "]", ";", "}", "}", "}", "}", "return", "$", "this", "->", "timestart", ";", "}" ]
Returns the time since when we want to show recent activity For guest users it is 2 days, for registered users it is the time of last access to the course @return int
[ "Returns", "the", "time", "since", "when", "we", "want", "to", "show", "recent", "activity" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/recent_activity/block_recent_activity.php#L86-L100
218,904
moodle/moodle
blocks/recent_activity/block_recent_activity.php
block_recent_activity.get_structural_changes
protected function get_structural_changes() { global $DB; $course = $this->page->course; $context = context_course::instance($course->id); $canviewdeleted = has_capability('block/recent_activity:viewdeletemodule', $context); $canviewupdated = has_capability('block/recent_activity:viewaddupdatemodule', $context); if (!$canviewdeleted && !$canviewupdated) { return; } $timestart = $this->get_timestart(); $changelist = array(); // The following query will retrieve the latest action for each course module in the specified course. // Also the query filters out the modules that were created and then deleted during the given interval. $sql = "SELECT cmid, MIN(action) AS minaction, MAX(action) AS maxaction, MAX(modname) AS modname FROM {block_recent_activity} WHERE timecreated > ? AND courseid = ? GROUP BY cmid ORDER BY MAX(timecreated) ASC"; $params = array($timestart, $course->id); $logs = $DB->get_records_sql($sql, $params); if (isset($logs[0])) { // If special record for this course and cmid=0 is present, migrate logs. self::migrate_logs($course); $logs = $DB->get_records_sql($sql, $params); } if ($logs) { $modinfo = get_fast_modinfo($course); foreach ($logs as $log) { // We used aggregate functions since constants CM_CREATED, CM_UPDATED and CM_DELETED have ascending order (0,1,2). $wasdeleted = ($log->maxaction == block_recent_activity_observer::CM_DELETED); $wascreated = ($log->minaction == block_recent_activity_observer::CM_CREATED); if ($wasdeleted && $wascreated) { // Activity was created and deleted within this interval. Do not show it. continue; } else if ($wasdeleted && $canviewdeleted) { if (plugin_supports('mod', $log->modname, FEATURE_NO_VIEW_LINK, false)) { // Better to call cm_info::has_view() because it can be dynamic. // But there is no instance of cm_info now. continue; } // Unfortunately we do not know if the mod was visible. $modnames = get_module_types_names(); $changelist[$log->cmid] = array('action' => 'delete mod', 'module' => (object)array( 'modname' => $log->modname, 'modfullname' => isset($modnames[$log->modname]) ? $modnames[$log->modname] : $log->modname )); } else if (!$wasdeleted && isset($modinfo->cms[$log->cmid]) && $canviewupdated) { // Module was either added or updated during this interval and it currently exists. // If module was both added and updated show only "add" action. $cm = $modinfo->cms[$log->cmid]; if ($cm->has_view() && $cm->uservisible) { $changelist[$log->cmid] = array( 'action' => $wascreated ? 'add mod' : 'update mod', 'module' => $cm ); } } } } return $changelist; }
php
protected function get_structural_changes() { global $DB; $course = $this->page->course; $context = context_course::instance($course->id); $canviewdeleted = has_capability('block/recent_activity:viewdeletemodule', $context); $canviewupdated = has_capability('block/recent_activity:viewaddupdatemodule', $context); if (!$canviewdeleted && !$canviewupdated) { return; } $timestart = $this->get_timestart(); $changelist = array(); // The following query will retrieve the latest action for each course module in the specified course. // Also the query filters out the modules that were created and then deleted during the given interval. $sql = "SELECT cmid, MIN(action) AS minaction, MAX(action) AS maxaction, MAX(modname) AS modname FROM {block_recent_activity} WHERE timecreated > ? AND courseid = ? GROUP BY cmid ORDER BY MAX(timecreated) ASC"; $params = array($timestart, $course->id); $logs = $DB->get_records_sql($sql, $params); if (isset($logs[0])) { // If special record for this course and cmid=0 is present, migrate logs. self::migrate_logs($course); $logs = $DB->get_records_sql($sql, $params); } if ($logs) { $modinfo = get_fast_modinfo($course); foreach ($logs as $log) { // We used aggregate functions since constants CM_CREATED, CM_UPDATED and CM_DELETED have ascending order (0,1,2). $wasdeleted = ($log->maxaction == block_recent_activity_observer::CM_DELETED); $wascreated = ($log->minaction == block_recent_activity_observer::CM_CREATED); if ($wasdeleted && $wascreated) { // Activity was created and deleted within this interval. Do not show it. continue; } else if ($wasdeleted && $canviewdeleted) { if (plugin_supports('mod', $log->modname, FEATURE_NO_VIEW_LINK, false)) { // Better to call cm_info::has_view() because it can be dynamic. // But there is no instance of cm_info now. continue; } // Unfortunately we do not know if the mod was visible. $modnames = get_module_types_names(); $changelist[$log->cmid] = array('action' => 'delete mod', 'module' => (object)array( 'modname' => $log->modname, 'modfullname' => isset($modnames[$log->modname]) ? $modnames[$log->modname] : $log->modname )); } else if (!$wasdeleted && isset($modinfo->cms[$log->cmid]) && $canviewupdated) { // Module was either added or updated during this interval and it currently exists. // If module was both added and updated show only "add" action. $cm = $modinfo->cms[$log->cmid]; if ($cm->has_view() && $cm->uservisible) { $changelist[$log->cmid] = array( 'action' => $wascreated ? 'add mod' : 'update mod', 'module' => $cm ); } } } } return $changelist; }
[ "protected", "function", "get_structural_changes", "(", ")", "{", "global", "$", "DB", ";", "$", "course", "=", "$", "this", "->", "page", "->", "course", ";", "$", "context", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "$", "canviewdeleted", "=", "has_capability", "(", "'block/recent_activity:viewdeletemodule'", ",", "$", "context", ")", ";", "$", "canviewupdated", "=", "has_capability", "(", "'block/recent_activity:viewaddupdatemodule'", ",", "$", "context", ")", ";", "if", "(", "!", "$", "canviewdeleted", "&&", "!", "$", "canviewupdated", ")", "{", "return", ";", "}", "$", "timestart", "=", "$", "this", "->", "get_timestart", "(", ")", ";", "$", "changelist", "=", "array", "(", ")", ";", "// The following query will retrieve the latest action for each course module in the specified course.", "// Also the query filters out the modules that were created and then deleted during the given interval.", "$", "sql", "=", "\"SELECT\n cmid, MIN(action) AS minaction, MAX(action) AS maxaction, MAX(modname) AS modname\n FROM {block_recent_activity}\n WHERE timecreated > ? AND courseid = ?\n GROUP BY cmid\n ORDER BY MAX(timecreated) ASC\"", ";", "$", "params", "=", "array", "(", "$", "timestart", ",", "$", "course", "->", "id", ")", ";", "$", "logs", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "if", "(", "isset", "(", "$", "logs", "[", "0", "]", ")", ")", "{", "// If special record for this course and cmid=0 is present, migrate logs.", "self", "::", "migrate_logs", "(", "$", "course", ")", ";", "$", "logs", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "}", "if", "(", "$", "logs", ")", "{", "$", "modinfo", "=", "get_fast_modinfo", "(", "$", "course", ")", ";", "foreach", "(", "$", "logs", "as", "$", "log", ")", "{", "// We used aggregate functions since constants CM_CREATED, CM_UPDATED and CM_DELETED have ascending order (0,1,2).", "$", "wasdeleted", "=", "(", "$", "log", "->", "maxaction", "==", "block_recent_activity_observer", "::", "CM_DELETED", ")", ";", "$", "wascreated", "=", "(", "$", "log", "->", "minaction", "==", "block_recent_activity_observer", "::", "CM_CREATED", ")", ";", "if", "(", "$", "wasdeleted", "&&", "$", "wascreated", ")", "{", "// Activity was created and deleted within this interval. Do not show it.", "continue", ";", "}", "else", "if", "(", "$", "wasdeleted", "&&", "$", "canviewdeleted", ")", "{", "if", "(", "plugin_supports", "(", "'mod'", ",", "$", "log", "->", "modname", ",", "FEATURE_NO_VIEW_LINK", ",", "false", ")", ")", "{", "// Better to call cm_info::has_view() because it can be dynamic.", "// But there is no instance of cm_info now.", "continue", ";", "}", "// Unfortunately we do not know if the mod was visible.", "$", "modnames", "=", "get_module_types_names", "(", ")", ";", "$", "changelist", "[", "$", "log", "->", "cmid", "]", "=", "array", "(", "'action'", "=>", "'delete mod'", ",", "'module'", "=>", "(", "object", ")", "array", "(", "'modname'", "=>", "$", "log", "->", "modname", ",", "'modfullname'", "=>", "isset", "(", "$", "modnames", "[", "$", "log", "->", "modname", "]", ")", "?", "$", "modnames", "[", "$", "log", "->", "modname", "]", ":", "$", "log", "->", "modname", ")", ")", ";", "}", "else", "if", "(", "!", "$", "wasdeleted", "&&", "isset", "(", "$", "modinfo", "->", "cms", "[", "$", "log", "->", "cmid", "]", ")", "&&", "$", "canviewupdated", ")", "{", "// Module was either added or updated during this interval and it currently exists.", "// If module was both added and updated show only \"add\" action.", "$", "cm", "=", "$", "modinfo", "->", "cms", "[", "$", "log", "->", "cmid", "]", ";", "if", "(", "$", "cm", "->", "has_view", "(", ")", "&&", "$", "cm", "->", "uservisible", ")", "{", "$", "changelist", "[", "$", "log", "->", "cmid", "]", "=", "array", "(", "'action'", "=>", "$", "wascreated", "?", "'add mod'", ":", "'update mod'", ",", "'module'", "=>", "$", "cm", ")", ";", "}", "}", "}", "}", "return", "$", "changelist", ";", "}" ]
Returns list of recent changes in course structure It includes adding, editing or deleting of the resources or activities Excludes changes on modules without a view link (i.e. labels), and also if activity was both added and deleted @return array array of changes. Each element is an array containing attributes: 'action' - one of: 'add mod', 'update mod', 'delete mod' 'module' - instance of cm_info (for 'delete mod' it is an object with attributes modname and modfullname)
[ "Returns", "list", "of", "recent", "changes", "in", "course", "structure" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/recent_activity/block_recent_activity.php#L127-L192
218,905
moodle/moodle
blocks/recent_activity/block_recent_activity.php
block_recent_activity.get_modules_recent_activity
protected function get_modules_recent_activity() { $context = context_course::instance($this->page->course->id); $viewfullnames = has_capability('moodle/site:viewfullnames', $context); $hascontent = false; $modinfo = get_fast_modinfo($this->page->course); $usedmodules = $modinfo->get_used_module_names(); $recentactivity = array(); foreach ($usedmodules as $modname => $modfullname) { // Each module gets it's own logs and prints them ob_start(); $hascontent = component_callback('mod_'. $modname, 'print_recent_activity', array($this->page->course, $viewfullnames, $this->get_timestart()), false); if ($hascontent) { $recentactivity[$modname] = ob_get_contents(); } ob_end_clean(); } return $recentactivity; }
php
protected function get_modules_recent_activity() { $context = context_course::instance($this->page->course->id); $viewfullnames = has_capability('moodle/site:viewfullnames', $context); $hascontent = false; $modinfo = get_fast_modinfo($this->page->course); $usedmodules = $modinfo->get_used_module_names(); $recentactivity = array(); foreach ($usedmodules as $modname => $modfullname) { // Each module gets it's own logs and prints them ob_start(); $hascontent = component_callback('mod_'. $modname, 'print_recent_activity', array($this->page->course, $viewfullnames, $this->get_timestart()), false); if ($hascontent) { $recentactivity[$modname] = ob_get_contents(); } ob_end_clean(); } return $recentactivity; }
[ "protected", "function", "get_modules_recent_activity", "(", ")", "{", "$", "context", "=", "context_course", "::", "instance", "(", "$", "this", "->", "page", "->", "course", "->", "id", ")", ";", "$", "viewfullnames", "=", "has_capability", "(", "'moodle/site:viewfullnames'", ",", "$", "context", ")", ";", "$", "hascontent", "=", "false", ";", "$", "modinfo", "=", "get_fast_modinfo", "(", "$", "this", "->", "page", "->", "course", ")", ";", "$", "usedmodules", "=", "$", "modinfo", "->", "get_used_module_names", "(", ")", ";", "$", "recentactivity", "=", "array", "(", ")", ";", "foreach", "(", "$", "usedmodules", "as", "$", "modname", "=>", "$", "modfullname", ")", "{", "// Each module gets it's own logs and prints them", "ob_start", "(", ")", ";", "$", "hascontent", "=", "component_callback", "(", "'mod_'", ".", "$", "modname", ",", "'print_recent_activity'", ",", "array", "(", "$", "this", "->", "page", "->", "course", ",", "$", "viewfullnames", ",", "$", "this", "->", "get_timestart", "(", ")", ")", ",", "false", ")", ";", "if", "(", "$", "hascontent", ")", "{", "$", "recentactivity", "[", "$", "modname", "]", "=", "ob_get_contents", "(", ")", ";", "}", "ob_end_clean", "(", ")", ";", "}", "return", "$", "recentactivity", ";", "}" ]
Returns list of recent activity within modules For each used module type executes callback MODULE_print_recent_activity() @return array array of pairs moduletype => content
[ "Returns", "list", "of", "recent", "activity", "within", "modules" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/recent_activity/block_recent_activity.php#L201-L220
218,906
moodle/moodle
lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php
PHPExcel_CachedObjectStorage_CacheBase.getSortedCellList
public function getSortedCellList() { $sortKeys = array(); foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; } ksort($sortKeys); return array_values($sortKeys); }
php
public function getSortedCellList() { $sortKeys = array(); foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; } ksort($sortKeys); return array_values($sortKeys); }
[ "public", "function", "getSortedCellList", "(", ")", "{", "$", "sortKeys", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getCellList", "(", ")", "as", "$", "coord", ")", "{", "sscanf", "(", "$", "coord", ",", "'%[A-Z]%d'", ",", "$", "column", ",", "$", "row", ")", ";", "$", "sortKeys", "[", "sprintf", "(", "'%09d%3s'", ",", "$", "row", ",", "$", "column", ")", "]", "=", "$", "coord", ";", "}", "ksort", "(", "$", "sortKeys", ")", ";", "return", "array_values", "(", "$", "sortKeys", ")", ";", "}" ]
Sort the list of all cell addresses currently held in cache by row and column @return string[]
[ "Sort", "the", "list", "of", "all", "cell", "addresses", "currently", "held", "in", "cache", "by", "row", "and", "column" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php#L172-L182
218,907
moodle/moodle
lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php
PHPExcel_CachedObjectStorage_CacheBase.getHighestRowAndColumn
public function getHighestRowAndColumn() { // Lookup highest column and highest row $col = array('A' => '1A'); $row = array(1); foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); $row[$r] = $r; $col[$c] = strlen($c).$c; } if (!empty($row)) { // Determine highest column and row $highestRow = max($row); $highestColumn = substr(max($col), 1); } return array( 'row' => $highestRow, 'column' => $highestColumn ); }
php
public function getHighestRowAndColumn() { // Lookup highest column and highest row $col = array('A' => '1A'); $row = array(1); foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); $row[$r] = $r; $col[$c] = strlen($c).$c; } if (!empty($row)) { // Determine highest column and row $highestRow = max($row); $highestColumn = substr(max($col), 1); } return array( 'row' => $highestRow, 'column' => $highestColumn ); }
[ "public", "function", "getHighestRowAndColumn", "(", ")", "{", "// Lookup highest column and highest row", "$", "col", "=", "array", "(", "'A'", "=>", "'1A'", ")", ";", "$", "row", "=", "array", "(", "1", ")", ";", "foreach", "(", "$", "this", "->", "getCellList", "(", ")", "as", "$", "coord", ")", "{", "sscanf", "(", "$", "coord", ",", "'%[A-Z]%d'", ",", "$", "c", ",", "$", "r", ")", ";", "$", "row", "[", "$", "r", "]", "=", "$", "r", ";", "$", "col", "[", "$", "c", "]", "=", "strlen", "(", "$", "c", ")", ".", "$", "c", ";", "}", "if", "(", "!", "empty", "(", "$", "row", ")", ")", "{", "// Determine highest column and row", "$", "highestRow", "=", "max", "(", "$", "row", ")", ";", "$", "highestColumn", "=", "substr", "(", "max", "(", "$", "col", ")", ",", "1", ")", ";", "}", "return", "array", "(", "'row'", "=>", "$", "highestRow", ",", "'column'", "=>", "$", "highestColumn", ")", ";", "}" ]
Get highest worksheet column and highest row that have cell records @return array Highest column name and highest row number
[ "Get", "highest", "worksheet", "column", "and", "highest", "row", "that", "have", "cell", "records" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php#L189-L209
218,908
moodle/moodle
lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php
PHPExcel_CachedObjectStorage_CacheBase.removeRow
public function removeRow($row) { foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($r == $row) { $this->deleteCacheData($coord); } } }
php
public function removeRow($row) { foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($r == $row) { $this->deleteCacheData($coord); } } }
[ "public", "function", "removeRow", "(", "$", "row", ")", "{", "foreach", "(", "$", "this", "->", "getCellList", "(", ")", "as", "$", "coord", ")", "{", "sscanf", "(", "$", "coord", ",", "'%[A-Z]%d'", ",", "$", "c", ",", "$", "r", ")", ";", "if", "(", "$", "r", "==", "$", "row", ")", "{", "$", "this", "->", "deleteCacheData", "(", "$", "coord", ")", ";", "}", "}", "}" ]
Remove a row, deleting all cells in that row @param string $row Row number to remove @return void
[ "Remove", "a", "row", "deleting", "all", "cells", "in", "that", "row" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php#L332-L340
218,909
moodle/moodle
lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php
PHPExcel_CachedObjectStorage_CacheBase.removeColumn
public function removeColumn($column) { foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($c == $column) { $this->deleteCacheData($coord); } } }
php
public function removeColumn($column) { foreach ($this->getCellList() as $coord) { sscanf($coord, '%[A-Z]%d', $c, $r); if ($c == $column) { $this->deleteCacheData($coord); } } }
[ "public", "function", "removeColumn", "(", "$", "column", ")", "{", "foreach", "(", "$", "this", "->", "getCellList", "(", ")", "as", "$", "coord", ")", "{", "sscanf", "(", "$", "coord", ",", "'%[A-Z]%d'", ",", "$", "c", ",", "$", "r", ")", ";", "if", "(", "$", "c", "==", "$", "column", ")", "{", "$", "this", "->", "deleteCacheData", "(", "$", "coord", ")", ";", "}", "}", "}" ]
Remove a column, deleting all cells in that column @param string $column Column ID to remove @return void
[ "Remove", "a", "column", "deleting", "all", "cells", "in", "that", "column" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel/CachedObjectStorage/CacheBase.php#L348-L356
218,910
moodle/moodle
cache/stores/redis/addinstanceform.php
cachestore_redis_addinstance_form.configuration_definition
protected function configuration_definition() { $form = $this->_form; $form->addElement('text', 'server', get_string('server', 'cachestore_redis'), array('size' => 24)); $form->setType('server', PARAM_TEXT); $form->addHelpButton('server', 'server', 'cachestore_redis'); $form->addRule('server', get_string('required'), 'required'); $form->addElement('passwordunmask', 'password', get_string('password', 'cachestore_redis')); $form->setType('password', PARAM_RAW); $form->addHelpButton('password', 'password', 'cachestore_redis'); $form->addElement('text', 'prefix', get_string('prefix', 'cachestore_redis'), array('size' => 16)); $form->setType('prefix', PARAM_TEXT); // We set to text but we have a rule to limit to alphanumext. $form->addHelpButton('prefix', 'prefix', 'cachestore_redis'); $form->addRule('prefix', get_string('prefixinvalid', 'cachestore_redis'), 'regex', '#^[a-zA-Z0-9\-_]+$#'); $serializeroptions = cachestore_redis::config_get_serializer_options(); $form->addElement('select', 'serializer', get_string('useserializer', 'cachestore_redis'), $serializeroptions); $form->addHelpButton('serializer', 'useserializer', 'cachestore_redis'); $form->setDefault('serializer', Redis::SERIALIZER_PHP); $form->setType('serializer', PARAM_INT); }
php
protected function configuration_definition() { $form = $this->_form; $form->addElement('text', 'server', get_string('server', 'cachestore_redis'), array('size' => 24)); $form->setType('server', PARAM_TEXT); $form->addHelpButton('server', 'server', 'cachestore_redis'); $form->addRule('server', get_string('required'), 'required'); $form->addElement('passwordunmask', 'password', get_string('password', 'cachestore_redis')); $form->setType('password', PARAM_RAW); $form->addHelpButton('password', 'password', 'cachestore_redis'); $form->addElement('text', 'prefix', get_string('prefix', 'cachestore_redis'), array('size' => 16)); $form->setType('prefix', PARAM_TEXT); // We set to text but we have a rule to limit to alphanumext. $form->addHelpButton('prefix', 'prefix', 'cachestore_redis'); $form->addRule('prefix', get_string('prefixinvalid', 'cachestore_redis'), 'regex', '#^[a-zA-Z0-9\-_]+$#'); $serializeroptions = cachestore_redis::config_get_serializer_options(); $form->addElement('select', 'serializer', get_string('useserializer', 'cachestore_redis'), $serializeroptions); $form->addHelpButton('serializer', 'useserializer', 'cachestore_redis'); $form->setDefault('serializer', Redis::SERIALIZER_PHP); $form->setType('serializer', PARAM_INT); }
[ "protected", "function", "configuration_definition", "(", ")", "{", "$", "form", "=", "$", "this", "->", "_form", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'server'", ",", "get_string", "(", "'server'", ",", "'cachestore_redis'", ")", ",", "array", "(", "'size'", "=>", "24", ")", ")", ";", "$", "form", "->", "setType", "(", "'server'", ",", "PARAM_TEXT", ")", ";", "$", "form", "->", "addHelpButton", "(", "'server'", ",", "'server'", ",", "'cachestore_redis'", ")", ";", "$", "form", "->", "addRule", "(", "'server'", ",", "get_string", "(", "'required'", ")", ",", "'required'", ")", ";", "$", "form", "->", "addElement", "(", "'passwordunmask'", ",", "'password'", ",", "get_string", "(", "'password'", ",", "'cachestore_redis'", ")", ")", ";", "$", "form", "->", "setType", "(", "'password'", ",", "PARAM_RAW", ")", ";", "$", "form", "->", "addHelpButton", "(", "'password'", ",", "'password'", ",", "'cachestore_redis'", ")", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'prefix'", ",", "get_string", "(", "'prefix'", ",", "'cachestore_redis'", ")", ",", "array", "(", "'size'", "=>", "16", ")", ")", ";", "$", "form", "->", "setType", "(", "'prefix'", ",", "PARAM_TEXT", ")", ";", "// We set to text but we have a rule to limit to alphanumext.", "$", "form", "->", "addHelpButton", "(", "'prefix'", ",", "'prefix'", ",", "'cachestore_redis'", ")", ";", "$", "form", "->", "addRule", "(", "'prefix'", ",", "get_string", "(", "'prefixinvalid'", ",", "'cachestore_redis'", ")", ",", "'regex'", ",", "'#^[a-zA-Z0-9\\-_]+$#'", ")", ";", "$", "serializeroptions", "=", "cachestore_redis", "::", "config_get_serializer_options", "(", ")", ";", "$", "form", "->", "addElement", "(", "'select'", ",", "'serializer'", ",", "get_string", "(", "'useserializer'", ",", "'cachestore_redis'", ")", ",", "$", "serializeroptions", ")", ";", "$", "form", "->", "addHelpButton", "(", "'serializer'", ",", "'useserializer'", ",", "'cachestore_redis'", ")", ";", "$", "form", "->", "setDefault", "(", "'serializer'", ",", "Redis", "::", "SERIALIZER_PHP", ")", ";", "$", "form", "->", "setType", "(", "'serializer'", ",", "PARAM_INT", ")", ";", "}" ]
Builds the form for creating an instance.
[ "Builds", "the", "form", "for", "creating", "an", "instance", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/cache/stores/redis/addinstanceform.php#L39-L61
218,911
moodle/moodle
lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php
CachingStrategyFactory.getBestCachingStrategy
public function getBestCachingStrategy($sharedStringsUniqueCount, $tempFolder = null) { if ($this->isInMemoryStrategyUsageSafe($sharedStringsUniqueCount)) { return new InMemoryStrategy($sharedStringsUniqueCount); } else { return new FileBasedStrategy($tempFolder, self::MAX_NUM_STRINGS_PER_TEMP_FILE); } }
php
public function getBestCachingStrategy($sharedStringsUniqueCount, $tempFolder = null) { if ($this->isInMemoryStrategyUsageSafe($sharedStringsUniqueCount)) { return new InMemoryStrategy($sharedStringsUniqueCount); } else { return new FileBasedStrategy($tempFolder, self::MAX_NUM_STRINGS_PER_TEMP_FILE); } }
[ "public", "function", "getBestCachingStrategy", "(", "$", "sharedStringsUniqueCount", ",", "$", "tempFolder", "=", "null", ")", "{", "if", "(", "$", "this", "->", "isInMemoryStrategyUsageSafe", "(", "$", "sharedStringsUniqueCount", ")", ")", "{", "return", "new", "InMemoryStrategy", "(", "$", "sharedStringsUniqueCount", ")", ";", "}", "else", "{", "return", "new", "FileBasedStrategy", "(", "$", "tempFolder", ",", "self", "::", "MAX_NUM_STRINGS_PER_TEMP_FILE", ")", ";", "}", "}" ]
Returns the best caching strategy, given the number of unique shared strings and the amount of memory available. @param int|null $sharedStringsUniqueCount Number of unique shared strings (NULL if unknown) @param string|void $tempFolder Temporary folder where the temporary files to store shared strings will be stored @return CachingStrategyInterface The best caching strategy
[ "Returns", "the", "best", "caching", "strategy", "given", "the", "number", "of", "unique", "shared", "strings", "and", "the", "amount", "of", "memory", "available", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php#L85-L92
218,912
moodle/moodle
lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php
CachingStrategyFactory.isInMemoryStrategyUsageSafe
protected function isInMemoryStrategyUsageSafe($sharedStringsUniqueCount) { // if the number of shared strings in unknown, do not use "in memory" strategy if ($sharedStringsUniqueCount === null) { return false; } $memoryAvailable = $this->getMemoryLimitInKB(); if ($memoryAvailable === -1) { // if cannot get memory limit or if memory limit set as unlimited, don't trust and play safe return ($sharedStringsUniqueCount < self::MAX_NUM_STRINGS_PER_TEMP_FILE); } else { $memoryNeeded = $sharedStringsUniqueCount * self::AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB; return ($memoryAvailable > $memoryNeeded); } }
php
protected function isInMemoryStrategyUsageSafe($sharedStringsUniqueCount) { // if the number of shared strings in unknown, do not use "in memory" strategy if ($sharedStringsUniqueCount === null) { return false; } $memoryAvailable = $this->getMemoryLimitInKB(); if ($memoryAvailable === -1) { // if cannot get memory limit or if memory limit set as unlimited, don't trust and play safe return ($sharedStringsUniqueCount < self::MAX_NUM_STRINGS_PER_TEMP_FILE); } else { $memoryNeeded = $sharedStringsUniqueCount * self::AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB; return ($memoryAvailable > $memoryNeeded); } }
[ "protected", "function", "isInMemoryStrategyUsageSafe", "(", "$", "sharedStringsUniqueCount", ")", "{", "// if the number of shared strings in unknown, do not use \"in memory\" strategy", "if", "(", "$", "sharedStringsUniqueCount", "===", "null", ")", "{", "return", "false", ";", "}", "$", "memoryAvailable", "=", "$", "this", "->", "getMemoryLimitInKB", "(", ")", ";", "if", "(", "$", "memoryAvailable", "===", "-", "1", ")", "{", "// if cannot get memory limit or if memory limit set as unlimited, don't trust and play safe", "return", "(", "$", "sharedStringsUniqueCount", "<", "self", "::", "MAX_NUM_STRINGS_PER_TEMP_FILE", ")", ";", "}", "else", "{", "$", "memoryNeeded", "=", "$", "sharedStringsUniqueCount", "*", "self", "::", "AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB", ";", "return", "(", "$", "memoryAvailable", ">", "$", "memoryNeeded", ")", ";", "}", "}" ]
Returns whether it is safe to use in-memory caching, given the number of unique shared strings and the amount of memory available. @param int|null $sharedStringsUniqueCount Number of unique shared strings (NULL if unknown) @return bool
[ "Returns", "whether", "it", "is", "safe", "to", "use", "in", "-", "memory", "caching", "given", "the", "number", "of", "unique", "shared", "strings", "and", "the", "amount", "of", "memory", "available", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php#L101-L117
218,913
moodle/moodle
lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php
CachingStrategyFactory.getMemoryLimitInKB
protected function getMemoryLimitInKB() { $memoryLimitFormatted = $this->getMemoryLimitFromIni(); $memoryLimitFormatted = strtolower(trim($memoryLimitFormatted)); // No memory limit if ($memoryLimitFormatted === '-1') { return -1; } if (preg_match('/(\d+)([bkmgt])b?/', $memoryLimitFormatted, $matches)) { $amount = intval($matches[1]); $unit = $matches[2]; switch ($unit) { case 'b': return ($amount / 1024); case 'k': return $amount; case 'm': return ($amount * 1024); case 'g': return ($amount * 1024 * 1024); case 't': return ($amount * 1024 * 1024 * 1024); } } return -1; }
php
protected function getMemoryLimitInKB() { $memoryLimitFormatted = $this->getMemoryLimitFromIni(); $memoryLimitFormatted = strtolower(trim($memoryLimitFormatted)); // No memory limit if ($memoryLimitFormatted === '-1') { return -1; } if (preg_match('/(\d+)([bkmgt])b?/', $memoryLimitFormatted, $matches)) { $amount = intval($matches[1]); $unit = $matches[2]; switch ($unit) { case 'b': return ($amount / 1024); case 'k': return $amount; case 'm': return ($amount * 1024); case 'g': return ($amount * 1024 * 1024); case 't': return ($amount * 1024 * 1024 * 1024); } } return -1; }
[ "protected", "function", "getMemoryLimitInKB", "(", ")", "{", "$", "memoryLimitFormatted", "=", "$", "this", "->", "getMemoryLimitFromIni", "(", ")", ";", "$", "memoryLimitFormatted", "=", "strtolower", "(", "trim", "(", "$", "memoryLimitFormatted", ")", ")", ";", "// No memory limit", "if", "(", "$", "memoryLimitFormatted", "===", "'-1'", ")", "{", "return", "-", "1", ";", "}", "if", "(", "preg_match", "(", "'/(\\d+)([bkmgt])b?/'", ",", "$", "memoryLimitFormatted", ",", "$", "matches", ")", ")", "{", "$", "amount", "=", "intval", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "unit", "=", "$", "matches", "[", "2", "]", ";", "switch", "(", "$", "unit", ")", "{", "case", "'b'", ":", "return", "(", "$", "amount", "/", "1024", ")", ";", "case", "'k'", ":", "return", "$", "amount", ";", "case", "'m'", ":", "return", "(", "$", "amount", "*", "1024", ")", ";", "case", "'g'", ":", "return", "(", "$", "amount", "*", "1024", "*", "1024", ")", ";", "case", "'t'", ":", "return", "(", "$", "amount", "*", "1024", "*", "1024", "*", "1024", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Returns the PHP "memory_limit" in Kilobytes @return float
[ "Returns", "the", "PHP", "memory_limit", "in", "Kilobytes" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/spout/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php#L124-L148
218,914
moodle/moodle
user/classes/privacy/provider.php
provider.delete_user_data
protected static function delete_user_data(int $userid, \context $context) { global $DB; // Delete password history. $DB->delete_records('user_password_history', ['userid' => $userid]); // Delete last access. $DB->delete_records('user_lastaccess', ['userid' => $userid]); // Delete password resets. $DB->delete_records('user_password_resets', ['userid' => $userid]); // Delete user devices. $DB->delete_records('user_devices', ['userid' => $userid]); // Delete user course requests. $DB->delete_records('course_request', ['requester' => $userid]); // Delete sessions. $DB->delete_records('sessions', ['userid' => $userid]); // Do I delete user preferences? Seems like the right place to do it. $DB->delete_records('user_preferences', ['userid' => $userid]); // Delete all of the files for this user. $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user'); // For the user record itself we only want to remove unnecessary data. We still need the core data to keep as a record // that we actually did follow the request to be forgotten. $user = \core_user::get_user($userid); // Update fields we wish to change to nothing. $user->deleted = 1; $user->idnumber = ''; $user->emailstop = 0; $user->icq = ''; $user->skype = ''; $user->yahoo = ''; $user->aim = ''; $user->msn = ''; $user->phone1 = ''; $user->phone2 = ''; $user->institution = ''; $user->department = ''; $user->address = ''; $user->city = ''; $user->country = ''; $user->lang = ''; $user->calendartype = ''; $user->theme = ''; $user->timezone = ''; $user->firstaccess = 0; $user->lastaccess = 0; $user->lastlogin = 0; $user->currentlogin = 0; $user->lastip = 0; $user->secret = ''; $user->picture = ''; $user->url = ''; $user->description = ''; $user->descriptionformat = 0; $user->mailformat = 0; $user->maildigest = 0; $user->maildisplay = 0; $user->autosubscribe = 0; $user->trackforums = 0; $user->timecreated = 0; $user->timemodified = 0; $user->trustbitmask = 0; $user->imagealt = ''; $user->lastnamephonetic = ''; $user->firstnamephonetic = ''; $user->middlename = ''; $user->alternatename = ''; $DB->update_record('user', $user); }
php
protected static function delete_user_data(int $userid, \context $context) { global $DB; // Delete password history. $DB->delete_records('user_password_history', ['userid' => $userid]); // Delete last access. $DB->delete_records('user_lastaccess', ['userid' => $userid]); // Delete password resets. $DB->delete_records('user_password_resets', ['userid' => $userid]); // Delete user devices. $DB->delete_records('user_devices', ['userid' => $userid]); // Delete user course requests. $DB->delete_records('course_request', ['requester' => $userid]); // Delete sessions. $DB->delete_records('sessions', ['userid' => $userid]); // Do I delete user preferences? Seems like the right place to do it. $DB->delete_records('user_preferences', ['userid' => $userid]); // Delete all of the files for this user. $fs = get_file_storage(); $fs->delete_area_files($context->id, 'user'); // For the user record itself we only want to remove unnecessary data. We still need the core data to keep as a record // that we actually did follow the request to be forgotten. $user = \core_user::get_user($userid); // Update fields we wish to change to nothing. $user->deleted = 1; $user->idnumber = ''; $user->emailstop = 0; $user->icq = ''; $user->skype = ''; $user->yahoo = ''; $user->aim = ''; $user->msn = ''; $user->phone1 = ''; $user->phone2 = ''; $user->institution = ''; $user->department = ''; $user->address = ''; $user->city = ''; $user->country = ''; $user->lang = ''; $user->calendartype = ''; $user->theme = ''; $user->timezone = ''; $user->firstaccess = 0; $user->lastaccess = 0; $user->lastlogin = 0; $user->currentlogin = 0; $user->lastip = 0; $user->secret = ''; $user->picture = ''; $user->url = ''; $user->description = ''; $user->descriptionformat = 0; $user->mailformat = 0; $user->maildigest = 0; $user->maildisplay = 0; $user->autosubscribe = 0; $user->trackforums = 0; $user->timecreated = 0; $user->timemodified = 0; $user->trustbitmask = 0; $user->imagealt = ''; $user->lastnamephonetic = ''; $user->firstnamephonetic = ''; $user->middlename = ''; $user->alternatename = ''; $DB->update_record('user', $user); }
[ "protected", "static", "function", "delete_user_data", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ";", "// Delete password history.", "$", "DB", "->", "delete_records", "(", "'user_password_history'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Delete last access.", "$", "DB", "->", "delete_records", "(", "'user_lastaccess'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Delete password resets.", "$", "DB", "->", "delete_records", "(", "'user_password_resets'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Delete user devices.", "$", "DB", "->", "delete_records", "(", "'user_devices'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Delete user course requests.", "$", "DB", "->", "delete_records", "(", "'course_request'", ",", "[", "'requester'", "=>", "$", "userid", "]", ")", ";", "// Delete sessions.", "$", "DB", "->", "delete_records", "(", "'sessions'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Do I delete user preferences? Seems like the right place to do it.", "$", "DB", "->", "delete_records", "(", "'user_preferences'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "// Delete all of the files for this user.", "$", "fs", "=", "get_file_storage", "(", ")", ";", "$", "fs", "->", "delete_area_files", "(", "$", "context", "->", "id", ",", "'user'", ")", ";", "// For the user record itself we only want to remove unnecessary data. We still need the core data to keep as a record", "// that we actually did follow the request to be forgotten.", "$", "user", "=", "\\", "core_user", "::", "get_user", "(", "$", "userid", ")", ";", "// Update fields we wish to change to nothing.", "$", "user", "->", "deleted", "=", "1", ";", "$", "user", "->", "idnumber", "=", "''", ";", "$", "user", "->", "emailstop", "=", "0", ";", "$", "user", "->", "icq", "=", "''", ";", "$", "user", "->", "skype", "=", "''", ";", "$", "user", "->", "yahoo", "=", "''", ";", "$", "user", "->", "aim", "=", "''", ";", "$", "user", "->", "msn", "=", "''", ";", "$", "user", "->", "phone1", "=", "''", ";", "$", "user", "->", "phone2", "=", "''", ";", "$", "user", "->", "institution", "=", "''", ";", "$", "user", "->", "department", "=", "''", ";", "$", "user", "->", "address", "=", "''", ";", "$", "user", "->", "city", "=", "''", ";", "$", "user", "->", "country", "=", "''", ";", "$", "user", "->", "lang", "=", "''", ";", "$", "user", "->", "calendartype", "=", "''", ";", "$", "user", "->", "theme", "=", "''", ";", "$", "user", "->", "timezone", "=", "''", ";", "$", "user", "->", "firstaccess", "=", "0", ";", "$", "user", "->", "lastaccess", "=", "0", ";", "$", "user", "->", "lastlogin", "=", "0", ";", "$", "user", "->", "currentlogin", "=", "0", ";", "$", "user", "->", "lastip", "=", "0", ";", "$", "user", "->", "secret", "=", "''", ";", "$", "user", "->", "picture", "=", "''", ";", "$", "user", "->", "url", "=", "''", ";", "$", "user", "->", "description", "=", "''", ";", "$", "user", "->", "descriptionformat", "=", "0", ";", "$", "user", "->", "mailformat", "=", "0", ";", "$", "user", "->", "maildigest", "=", "0", ";", "$", "user", "->", "maildisplay", "=", "0", ";", "$", "user", "->", "autosubscribe", "=", "0", ";", "$", "user", "->", "trackforums", "=", "0", ";", "$", "user", "->", "timecreated", "=", "0", ";", "$", "user", "->", "timemodified", "=", "0", ";", "$", "user", "->", "trustbitmask", "=", "0", ";", "$", "user", "->", "imagealt", "=", "''", ";", "$", "user", "->", "lastnamephonetic", "=", "''", ";", "$", "user", "->", "firstnamephonetic", "=", "''", ";", "$", "user", "->", "middlename", "=", "''", ";", "$", "user", "->", "alternatename", "=", "''", ";", "$", "DB", "->", "update_record", "(", "'user'", ",", "$", "user", ")", ";", "}" ]
Deletes non vital information about a user. @param int $userid The user ID to delete @param \context $context The user context
[ "Deletes", "non", "vital", "information", "about", "a", "user", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L282-L351
218,915
moodle/moodle
user/classes/privacy/provider.php
provider.export_password_resets
protected static function export_password_resets(int $userid, \context $context) { global $DB; $records = $DB->get_records('user_password_resets', ['userid' => $userid]); if (!empty($records)) { $passwordresets = (object) array_map(function($record) { return [ 'timerequested' => transform::datetime($record->timerequested), 'timererequested' => transform::datetime($record->timererequested) ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:passwordresetpath', 'user')], $passwordresets); } }
php
protected static function export_password_resets(int $userid, \context $context) { global $DB; $records = $DB->get_records('user_password_resets', ['userid' => $userid]); if (!empty($records)) { $passwordresets = (object) array_map(function($record) { return [ 'timerequested' => transform::datetime($record->timerequested), 'timererequested' => transform::datetime($record->timererequested) ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:passwordresetpath', 'user')], $passwordresets); } }
[ "protected", "static", "function", "export_password_resets", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ";", "$", "records", "=", "$", "DB", "->", "get_records", "(", "'user_password_resets'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "records", ")", ")", "{", "$", "passwordresets", "=", "(", "object", ")", "array_map", "(", "function", "(", "$", "record", ")", "{", "return", "[", "'timerequested'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timerequested", ")", ",", "'timererequested'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timererequested", ")", "]", ";", "}", ",", "$", "records", ")", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "[", "get_string", "(", "'privacy:passwordresetpath'", ",", "'user'", ")", "]", ",", "$", "passwordresets", ")", ";", "}", "}" ]
Exports information about password resets. @param int $userid The user ID @param \context $context Context for this user.
[ "Exports", "information", "about", "password", "resets", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L454-L466
218,916
moodle/moodle
user/classes/privacy/provider.php
provider.export_user_devices
protected static function export_user_devices(int $userid, \context $context) { global $DB; $records = $DB->get_records('user_devices', ['userid' => $userid]); if (!empty($records)) { $userdevices = (object) array_map(function($record) { return [ 'appid' => $record->appid, 'name' => $record->name, 'model' => $record->model, 'platform' => $record->platform, 'version' => $record->version, 'timecreated' => transform::datetime($record->timecreated), 'timemodified' => transform::datetime($record->timemodified) ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:devicespath', 'user')], $userdevices); } }
php
protected static function export_user_devices(int $userid, \context $context) { global $DB; $records = $DB->get_records('user_devices', ['userid' => $userid]); if (!empty($records)) { $userdevices = (object) array_map(function($record) { return [ 'appid' => $record->appid, 'name' => $record->name, 'model' => $record->model, 'platform' => $record->platform, 'version' => $record->version, 'timecreated' => transform::datetime($record->timecreated), 'timemodified' => transform::datetime($record->timemodified) ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:devicespath', 'user')], $userdevices); } }
[ "protected", "static", "function", "export_user_devices", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ";", "$", "records", "=", "$", "DB", "->", "get_records", "(", "'user_devices'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "records", ")", ")", "{", "$", "userdevices", "=", "(", "object", ")", "array_map", "(", "function", "(", "$", "record", ")", "{", "return", "[", "'appid'", "=>", "$", "record", "->", "appid", ",", "'name'", "=>", "$", "record", "->", "name", ",", "'model'", "=>", "$", "record", "->", "model", ",", "'platform'", "=>", "$", "record", "->", "platform", ",", "'version'", "=>", "$", "record", "->", "version", ",", "'timecreated'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timecreated", ")", ",", "'timemodified'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timemodified", ")", "]", ";", "}", ",", "$", "records", ")", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "[", "get_string", "(", "'privacy:devicespath'", ",", "'user'", ")", "]", ",", "$", "userdevices", ")", ";", "}", "}" ]
Exports information about the user's mobile devices. @param int $userid The user ID. @param \context $context Context for this user.
[ "Exports", "information", "about", "the", "user", "s", "mobile", "devices", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L474-L491
218,917
moodle/moodle
user/classes/privacy/provider.php
provider.export_course_requests
protected static function export_course_requests(int $userid, \context $context) { global $DB; $sql = "SELECT cr.shortname, cr.fullname, cr.summary, cc.name AS category, cr.reason FROM {course_request} cr JOIN {course_categories} cc ON cr.category = cc.id WHERE cr.requester = :userid"; $params = ['userid' => $userid]; $records = $DB->get_records_sql($sql, $params); if ($records) { writer::with_context($context)->export_data([get_string('privacy:courserequestpath', 'user')], (object) $records); } }
php
protected static function export_course_requests(int $userid, \context $context) { global $DB; $sql = "SELECT cr.shortname, cr.fullname, cr.summary, cc.name AS category, cr.reason FROM {course_request} cr JOIN {course_categories} cc ON cr.category = cc.id WHERE cr.requester = :userid"; $params = ['userid' => $userid]; $records = $DB->get_records_sql($sql, $params); if ($records) { writer::with_context($context)->export_data([get_string('privacy:courserequestpath', 'user')], (object) $records); } }
[ "protected", "static", "function", "export_course_requests", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "\"SELECT cr.shortname, cr.fullname, cr.summary, cc.name AS category, cr.reason\n FROM {course_request} cr\n JOIN {course_categories} cc ON cr.category = cc.id\n WHERE cr.requester = :userid\"", ";", "$", "params", "=", "[", "'userid'", "=>", "$", "userid", "]", ";", "$", "records", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "if", "(", "$", "records", ")", "{", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "[", "get_string", "(", "'privacy:courserequestpath'", ",", "'user'", ")", "]", ",", "(", "object", ")", "$", "records", ")", ";", "}", "}" ]
Exports information about course requests this user made. @param int $userid The user ID. @param \context $context The context object
[ "Exports", "information", "about", "course", "requests", "this", "user", "made", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L499-L510
218,918
moodle/moodle
user/classes/privacy/provider.php
provider.export_password_history
protected static function export_password_history(int $userid, \context $context) { global $DB; // Just provide a count of how many entries we have. $recordcount = $DB->count_records('user_password_history', ['userid' => $userid]); if ($recordcount) { $passwordhistory = (object) ['password_history_count' => $recordcount]; writer::with_context($context)->export_data([get_string('privacy:passwordhistorypath', 'user')], $passwordhistory); } }
php
protected static function export_password_history(int $userid, \context $context) { global $DB; // Just provide a count of how many entries we have. $recordcount = $DB->count_records('user_password_history', ['userid' => $userid]); if ($recordcount) { $passwordhistory = (object) ['password_history_count' => $recordcount]; writer::with_context($context)->export_data([get_string('privacy:passwordhistorypath', 'user')], $passwordhistory); } }
[ "protected", "static", "function", "export_password_history", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ";", "// Just provide a count of how many entries we have.", "$", "recordcount", "=", "$", "DB", "->", "count_records", "(", "'user_password_history'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "if", "(", "$", "recordcount", ")", "{", "$", "passwordhistory", "=", "(", "object", ")", "[", "'password_history_count'", "=>", "$", "recordcount", "]", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "[", "get_string", "(", "'privacy:passwordhistorypath'", ",", "'user'", ")", "]", ",", "$", "passwordhistory", ")", ";", "}", "}" ]
Get details about the user's password history. @param int $userid The user ID that we are getting the password history for. @param \context $context the user context.
[ "Get", "details", "about", "the", "user", "s", "password", "history", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L518-L527
218,919
moodle/moodle
user/classes/privacy/provider.php
provider.export_user_session_data
protected static function export_user_session_data(int $userid, \context $context) { global $DB, $SESSION; $records = $DB->get_records('sessions', ['userid' => $userid]); if (!empty($records)) { $sessiondata = (object) array_map(function($record) { return [ 'state' => $record->state, 'sessdata' => base64_decode($record->sessdata), 'timecreated' => transform::datetime($record->timecreated), 'timemodified' => transform::datetime($record->timemodified), 'firstip' => $record->firstip, 'lastip' => $record->lastip ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:sessionpath', 'user')], $sessiondata); } }
php
protected static function export_user_session_data(int $userid, \context $context) { global $DB, $SESSION; $records = $DB->get_records('sessions', ['userid' => $userid]); if (!empty($records)) { $sessiondata = (object) array_map(function($record) { return [ 'state' => $record->state, 'sessdata' => base64_decode($record->sessdata), 'timecreated' => transform::datetime($record->timecreated), 'timemodified' => transform::datetime($record->timemodified), 'firstip' => $record->firstip, 'lastip' => $record->lastip ]; }, $records); writer::with_context($context)->export_data([get_string('privacy:sessionpath', 'user')], $sessiondata); } }
[ "protected", "static", "function", "export_user_session_data", "(", "int", "$", "userid", ",", "\\", "context", "$", "context", ")", "{", "global", "$", "DB", ",", "$", "SESSION", ";", "$", "records", "=", "$", "DB", "->", "get_records", "(", "'sessions'", ",", "[", "'userid'", "=>", "$", "userid", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "records", ")", ")", "{", "$", "sessiondata", "=", "(", "object", ")", "array_map", "(", "function", "(", "$", "record", ")", "{", "return", "[", "'state'", "=>", "$", "record", "->", "state", ",", "'sessdata'", "=>", "base64_decode", "(", "$", "record", "->", "sessdata", ")", ",", "'timecreated'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timecreated", ")", ",", "'timemodified'", "=>", "transform", "::", "datetime", "(", "$", "record", "->", "timemodified", ")", ",", "'firstip'", "=>", "$", "record", "->", "firstip", ",", "'lastip'", "=>", "$", "record", "->", "lastip", "]", ";", "}", ",", "$", "records", ")", ";", "writer", "::", "with_context", "(", "$", "context", ")", "->", "export_data", "(", "[", "get_string", "(", "'privacy:sessionpath'", ",", "'user'", ")", "]", ",", "$", "sessiondata", ")", ";", "}", "}" ]
Exports information about the user's session. @param int $userid The user ID. @param \context $context The context for this user.
[ "Exports", "information", "about", "the", "user", "s", "session", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/classes/privacy/provider.php#L535-L552
218,920
moodle/moodle
lib/markdown/MarkdownExtra.php
MarkdownExtra._doAnchors_inline_callback
protected function _doAnchors_inline_callback($matches) { $whole_match = $matches[1]; $link_text = $this->runSpanGamut($matches[2]); $url = $matches[3] == '' ? $matches[4] : $matches[3]; $title =& $matches[7]; $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]); // if the URL was of the form <s p a c e s> it got caught by the HTML // tag parser and hashed. Need to reverse the process before using the URL. $unhashed = $this->unhash($url); if ($unhashed != $url) $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if (isset($title)) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $result .= $attr; $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; return $this->hashPart($result); }
php
protected function _doAnchors_inline_callback($matches) { $whole_match = $matches[1]; $link_text = $this->runSpanGamut($matches[2]); $url = $matches[3] == '' ? $matches[4] : $matches[3]; $title =& $matches[7]; $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]); // if the URL was of the form <s p a c e s> it got caught by the HTML // tag parser and hashed. Need to reverse the process before using the URL. $unhashed = $this->unhash($url); if ($unhashed != $url) $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if (isset($title)) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $result .= $attr; $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; return $this->hashPart($result); }
[ "protected", "function", "_doAnchors_inline_callback", "(", "$", "matches", ")", "{", "$", "whole_match", "=", "$", "matches", "[", "1", "]", ";", "$", "link_text", "=", "$", "this", "->", "runSpanGamut", "(", "$", "matches", "[", "2", "]", ")", ";", "$", "url", "=", "$", "matches", "[", "3", "]", "==", "''", "?", "$", "matches", "[", "4", "]", ":", "$", "matches", "[", "3", "]", ";", "$", "title", "=", "&", "$", "matches", "[", "7", "]", ";", "$", "attr", "=", "$", "this", "->", "doExtraAttributes", "(", "\"a\"", ",", "$", "dummy", "=", "&", "$", "matches", "[", "8", "]", ")", ";", "// if the URL was of the form <s p a c e s> it got caught by the HTML", "// tag parser and hashed. Need to reverse the process before using the URL.", "$", "unhashed", "=", "$", "this", "->", "unhash", "(", "$", "url", ")", ";", "if", "(", "$", "unhashed", "!=", "$", "url", ")", "$", "url", "=", "preg_replace", "(", "'/^<(.*)>$/'", ",", "'\\1'", ",", "$", "unhashed", ")", ";", "$", "url", "=", "$", "this", "->", "encodeURLAttribute", "(", "$", "url", ")", ";", "$", "result", "=", "\"<a href=\\\"$url\\\"\"", ";", "if", "(", "isset", "(", "$", "title", ")", ")", "{", "$", "title", "=", "$", "this", "->", "encodeAttribute", "(", "$", "title", ")", ";", "$", "result", ".=", "\" title=\\\"$title\\\"\"", ";", "}", "$", "result", ".=", "$", "attr", ";", "$", "link_text", "=", "$", "this", "->", "runSpanGamut", "(", "$", "link_text", ")", ";", "$", "result", ".=", "\">$link_text</a>\"", ";", "return", "$", "this", "->", "hashPart", "(", "$", "result", ")", ";", "}" ]
Callback for inline anchors @param array $matches @return string
[ "Callback", "for", "inline", "anchors" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/markdown/MarkdownExtra.php#L871-L897
218,921
moodle/moodle
lib/markdown/MarkdownExtra.php
MarkdownExtra._doTable_leadingPipe_callback
protected function _doTable_leadingPipe_callback($matches) { $head = $matches[1]; $underline = $matches[2]; $content = $matches[3]; $content = preg_replace('/^ *[|]/m', '', $content); return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); }
php
protected function _doTable_leadingPipe_callback($matches) { $head = $matches[1]; $underline = $matches[2]; $content = $matches[3]; $content = preg_replace('/^ *[|]/m', '', $content); return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); }
[ "protected", "function", "_doTable_leadingPipe_callback", "(", "$", "matches", ")", "{", "$", "head", "=", "$", "matches", "[", "1", "]", ";", "$", "underline", "=", "$", "matches", "[", "2", "]", ";", "$", "content", "=", "$", "matches", "[", "3", "]", ";", "$", "content", "=", "preg_replace", "(", "'/^ *[|]/m'", ",", "''", ",", "$", "content", ")", ";", "return", "$", "this", "->", "_doTable_callback", "(", "array", "(", "$", "matches", "[", "0", "]", ",", "$", "head", ",", "$", "underline", ",", "$", "content", ")", ")", ";", "}" ]
Callback for removing the leading pipe for each row @param array $matches @return string
[ "Callback", "for", "removing", "the", "leading", "pipe", "for", "each", "row" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/markdown/MarkdownExtra.php#L1156-L1164
218,922
moodle/moodle
lib/markdown/MarkdownExtra.php
MarkdownExtra._appendFootnotes_callback
protected function _appendFootnotes_callback($matches) { $node_id = $this->fn_id_prefix . $matches[1]; // Create footnote marker only if it has a corresponding footnote *and* // the footnote hasn't been used by another marker. if (isset($this->footnotes[$node_id])) { $num =& $this->footnotes_numbers[$node_id]; if (!isset($num)) { // Transfer footnote content to the ordered list and give it its // number $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; $this->footnotes_ref_count[$node_id] = 1; $num = $this->footnote_counter++; $ref_count_mark = ''; } else { $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1; } $attr = ""; if ($this->fn_link_class != "") { $class = $this->fn_link_class; $class = $this->encodeAttribute($class); $attr .= " class=\"$class\""; } if ($this->fn_link_title != "") { $title = $this->fn_link_title; $title = $this->encodeAttribute($title); $attr .= " title=\"$title\""; } $attr = str_replace("%%", $num, $attr); $node_id = $this->encodeAttribute($node_id); return "<sup id=\"fnref$ref_count_mark:$node_id\">". "<a href=\"#fn:$node_id\"$attr>$num</a>". "</sup>"; } return "[^" . $matches[1] . "]"; }
php
protected function _appendFootnotes_callback($matches) { $node_id = $this->fn_id_prefix . $matches[1]; // Create footnote marker only if it has a corresponding footnote *and* // the footnote hasn't been used by another marker. if (isset($this->footnotes[$node_id])) { $num =& $this->footnotes_numbers[$node_id]; if (!isset($num)) { // Transfer footnote content to the ordered list and give it its // number $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; $this->footnotes_ref_count[$node_id] = 1; $num = $this->footnote_counter++; $ref_count_mark = ''; } else { $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1; } $attr = ""; if ($this->fn_link_class != "") { $class = $this->fn_link_class; $class = $this->encodeAttribute($class); $attr .= " class=\"$class\""; } if ($this->fn_link_title != "") { $title = $this->fn_link_title; $title = $this->encodeAttribute($title); $attr .= " title=\"$title\""; } $attr = str_replace("%%", $num, $attr); $node_id = $this->encodeAttribute($node_id); return "<sup id=\"fnref$ref_count_mark:$node_id\">". "<a href=\"#fn:$node_id\"$attr>$num</a>". "</sup>"; } return "[^" . $matches[1] . "]"; }
[ "protected", "function", "_appendFootnotes_callback", "(", "$", "matches", ")", "{", "$", "node_id", "=", "$", "this", "->", "fn_id_prefix", ".", "$", "matches", "[", "1", "]", ";", "// Create footnote marker only if it has a corresponding footnote *and*", "// the footnote hasn't been used by another marker.", "if", "(", "isset", "(", "$", "this", "->", "footnotes", "[", "$", "node_id", "]", ")", ")", "{", "$", "num", "=", "&", "$", "this", "->", "footnotes_numbers", "[", "$", "node_id", "]", ";", "if", "(", "!", "isset", "(", "$", "num", ")", ")", "{", "// Transfer footnote content to the ordered list and give it its", "// number", "$", "this", "->", "footnotes_ordered", "[", "$", "node_id", "]", "=", "$", "this", "->", "footnotes", "[", "$", "node_id", "]", ";", "$", "this", "->", "footnotes_ref_count", "[", "$", "node_id", "]", "=", "1", ";", "$", "num", "=", "$", "this", "->", "footnote_counter", "++", ";", "$", "ref_count_mark", "=", "''", ";", "}", "else", "{", "$", "ref_count_mark", "=", "$", "this", "->", "footnotes_ref_count", "[", "$", "node_id", "]", "+=", "1", ";", "}", "$", "attr", "=", "\"\"", ";", "if", "(", "$", "this", "->", "fn_link_class", "!=", "\"\"", ")", "{", "$", "class", "=", "$", "this", "->", "fn_link_class", ";", "$", "class", "=", "$", "this", "->", "encodeAttribute", "(", "$", "class", ")", ";", "$", "attr", ".=", "\" class=\\\"$class\\\"\"", ";", "}", "if", "(", "$", "this", "->", "fn_link_title", "!=", "\"\"", ")", "{", "$", "title", "=", "$", "this", "->", "fn_link_title", ";", "$", "title", "=", "$", "this", "->", "encodeAttribute", "(", "$", "title", ")", ";", "$", "attr", ".=", "\" title=\\\"$title\\\"\"", ";", "}", "$", "attr", "=", "str_replace", "(", "\"%%\"", ",", "$", "num", ",", "$", "attr", ")", ";", "$", "node_id", "=", "$", "this", "->", "encodeAttribute", "(", "$", "node_id", ")", ";", "return", "\"<sup id=\\\"fnref$ref_count_mark:$node_id\\\">\"", ".", "\"<a href=\\\"#fn:$node_id\\\"$attr>$num</a>\"", ".", "\"</sup>\"", ";", "}", "return", "\"[^\"", ".", "$", "matches", "[", "1", "]", ".", "\"]\"", ";", "}" ]
Callback for appending footnotes @param array $matches @return string
[ "Callback", "for", "appending", "footnotes" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/markdown/MarkdownExtra.php#L1669-L1709
218,923
moodle/moodle
lib/markdown/MarkdownExtra.php
MarkdownExtra._stripAbbreviations_callback
protected function _stripAbbreviations_callback($matches) { $abbr_word = $matches[1]; $abbr_desc = $matches[2]; if ($this->abbr_word_re) { $this->abbr_word_re .= '|'; } $this->abbr_word_re .= preg_quote($abbr_word); $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); return ''; // String that will replace the block }
php
protected function _stripAbbreviations_callback($matches) { $abbr_word = $matches[1]; $abbr_desc = $matches[2]; if ($this->abbr_word_re) { $this->abbr_word_re .= '|'; } $this->abbr_word_re .= preg_quote($abbr_word); $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); return ''; // String that will replace the block }
[ "protected", "function", "_stripAbbreviations_callback", "(", "$", "matches", ")", "{", "$", "abbr_word", "=", "$", "matches", "[", "1", "]", ";", "$", "abbr_desc", "=", "$", "matches", "[", "2", "]", ";", "if", "(", "$", "this", "->", "abbr_word_re", ")", "{", "$", "this", "->", "abbr_word_re", ".=", "'|'", ";", "}", "$", "this", "->", "abbr_word_re", ".=", "preg_quote", "(", "$", "abbr_word", ")", ";", "$", "this", "->", "abbr_desciptions", "[", "$", "abbr_word", "]", "=", "trim", "(", "$", "abbr_desc", ")", ";", "return", "''", ";", "// String that will replace the block", "}" ]
Callback for stripping abbreviations @param array $matches @return string
[ "Callback", "for", "stripping", "abbreviations" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/markdown/MarkdownExtra.php#L1736-L1745
218,924
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.set_observer
public function set_observer($observer) { $this->observer = $observer; foreach ($this->questionattempts as $qa) { $qa->set_observer($observer); } }
php
public function set_observer($observer) { $this->observer = $observer; foreach ($this->questionattempts as $qa) { $qa->set_observer($observer); } }
[ "public", "function", "set_observer", "(", "$", "observer", ")", "{", "$", "this", "->", "observer", "=", "$", "observer", ";", "foreach", "(", "$", "this", "->", "questionattempts", "as", "$", "qa", ")", "{", "$", "qa", "->", "set_observer", "(", "$", "observer", ")", ";", "}", "}" ]
You should almost certainly not call this method from your code. It is for internal use only. @param question_usage_observer that should be used to tracking changes made to this usage.
[ "You", "should", "almost", "certainly", "not", "call", "this", "method", "from", "your", "code", ".", "It", "is", "for", "internal", "use", "only", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L149-L154
218,925
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.add_question
public function add_question(question_definition $question, $maxmark = null) { $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark); $qa->set_slot($this->next_slot_number()); $this->questionattempts[$this->next_slot_number()] = $qa; $this->observer->notify_attempt_added($qa); return $qa->get_slot(); }
php
public function add_question(question_definition $question, $maxmark = null) { $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark); $qa->set_slot($this->next_slot_number()); $this->questionattempts[$this->next_slot_number()] = $qa; $this->observer->notify_attempt_added($qa); return $qa->get_slot(); }
[ "public", "function", "add_question", "(", "question_definition", "$", "question", ",", "$", "maxmark", "=", "null", ")", "{", "$", "qa", "=", "new", "question_attempt", "(", "$", "question", ",", "$", "this", "->", "get_id", "(", ")", ",", "$", "this", "->", "observer", ",", "$", "maxmark", ")", ";", "$", "qa", "->", "set_slot", "(", "$", "this", "->", "next_slot_number", "(", ")", ")", ";", "$", "this", "->", "questionattempts", "[", "$", "this", "->", "next_slot_number", "(", ")", "]", "=", "$", "qa", ";", "$", "this", "->", "observer", "->", "notify_attempt_added", "(", "$", "qa", ")", ";", "return", "$", "qa", "->", "get_slot", "(", ")", ";", "}" ]
Add another question to this usage. The added question is not started until you call {@link start_question()} on it. @param question_definition $question the question to add. @param number $maxmark the maximum this question will be marked out of in this attempt (optional). If not given, $question->defaultmark is used. @return int the number used to identify this question within this usage.
[ "Add", "another", "question", "to", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L167-L173
218,926
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.add_question_in_place_of_other
public function add_question_in_place_of_other($slot, question_definition $question, $maxmark = null) { $newslot = $this->next_slot_number(); $oldqa = $this->get_question_attempt($slot); $oldqa->set_slot($newslot); $this->questionattempts[$newslot] = $oldqa; if ($maxmark === null) { $maxmark = $oldqa->get_max_mark(); } $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark); $qa->set_slot($slot); $this->questionattempts[$slot] = $qa; $this->observer->notify_attempt_moved($oldqa, $slot); $this->observer->notify_attempt_added($qa); return $newslot; }
php
public function add_question_in_place_of_other($slot, question_definition $question, $maxmark = null) { $newslot = $this->next_slot_number(); $oldqa = $this->get_question_attempt($slot); $oldqa->set_slot($newslot); $this->questionattempts[$newslot] = $oldqa; if ($maxmark === null) { $maxmark = $oldqa->get_max_mark(); } $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark); $qa->set_slot($slot); $this->questionattempts[$slot] = $qa; $this->observer->notify_attempt_moved($oldqa, $slot); $this->observer->notify_attempt_added($qa); return $newslot; }
[ "public", "function", "add_question_in_place_of_other", "(", "$", "slot", ",", "question_definition", "$", "question", ",", "$", "maxmark", "=", "null", ")", "{", "$", "newslot", "=", "$", "this", "->", "next_slot_number", "(", ")", ";", "$", "oldqa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "oldqa", "->", "set_slot", "(", "$", "newslot", ")", ";", "$", "this", "->", "questionattempts", "[", "$", "newslot", "]", "=", "$", "oldqa", ";", "if", "(", "$", "maxmark", "===", "null", ")", "{", "$", "maxmark", "=", "$", "oldqa", "->", "get_max_mark", "(", ")", ";", "}", "$", "qa", "=", "new", "question_attempt", "(", "$", "question", ",", "$", "this", "->", "get_id", "(", ")", ",", "$", "this", "->", "observer", ",", "$", "maxmark", ")", ";", "$", "qa", "->", "set_slot", "(", "$", "slot", ")", ";", "$", "this", "->", "questionattempts", "[", "$", "slot", "]", "=", "$", "qa", ";", "$", "this", "->", "observer", "->", "notify_attempt_moved", "(", "$", "oldqa", ",", "$", "slot", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_added", "(", "$", "qa", ")", ";", "return", "$", "newslot", ";", "}" ]
Add another question to this usage, in the place of an existing slot. The question_attempt that was in that slot is moved to the end at a new slot number, which is returned. The added question is not started until you call {@link start_question()} on it. @param int $slot the slot-number of the question to replace. @param question_definition $question the question to add. @param number $maxmark the maximum this question will be marked out of in this attempt (optional). If not given, the max mark from the $qa we are replacing is used. @return int the new slot number of the question that was displaced.
[ "Add", "another", "question", "to", "this", "usage", "in", "the", "place", "of", "an", "existing", "slot", ".", "The", "question_attempt", "that", "was", "in", "that", "slot", "is", "moved", "to", "the", "end", "at", "a", "new", "slot", "number", "which", "is", "returned", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L190-L209
218,927
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.get_total_mark
public function get_total_mark() { $mark = 0; foreach ($this->questionattempts as $qa) { if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) { return null; } $mark += $qa->get_mark(); } return $mark; }
php
public function get_total_mark() { $mark = 0; foreach ($this->questionattempts as $qa) { if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) { return null; } $mark += $qa->get_mark(); } return $mark; }
[ "public", "function", "get_total_mark", "(", ")", "{", "$", "mark", "=", "0", ";", "foreach", "(", "$", "this", "->", "questionattempts", "as", "$", "qa", ")", "{", "if", "(", "$", "qa", "->", "get_max_mark", "(", ")", ">", "0", "&&", "$", "qa", "->", "get_state", "(", ")", "==", "question_state", "::", "$", "needsgrading", ")", "{", "return", "null", ";", "}", "$", "mark", "+=", "$", "qa", "->", "get_mark", "(", ")", ";", "}", "return", "$", "mark", ";", "}" ]
Get the total mark for all questions in this usage. @return number The sum of marks of all the question_attempts in this usage.
[ "Get", "the", "total", "mark", "for", "all", "questions", "in", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L363-L372
218,928
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.get_summary_information
public function get_summary_information(question_display_options $options) { return question_engine::get_behaviour_type($this->preferredbehaviour) ->summarise_usage($this, $options); }
php
public function get_summary_information(question_display_options $options) { return question_engine::get_behaviour_type($this->preferredbehaviour) ->summarise_usage($this, $options); }
[ "public", "function", "get_summary_information", "(", "question_display_options", "$", "options", ")", "{", "return", "question_engine", "::", "get_behaviour_type", "(", "$", "this", "->", "preferredbehaviour", ")", "->", "summarise_usage", "(", "$", "this", ",", "$", "options", ")", ";", "}" ]
Get summary information about this usage. Some behaviours may be able to provide interesting summary information about the attempt as a whole, and this method provides access to that data. To see how this works, try setting a quiz to one of the CBM behaviours, and then look at the extra information displayed at the top of the quiz review page once you have sumitted an attempt. In the return value, the array keys are identifiers of the form qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary. The values are arrays with two items, title and content. Each of these will be either a string, or a renderable. @return array as described above.
[ "Get", "summary", "information", "about", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L390-L393
218,929
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.set_question_attempt_metadata
public function set_question_attempt_metadata($slot, $name, $value) { $this->get_question_attempt($slot)->set_metadata($name, $value); }
php
public function set_question_attempt_metadata($slot, $name, $value) { $this->get_question_attempt($slot)->set_metadata($name, $value); }
[ "public", "function", "set_question_attempt_metadata", "(", "$", "slot", ",", "$", "name", ",", "$", "value", ")", "{", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", "->", "set_metadata", "(", "$", "name", ",", "$", "value", ")", ";", "}" ]
Set some metadata for a particular question attempt in this usage. @param int $slot the slot number of the question of inerest. @param string $name the name of the metadata variable to return. @param string $value the value to set that metadata variable to.
[ "Set", "some", "metadata", "for", "a", "particular", "question", "attempt", "in", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L433-L435
218,930
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.replace_loaded_question_attempt_info
public function replace_loaded_question_attempt_info($slot, $qa) { $this->check_slot($slot); $this->questionattempts[$slot] = $qa; }
php
public function replace_loaded_question_attempt_info($slot, $qa) { $this->check_slot($slot); $this->questionattempts[$slot] = $qa; }
[ "public", "function", "replace_loaded_question_attempt_info", "(", "$", "slot", ",", "$", "qa", ")", "{", "$", "this", "->", "check_slot", "(", "$", "slot", ")", ";", "$", "this", "->", "questionattempts", "[", "$", "slot", "]", "=", "$", "qa", ";", "}" ]
Replace a particular question_attempt with a different one. For internal use only. Used when reloading the state of a question from the database. @param array $records Raw records loaded from the database. @param int $questionattemptid The id of the question_attempt to extract. @return question_attempt The newly constructed question_attempt_step.
[ "Replace", "a", "particular", "question_attempt", "with", "a", "different", "one", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L506-L509
218,931
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.start_question
public function start_question($slot, $variant = null, $timenow = null) { if (is_null($variant)) { $variant = rand(1, $this->get_num_variants($slot)); } $qa = $this->get_question_attempt($slot); $qa->start($this->preferredbehaviour, $variant, array(), $timenow); $this->observer->notify_attempt_modified($qa); }
php
public function start_question($slot, $variant = null, $timenow = null) { if (is_null($variant)) { $variant = rand(1, $this->get_num_variants($slot)); } $qa = $this->get_question_attempt($slot); $qa->start($this->preferredbehaviour, $variant, array(), $timenow); $this->observer->notify_attempt_modified($qa); }
[ "public", "function", "start_question", "(", "$", "slot", ",", "$", "variant", "=", "null", ",", "$", "timenow", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "variant", ")", ")", "{", "$", "variant", "=", "rand", "(", "1", ",", "$", "this", "->", "get_num_variants", "(", "$", "slot", ")", ")", ";", "}", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "qa", "->", "start", "(", "$", "this", "->", "preferredbehaviour", ",", "$", "variant", ",", "array", "(", ")", ",", "$", "timenow", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "qa", ")", ";", "}" ]
Start the attempt at a question that has been added to this usage. @param int $slot the number used to identify this question within this usage. @param int $variant which variant of the question to use. Must be between 1 and ->get_num_variants($slot) inclusive. If not give, a variant is chosen at random. @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
[ "Start", "the", "attempt", "at", "a", "question", "that", "has", "been", "added", "to", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L548-L556
218,932
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.start_all_questions
public function start_all_questions(question_variant_selection_strategy $variantstrategy = null, $timestamp = null, $userid = null) { if (is_null($variantstrategy)) { $variantstrategy = new question_variant_random_strategy(); } foreach ($this->questionattempts as $qa) { $qa->start($this->preferredbehaviour, $qa->select_variant($variantstrategy), array(), $timestamp, $userid); $this->observer->notify_attempt_modified($qa); } }
php
public function start_all_questions(question_variant_selection_strategy $variantstrategy = null, $timestamp = null, $userid = null) { if (is_null($variantstrategy)) { $variantstrategy = new question_variant_random_strategy(); } foreach ($this->questionattempts as $qa) { $qa->start($this->preferredbehaviour, $qa->select_variant($variantstrategy), array(), $timestamp, $userid); $this->observer->notify_attempt_modified($qa); } }
[ "public", "function", "start_all_questions", "(", "question_variant_selection_strategy", "$", "variantstrategy", "=", "null", ",", "$", "timestamp", "=", "null", ",", "$", "userid", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "variantstrategy", ")", ")", "{", "$", "variantstrategy", "=", "new", "question_variant_random_strategy", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "questionattempts", "as", "$", "qa", ")", "{", "$", "qa", "->", "start", "(", "$", "this", "->", "preferredbehaviour", ",", "$", "qa", "->", "select_variant", "(", "$", "variantstrategy", ")", ",", "array", "(", ")", ",", "$", "timestamp", ",", "$", "userid", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "qa", ")", ";", "}", "}" ]
Start the attempt at all questions that has been added to this usage. @param question_variant_selection_strategy how to pick which variant of each question to use. @param int $timestamp optional, the timstamp to record for this action. Defaults to now. @param int $userid optional, the user to attribute this action to. Defaults to the current user.
[ "Start", "the", "attempt", "at", "all", "questions", "that", "has", "been", "added", "to", "this", "usage", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L564-L575
218,933
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.process_all_actions
public function process_all_actions($timestamp = null, $postdata = null) { foreach ($this->get_slots_in_request($postdata) as $slot) { if (!$this->validate_sequence_number($slot, $postdata)) { continue; } $submitteddata = $this->extract_responses($slot, $postdata); $this->process_action($slot, $submitteddata, $timestamp); } $this->update_question_flags($postdata); }
php
public function process_all_actions($timestamp = null, $postdata = null) { foreach ($this->get_slots_in_request($postdata) as $slot) { if (!$this->validate_sequence_number($slot, $postdata)) { continue; } $submitteddata = $this->extract_responses($slot, $postdata); $this->process_action($slot, $submitteddata, $timestamp); } $this->update_question_flags($postdata); }
[ "public", "function", "process_all_actions", "(", "$", "timestamp", "=", "null", ",", "$", "postdata", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "get_slots_in_request", "(", "$", "postdata", ")", "as", "$", "slot", ")", "{", "if", "(", "!", "$", "this", "->", "validate_sequence_number", "(", "$", "slot", ",", "$", "postdata", ")", ")", "{", "continue", ";", "}", "$", "submitteddata", "=", "$", "this", "->", "extract_responses", "(", "$", "slot", ",", "$", "postdata", ")", ";", "$", "this", "->", "process_action", "(", "$", "slot", ",", "$", "submitteddata", ",", "$", "timestamp", ")", ";", "}", "$", "this", "->", "update_question_flags", "(", "$", "postdata", ")", ";", "}" ]
Process all the question actions in the current request. If there is a parameter slots included in the post data, then only those question numbers will be processed, otherwise all questions in this useage will be. This function also does {@link update_question_flags()}. @param int $timestamp optional, use this timestamp as 'now'. @param array $postdata optional, only intended for testing. Use this data instead of the data from $_POST.
[ "Process", "all", "the", "question", "actions", "in", "the", "current", "request", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L604-L613
218,934
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.process_all_autosaves
public function process_all_autosaves($timestamp = null, $postdata = null) { foreach ($this->get_slots_in_request($postdata) as $slot) { if (!$this->is_autosave_required($slot, $postdata)) { continue; } $submitteddata = $this->extract_responses($slot, $postdata); $this->process_autosave($slot, $submitteddata, $timestamp); } $this->update_question_flags($postdata); }
php
public function process_all_autosaves($timestamp = null, $postdata = null) { foreach ($this->get_slots_in_request($postdata) as $slot) { if (!$this->is_autosave_required($slot, $postdata)) { continue; } $submitteddata = $this->extract_responses($slot, $postdata); $this->process_autosave($slot, $submitteddata, $timestamp); } $this->update_question_flags($postdata); }
[ "public", "function", "process_all_autosaves", "(", "$", "timestamp", "=", "null", ",", "$", "postdata", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "get_slots_in_request", "(", "$", "postdata", ")", "as", "$", "slot", ")", "{", "if", "(", "!", "$", "this", "->", "is_autosave_required", "(", "$", "slot", ",", "$", "postdata", ")", ")", "{", "continue", ";", "}", "$", "submitteddata", "=", "$", "this", "->", "extract_responses", "(", "$", "slot", ",", "$", "postdata", ")", ";", "$", "this", "->", "process_autosave", "(", "$", "slot", ",", "$", "submitteddata", ",", "$", "timestamp", ")", ";", "}", "$", "this", "->", "update_question_flags", "(", "$", "postdata", ")", ";", "}" ]
Process all the question autosave data in the current request. If there is a parameter slots included in the post data, then only those question numbers will be processed, otherwise all questions in this useage will be. This function also does {@link update_question_flags()}. @param int $timestamp optional, use this timestamp as 'now'. @param array $postdata optional, only intended for testing. Use this data instead of the data from $_POST.
[ "Process", "all", "the", "question", "autosave", "data", "in", "the", "current", "request", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L628-L637
218,935
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.get_slots_in_request
protected function get_slots_in_request($postdata = null) { // Note: we must not use "question_attempt::get_submitted_var()" because there is no attempt instance!!! if (is_null($postdata)) { $slots = optional_param('slots', null, PARAM_SEQUENCE); } else if (array_key_exists('slots', $postdata)) { $slots = clean_param($postdata['slots'], PARAM_SEQUENCE); } else { $slots = null; } if (is_null($slots)) { $slots = $this->get_slots(); } else if (!$slots) { $slots = array(); } else { $slots = explode(',', $slots); } return $slots; }
php
protected function get_slots_in_request($postdata = null) { // Note: we must not use "question_attempt::get_submitted_var()" because there is no attempt instance!!! if (is_null($postdata)) { $slots = optional_param('slots', null, PARAM_SEQUENCE); } else if (array_key_exists('slots', $postdata)) { $slots = clean_param($postdata['slots'], PARAM_SEQUENCE); } else { $slots = null; } if (is_null($slots)) { $slots = $this->get_slots(); } else if (!$slots) { $slots = array(); } else { $slots = explode(',', $slots); } return $slots; }
[ "protected", "function", "get_slots_in_request", "(", "$", "postdata", "=", "null", ")", "{", "// Note: we must not use \"question_attempt::get_submitted_var()\" because there is no attempt instance!!!", "if", "(", "is_null", "(", "$", "postdata", ")", ")", "{", "$", "slots", "=", "optional_param", "(", "'slots'", ",", "null", ",", "PARAM_SEQUENCE", ")", ";", "}", "else", "if", "(", "array_key_exists", "(", "'slots'", ",", "$", "postdata", ")", ")", "{", "$", "slots", "=", "clean_param", "(", "$", "postdata", "[", "'slots'", "]", ",", "PARAM_SEQUENCE", ")", ";", "}", "else", "{", "$", "slots", "=", "null", ";", "}", "if", "(", "is_null", "(", "$", "slots", ")", ")", "{", "$", "slots", "=", "$", "this", "->", "get_slots", "(", ")", ";", "}", "else", "if", "(", "!", "$", "slots", ")", "{", "$", "slots", "=", "array", "(", ")", ";", "}", "else", "{", "$", "slots", "=", "explode", "(", "','", ",", "$", "slots", ")", ";", "}", "return", "$", "slots", ";", "}" ]
Get the list of slot numbers that should be processed as part of processing the current request. @param array $postdata optional, only intended for testing. Use this data instead of the data from $_POST. @return array of slot numbers.
[ "Get", "the", "list", "of", "slot", "numbers", "that", "should", "be", "processed", "as", "part", "of", "processing", "the", "current", "request", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L646-L663
218,936
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.prepare_simulated_post_data
public function prepare_simulated_post_data($simulatedresponses) { $simulatedpostdata = array(); $simulatedpostdata['slots'] = implode(',', array_keys($simulatedresponses)); foreach ($simulatedresponses as $slot => $responsedata) { $slotresponse = array(); // Behaviour vars should not be processed by question type, just add prefix. $behaviourvars = $this->get_question_attempt($slot)->get_behaviour()->get_expected_data(); foreach (array_keys($responsedata) as $responsedatakey) { if ($responsedatakey{0} === '-') { $behaviourvarname = substr($responsedatakey, 1); if (isset($behaviourvars[$behaviourvarname])) { // Expected behaviour var found. if ($responsedata[$responsedatakey]) { // Only set the behaviour var if the column value from the cvs file is non zero. // The behaviours only look at whether the var is set or not they don't look at the value. $slotresponse[$responsedatakey] = $responsedata[$responsedatakey]; } } // Remove both expected and unexpected vars from data passed to question type. unset($responsedata[$responsedatakey]); } } $slotresponse += $this->get_question($slot)->prepare_simulated_post_data($responsedata); $slotresponse[':sequencecheck'] = $this->get_question_attempt($slot)->get_sequence_check_count(); // Add this slot's prefix to slot data. $prefix = $this->get_field_prefix($slot); foreach ($slotresponse as $key => $value) { $simulatedpostdata[$prefix.$key] = $value; } } return $simulatedpostdata; }
php
public function prepare_simulated_post_data($simulatedresponses) { $simulatedpostdata = array(); $simulatedpostdata['slots'] = implode(',', array_keys($simulatedresponses)); foreach ($simulatedresponses as $slot => $responsedata) { $slotresponse = array(); // Behaviour vars should not be processed by question type, just add prefix. $behaviourvars = $this->get_question_attempt($slot)->get_behaviour()->get_expected_data(); foreach (array_keys($responsedata) as $responsedatakey) { if ($responsedatakey{0} === '-') { $behaviourvarname = substr($responsedatakey, 1); if (isset($behaviourvars[$behaviourvarname])) { // Expected behaviour var found. if ($responsedata[$responsedatakey]) { // Only set the behaviour var if the column value from the cvs file is non zero. // The behaviours only look at whether the var is set or not they don't look at the value. $slotresponse[$responsedatakey] = $responsedata[$responsedatakey]; } } // Remove both expected and unexpected vars from data passed to question type. unset($responsedata[$responsedatakey]); } } $slotresponse += $this->get_question($slot)->prepare_simulated_post_data($responsedata); $slotresponse[':sequencecheck'] = $this->get_question_attempt($slot)->get_sequence_check_count(); // Add this slot's prefix to slot data. $prefix = $this->get_field_prefix($slot); foreach ($slotresponse as $key => $value) { $simulatedpostdata[$prefix.$key] = $value; } } return $simulatedpostdata; }
[ "public", "function", "prepare_simulated_post_data", "(", "$", "simulatedresponses", ")", "{", "$", "simulatedpostdata", "=", "array", "(", ")", ";", "$", "simulatedpostdata", "[", "'slots'", "]", "=", "implode", "(", "','", ",", "array_keys", "(", "$", "simulatedresponses", ")", ")", ";", "foreach", "(", "$", "simulatedresponses", "as", "$", "slot", "=>", "$", "responsedata", ")", "{", "$", "slotresponse", "=", "array", "(", ")", ";", "// Behaviour vars should not be processed by question type, just add prefix.", "$", "behaviourvars", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", "->", "get_behaviour", "(", ")", "->", "get_expected_data", "(", ")", ";", "foreach", "(", "array_keys", "(", "$", "responsedata", ")", "as", "$", "responsedatakey", ")", "{", "if", "(", "$", "responsedatakey", "{", "0", "}", "===", "'-'", ")", "{", "$", "behaviourvarname", "=", "substr", "(", "$", "responsedatakey", ",", "1", ")", ";", "if", "(", "isset", "(", "$", "behaviourvars", "[", "$", "behaviourvarname", "]", ")", ")", "{", "// Expected behaviour var found.", "if", "(", "$", "responsedata", "[", "$", "responsedatakey", "]", ")", "{", "// Only set the behaviour var if the column value from the cvs file is non zero.", "// The behaviours only look at whether the var is set or not they don't look at the value.", "$", "slotresponse", "[", "$", "responsedatakey", "]", "=", "$", "responsedata", "[", "$", "responsedatakey", "]", ";", "}", "}", "// Remove both expected and unexpected vars from data passed to question type.", "unset", "(", "$", "responsedata", "[", "$", "responsedatakey", "]", ")", ";", "}", "}", "$", "slotresponse", "+=", "$", "this", "->", "get_question", "(", "$", "slot", ")", "->", "prepare_simulated_post_data", "(", "$", "responsedata", ")", ";", "$", "slotresponse", "[", "':sequencecheck'", "]", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", "->", "get_sequence_check_count", "(", ")", ";", "// Add this slot's prefix to slot data.", "$", "prefix", "=", "$", "this", "->", "get_field_prefix", "(", "$", "slot", ")", ";", "foreach", "(", "$", "slotresponse", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "simulatedpostdata", "[", "$", "prefix", ".", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "simulatedpostdata", ";", "}" ]
Transform an array of response data for slots to an array of post data as you would get from quiz attempt form. @param $simulatedresponses array keys are slot nos => contains arrays representing student responses which will be passed to question_definition::prepare_simulated_post_data method and then have the appropriate prefix added. @return array simulated post data
[ "Transform", "an", "array", "of", "response", "data", "for", "slots", "to", "an", "array", "of", "post", "data", "as", "you", "would", "get", "from", "quiz", "attempt", "form", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L686-L720
218,937
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.process_action
public function process_action($slot, $submitteddata, $timestamp = null) { $qa = $this->get_question_attempt($slot); $qa->process_action($submitteddata, $timestamp); $this->observer->notify_attempt_modified($qa); }
php
public function process_action($slot, $submitteddata, $timestamp = null) { $qa = $this->get_question_attempt($slot); $qa->process_action($submitteddata, $timestamp); $this->observer->notify_attempt_modified($qa); }
[ "public", "function", "process_action", "(", "$", "slot", ",", "$", "submitteddata", ",", "$", "timestamp", "=", "null", ")", "{", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "qa", "->", "process_action", "(", "$", "submitteddata", ",", "$", "timestamp", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "qa", ")", ";", "}" ]
Process a specific action on a specific question. @param int $slot the number used to identify this question within this usage. @param $submitteddata the submitted data that constitutes the action.
[ "Process", "a", "specific", "action", "on", "a", "specific", "question", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L727-L731
218,938
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.validate_sequence_number
public function validate_sequence_number($slot, $postdata = null) { $qa = $this->get_question_attempt($slot); $sequencecheck = $qa->get_submitted_var( $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata); if (is_null($sequencecheck)) { return false; } else if ($sequencecheck != $qa->get_sequence_check_count()) { throw new question_out_of_sequence_exception($this->id, $slot, $postdata); } else { return true; } }
php
public function validate_sequence_number($slot, $postdata = null) { $qa = $this->get_question_attempt($slot); $sequencecheck = $qa->get_submitted_var( $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata); if (is_null($sequencecheck)) { return false; } else if ($sequencecheck != $qa->get_sequence_check_count()) { throw new question_out_of_sequence_exception($this->id, $slot, $postdata); } else { return true; } }
[ "public", "function", "validate_sequence_number", "(", "$", "slot", ",", "$", "postdata", "=", "null", ")", "{", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "sequencecheck", "=", "$", "qa", "->", "get_submitted_var", "(", "$", "qa", "->", "get_control_field_name", "(", "'sequencecheck'", ")", ",", "PARAM_INT", ",", "$", "postdata", ")", ";", "if", "(", "is_null", "(", "$", "sequencecheck", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "$", "sequencecheck", "!=", "$", "qa", "->", "get_sequence_check_count", "(", ")", ")", "{", "throw", "new", "question_out_of_sequence_exception", "(", "$", "this", "->", "id", ",", "$", "slot", ",", "$", "postdata", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Check that the sequence number, that detects weird things like the student clicking back, is OK. If the sequence check variable is not present, returns false. If the check variable is present and correct, returns true. If the variable is present and wrong, throws an exception. @param int $slot the number used to identify this question within this usage. @param array $submitteddata the submitted data that constitutes the action. @return bool true if the check variable is present and correct. False if it is missing. (Throws an exception if the check fails.)
[ "Check", "that", "the", "sequence", "number", "that", "detects", "weird", "things", "like", "the", "student", "clicking", "back", "is", "OK", ".", "If", "the", "sequence", "check", "variable", "is", "not", "present", "returns", "false", ".", "If", "the", "check", "variable", "is", "present", "and", "correct", "returns", "true", ".", "If", "the", "variable", "is", "present", "and", "wrong", "throws", "an", "exception", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L755-L766
218,939
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.is_autosave_required
public function is_autosave_required($slot, $postdata = null) { $qa = $this->get_question_attempt($slot); $sequencecheck = $qa->get_submitted_var( $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata); if (is_null($sequencecheck)) { return false; } else if ($sequencecheck != $qa->get_sequence_check_count()) { return false; } else { return true; } }
php
public function is_autosave_required($slot, $postdata = null) { $qa = $this->get_question_attempt($slot); $sequencecheck = $qa->get_submitted_var( $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata); if (is_null($sequencecheck)) { return false; } else if ($sequencecheck != $qa->get_sequence_check_count()) { return false; } else { return true; } }
[ "public", "function", "is_autosave_required", "(", "$", "slot", ",", "$", "postdata", "=", "null", ")", "{", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "sequencecheck", "=", "$", "qa", "->", "get_submitted_var", "(", "$", "qa", "->", "get_control_field_name", "(", "'sequencecheck'", ")", ",", "PARAM_INT", ",", "$", "postdata", ")", ";", "if", "(", "is_null", "(", "$", "sequencecheck", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "$", "sequencecheck", "!=", "$", "qa", "->", "get_sequence_check_count", "(", ")", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Check, based on the sequence number, whether this auto-save is still required. @param int $slot the number used to identify this question within this usage. @param array $submitteddata the submitted data that constitutes the action. @return bool true if the check variable is present and correct, otherwise false.
[ "Check", "based", "on", "the", "sequence", "number", "whether", "this", "auto", "-", "save", "is", "still", "required", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L774-L785
218,940
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.finish_question
public function finish_question($slot, $timestamp = null) { $qa = $this->get_question_attempt($slot); $qa->finish($timestamp); $this->observer->notify_attempt_modified($qa); }
php
public function finish_question($slot, $timestamp = null) { $qa = $this->get_question_attempt($slot); $qa->finish($timestamp); $this->observer->notify_attempt_modified($qa); }
[ "public", "function", "finish_question", "(", "$", "slot", ",", "$", "timestamp", "=", "null", ")", "{", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "qa", "->", "finish", "(", "$", "timestamp", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "qa", ")", ";", "}" ]
Finish the active phase of an attempt at a question. This is an external act of finishing the attempt. Think, for example, of the 'Submit all and finish' button in the quiz. Some behaviours, (for example, immediatefeedback) give a way of finishing the active phase of a question attempt as part of a {@link process_action()} call. After the active phase is over, the only changes possible are things like manual grading, or changing the flag state. @param int $slot the number used to identify this question within this usage.
[ "Finish", "the", "active", "phase", "of", "an", "attempt", "at", "a", "question", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L828-L832
218,941
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.manual_grade
public function manual_grade($slot, $comment, $mark, $commentformat = null) { $qa = $this->get_question_attempt($slot); $qa->manual_grade($comment, $mark, $commentformat); $this->observer->notify_attempt_modified($qa); }
php
public function manual_grade($slot, $comment, $mark, $commentformat = null) { $qa = $this->get_question_attempt($slot); $qa->manual_grade($comment, $mark, $commentformat); $this->observer->notify_attempt_modified($qa); }
[ "public", "function", "manual_grade", "(", "$", "slot", ",", "$", "comment", ",", "$", "mark", ",", "$", "commentformat", "=", "null", ")", "{", "$", "qa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "$", "qa", "->", "manual_grade", "(", "$", "comment", ",", "$", "mark", ",", "$", "commentformat", ")", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "qa", ")", ";", "}" ]
Perform a manual grading action on a question attempt. @param int $slot the number used to identify this question within this usage. @param string $comment the comment being added to the question attempt. @param number $mark the mark that is being assigned. Can be null to just add a comment. @param int $commentformat one of the FORMAT_... constants. The format of $comment.
[ "Perform", "a", "manual", "grading", "action", "on", "a", "question", "attempt", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L853-L857
218,942
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.regrade_question
public function regrade_question($slot, $finished = false, $newmaxmark = null) { $oldqa = $this->get_question_attempt($slot); if (is_null($newmaxmark)) { $newmaxmark = $oldqa->get_max_mark(); } $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(), $this->observer, $newmaxmark); $newqa->set_database_id($oldqa->get_database_id()); $newqa->set_slot($oldqa->get_slot()); $newqa->regrade($oldqa, $finished); $this->questionattempts[$slot] = $newqa; $this->observer->notify_attempt_modified($newqa); }
php
public function regrade_question($slot, $finished = false, $newmaxmark = null) { $oldqa = $this->get_question_attempt($slot); if (is_null($newmaxmark)) { $newmaxmark = $oldqa->get_max_mark(); } $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(), $this->observer, $newmaxmark); $newqa->set_database_id($oldqa->get_database_id()); $newqa->set_slot($oldqa->get_slot()); $newqa->regrade($oldqa, $finished); $this->questionattempts[$slot] = $newqa; $this->observer->notify_attempt_modified($newqa); }
[ "public", "function", "regrade_question", "(", "$", "slot", ",", "$", "finished", "=", "false", ",", "$", "newmaxmark", "=", "null", ")", "{", "$", "oldqa", "=", "$", "this", "->", "get_question_attempt", "(", "$", "slot", ")", ";", "if", "(", "is_null", "(", "$", "newmaxmark", ")", ")", "{", "$", "newmaxmark", "=", "$", "oldqa", "->", "get_max_mark", "(", ")", ";", "}", "$", "newqa", "=", "new", "question_attempt", "(", "$", "oldqa", "->", "get_question", "(", ")", ",", "$", "oldqa", "->", "get_usage_id", "(", ")", ",", "$", "this", "->", "observer", ",", "$", "newmaxmark", ")", ";", "$", "newqa", "->", "set_database_id", "(", "$", "oldqa", "->", "get_database_id", "(", ")", ")", ";", "$", "newqa", "->", "set_slot", "(", "$", "oldqa", "->", "get_slot", "(", ")", ")", ";", "$", "newqa", "->", "regrade", "(", "$", "oldqa", ",", "$", "finished", ")", ";", "$", "this", "->", "questionattempts", "[", "$", "slot", "]", "=", "$", "newqa", ";", "$", "this", "->", "observer", "->", "notify_attempt_modified", "(", "$", "newqa", ")", ";", "}" ]
Regrade a question in this usage. This replays the sequence of submitted actions to recompute the outcomes. @param int $slot the number used to identify this question within this usage. @param bool $finished whether the question attempt should be forced to be finished after the regrade, or whether it may still be in progress (default false). @param number $newmaxmark (optional) if given, will change the max mark while regrading.
[ "Regrade", "a", "question", "in", "this", "usage", ".", "This", "replays", "the", "sequence", "of", "submitted", "actions", "to", "recompute", "the", "outcomes", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L867-L881
218,943
moodle/moodle
question/engine/questionusage.php
question_usage_by_activity.load_from_records
public static function load_from_records($records, $qubaid) { $record = $records->current(); while ($record->qubaid != $qubaid) { $records->next(); if (!$records->valid()) { throw new coding_exception("Question usage {$qubaid} not found in the database."); } $record = $records->current(); } $quba = new question_usage_by_activity($record->component, context::instance_by_id($record->contextid, IGNORE_MISSING)); $quba->set_id_from_database($record->qubaid); $quba->set_preferred_behaviour($record->preferredbehaviour); $quba->observer = new question_engine_unit_of_work($quba); // If slot is null then the current pointer in $records will not be // advanced in the while loop below, and we get stuck in an infinite loop, // since this method is supposed to always consume at least one record. // Therefore, in this case, advance the record here. if (is_null($record->slot)) { $records->next(); } while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) { $quba->questionattempts[$record->slot] = question_attempt::load_from_records($records, $record->questionattemptid, $quba->observer, $quba->get_preferred_behaviour()); if ($records->valid()) { $record = $records->current(); } else { $record = false; } } return $quba; }
php
public static function load_from_records($records, $qubaid) { $record = $records->current(); while ($record->qubaid != $qubaid) { $records->next(); if (!$records->valid()) { throw new coding_exception("Question usage {$qubaid} not found in the database."); } $record = $records->current(); } $quba = new question_usage_by_activity($record->component, context::instance_by_id($record->contextid, IGNORE_MISSING)); $quba->set_id_from_database($record->qubaid); $quba->set_preferred_behaviour($record->preferredbehaviour); $quba->observer = new question_engine_unit_of_work($quba); // If slot is null then the current pointer in $records will not be // advanced in the while loop below, and we get stuck in an infinite loop, // since this method is supposed to always consume at least one record. // Therefore, in this case, advance the record here. if (is_null($record->slot)) { $records->next(); } while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) { $quba->questionattempts[$record->slot] = question_attempt::load_from_records($records, $record->questionattemptid, $quba->observer, $quba->get_preferred_behaviour()); if ($records->valid()) { $record = $records->current(); } else { $record = false; } } return $quba; }
[ "public", "static", "function", "load_from_records", "(", "$", "records", ",", "$", "qubaid", ")", "{", "$", "record", "=", "$", "records", "->", "current", "(", ")", ";", "while", "(", "$", "record", "->", "qubaid", "!=", "$", "qubaid", ")", "{", "$", "records", "->", "next", "(", ")", ";", "if", "(", "!", "$", "records", "->", "valid", "(", ")", ")", "{", "throw", "new", "coding_exception", "(", "\"Question usage {$qubaid} not found in the database.\"", ")", ";", "}", "$", "record", "=", "$", "records", "->", "current", "(", ")", ";", "}", "$", "quba", "=", "new", "question_usage_by_activity", "(", "$", "record", "->", "component", ",", "context", "::", "instance_by_id", "(", "$", "record", "->", "contextid", ",", "IGNORE_MISSING", ")", ")", ";", "$", "quba", "->", "set_id_from_database", "(", "$", "record", "->", "qubaid", ")", ";", "$", "quba", "->", "set_preferred_behaviour", "(", "$", "record", "->", "preferredbehaviour", ")", ";", "$", "quba", "->", "observer", "=", "new", "question_engine_unit_of_work", "(", "$", "quba", ")", ";", "// If slot is null then the current pointer in $records will not be", "// advanced in the while loop below, and we get stuck in an infinite loop,", "// since this method is supposed to always consume at least one record.", "// Therefore, in this case, advance the record here.", "if", "(", "is_null", "(", "$", "record", "->", "slot", ")", ")", "{", "$", "records", "->", "next", "(", ")", ";", "}", "while", "(", "$", "record", "&&", "$", "record", "->", "qubaid", "==", "$", "qubaid", "&&", "!", "is_null", "(", "$", "record", "->", "slot", ")", ")", "{", "$", "quba", "->", "questionattempts", "[", "$", "record", "->", "slot", "]", "=", "question_attempt", "::", "load_from_records", "(", "$", "records", ",", "$", "record", "->", "questionattemptid", ",", "$", "quba", "->", "observer", ",", "$", "quba", "->", "get_preferred_behaviour", "(", ")", ")", ";", "if", "(", "$", "records", "->", "valid", "(", ")", ")", "{", "$", "record", "=", "$", "records", "->", "current", "(", ")", ";", "}", "else", "{", "$", "record", "=", "false", ";", "}", "}", "return", "$", "quba", ";", "}" ]
Create a question_usage_by_activity from records loaded from the database. For internal use only. @param Iterator $records Raw records loaded from the database. @param int $questionattemptid The id of the question_attempt to extract. @return question_usage_by_activity The newly constructed usage.
[ "Create", "a", "question_usage_by_activity", "from", "records", "loaded", "from", "the", "database", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/questionusage.php#L912-L950
218,944
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.generate_shortname
public static function generate_shortname($data, $templateshortname) { if (empty($templateshortname) && !is_numeric($templateshortname)) { return null; } if (strpos($templateshortname, '%') === false) { return $templateshortname; } $course = (object) $data; $fullname = isset($course->fullname) ? $course->fullname : ''; $idnumber = isset($course->idnumber) ? $course->idnumber : ''; $callback = partial(array('tool_uploadcourse_helper', 'generate_shortname_callback'), $fullname, $idnumber); $result = preg_replace_callback('/(?<!%)%([+~-])?(\d)*([fi])/', $callback, $templateshortname); if (!is_null($result)) { $result = clean_param($result, PARAM_TEXT); } if (empty($result) && !is_numeric($result)) { $result = null; } return $result; }
php
public static function generate_shortname($data, $templateshortname) { if (empty($templateshortname) && !is_numeric($templateshortname)) { return null; } if (strpos($templateshortname, '%') === false) { return $templateshortname; } $course = (object) $data; $fullname = isset($course->fullname) ? $course->fullname : ''; $idnumber = isset($course->idnumber) ? $course->idnumber : ''; $callback = partial(array('tool_uploadcourse_helper', 'generate_shortname_callback'), $fullname, $idnumber); $result = preg_replace_callback('/(?<!%)%([+~-])?(\d)*([fi])/', $callback, $templateshortname); if (!is_null($result)) { $result = clean_param($result, PARAM_TEXT); } if (empty($result) && !is_numeric($result)) { $result = null; } return $result; }
[ "public", "static", "function", "generate_shortname", "(", "$", "data", ",", "$", "templateshortname", ")", "{", "if", "(", "empty", "(", "$", "templateshortname", ")", "&&", "!", "is_numeric", "(", "$", "templateshortname", ")", ")", "{", "return", "null", ";", "}", "if", "(", "strpos", "(", "$", "templateshortname", ",", "'%'", ")", "===", "false", ")", "{", "return", "$", "templateshortname", ";", "}", "$", "course", "=", "(", "object", ")", "$", "data", ";", "$", "fullname", "=", "isset", "(", "$", "course", "->", "fullname", ")", "?", "$", "course", "->", "fullname", ":", "''", ";", "$", "idnumber", "=", "isset", "(", "$", "course", "->", "idnumber", ")", "?", "$", "course", "->", "idnumber", ":", "''", ";", "$", "callback", "=", "partial", "(", "array", "(", "'tool_uploadcourse_helper'", ",", "'generate_shortname_callback'", ")", ",", "$", "fullname", ",", "$", "idnumber", ")", ";", "$", "result", "=", "preg_replace_callback", "(", "'/(?<!%)%([+~-])?(\\d)*([fi])/'", ",", "$", "callback", ",", "$", "templateshortname", ")", ";", "if", "(", "!", "is_null", "(", "$", "result", ")", ")", "{", "$", "result", "=", "clean_param", "(", "$", "result", ",", "PARAM_TEXT", ")", ";", "}", "if", "(", "empty", "(", "$", "result", ")", "&&", "!", "is_numeric", "(", "$", "result", ")", ")", "{", "$", "result", "=", "null", ";", "}", "return", "$", "result", ";", "}" ]
Generate a shortname based on a template. @param array|object $data course data. @param string $templateshortname template of shortname. @return null|string shortname based on the template, or null when an error occured.
[ "Generate", "a", "shortname", "based", "on", "a", "template", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L46-L70
218,945
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.generate_shortname_callback
public static function generate_shortname_callback($fullname, $idnumber, $block) { switch ($block[3]) { case 'f': $repl = $fullname; break; case 'i': $repl = $idnumber; break; default: return $block[0]; } switch ($block[1]) { case '+': $repl = core_text::strtoupper($repl); break; case '-': $repl = core_text::strtolower($repl); break; case '~': $repl = core_text::strtotitle($repl); break; } if (!empty($block[2])) { $repl = core_text::substr($repl, 0, $block[2]); } return $repl; }
php
public static function generate_shortname_callback($fullname, $idnumber, $block) { switch ($block[3]) { case 'f': $repl = $fullname; break; case 'i': $repl = $idnumber; break; default: return $block[0]; } switch ($block[1]) { case '+': $repl = core_text::strtoupper($repl); break; case '-': $repl = core_text::strtolower($repl); break; case '~': $repl = core_text::strtotitle($repl); break; } if (!empty($block[2])) { $repl = core_text::substr($repl, 0, $block[2]); } return $repl; }
[ "public", "static", "function", "generate_shortname_callback", "(", "$", "fullname", ",", "$", "idnumber", ",", "$", "block", ")", "{", "switch", "(", "$", "block", "[", "3", "]", ")", "{", "case", "'f'", ":", "$", "repl", "=", "$", "fullname", ";", "break", ";", "case", "'i'", ":", "$", "repl", "=", "$", "idnumber", ";", "break", ";", "default", ":", "return", "$", "block", "[", "0", "]", ";", "}", "switch", "(", "$", "block", "[", "1", "]", ")", "{", "case", "'+'", ":", "$", "repl", "=", "core_text", "::", "strtoupper", "(", "$", "repl", ")", ";", "break", ";", "case", "'-'", ":", "$", "repl", "=", "core_text", "::", "strtolower", "(", "$", "repl", ")", ";", "break", ";", "case", "'~'", ":", "$", "repl", "=", "core_text", "::", "strtotitle", "(", "$", "repl", ")", ";", "break", ";", "}", "if", "(", "!", "empty", "(", "$", "block", "[", "2", "]", ")", ")", "{", "$", "repl", "=", "core_text", "::", "substr", "(", "$", "repl", ",", "0", ",", "$", "block", "[", "2", "]", ")", ";", "}", "return", "$", "repl", ";", "}" ]
Callback used when generating a shortname based on a template. @param string $fullname full name. @param string $idnumber ID number. @param array $block result from preg_replace_callback. @return string
[ "Callback", "used", "when", "generating", "a", "shortname", "based", "on", "a", "template", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L80-L109
218,946
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.get_enrolment_data
public static function get_enrolment_data($data) { $enrolmethods = array(); $enroloptions = array(); foreach ($data as $field => $value) { // Enrolmnent data. $matches = array(); if (preg_match('/^enrolment_(\d+)(_(.+))?$/', $field, $matches)) { $key = $matches[1]; if (!isset($enroloptions[$key])) { $enroloptions[$key] = array(); } if (empty($matches[3])) { $enrolmethods[$key] = $value; } else { $enroloptions[$key][$matches[3]] = $value; } } } // Combining enrolment methods and their options in a single array. $enrolmentdata = array(); if (!empty($enrolmethods)) { $enrolmentplugins = self::get_enrolment_plugins(); foreach ($enrolmethods as $key => $method) { if (!array_key_exists($method, $enrolmentplugins)) { // Error! continue; } $enrolmentdata[$enrolmethods[$key]] = $enroloptions[$key]; } } return $enrolmentdata; }
php
public static function get_enrolment_data($data) { $enrolmethods = array(); $enroloptions = array(); foreach ($data as $field => $value) { // Enrolmnent data. $matches = array(); if (preg_match('/^enrolment_(\d+)(_(.+))?$/', $field, $matches)) { $key = $matches[1]; if (!isset($enroloptions[$key])) { $enroloptions[$key] = array(); } if (empty($matches[3])) { $enrolmethods[$key] = $value; } else { $enroloptions[$key][$matches[3]] = $value; } } } // Combining enrolment methods and their options in a single array. $enrolmentdata = array(); if (!empty($enrolmethods)) { $enrolmentplugins = self::get_enrolment_plugins(); foreach ($enrolmethods as $key => $method) { if (!array_key_exists($method, $enrolmentplugins)) { // Error! continue; } $enrolmentdata[$enrolmethods[$key]] = $enroloptions[$key]; } } return $enrolmentdata; }
[ "public", "static", "function", "get_enrolment_data", "(", "$", "data", ")", "{", "$", "enrolmethods", "=", "array", "(", ")", ";", "$", "enroloptions", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "field", "=>", "$", "value", ")", "{", "// Enrolmnent data.", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "preg_match", "(", "'/^enrolment_(\\d+)(_(.+))?$/'", ",", "$", "field", ",", "$", "matches", ")", ")", "{", "$", "key", "=", "$", "matches", "[", "1", "]", ";", "if", "(", "!", "isset", "(", "$", "enroloptions", "[", "$", "key", "]", ")", ")", "{", "$", "enroloptions", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "matches", "[", "3", "]", ")", ")", "{", "$", "enrolmethods", "[", "$", "key", "]", "=", "$", "value", ";", "}", "else", "{", "$", "enroloptions", "[", "$", "key", "]", "[", "$", "matches", "[", "3", "]", "]", "=", "$", "value", ";", "}", "}", "}", "// Combining enrolment methods and their options in a single array.", "$", "enrolmentdata", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "enrolmethods", ")", ")", "{", "$", "enrolmentplugins", "=", "self", "::", "get_enrolment_plugins", "(", ")", ";", "foreach", "(", "$", "enrolmethods", "as", "$", "key", "=>", "$", "method", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "method", ",", "$", "enrolmentplugins", ")", ")", "{", "// Error!", "continue", ";", "}", "$", "enrolmentdata", "[", "$", "enrolmethods", "[", "$", "key", "]", "]", "=", "$", "enroloptions", "[", "$", "key", "]", ";", "}", "}", "return", "$", "enrolmentdata", ";", "}" ]
Extract enrolment data from passed data. Constructs an array of methods, and their options: array( 'method1' => array( 'option1' => value, 'option2' => value ), 'method2' => array( 'option1' => value, 'option2' => value ) ) @param array $data data to extract the enrolment data from. @return array
[ "Extract", "enrolment", "data", "from", "passed", "data", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L138-L171
218,947
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.get_enrolment_plugins
public static function get_enrolment_plugins() { $cache = cache::make('tool_uploadcourse', 'helper'); if (($enrol = $cache->get('enrol')) === false) { $enrol = enrol_get_plugins(false); $cache->set('enrol', $enrol); } return $enrol; }
php
public static function get_enrolment_plugins() { $cache = cache::make('tool_uploadcourse', 'helper'); if (($enrol = $cache->get('enrol')) === false) { $enrol = enrol_get_plugins(false); $cache->set('enrol', $enrol); } return $enrol; }
[ "public", "static", "function", "get_enrolment_plugins", "(", ")", "{", "$", "cache", "=", "cache", "::", "make", "(", "'tool_uploadcourse'", ",", "'helper'", ")", ";", "if", "(", "(", "$", "enrol", "=", "$", "cache", "->", "get", "(", "'enrol'", ")", ")", "===", "false", ")", "{", "$", "enrol", "=", "enrol_get_plugins", "(", "false", ")", ";", "$", "cache", "->", "set", "(", "'enrol'", ",", "$", "enrol", ")", ";", "}", "return", "$", "enrol", ";", "}" ]
Return the enrolment plugins. The result is cached for faster execution. @return array
[ "Return", "the", "enrolment", "plugins", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L180-L187
218,948
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.get_restore_content_dir
public static function get_restore_content_dir($backupfile = null, $shortname = null, &$errors = array()) { global $CFG, $DB, $USER; $cachekey = null; if (!empty($backupfile)) { $backupfile = realpath($backupfile); if (empty($backupfile) || !is_readable($backupfile)) { $errors['cannotreadbackupfile'] = new lang_string('cannotreadbackupfile', 'tool_uploadcourse'); return false; } $cachekey = 'backup_path:' . $backupfile; } else if (!empty($shortname) || is_numeric($shortname)) { $cachekey = 'backup_sn:' . $shortname; } if (empty($cachekey)) { return false; } // If $CFG->keeptempdirectoriesonbackup is not set to true, any restore happening would // automatically delete the backup directory... causing the cache to return an unexisting directory. $usecache = !empty($CFG->keeptempdirectoriesonbackup); if ($usecache) { $cache = cache::make('tool_uploadcourse', 'helper'); } // If we don't use the cache, or if we do and not set, or the directory doesn't exist any more. if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir(get_backup_temp_directory($backupid)))) { // Use null instead of false because it would consider that the cache key has not been set. $backupid = null; if (!empty($backupfile)) { // Extracting the backup file. $packer = get_file_packer('application/vnd.moodle.backup'); $backupid = restore_controller::get_tempdir_name(SITEID, $USER->id); $path = make_backup_temp_directory($backupid, false); $result = $packer->extract_to_pathname($backupfile, $path); if (!$result) { $errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse'); } } else if (!empty($shortname) || is_numeric($shortname)) { // Creating restore from an existing course. $courseid = $DB->get_field('course', 'id', array('shortname' => $shortname), IGNORE_MISSING); if (!empty($courseid)) { $bc = new backup_controller(backup::TYPE_1COURSE, $courseid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); $bc->execute_plan(); $backupid = $bc->get_backupid(); $bc->destroy(); } else { $errors['coursetorestorefromdoesnotexist'] = new lang_string('coursetorestorefromdoesnotexist', 'tool_uploadcourse'); } } if ($usecache) { $cache->set($cachekey, $backupid); } } if ($backupid === null) { $backupid = false; } return $backupid; }
php
public static function get_restore_content_dir($backupfile = null, $shortname = null, &$errors = array()) { global $CFG, $DB, $USER; $cachekey = null; if (!empty($backupfile)) { $backupfile = realpath($backupfile); if (empty($backupfile) || !is_readable($backupfile)) { $errors['cannotreadbackupfile'] = new lang_string('cannotreadbackupfile', 'tool_uploadcourse'); return false; } $cachekey = 'backup_path:' . $backupfile; } else if (!empty($shortname) || is_numeric($shortname)) { $cachekey = 'backup_sn:' . $shortname; } if (empty($cachekey)) { return false; } // If $CFG->keeptempdirectoriesonbackup is not set to true, any restore happening would // automatically delete the backup directory... causing the cache to return an unexisting directory. $usecache = !empty($CFG->keeptempdirectoriesonbackup); if ($usecache) { $cache = cache::make('tool_uploadcourse', 'helper'); } // If we don't use the cache, or if we do and not set, or the directory doesn't exist any more. if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir(get_backup_temp_directory($backupid)))) { // Use null instead of false because it would consider that the cache key has not been set. $backupid = null; if (!empty($backupfile)) { // Extracting the backup file. $packer = get_file_packer('application/vnd.moodle.backup'); $backupid = restore_controller::get_tempdir_name(SITEID, $USER->id); $path = make_backup_temp_directory($backupid, false); $result = $packer->extract_to_pathname($backupfile, $path); if (!$result) { $errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse'); } } else if (!empty($shortname) || is_numeric($shortname)) { // Creating restore from an existing course. $courseid = $DB->get_field('course', 'id', array('shortname' => $shortname), IGNORE_MISSING); if (!empty($courseid)) { $bc = new backup_controller(backup::TYPE_1COURSE, $courseid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); $bc->execute_plan(); $backupid = $bc->get_backupid(); $bc->destroy(); } else { $errors['coursetorestorefromdoesnotexist'] = new lang_string('coursetorestorefromdoesnotexist', 'tool_uploadcourse'); } } if ($usecache) { $cache->set($cachekey, $backupid); } } if ($backupid === null) { $backupid = false; } return $backupid; }
[ "public", "static", "function", "get_restore_content_dir", "(", "$", "backupfile", "=", "null", ",", "$", "shortname", "=", "null", ",", "&", "$", "errors", "=", "array", "(", ")", ")", "{", "global", "$", "CFG", ",", "$", "DB", ",", "$", "USER", ";", "$", "cachekey", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "backupfile", ")", ")", "{", "$", "backupfile", "=", "realpath", "(", "$", "backupfile", ")", ";", "if", "(", "empty", "(", "$", "backupfile", ")", "||", "!", "is_readable", "(", "$", "backupfile", ")", ")", "{", "$", "errors", "[", "'cannotreadbackupfile'", "]", "=", "new", "lang_string", "(", "'cannotreadbackupfile'", ",", "'tool_uploadcourse'", ")", ";", "return", "false", ";", "}", "$", "cachekey", "=", "'backup_path:'", ".", "$", "backupfile", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "shortname", ")", "||", "is_numeric", "(", "$", "shortname", ")", ")", "{", "$", "cachekey", "=", "'backup_sn:'", ".", "$", "shortname", ";", "}", "if", "(", "empty", "(", "$", "cachekey", ")", ")", "{", "return", "false", ";", "}", "// If $CFG->keeptempdirectoriesonbackup is not set to true, any restore happening would", "// automatically delete the backup directory... causing the cache to return an unexisting directory.", "$", "usecache", "=", "!", "empty", "(", "$", "CFG", "->", "keeptempdirectoriesonbackup", ")", ";", "if", "(", "$", "usecache", ")", "{", "$", "cache", "=", "cache", "::", "make", "(", "'tool_uploadcourse'", ",", "'helper'", ")", ";", "}", "// If we don't use the cache, or if we do and not set, or the directory doesn't exist any more.", "if", "(", "!", "$", "usecache", "||", "(", "(", "$", "backupid", "=", "$", "cache", "->", "get", "(", "$", "cachekey", ")", ")", "===", "false", "||", "!", "is_dir", "(", "get_backup_temp_directory", "(", "$", "backupid", ")", ")", ")", ")", "{", "// Use null instead of false because it would consider that the cache key has not been set.", "$", "backupid", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "backupfile", ")", ")", "{", "// Extracting the backup file.", "$", "packer", "=", "get_file_packer", "(", "'application/vnd.moodle.backup'", ")", ";", "$", "backupid", "=", "restore_controller", "::", "get_tempdir_name", "(", "SITEID", ",", "$", "USER", "->", "id", ")", ";", "$", "path", "=", "make_backup_temp_directory", "(", "$", "backupid", ",", "false", ")", ";", "$", "result", "=", "$", "packer", "->", "extract_to_pathname", "(", "$", "backupfile", ",", "$", "path", ")", ";", "if", "(", "!", "$", "result", ")", "{", "$", "errors", "[", "'invalidbackupfile'", "]", "=", "new", "lang_string", "(", "'invalidbackupfile'", ",", "'tool_uploadcourse'", ")", ";", "}", "}", "else", "if", "(", "!", "empty", "(", "$", "shortname", ")", "||", "is_numeric", "(", "$", "shortname", ")", ")", "{", "// Creating restore from an existing course.", "$", "courseid", "=", "$", "DB", "->", "get_field", "(", "'course'", ",", "'id'", ",", "array", "(", "'shortname'", "=>", "$", "shortname", ")", ",", "IGNORE_MISSING", ")", ";", "if", "(", "!", "empty", "(", "$", "courseid", ")", ")", "{", "$", "bc", "=", "new", "backup_controller", "(", "backup", "::", "TYPE_1COURSE", ",", "$", "courseid", ",", "backup", "::", "FORMAT_MOODLE", ",", "backup", "::", "INTERACTIVE_NO", ",", "backup", "::", "MODE_IMPORT", ",", "$", "USER", "->", "id", ")", ";", "$", "bc", "->", "execute_plan", "(", ")", ";", "$", "backupid", "=", "$", "bc", "->", "get_backupid", "(", ")", ";", "$", "bc", "->", "destroy", "(", ")", ";", "}", "else", "{", "$", "errors", "[", "'coursetorestorefromdoesnotexist'", "]", "=", "new", "lang_string", "(", "'coursetorestorefromdoesnotexist'", ",", "'tool_uploadcourse'", ")", ";", "}", "}", "if", "(", "$", "usecache", ")", "{", "$", "cache", "->", "set", "(", "$", "cachekey", ",", "$", "backupid", ")", ";", "}", "}", "if", "(", "$", "backupid", "===", "null", ")", "{", "$", "backupid", "=", "false", ";", "}", "return", "$", "backupid", ";", "}" ]
Get the restore content tempdir. The tempdir is the sub directory in which the backup has been extracted. This caches the result for better performance, but $CFG->keeptempdirectoriesonbackup needs to be enabled, otherwise the cache is ignored. @param string $backupfile path to a backup file. @param string $shortname shortname of a course. @param array $errors will be populated with errors found. @return string|false false when the backup couldn't retrieved.
[ "Get", "the", "restore", "content", "tempdir", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L202-L267
218,949
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.get_role_ids
public static function get_role_ids() { $cache = cache::make('tool_uploadcourse', 'helper'); if (($roles = $cache->get('roles')) === false) { $roles = array(); $rolesraw = get_all_roles(); foreach ($rolesraw as $role) { $roles[$role->shortname] = $role->id; } $cache->set('roles', $roles); } return $roles; }
php
public static function get_role_ids() { $cache = cache::make('tool_uploadcourse', 'helper'); if (($roles = $cache->get('roles')) === false) { $roles = array(); $rolesraw = get_all_roles(); foreach ($rolesraw as $role) { $roles[$role->shortname] = $role->id; } $cache->set('roles', $roles); } return $roles; }
[ "public", "static", "function", "get_role_ids", "(", ")", "{", "$", "cache", "=", "cache", "::", "make", "(", "'tool_uploadcourse'", ",", "'helper'", ")", ";", "if", "(", "(", "$", "roles", "=", "$", "cache", "->", "get", "(", "'roles'", ")", ")", "===", "false", ")", "{", "$", "roles", "=", "array", "(", ")", ";", "$", "rolesraw", "=", "get_all_roles", "(", ")", ";", "foreach", "(", "$", "rolesraw", "as", "$", "role", ")", "{", "$", "roles", "[", "$", "role", "->", "shortname", "]", "=", "$", "role", "->", "id", ";", "}", "$", "cache", "->", "set", "(", "'roles'", ",", "$", "roles", ")", ";", "}", "return", "$", "roles", ";", "}" ]
Return the role IDs. The result is cached for faster execution. @return array
[ "Return", "the", "role", "IDs", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L276-L287
218,950
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.get_role_names
public static function get_role_names($data, &$errors = array()) { $rolenames = array(); $rolesids = self::get_role_ids(); $invalidroles = array(); foreach ($data as $field => $value) { $matches = array(); if (preg_match('/^role_(.+)?$/', $field, $matches)) { if (!isset($rolesids[$matches[1]])) { $invalidroles[] = $matches[1]; continue; } $rolenames['role_' . $rolesids[$matches[1]]] = $value; } } if (!empty($invalidroles)) { $errors['invalidroles'] = new lang_string('invalidroles', 'tool_uploadcourse', implode(', ', $invalidroles)); } // Roles names. return $rolenames; }
php
public static function get_role_names($data, &$errors = array()) { $rolenames = array(); $rolesids = self::get_role_ids(); $invalidroles = array(); foreach ($data as $field => $value) { $matches = array(); if (preg_match('/^role_(.+)?$/', $field, $matches)) { if (!isset($rolesids[$matches[1]])) { $invalidroles[] = $matches[1]; continue; } $rolenames['role_' . $rolesids[$matches[1]]] = $value; } } if (!empty($invalidroles)) { $errors['invalidroles'] = new lang_string('invalidroles', 'tool_uploadcourse', implode(', ', $invalidroles)); } // Roles names. return $rolenames; }
[ "public", "static", "function", "get_role_names", "(", "$", "data", ",", "&", "$", "errors", "=", "array", "(", ")", ")", "{", "$", "rolenames", "=", "array", "(", ")", ";", "$", "rolesids", "=", "self", "::", "get_role_ids", "(", ")", ";", "$", "invalidroles", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "preg_match", "(", "'/^role_(.+)?$/'", ",", "$", "field", ",", "$", "matches", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "rolesids", "[", "$", "matches", "[", "1", "]", "]", ")", ")", "{", "$", "invalidroles", "[", "]", "=", "$", "matches", "[", "1", "]", ";", "continue", ";", "}", "$", "rolenames", "[", "'role_'", ".", "$", "rolesids", "[", "$", "matches", "[", "1", "]", "]", "]", "=", "$", "value", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "invalidroles", ")", ")", "{", "$", "errors", "[", "'invalidroles'", "]", "=", "new", "lang_string", "(", "'invalidroles'", ",", "'tool_uploadcourse'", ",", "implode", "(", "', '", ",", "$", "invalidroles", ")", ")", ";", "}", "// Roles names.", "return", "$", "rolenames", ";", "}" ]
Get the role renaming data from the passed data. @param array $data data to extract the names from. @param array $errors will be populated with errors found. @return array where the key is the role_<id>, the value is the new name.
[ "Get", "the", "role", "renaming", "data", "from", "the", "passed", "data", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L296-L319
218,951
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.increment_idnumber
public static function increment_idnumber($idnumber) { global $DB; while ($DB->record_exists('course', array('idnumber' => $idnumber))) { $matches = array(); if (!preg_match('/(.*?)([0-9]+)$/', $idnumber, $matches)) { $newidnumber = $idnumber . '_2'; } else { $newidnumber = $matches[1] . ((int) $matches[2] + 1); } $idnumber = $newidnumber; } return $idnumber; }
php
public static function increment_idnumber($idnumber) { global $DB; while ($DB->record_exists('course', array('idnumber' => $idnumber))) { $matches = array(); if (!preg_match('/(.*?)([0-9]+)$/', $idnumber, $matches)) { $newidnumber = $idnumber . '_2'; } else { $newidnumber = $matches[1] . ((int) $matches[2] + 1); } $idnumber = $newidnumber; } return $idnumber; }
[ "public", "static", "function", "increment_idnumber", "(", "$", "idnumber", ")", "{", "global", "$", "DB", ";", "while", "(", "$", "DB", "->", "record_exists", "(", "'course'", ",", "array", "(", "'idnumber'", "=>", "$", "idnumber", ")", ")", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "!", "preg_match", "(", "'/(.*?)([0-9]+)$/'", ",", "$", "idnumber", ",", "$", "matches", ")", ")", "{", "$", "newidnumber", "=", "$", "idnumber", ".", "'_2'", ";", "}", "else", "{", "$", "newidnumber", "=", "$", "matches", "[", "1", "]", ".", "(", "(", "int", ")", "$", "matches", "[", "2", "]", "+", "1", ")", ";", "}", "$", "idnumber", "=", "$", "newidnumber", ";", "}", "return", "$", "idnumber", ";", "}" ]
Helper to increment an ID number. This first checks if the ID number is in use. @param string $idnumber ID number to increment. @return string new ID number.
[ "Helper", "to", "increment", "an", "ID", "number", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L329-L341
218,952
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.increment_shortname
public static function increment_shortname($shortname) { global $DB; do { $matches = array(); if (!preg_match('/(.*?)([0-9]+)$/', $shortname, $matches)) { $newshortname = $shortname . '_2'; } else { $newshortname = $matches[1] . ($matches[2]+1); } $shortname = $newshortname; } while ($DB->record_exists('course', array('shortname' => $shortname))); return $shortname; }
php
public static function increment_shortname($shortname) { global $DB; do { $matches = array(); if (!preg_match('/(.*?)([0-9]+)$/', $shortname, $matches)) { $newshortname = $shortname . '_2'; } else { $newshortname = $matches[1] . ($matches[2]+1); } $shortname = $newshortname; } while ($DB->record_exists('course', array('shortname' => $shortname))); return $shortname; }
[ "public", "static", "function", "increment_shortname", "(", "$", "shortname", ")", "{", "global", "$", "DB", ";", "do", "{", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "!", "preg_match", "(", "'/(.*?)([0-9]+)$/'", ",", "$", "shortname", ",", "$", "matches", ")", ")", "{", "$", "newshortname", "=", "$", "shortname", ".", "'_2'", ";", "}", "else", "{", "$", "newshortname", "=", "$", "matches", "[", "1", "]", ".", "(", "$", "matches", "[", "2", "]", "+", "1", ")", ";", "}", "$", "shortname", "=", "$", "newshortname", ";", "}", "while", "(", "$", "DB", "->", "record_exists", "(", "'course'", ",", "array", "(", "'shortname'", "=>", "$", "shortname", ")", ")", ")", ";", "return", "$", "shortname", ";", "}" ]
Helper to increment a shortname. This considers that the shortname passed has to be incremented. @param string $shortname shortname to increment. @return string new shortname.
[ "Helper", "to", "increment", "a", "shortname", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L351-L363
218,953
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.resolve_category
public static function resolve_category($data, &$errors = array()) { $catid = null; if (!empty($data['category'])) { $category = core_course_category::get((int) $data['category'], IGNORE_MISSING); if (!empty($category) && !empty($category->id)) { $catid = $category->id; } else { $errors['couldnotresolvecatgorybyid'] = new lang_string('couldnotresolvecatgorybyid', 'tool_uploadcourse'); } } if (empty($catid) && !empty($data['category_idnumber'])) { $catid = self::resolve_category_by_idnumber($data['category_idnumber']); if (empty($catid)) { $errors['couldnotresolvecatgorybyidnumber'] = new lang_string('couldnotresolvecatgorybyidnumber', 'tool_uploadcourse'); } } if (empty($catid) && !empty($data['category_path'])) { $catid = self::resolve_category_by_path(explode(' / ', $data['category_path'])); if (empty($catid)) { $errors['couldnotresolvecatgorybypath'] = new lang_string('couldnotresolvecatgorybypath', 'tool_uploadcourse'); } } return $catid; }
php
public static function resolve_category($data, &$errors = array()) { $catid = null; if (!empty($data['category'])) { $category = core_course_category::get((int) $data['category'], IGNORE_MISSING); if (!empty($category) && !empty($category->id)) { $catid = $category->id; } else { $errors['couldnotresolvecatgorybyid'] = new lang_string('couldnotresolvecatgorybyid', 'tool_uploadcourse'); } } if (empty($catid) && !empty($data['category_idnumber'])) { $catid = self::resolve_category_by_idnumber($data['category_idnumber']); if (empty($catid)) { $errors['couldnotresolvecatgorybyidnumber'] = new lang_string('couldnotresolvecatgorybyidnumber', 'tool_uploadcourse'); } } if (empty($catid) && !empty($data['category_path'])) { $catid = self::resolve_category_by_path(explode(' / ', $data['category_path'])); if (empty($catid)) { $errors['couldnotresolvecatgorybypath'] = new lang_string('couldnotresolvecatgorybypath', 'tool_uploadcourse'); } } return $catid; }
[ "public", "static", "function", "resolve_category", "(", "$", "data", ",", "&", "$", "errors", "=", "array", "(", ")", ")", "{", "$", "catid", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "data", "[", "'category'", "]", ")", ")", "{", "$", "category", "=", "core_course_category", "::", "get", "(", "(", "int", ")", "$", "data", "[", "'category'", "]", ",", "IGNORE_MISSING", ")", ";", "if", "(", "!", "empty", "(", "$", "category", ")", "&&", "!", "empty", "(", "$", "category", "->", "id", ")", ")", "{", "$", "catid", "=", "$", "category", "->", "id", ";", "}", "else", "{", "$", "errors", "[", "'couldnotresolvecatgorybyid'", "]", "=", "new", "lang_string", "(", "'couldnotresolvecatgorybyid'", ",", "'tool_uploadcourse'", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "catid", ")", "&&", "!", "empty", "(", "$", "data", "[", "'category_idnumber'", "]", ")", ")", "{", "$", "catid", "=", "self", "::", "resolve_category_by_idnumber", "(", "$", "data", "[", "'category_idnumber'", "]", ")", ";", "if", "(", "empty", "(", "$", "catid", ")", ")", "{", "$", "errors", "[", "'couldnotresolvecatgorybyidnumber'", "]", "=", "new", "lang_string", "(", "'couldnotresolvecatgorybyidnumber'", ",", "'tool_uploadcourse'", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "catid", ")", "&&", "!", "empty", "(", "$", "data", "[", "'category_path'", "]", ")", ")", "{", "$", "catid", "=", "self", "::", "resolve_category_by_path", "(", "explode", "(", "' / '", ",", "$", "data", "[", "'category_path'", "]", ")", ")", ";", "if", "(", "empty", "(", "$", "catid", ")", ")", "{", "$", "errors", "[", "'couldnotresolvecatgorybypath'", "]", "=", "new", "lang_string", "(", "'couldnotresolvecatgorybypath'", ",", "'tool_uploadcourse'", ")", ";", "}", "}", "return", "$", "catid", ";", "}" ]
Resolve a category based on the data passed. Key accepted are: - category, which is supposed to be a category ID. - category_idnumber - category_path, array of categories from parent to child. @param array $data to resolve the category from. @param array $errors will be populated with errors found. @return int category ID.
[ "Resolve", "a", "category", "based", "on", "the", "data", "passed", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L377-L406
218,954
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.resolve_category_by_idnumber
public static function resolve_category_by_idnumber($idnumber) { global $DB; $cache = cache::make('tool_uploadcourse', 'helper'); $cachekey = 'cat_idn_' . $idnumber; if (($id = $cache->get($cachekey)) === false) { $params = array('idnumber' => $idnumber); $id = $DB->get_field_select('course_categories', 'id', 'idnumber = :idnumber', $params, IGNORE_MISSING); // Little hack to be able to differenciate between the cache not set and a category not found. if ($id === false) { $id = -1; } $cache->set($cachekey, $id); } // Little hack to be able to differenciate between the cache not set and a category not found. if ($id == -1) { $id = false; } return $id; }
php
public static function resolve_category_by_idnumber($idnumber) { global $DB; $cache = cache::make('tool_uploadcourse', 'helper'); $cachekey = 'cat_idn_' . $idnumber; if (($id = $cache->get($cachekey)) === false) { $params = array('idnumber' => $idnumber); $id = $DB->get_field_select('course_categories', 'id', 'idnumber = :idnumber', $params, IGNORE_MISSING); // Little hack to be able to differenciate between the cache not set and a category not found. if ($id === false) { $id = -1; } $cache->set($cachekey, $id); } // Little hack to be able to differenciate between the cache not set and a category not found. if ($id == -1) { $id = false; } return $id; }
[ "public", "static", "function", "resolve_category_by_idnumber", "(", "$", "idnumber", ")", "{", "global", "$", "DB", ";", "$", "cache", "=", "cache", "::", "make", "(", "'tool_uploadcourse'", ",", "'helper'", ")", ";", "$", "cachekey", "=", "'cat_idn_'", ".", "$", "idnumber", ";", "if", "(", "(", "$", "id", "=", "$", "cache", "->", "get", "(", "$", "cachekey", ")", ")", "===", "false", ")", "{", "$", "params", "=", "array", "(", "'idnumber'", "=>", "$", "idnumber", ")", ";", "$", "id", "=", "$", "DB", "->", "get_field_select", "(", "'course_categories'", ",", "'id'", ",", "'idnumber = :idnumber'", ",", "$", "params", ",", "IGNORE_MISSING", ")", ";", "// Little hack to be able to differenciate between the cache not set and a category not found.", "if", "(", "$", "id", "===", "false", ")", "{", "$", "id", "=", "-", "1", ";", "}", "$", "cache", "->", "set", "(", "$", "cachekey", ",", "$", "id", ")", ";", "}", "// Little hack to be able to differenciate between the cache not set and a category not found.", "if", "(", "$", "id", "==", "-", "1", ")", "{", "$", "id", "=", "false", ";", "}", "return", "$", "id", ";", "}" ]
Resolve a category by ID number. @param string $idnumber category ID number. @return int category ID.
[ "Resolve", "a", "category", "by", "ID", "number", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L414-L436
218,955
moodle/moodle
admin/tool/uploadcourse/classes/helper.php
tool_uploadcourse_helper.resolve_category_by_path
public static function resolve_category_by_path(array $path) { global $DB; $cache = cache::make('tool_uploadcourse', 'helper'); $cachekey = 'cat_path_' . serialize($path); if (($id = $cache->get($cachekey)) === false) { $parent = 0; $sql = 'name = :name AND parent = :parent'; while ($name = array_shift($path)) { $params = array('name' => $name, 'parent' => $parent); if ($records = $DB->get_records_select('course_categories', $sql, $params, null, 'id, parent')) { if (count($records) > 1) { // Too many records with the same name! $id = -1; break; } $record = reset($records); $id = $record->id; $parent = $record->id; } else { // Not found. $id = -1; break; } } $cache->set($cachekey, $id); } // We save -1 when the category has not been found to be able to know if the cache was set. if ($id == -1) { $id = false; } return $id; }
php
public static function resolve_category_by_path(array $path) { global $DB; $cache = cache::make('tool_uploadcourse', 'helper'); $cachekey = 'cat_path_' . serialize($path); if (($id = $cache->get($cachekey)) === false) { $parent = 0; $sql = 'name = :name AND parent = :parent'; while ($name = array_shift($path)) { $params = array('name' => $name, 'parent' => $parent); if ($records = $DB->get_records_select('course_categories', $sql, $params, null, 'id, parent')) { if (count($records) > 1) { // Too many records with the same name! $id = -1; break; } $record = reset($records); $id = $record->id; $parent = $record->id; } else { // Not found. $id = -1; break; } } $cache->set($cachekey, $id); } // We save -1 when the category has not been found to be able to know if the cache was set. if ($id == -1) { $id = false; } return $id; }
[ "public", "static", "function", "resolve_category_by_path", "(", "array", "$", "path", ")", "{", "global", "$", "DB", ";", "$", "cache", "=", "cache", "::", "make", "(", "'tool_uploadcourse'", ",", "'helper'", ")", ";", "$", "cachekey", "=", "'cat_path_'", ".", "serialize", "(", "$", "path", ")", ";", "if", "(", "(", "$", "id", "=", "$", "cache", "->", "get", "(", "$", "cachekey", ")", ")", "===", "false", ")", "{", "$", "parent", "=", "0", ";", "$", "sql", "=", "'name = :name AND parent = :parent'", ";", "while", "(", "$", "name", "=", "array_shift", "(", "$", "path", ")", ")", "{", "$", "params", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'parent'", "=>", "$", "parent", ")", ";", "if", "(", "$", "records", "=", "$", "DB", "->", "get_records_select", "(", "'course_categories'", ",", "$", "sql", ",", "$", "params", ",", "null", ",", "'id, parent'", ")", ")", "{", "if", "(", "count", "(", "$", "records", ")", ">", "1", ")", "{", "// Too many records with the same name!", "$", "id", "=", "-", "1", ";", "break", ";", "}", "$", "record", "=", "reset", "(", "$", "records", ")", ";", "$", "id", "=", "$", "record", "->", "id", ";", "$", "parent", "=", "$", "record", "->", "id", ";", "}", "else", "{", "// Not found.", "$", "id", "=", "-", "1", ";", "break", ";", "}", "}", "$", "cache", "->", "set", "(", "$", "cachekey", ",", "$", "id", ")", ";", "}", "// We save -1 when the category has not been found to be able to know if the cache was set.", "if", "(", "$", "id", "==", "-", "1", ")", "{", "$", "id", "=", "false", ";", "}", "return", "$", "id", ";", "}" ]
Resolve a category by path. @param array $path category names indexed from parent to children. @return int category ID.
[ "Resolve", "a", "category", "by", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/helper.php#L444-L476
218,956
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.do_query
private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) { list($sql, $params, $type) = $this->fix_sql_params($sql, $params); /* * Bound variables *are* supported. Until I can get it to work, emulate the bindings * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY() * doesn't return a value (no result set) * * -- somebody from MS */ $sql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, $sql_query_type); if (!$scrollable) { // Only supporting next row $result = sqlsrv_query($this->sqlsrv, $sql); } else { // Supporting absolute/relative rows $result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC)); } if ($result === false) { // TODO do something with error or just use if DEV or DEBUG? $dberr = $this->get_last_error(); } $this->query_end($result); if ($free_result) { $this->free_result($result); return true; } return $result; }
php
private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) { list($sql, $params, $type) = $this->fix_sql_params($sql, $params); /* * Bound variables *are* supported. Until I can get it to work, emulate the bindings * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY() * doesn't return a value (no result set) * * -- somebody from MS */ $sql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, $sql_query_type); if (!$scrollable) { // Only supporting next row $result = sqlsrv_query($this->sqlsrv, $sql); } else { // Supporting absolute/relative rows $result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC)); } if ($result === false) { // TODO do something with error or just use if DEV or DEBUG? $dberr = $this->get_last_error(); } $this->query_end($result); if ($free_result) { $this->free_result($result); return true; } return $result; }
[ "private", "function", "do_query", "(", "$", "sql", ",", "$", "params", ",", "$", "sql_query_type", ",", "$", "free_result", "=", "true", ",", "$", "scrollable", "=", "false", ")", "{", "list", "(", "$", "sql", ",", "$", "params", ",", "$", "type", ")", "=", "$", "this", "->", "fix_sql_params", "(", "$", "sql", ",", "$", "params", ")", ";", "/*\n * Bound variables *are* supported. Until I can get it to work, emulate the bindings\n * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY()\n * doesn't return a value (no result set)\n *\n * -- somebody from MS\n */", "$", "sql", "=", "$", "this", "->", "emulate_bound_params", "(", "$", "sql", ",", "$", "params", ")", ";", "$", "this", "->", "query_start", "(", "$", "sql", ",", "$", "params", ",", "$", "sql_query_type", ")", ";", "if", "(", "!", "$", "scrollable", ")", "{", "// Only supporting next row", "$", "result", "=", "sqlsrv_query", "(", "$", "this", "->", "sqlsrv", ",", "$", "sql", ")", ";", "}", "else", "{", "// Supporting absolute/relative rows", "$", "result", "=", "sqlsrv_query", "(", "$", "this", "->", "sqlsrv", ",", "$", "sql", ",", "array", "(", ")", ",", "array", "(", "'Scrollable'", "=>", "SQLSRV_CURSOR_STATIC", ")", ")", ";", "}", "if", "(", "$", "result", "===", "false", ")", "{", "// TODO do something with error or just use if DEV or DEBUG?", "$", "dberr", "=", "$", "this", "->", "get_last_error", "(", ")", ";", "}", "$", "this", "->", "query_end", "(", "$", "result", ")", ";", "if", "(", "$", "free_result", ")", "{", "$", "this", "->", "free_result", "(", "$", "result", ")", ";", "return", "true", ";", "}", "return", "$", "result", ";", "}" ]
Prepare the query binding and do the actual query. @param string $sql The sql statement @param array $params array of params for binding. If NULL, they are ignored. @param int $sql_query_type - Type of operation @param bool $free_result - Default true, transaction query will be freed. @param bool $scrollable - Default false, to use for quickly seeking to target records @return resource|bool result
[ "Prepare", "the", "query", "binding", "and", "do", "the", "actual", "query", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L407-L438
218,957
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.sqlsrvtype2moodletype
private function sqlsrvtype2moodletype($sqlsrv_type) { $type = null; switch (strtoupper($sqlsrv_type)) { case 'BIT': $type = 'L'; break; case 'INT': case 'SMALLINT': case 'INTEGER': case 'BIGINT': $type = 'I'; break; case 'DECIMAL': case 'REAL': case 'FLOAT': $type = 'N'; break; case 'VARCHAR': case 'NVARCHAR': $type = 'C'; break; case 'TEXT': case 'NTEXT': case 'VARCHAR(MAX)': case 'NVARCHAR(MAX)': $type = 'X'; break; case 'IMAGE': case 'VARBINARY': case 'VARBINARY(MAX)': $type = 'B'; break; case 'DATETIME': $type = 'D'; break; } if (!$type) { throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type); } return $type; }
php
private function sqlsrvtype2moodletype($sqlsrv_type) { $type = null; switch (strtoupper($sqlsrv_type)) { case 'BIT': $type = 'L'; break; case 'INT': case 'SMALLINT': case 'INTEGER': case 'BIGINT': $type = 'I'; break; case 'DECIMAL': case 'REAL': case 'FLOAT': $type = 'N'; break; case 'VARCHAR': case 'NVARCHAR': $type = 'C'; break; case 'TEXT': case 'NTEXT': case 'VARCHAR(MAX)': case 'NVARCHAR(MAX)': $type = 'X'; break; case 'IMAGE': case 'VARBINARY': case 'VARBINARY(MAX)': $type = 'B'; break; case 'DATETIME': $type = 'D'; break; } if (!$type) { throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type); } return $type; }
[ "private", "function", "sqlsrvtype2moodletype", "(", "$", "sqlsrv_type", ")", "{", "$", "type", "=", "null", ";", "switch", "(", "strtoupper", "(", "$", "sqlsrv_type", ")", ")", "{", "case", "'BIT'", ":", "$", "type", "=", "'L'", ";", "break", ";", "case", "'INT'", ":", "case", "'SMALLINT'", ":", "case", "'INTEGER'", ":", "case", "'BIGINT'", ":", "$", "type", "=", "'I'", ";", "break", ";", "case", "'DECIMAL'", ":", "case", "'REAL'", ":", "case", "'FLOAT'", ":", "$", "type", "=", "'N'", ";", "break", ";", "case", "'VARCHAR'", ":", "case", "'NVARCHAR'", ":", "$", "type", "=", "'C'", ";", "break", ";", "case", "'TEXT'", ":", "case", "'NTEXT'", ":", "case", "'VARCHAR(MAX)'", ":", "case", "'NVARCHAR(MAX)'", ":", "$", "type", "=", "'X'", ";", "break", ";", "case", "'IMAGE'", ":", "case", "'VARBINARY'", ":", "case", "'VARBINARY(MAX)'", ":", "$", "type", "=", "'B'", ";", "break", ";", "case", "'DATETIME'", ":", "$", "type", "=", "'D'", ";", "break", ";", "}", "if", "(", "!", "$", "type", ")", "{", "throw", "new", "dml_exception", "(", "'invalidsqlsrvnativetype'", ",", "$", "sqlsrv_type", ")", ";", "}", "return", "$", "type", ";", "}" ]
Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones) @param string $sqlsrv_type native sqlsrv data type @return string 1-char database_column_info data type
[ "Provides", "mapping", "between", "sqlsrv", "native", "data", "types", "and", "moodle_database", "-", "database_column_info", "-", "ones", ")" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L707-L755
218,958
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.add_no_lock_to_temp_tables
protected function add_no_lock_to_temp_tables($sql) { return preg_replace_callback('/(\{([a-z][a-z0-9_]*)\})(\s+(\w+))?/', function($matches) { $table = $matches[1]; // With the braces, so we can put it back in the query. $name = $matches[2]; // Without the braces, so we can check if it's a temptable. $tail = isset($matches[3]) ? $matches[3] : ''; // Catch the next word afterwards so that we can check if it's an alias. $replacement = $matches[0]; // The table and the word following it, so we can replace it back if no changes are needed. if ($this->temptables && $this->temptables->is_temptable($name)) { if (!empty($tail)) { if (in_array(strtolower(trim($tail)), $this->reservewords)) { // If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between. return $table . ' WITH (NOLOCK)' . $tail; } } // If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match. return $replacement . ' WITH (NOLOCK)'; } else { return $replacement; } }, $sql); }
php
protected function add_no_lock_to_temp_tables($sql) { return preg_replace_callback('/(\{([a-z][a-z0-9_]*)\})(\s+(\w+))?/', function($matches) { $table = $matches[1]; // With the braces, so we can put it back in the query. $name = $matches[2]; // Without the braces, so we can check if it's a temptable. $tail = isset($matches[3]) ? $matches[3] : ''; // Catch the next word afterwards so that we can check if it's an alias. $replacement = $matches[0]; // The table and the word following it, so we can replace it back if no changes are needed. if ($this->temptables && $this->temptables->is_temptable($name)) { if (!empty($tail)) { if (in_array(strtolower(trim($tail)), $this->reservewords)) { // If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between. return $table . ' WITH (NOLOCK)' . $tail; } } // If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match. return $replacement . ' WITH (NOLOCK)'; } else { return $replacement; } }, $sql); }
[ "protected", "function", "add_no_lock_to_temp_tables", "(", "$", "sql", ")", "{", "return", "preg_replace_callback", "(", "'/(\\{([a-z][a-z0-9_]*)\\})(\\s+(\\w+))?/'", ",", "function", "(", "$", "matches", ")", "{", "$", "table", "=", "$", "matches", "[", "1", "]", ";", "// With the braces, so we can put it back in the query.", "$", "name", "=", "$", "matches", "[", "2", "]", ";", "// Without the braces, so we can check if it's a temptable.", "$", "tail", "=", "isset", "(", "$", "matches", "[", "3", "]", ")", "?", "$", "matches", "[", "3", "]", ":", "''", ";", "// Catch the next word afterwards so that we can check if it's an alias.", "$", "replacement", "=", "$", "matches", "[", "0", "]", ";", "// The table and the word following it, so we can replace it back if no changes are needed.", "if", "(", "$", "this", "->", "temptables", "&&", "$", "this", "->", "temptables", "->", "is_temptable", "(", "$", "name", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "tail", ")", ")", "{", "if", "(", "in_array", "(", "strtolower", "(", "trim", "(", "$", "tail", ")", ")", ",", "$", "this", "->", "reservewords", ")", ")", "{", "// If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between.", "return", "$", "table", ".", "' WITH (NOLOCK)'", ".", "$", "tail", ";", "}", "}", "// If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match.", "return", "$", "replacement", ".", "' WITH (NOLOCK)'", ";", "}", "else", "{", "return", "$", "replacement", ";", "}", "}", ",", "$", "sql", ")", ";", "}" ]
Use NOLOCK on any temp tables. Since it's a temp table and uncommitted reads are low risk anyway. @param string $sql the SQL select query to execute. @return string The SQL, with WITH (NOLOCK) added to all temp tables
[ "Use", "NOLOCK", "on", "any", "temp", "tables", ".", "Since", "it", "s", "a", "temp", "table", "and", "uncommitted", "reads", "are", "low", "risk", "anyway", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L910-L930
218,959
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.create_recordset
protected function create_recordset($result) { $rs = new sqlsrv_native_moodle_recordset($result, $this); $this->recordsets[] = $rs; return $rs; }
php
protected function create_recordset($result) { $rs = new sqlsrv_native_moodle_recordset($result, $this); $this->recordsets[] = $rs; return $rs; }
[ "protected", "function", "create_recordset", "(", "$", "result", ")", "{", "$", "rs", "=", "new", "sqlsrv_native_moodle_recordset", "(", "$", "result", ",", "$", "this", ")", ";", "$", "this", "->", "recordsets", "[", "]", "=", "$", "rs", ";", "return", "$", "rs", ";", "}" ]
Create a record set and initialize with first row @param mixed $result @return sqlsrv_native_moodle_recordset
[ "Create", "a", "record", "set", "and", "initialize", "with", "first", "row" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L938-L942
218,960
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.recordset_closed
public function recordset_closed(sqlsrv_native_moodle_recordset $rs) { if ($key = array_search($rs, $this->recordsets, true)) { unset($this->recordsets[$key]); } }
php
public function recordset_closed(sqlsrv_native_moodle_recordset $rs) { if ($key = array_search($rs, $this->recordsets, true)) { unset($this->recordsets[$key]); } }
[ "public", "function", "recordset_closed", "(", "sqlsrv_native_moodle_recordset", "$", "rs", ")", "{", "if", "(", "$", "key", "=", "array_search", "(", "$", "rs", ",", "$", "this", "->", "recordsets", ",", "true", ")", ")", "{", "unset", "(", "$", "this", "->", "recordsets", "[", "$", "key", "]", ")", ";", "}", "}" ]
Do not use outside of recordset class. @internal @param sqlsrv_native_moodle_recordset $rs
[ "Do", "not", "use", "outside", "of", "recordset", "class", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L949-L953
218,961
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.sqlsrv_fetch_id
private function sqlsrv_fetch_id() { $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()'); if ($query_id === false) { $dberr = $this->get_last_error(); return false; } $row = $this->sqlsrv_fetchrow($query_id); return (int)$row[0]; }
php
private function sqlsrv_fetch_id() { $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()'); if ($query_id === false) { $dberr = $this->get_last_error(); return false; } $row = $this->sqlsrv_fetchrow($query_id); return (int)$row[0]; }
[ "private", "function", "sqlsrv_fetch_id", "(", ")", "{", "$", "query_id", "=", "sqlsrv_query", "(", "$", "this", "->", "sqlsrv", ",", "'SELECT SCOPE_IDENTITY()'", ")", ";", "if", "(", "$", "query_id", "===", "false", ")", "{", "$", "dberr", "=", "$", "this", "->", "get_last_error", "(", ")", ";", "return", "false", ";", "}", "$", "row", "=", "$", "this", "->", "sqlsrv_fetchrow", "(", "$", "query_id", ")", ";", "return", "(", "int", ")", "$", "row", "[", "0", "]", ";", "}" ]
Get the ID of the current action @return mixed ID
[ "Get", "the", "ID", "of", "the", "current", "action" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L1082-L1090
218,962
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.sqlsrv_fetchrow
private function sqlsrv_fetchrow($query_id) { $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC); if ($row === false) { $dberr = $this->get_last_error(); return false; } foreach ($row as $key => $value) { $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value; } return $row; }
php
private function sqlsrv_fetchrow($query_id) { $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC); if ($row === false) { $dberr = $this->get_last_error(); return false; } foreach ($row as $key => $value) { $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value; } return $row; }
[ "private", "function", "sqlsrv_fetchrow", "(", "$", "query_id", ")", "{", "$", "row", "=", "sqlsrv_fetch_array", "(", "$", "query_id", ",", "SQLSRV_FETCH_NUMERIC", ")", ";", "if", "(", "$", "row", "===", "false", ")", "{", "$", "dberr", "=", "$", "this", "->", "get_last_error", "(", ")", ";", "return", "false", ";", "}", "foreach", "(", "$", "row", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "row", "[", "$", "key", "]", "=", "(", "$", "value", "===", "' '", "||", "$", "value", "===", "NULL", ")", "?", "''", ":", "$", "value", ";", "}", "return", "$", "row", ";", "}" ]
Fetch a single row into an numbered array @param mixed $query_id
[ "Fetch", "a", "single", "row", "into", "an", "numbered", "array" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L1097-L1108
218,963
moodle/moodle
lib/dml/sqlsrv_native_moodle_database.php
sqlsrv_native_moodle_database.is_fulltext_search_supported
public function is_fulltext_search_supported() { global $CFG; $sql = "SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); if ($result) { if ($row = sqlsrv_fetch_array($result)) { $property = (bool)reset($row); } } $this->free_result($result); return !empty($property); }
php
public function is_fulltext_search_supported() { global $CFG; $sql = "SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); if ($result) { if ($row = sqlsrv_fetch_array($result)) { $property = (bool)reset($row); } } $this->free_result($result); return !empty($property); }
[ "public", "function", "is_fulltext_search_supported", "(", ")", "{", "global", "$", "CFG", ";", "$", "sql", "=", "\"SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')\"", ";", "$", "this", "->", "query_start", "(", "$", "sql", ",", "null", ",", "SQL_QUERY_AUX", ")", ";", "$", "result", "=", "sqlsrv_query", "(", "$", "this", "->", "sqlsrv", ",", "$", "sql", ")", ";", "$", "this", "->", "query_end", "(", "$", "result", ")", ";", "if", "(", "$", "result", ")", "{", "if", "(", "$", "row", "=", "sqlsrv_fetch_array", "(", "$", "result", ")", ")", "{", "$", "property", "=", "(", "bool", ")", "reset", "(", "$", "row", ")", ";", "}", "}", "$", "this", "->", "free_result", "(", "$", "result", ")", ";", "return", "!", "empty", "(", "$", "property", ")", ";", "}" ]
Is fulltext search enabled?. @return bool
[ "Is", "fulltext", "search", "enabled?", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dml/sqlsrv_native_moodle_database.php#L1595-L1610
218,964
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.get_backup_status_array
public static function get_backup_status_array() { global $DB; $result = array( self::BACKUP_STATUS_ERROR => 0, self::BACKUP_STATUS_OK => 0, self::BACKUP_STATUS_UNFINISHED => 0, self::BACKUP_STATUS_SKIPPED => 0, self::BACKUP_STATUS_WARNING => 0, self::BACKUP_STATUS_NOTYETRUN => 0 ); $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus'); foreach ($statuses as $status) { if (empty($status->statuscount)) { $status->statuscount = 0; } $result[(int)$status->laststatus] += $status->statuscount; } return $result; }
php
public static function get_backup_status_array() { global $DB; $result = array( self::BACKUP_STATUS_ERROR => 0, self::BACKUP_STATUS_OK => 0, self::BACKUP_STATUS_UNFINISHED => 0, self::BACKUP_STATUS_SKIPPED => 0, self::BACKUP_STATUS_WARNING => 0, self::BACKUP_STATUS_NOTYETRUN => 0 ); $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus'); foreach ($statuses as $status) { if (empty($status->statuscount)) { $status->statuscount = 0; } $result[(int)$status->laststatus] += $status->statuscount; } return $result; }
[ "public", "static", "function", "get_backup_status_array", "(", ")", "{", "global", "$", "DB", ";", "$", "result", "=", "array", "(", "self", "::", "BACKUP_STATUS_ERROR", "=>", "0", ",", "self", "::", "BACKUP_STATUS_OK", "=>", "0", ",", "self", "::", "BACKUP_STATUS_UNFINISHED", "=>", "0", ",", "self", "::", "BACKUP_STATUS_SKIPPED", "=>", "0", ",", "self", "::", "BACKUP_STATUS_WARNING", "=>", "0", ",", "self", "::", "BACKUP_STATUS_NOTYETRUN", "=>", "0", ")", ";", "$", "statuses", "=", "$", "DB", "->", "get_records_sql", "(", "'SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus'", ")", ";", "foreach", "(", "$", "statuses", "as", "$", "status", ")", "{", "if", "(", "empty", "(", "$", "status", "->", "statuscount", ")", ")", "{", "$", "status", "->", "statuscount", "=", "0", ";", "}", "$", "result", "[", "(", "int", ")", "$", "status", "->", "laststatus", "]", "+=", "$", "status", "->", "statuscount", ";", "}", "return", "$", "result", ";", "}" ]
Gets the results from the last automated backup that was run based upon the statuses of the courses that were looked at. @global moodle_database $DB @return array
[ "Gets", "the", "results", "from", "the", "last", "automated", "backup", "that", "was", "run", "based", "upon", "the", "statuses", "of", "the", "courses", "that", "were", "looked", "at", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L299-L321
218,965
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.calculate_next_automated_backup
public static function calculate_next_automated_backup($ignoredtimezone, $now) { $config = get_config('backup'); $backuptime = new DateTime('@' . $now); $backuptime->setTimezone(core_date::get_server_timezone_object()); $backuptime->setTime($config->backup_auto_hour, $config->backup_auto_minute); while ($backuptime->getTimestamp() < $now) { $backuptime->add(new DateInterval('P1D')); } // Get number of days from backup date to execute backups. $automateddays = substr($config->backup_auto_weekdays, $backuptime->format('w')) . $config->backup_auto_weekdays; $daysfromnow = strpos($automateddays, "1"); // Error, there are no days to schedule the backup for. if ($daysfromnow === false) { return 0; } if ($daysfromnow > 0) { $backuptime->add(new DateInterval('P' . $daysfromnow . 'D')); } return $backuptime->getTimestamp(); }
php
public static function calculate_next_automated_backup($ignoredtimezone, $now) { $config = get_config('backup'); $backuptime = new DateTime('@' . $now); $backuptime->setTimezone(core_date::get_server_timezone_object()); $backuptime->setTime($config->backup_auto_hour, $config->backup_auto_minute); while ($backuptime->getTimestamp() < $now) { $backuptime->add(new DateInterval('P1D')); } // Get number of days from backup date to execute backups. $automateddays = substr($config->backup_auto_weekdays, $backuptime->format('w')) . $config->backup_auto_weekdays; $daysfromnow = strpos($automateddays, "1"); // Error, there are no days to schedule the backup for. if ($daysfromnow === false) { return 0; } if ($daysfromnow > 0) { $backuptime->add(new DateInterval('P' . $daysfromnow . 'D')); } return $backuptime->getTimestamp(); }
[ "public", "static", "function", "calculate_next_automated_backup", "(", "$", "ignoredtimezone", ",", "$", "now", ")", "{", "$", "config", "=", "get_config", "(", "'backup'", ")", ";", "$", "backuptime", "=", "new", "DateTime", "(", "'@'", ".", "$", "now", ")", ";", "$", "backuptime", "->", "setTimezone", "(", "core_date", "::", "get_server_timezone_object", "(", ")", ")", ";", "$", "backuptime", "->", "setTime", "(", "$", "config", "->", "backup_auto_hour", ",", "$", "config", "->", "backup_auto_minute", ")", ";", "while", "(", "$", "backuptime", "->", "getTimestamp", "(", ")", "<", "$", "now", ")", "{", "$", "backuptime", "->", "add", "(", "new", "DateInterval", "(", "'P1D'", ")", ")", ";", "}", "// Get number of days from backup date to execute backups.", "$", "automateddays", "=", "substr", "(", "$", "config", "->", "backup_auto_weekdays", ",", "$", "backuptime", "->", "format", "(", "'w'", ")", ")", ".", "$", "config", "->", "backup_auto_weekdays", ";", "$", "daysfromnow", "=", "strpos", "(", "$", "automateddays", ",", "\"1\"", ")", ";", "// Error, there are no days to schedule the backup for.", "if", "(", "$", "daysfromnow", "===", "false", ")", "{", "return", "0", ";", "}", "if", "(", "$", "daysfromnow", ">", "0", ")", "{", "$", "backuptime", "->", "add", "(", "new", "DateInterval", "(", "'P'", ".", "$", "daysfromnow", ".", "'D'", ")", ")", ";", "}", "return", "$", "backuptime", "->", "getTimestamp", "(", ")", ";", "}" ]
Works out the next time the automated backup should be run. @param mixed $ignoredtimezone all settings are in server timezone! @param int $now timestamp, should not be in the past, most likely time() @return int timestamp of the next execution at server time
[ "Works", "out", "the", "next", "time", "the", "automated", "backup", "should", "be", "run", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L330-L356
218,966
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.outcome_from_results
public static function outcome_from_results($results) { $outcome = self::BACKUP_STATUS_OK; foreach ($results as $code => $value) { // Each possible error and warning code has to be specified in this switch // which basically analyses the results to return the correct backup status. switch ($code) { case 'missing_files_in_pool': $outcome = self::BACKUP_STATUS_WARNING; break; } // If we found the highest error level, we exit the loop. if ($outcome == self::BACKUP_STATUS_ERROR) { break; } } return $outcome; }
php
public static function outcome_from_results($results) { $outcome = self::BACKUP_STATUS_OK; foreach ($results as $code => $value) { // Each possible error and warning code has to be specified in this switch // which basically analyses the results to return the correct backup status. switch ($code) { case 'missing_files_in_pool': $outcome = self::BACKUP_STATUS_WARNING; break; } // If we found the highest error level, we exit the loop. if ($outcome == self::BACKUP_STATUS_ERROR) { break; } } return $outcome; }
[ "public", "static", "function", "outcome_from_results", "(", "$", "results", ")", "{", "$", "outcome", "=", "self", "::", "BACKUP_STATUS_OK", ";", "foreach", "(", "$", "results", "as", "$", "code", "=>", "$", "value", ")", "{", "// Each possible error and warning code has to be specified in this switch", "// which basically analyses the results to return the correct backup status.", "switch", "(", "$", "code", ")", "{", "case", "'missing_files_in_pool'", ":", "$", "outcome", "=", "self", "::", "BACKUP_STATUS_WARNING", ";", "break", ";", "}", "// If we found the highest error level, we exit the loop.", "if", "(", "$", "outcome", "==", "self", "::", "BACKUP_STATUS_ERROR", ")", "{", "break", ";", "}", "}", "return", "$", "outcome", ";", "}" ]
Returns the backup outcome by analysing its results. @param array $results returned by a backup @return int {@link self::BACKUP_STATUS_OK} and other constants
[ "Returns", "the", "backup", "outcome", "by", "analysing", "its", "results", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L454-L470
218,967
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.remove_deleted_courses_from_schedule
public static function remove_deleted_courses_from_schedule() { global $DB; $skipped = 0; $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)"; $rs = $DB->get_recordset_sql($sql); foreach ($rs as $deletedcourse) { //Doesn't exist, so delete from backup tables $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid)); $skipped++; } $rs->close(); return $skipped; }
php
public static function remove_deleted_courses_from_schedule() { global $DB; $skipped = 0; $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)"; $rs = $DB->get_recordset_sql($sql); foreach ($rs as $deletedcourse) { //Doesn't exist, so delete from backup tables $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid)); $skipped++; } $rs->close(); return $skipped; }
[ "public", "static", "function", "remove_deleted_courses_from_schedule", "(", ")", "{", "global", "$", "DB", ";", "$", "skipped", "=", "0", ";", "$", "sql", "=", "\"SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)\"", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ")", ";", "foreach", "(", "$", "rs", "as", "$", "deletedcourse", ")", "{", "//Doesn't exist, so delete from backup tables", "$", "DB", "->", "delete_records", "(", "'backup_courses'", ",", "array", "(", "'courseid'", "=>", "$", "deletedcourse", "->", "courseid", ")", ")", ";", "$", "skipped", "++", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "return", "$", "skipped", ";", "}" ]
Removes deleted courses fromn the backup_courses table so that we don't waste time backing them up. @global moodle_database $DB @return int
[ "Removes", "deleted", "courses", "fromn", "the", "backup_courses", "table", "so", "that", "we", "don", "t", "waste", "time", "backing", "them", "up", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L479-L491
218,968
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.get_automated_backup_state
public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) { global $DB; $config = get_config('backup'); $active = (int)$config->backup_auto_active; $weekdays = (string)$config->backup_auto_weekdays; // In case of automated backup also check that it is scheduled for at least one weekday. if ($active === self::AUTO_BACKUP_DISABLED || ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) || ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) { return self::STATE_DISABLED; } else if (!empty($config->backup_auto_running)) { // Detect if the backup_auto_running semaphore is a valid one // by looking for recent activity in the backup_controllers table // for backups of type backup::MODE_AUTOMATED $timetosee = 60 * 90; // Time to consider in order to clean the semaphore $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee)); if ($DB->record_exists_select('backup_controllers', "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) { return self::STATE_RUNNING; // Recent activity found, still running } else { // No recent activity found, let's clean the semaphore mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status'); backup_cron_automated_helper::set_state_running(false); } } return self::STATE_OK; }
php
public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) { global $DB; $config = get_config('backup'); $active = (int)$config->backup_auto_active; $weekdays = (string)$config->backup_auto_weekdays; // In case of automated backup also check that it is scheduled for at least one weekday. if ($active === self::AUTO_BACKUP_DISABLED || ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) || ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) { return self::STATE_DISABLED; } else if (!empty($config->backup_auto_running)) { // Detect if the backup_auto_running semaphore is a valid one // by looking for recent activity in the backup_controllers table // for backups of type backup::MODE_AUTOMATED $timetosee = 60 * 90; // Time to consider in order to clean the semaphore $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee)); if ($DB->record_exists_select('backup_controllers', "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) { return self::STATE_RUNNING; // Recent activity found, still running } else { // No recent activity found, let's clean the semaphore mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status'); backup_cron_automated_helper::set_state_running(false); } } return self::STATE_OK; }
[ "public", "static", "function", "get_automated_backup_state", "(", "$", "rundirective", "=", "self", "::", "RUN_ON_SCHEDULE", ")", "{", "global", "$", "DB", ";", "$", "config", "=", "get_config", "(", "'backup'", ")", ";", "$", "active", "=", "(", "int", ")", "$", "config", "->", "backup_auto_active", ";", "$", "weekdays", "=", "(", "string", ")", "$", "config", "->", "backup_auto_weekdays", ";", "// In case of automated backup also check that it is scheduled for at least one weekday.", "if", "(", "$", "active", "===", "self", "::", "AUTO_BACKUP_DISABLED", "||", "(", "$", "rundirective", "==", "self", "::", "RUN_ON_SCHEDULE", "&&", "$", "active", "===", "self", "::", "AUTO_BACKUP_MANUAL", ")", "||", "(", "$", "rundirective", "==", "self", "::", "RUN_ON_SCHEDULE", "&&", "strpos", "(", "$", "weekdays", ",", "'1'", ")", "===", "false", ")", ")", "{", "return", "self", "::", "STATE_DISABLED", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "config", "->", "backup_auto_running", ")", ")", "{", "// Detect if the backup_auto_running semaphore is a valid one", "// by looking for recent activity in the backup_controllers table", "// for backups of type backup::MODE_AUTOMATED", "$", "timetosee", "=", "60", "*", "90", ";", "// Time to consider in order to clean the semaphore", "$", "params", "=", "array", "(", "'purpose'", "=>", "backup", "::", "MODE_AUTOMATED", ",", "'timetolook'", "=>", "(", "time", "(", ")", "-", "$", "timetosee", ")", ")", ";", "if", "(", "$", "DB", "->", "record_exists_select", "(", "'backup_controllers'", ",", "\"operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook\"", ",", "$", "params", ")", ")", "{", "return", "self", "::", "STATE_RUNNING", ";", "// Recent activity found, still running", "}", "else", "{", "// No recent activity found, let's clean the semaphore", "mtrace", "(", "'Automated backups activity not found in last '", ".", "(", "int", ")", "$", "timetosee", "/", "60", ".", "' minutes. Cleaning running status'", ")", ";", "backup_cron_automated_helper", "::", "set_state_running", "(", "false", ")", ";", "}", "}", "return", "self", "::", "STATE_OK", ";", "}" ]
Gets the state of the automated backup system. @global moodle_database $DB @return int One of self::STATE_*
[ "Gets", "the", "state", "of", "the", "automated", "backup", "system", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L499-L527
218,969
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.set_state_running
public static function set_state_running($running = true) { if ($running === true) { if (self::get_automated_backup_state() === self::STATE_RUNNING) { throw new backup_helper_exception('backup_automated_already_running'); } set_config('backup_auto_running', '1', 'backup'); } else { unset_config('backup_auto_running', 'backup'); } return true; }
php
public static function set_state_running($running = true) { if ($running === true) { if (self::get_automated_backup_state() === self::STATE_RUNNING) { throw new backup_helper_exception('backup_automated_already_running'); } set_config('backup_auto_running', '1', 'backup'); } else { unset_config('backup_auto_running', 'backup'); } return true; }
[ "public", "static", "function", "set_state_running", "(", "$", "running", "=", "true", ")", "{", "if", "(", "$", "running", "===", "true", ")", "{", "if", "(", "self", "::", "get_automated_backup_state", "(", ")", "===", "self", "::", "STATE_RUNNING", ")", "{", "throw", "new", "backup_helper_exception", "(", "'backup_automated_already_running'", ")", ";", "}", "set_config", "(", "'backup_auto_running'", ",", "'1'", ",", "'backup'", ")", ";", "}", "else", "{", "unset_config", "(", "'backup_auto_running'", ",", "'backup'", ")", ";", "}", "return", "true", ";", "}" ]
Sets the state of the automated backup system. @param bool $running @return bool
[ "Sets", "the", "state", "of", "the", "automated", "backup", "system", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L535-L545
218,970
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.remove_excess_backups
public static function remove_excess_backups($course, $now = null) { $config = get_config('backup'); $maxkept = (int)$config->backup_auto_max_kept; $storage = $config->backup_auto_storage; $deletedays = (int)$config->backup_auto_delete_days; if ($maxkept == 0 && $deletedays == 0) { // Means keep all backup files and never delete backup after x days. return true; } if (!isset($now)) { $now = time(); } // Clean up excess backups in the course backup filearea. $deletedcoursebackups = false; if ($storage == self::STORAGE_COURSE || $storage == self::STORAGE_COURSE_AND_DIRECTORY) { $deletedcoursebackups = self::remove_excess_backups_from_course($course, $now); } // Clean up excess backups in the specified external directory. $deleteddirectorybackups = false; if ($storage == self::STORAGE_DIRECTORY || $storage == self::STORAGE_COURSE_AND_DIRECTORY) { $deleteddirectorybackups = self::remove_excess_backups_from_directory($course, $now); } if ($deletedcoursebackups || $deleteddirectorybackups) { return true; } else { return false; } }
php
public static function remove_excess_backups($course, $now = null) { $config = get_config('backup'); $maxkept = (int)$config->backup_auto_max_kept; $storage = $config->backup_auto_storage; $deletedays = (int)$config->backup_auto_delete_days; if ($maxkept == 0 && $deletedays == 0) { // Means keep all backup files and never delete backup after x days. return true; } if (!isset($now)) { $now = time(); } // Clean up excess backups in the course backup filearea. $deletedcoursebackups = false; if ($storage == self::STORAGE_COURSE || $storage == self::STORAGE_COURSE_AND_DIRECTORY) { $deletedcoursebackups = self::remove_excess_backups_from_course($course, $now); } // Clean up excess backups in the specified external directory. $deleteddirectorybackups = false; if ($storage == self::STORAGE_DIRECTORY || $storage == self::STORAGE_COURSE_AND_DIRECTORY) { $deleteddirectorybackups = self::remove_excess_backups_from_directory($course, $now); } if ($deletedcoursebackups || $deleteddirectorybackups) { return true; } else { return false; } }
[ "public", "static", "function", "remove_excess_backups", "(", "$", "course", ",", "$", "now", "=", "null", ")", "{", "$", "config", "=", "get_config", "(", "'backup'", ")", ";", "$", "maxkept", "=", "(", "int", ")", "$", "config", "->", "backup_auto_max_kept", ";", "$", "storage", "=", "$", "config", "->", "backup_auto_storage", ";", "$", "deletedays", "=", "(", "int", ")", "$", "config", "->", "backup_auto_delete_days", ";", "if", "(", "$", "maxkept", "==", "0", "&&", "$", "deletedays", "==", "0", ")", "{", "// Means keep all backup files and never delete backup after x days.", "return", "true", ";", "}", "if", "(", "!", "isset", "(", "$", "now", ")", ")", "{", "$", "now", "=", "time", "(", ")", ";", "}", "// Clean up excess backups in the course backup filearea.", "$", "deletedcoursebackups", "=", "false", ";", "if", "(", "$", "storage", "==", "self", "::", "STORAGE_COURSE", "||", "$", "storage", "==", "self", "::", "STORAGE_COURSE_AND_DIRECTORY", ")", "{", "$", "deletedcoursebackups", "=", "self", "::", "remove_excess_backups_from_course", "(", "$", "course", ",", "$", "now", ")", ";", "}", "// Clean up excess backups in the specified external directory.", "$", "deleteddirectorybackups", "=", "false", ";", "if", "(", "$", "storage", "==", "self", "::", "STORAGE_DIRECTORY", "||", "$", "storage", "==", "self", "::", "STORAGE_COURSE_AND_DIRECTORY", ")", "{", "$", "deleteddirectorybackups", "=", "self", "::", "remove_excess_backups_from_directory", "(", "$", "course", ",", "$", "now", ")", ";", "}", "if", "(", "$", "deletedcoursebackups", "||", "$", "deleteddirectorybackups", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Removes excess backups from a specified course. @param stdClass $course Course object @param int $now Starting time of the process @return bool Whether or not backups is being removed
[ "Removes", "excess", "backups", "from", "a", "specified", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L554-L586
218,971
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.remove_excess_backups_from_course
protected static function remove_excess_backups_from_course($course, $now) { $fs = get_file_storage(); $context = context_course::instance($course->id); $component = 'backup'; $filearea = 'automated'; $itemid = 0; $backupfiles = array(); $backupfilesarea = $fs->get_area_files($context->id, $component, $filearea, $itemid, 'timemodified DESC', false); // Store all the matching files into timemodified => stored_file array. foreach ($backupfilesarea as $backupfile) { $backupfiles[$backupfile->get_timemodified()] = $backupfile; } $backupstodelete = self::get_backups_to_delete($backupfiles, $now); if ($backupstodelete) { foreach ($backupstodelete as $backuptodelete) { $backuptodelete->delete(); } mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from the automated filearea'); return true; } else { return false; } }
php
protected static function remove_excess_backups_from_course($course, $now) { $fs = get_file_storage(); $context = context_course::instance($course->id); $component = 'backup'; $filearea = 'automated'; $itemid = 0; $backupfiles = array(); $backupfilesarea = $fs->get_area_files($context->id, $component, $filearea, $itemid, 'timemodified DESC', false); // Store all the matching files into timemodified => stored_file array. foreach ($backupfilesarea as $backupfile) { $backupfiles[$backupfile->get_timemodified()] = $backupfile; } $backupstodelete = self::get_backups_to_delete($backupfiles, $now); if ($backupstodelete) { foreach ($backupstodelete as $backuptodelete) { $backuptodelete->delete(); } mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from the automated filearea'); return true; } else { return false; } }
[ "protected", "static", "function", "remove_excess_backups_from_course", "(", "$", "course", ",", "$", "now", ")", "{", "$", "fs", "=", "get_file_storage", "(", ")", ";", "$", "context", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "$", "component", "=", "'backup'", ";", "$", "filearea", "=", "'automated'", ";", "$", "itemid", "=", "0", ";", "$", "backupfiles", "=", "array", "(", ")", ";", "$", "backupfilesarea", "=", "$", "fs", "->", "get_area_files", "(", "$", "context", "->", "id", ",", "$", "component", ",", "$", "filearea", ",", "$", "itemid", ",", "'timemodified DESC'", ",", "false", ")", ";", "// Store all the matching files into timemodified => stored_file array.", "foreach", "(", "$", "backupfilesarea", "as", "$", "backupfile", ")", "{", "$", "backupfiles", "[", "$", "backupfile", "->", "get_timemodified", "(", ")", "]", "=", "$", "backupfile", ";", "}", "$", "backupstodelete", "=", "self", "::", "get_backups_to_delete", "(", "$", "backupfiles", ",", "$", "now", ")", ";", "if", "(", "$", "backupstodelete", ")", "{", "foreach", "(", "$", "backupstodelete", "as", "$", "backuptodelete", ")", "{", "$", "backuptodelete", "->", "delete", "(", ")", ";", "}", "mtrace", "(", "'Deleted '", ".", "count", "(", "$", "backupstodelete", ")", ".", "' old backup file(s) from the automated filearea'", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Removes excess backups in the course backup filearea from a specified course. @param stdClass $course Course object @param int $now Starting time of the process @return bool Whether or not backups are being removed
[ "Removes", "excess", "backups", "in", "the", "course", "backup", "filearea", "from", "a", "specified", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L595-L618
218,972
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.remove_excess_backups_from_directory
protected static function remove_excess_backups_from_directory($course, $now) { $config = get_config('backup'); $dir = $config->backup_auto_destination; $isnotvaliddir = !file_exists($dir) || !is_dir($dir) || !is_writable($dir); if ($isnotvaliddir) { mtrace('Error: ' . $dir . ' does not appear to be a valid directory'); return false; } // Calculate backup filename regex, ignoring the date/time/info parts that can be // variable, depending of languages, formats and automated backup settings. $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-'; $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#'; // Store all the matching files into filename => timemodified array. $backupfiles = array(); foreach (scandir($dir) as $backupfile) { // Skip files not matching the naming convention. if (!preg_match($regex, $backupfile)) { continue; } // Read the information contained in the backup itself. try { $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $backupfile); } catch (backup_helper_exception $e) { mtrace('Error: ' . $backupfile . ' does not appear to be a valid backup (' . $e->errorcode . ')'); continue; } // Make sure this backup concerns the course and site we are looking for. if ($bcinfo->format === backup::FORMAT_MOODLE && $bcinfo->type === backup::TYPE_1COURSE && $bcinfo->original_course_id == $course->id && backup_general_helper::backup_is_samesite($bcinfo)) { $backupfiles[$bcinfo->backup_date] = $backupfile; } } $backupstodelete = self::get_backups_to_delete($backupfiles, $now); if ($backupstodelete) { foreach ($backupstodelete as $backuptodelete) { unlink($dir . '/' . $backuptodelete); } mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from external directory'); return true; } else { return false; } }
php
protected static function remove_excess_backups_from_directory($course, $now) { $config = get_config('backup'); $dir = $config->backup_auto_destination; $isnotvaliddir = !file_exists($dir) || !is_dir($dir) || !is_writable($dir); if ($isnotvaliddir) { mtrace('Error: ' . $dir . ' does not appear to be a valid directory'); return false; } // Calculate backup filename regex, ignoring the date/time/info parts that can be // variable, depending of languages, formats and automated backup settings. $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-'; $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#'; // Store all the matching files into filename => timemodified array. $backupfiles = array(); foreach (scandir($dir) as $backupfile) { // Skip files not matching the naming convention. if (!preg_match($regex, $backupfile)) { continue; } // Read the information contained in the backup itself. try { $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $backupfile); } catch (backup_helper_exception $e) { mtrace('Error: ' . $backupfile . ' does not appear to be a valid backup (' . $e->errorcode . ')'); continue; } // Make sure this backup concerns the course and site we are looking for. if ($bcinfo->format === backup::FORMAT_MOODLE && $bcinfo->type === backup::TYPE_1COURSE && $bcinfo->original_course_id == $course->id && backup_general_helper::backup_is_samesite($bcinfo)) { $backupfiles[$bcinfo->backup_date] = $backupfile; } } $backupstodelete = self::get_backups_to_delete($backupfiles, $now); if ($backupstodelete) { foreach ($backupstodelete as $backuptodelete) { unlink($dir . '/' . $backuptodelete); } mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from external directory'); return true; } else { return false; } }
[ "protected", "static", "function", "remove_excess_backups_from_directory", "(", "$", "course", ",", "$", "now", ")", "{", "$", "config", "=", "get_config", "(", "'backup'", ")", ";", "$", "dir", "=", "$", "config", "->", "backup_auto_destination", ";", "$", "isnotvaliddir", "=", "!", "file_exists", "(", "$", "dir", ")", "||", "!", "is_dir", "(", "$", "dir", ")", "||", "!", "is_writable", "(", "$", "dir", ")", ";", "if", "(", "$", "isnotvaliddir", ")", "{", "mtrace", "(", "'Error: '", ".", "$", "dir", ".", "' does not appear to be a valid directory'", ")", ";", "return", "false", ";", "}", "// Calculate backup filename regex, ignoring the date/time/info parts that can be", "// variable, depending of languages, formats and automated backup settings.", "$", "filename", "=", "backup", "::", "FORMAT_MOODLE", ".", "'-'", ".", "backup", "::", "TYPE_1COURSE", ".", "'-'", ".", "$", "course", "->", "id", ".", "'-'", ";", "$", "regex", "=", "'#'", ".", "preg_quote", "(", "$", "filename", ",", "'#'", ")", ".", "'.*\\.mbz$#'", ";", "// Store all the matching files into filename => timemodified array.", "$", "backupfiles", "=", "array", "(", ")", ";", "foreach", "(", "scandir", "(", "$", "dir", ")", "as", "$", "backupfile", ")", "{", "// Skip files not matching the naming convention.", "if", "(", "!", "preg_match", "(", "$", "regex", ",", "$", "backupfile", ")", ")", "{", "continue", ";", "}", "// Read the information contained in the backup itself.", "try", "{", "$", "bcinfo", "=", "backup_general_helper", "::", "get_backup_information_from_mbz", "(", "$", "dir", ".", "'/'", ".", "$", "backupfile", ")", ";", "}", "catch", "(", "backup_helper_exception", "$", "e", ")", "{", "mtrace", "(", "'Error: '", ".", "$", "backupfile", ".", "' does not appear to be a valid backup ('", ".", "$", "e", "->", "errorcode", ".", "')'", ")", ";", "continue", ";", "}", "// Make sure this backup concerns the course and site we are looking for.", "if", "(", "$", "bcinfo", "->", "format", "===", "backup", "::", "FORMAT_MOODLE", "&&", "$", "bcinfo", "->", "type", "===", "backup", "::", "TYPE_1COURSE", "&&", "$", "bcinfo", "->", "original_course_id", "==", "$", "course", "->", "id", "&&", "backup_general_helper", "::", "backup_is_samesite", "(", "$", "bcinfo", ")", ")", "{", "$", "backupfiles", "[", "$", "bcinfo", "->", "backup_date", "]", "=", "$", "backupfile", ";", "}", "}", "$", "backupstodelete", "=", "self", "::", "get_backups_to_delete", "(", "$", "backupfiles", ",", "$", "now", ")", ";", "if", "(", "$", "backupstodelete", ")", "{", "foreach", "(", "$", "backupstodelete", "as", "$", "backuptodelete", ")", "{", "unlink", "(", "$", "dir", ".", "'/'", ".", "$", "backuptodelete", ")", ";", "}", "mtrace", "(", "'Deleted '", ".", "count", "(", "$", "backupstodelete", ")", ".", "' old backup file(s) from external directory'", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Removes excess backups in the specified external directory from a specified course. @param stdClass $course Course object @param int $now Starting time of the process @return bool Whether or not backups are being removed
[ "Removes", "excess", "backups", "in", "the", "specified", "external", "directory", "from", "a", "specified", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L627-L677
218,973
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.get_backups_to_delete
protected static function get_backups_to_delete($backupfiles, $now) { $config = get_config('backup'); $maxkept = (int)$config->backup_auto_max_kept; $deletedays = (int)$config->backup_auto_delete_days; $minkept = (int)$config->backup_auto_min_kept; // Sort by keys descending (newer to older filemodified). krsort($backupfiles); $tokeep = $maxkept; if ($deletedays > 0) { $deletedayssecs = $deletedays * DAYSECS; $tokeep = 0; $backupfileskeys = array_keys($backupfiles); foreach ($backupfileskeys as $timemodified) { $mustdeletebackup = $timemodified < ($now - $deletedayssecs); if ($mustdeletebackup || $tokeep >= $maxkept) { break; } $tokeep++; } if ($tokeep < $minkept) { $tokeep = $minkept; } } if (count($backupfiles) <= $tokeep) { // There are less or equal matching files than the desired number to keep, there is nothing to clean up. return false; } else { $backupstodelete = array_splice($backupfiles, $tokeep); return $backupstodelete; } }
php
protected static function get_backups_to_delete($backupfiles, $now) { $config = get_config('backup'); $maxkept = (int)$config->backup_auto_max_kept; $deletedays = (int)$config->backup_auto_delete_days; $minkept = (int)$config->backup_auto_min_kept; // Sort by keys descending (newer to older filemodified). krsort($backupfiles); $tokeep = $maxkept; if ($deletedays > 0) { $deletedayssecs = $deletedays * DAYSECS; $tokeep = 0; $backupfileskeys = array_keys($backupfiles); foreach ($backupfileskeys as $timemodified) { $mustdeletebackup = $timemodified < ($now - $deletedayssecs); if ($mustdeletebackup || $tokeep >= $maxkept) { break; } $tokeep++; } if ($tokeep < $minkept) { $tokeep = $minkept; } } if (count($backupfiles) <= $tokeep) { // There are less or equal matching files than the desired number to keep, there is nothing to clean up. return false; } else { $backupstodelete = array_splice($backupfiles, $tokeep); return $backupstodelete; } }
[ "protected", "static", "function", "get_backups_to_delete", "(", "$", "backupfiles", ",", "$", "now", ")", "{", "$", "config", "=", "get_config", "(", "'backup'", ")", ";", "$", "maxkept", "=", "(", "int", ")", "$", "config", "->", "backup_auto_max_kept", ";", "$", "deletedays", "=", "(", "int", ")", "$", "config", "->", "backup_auto_delete_days", ";", "$", "minkept", "=", "(", "int", ")", "$", "config", "->", "backup_auto_min_kept", ";", "// Sort by keys descending (newer to older filemodified).", "krsort", "(", "$", "backupfiles", ")", ";", "$", "tokeep", "=", "$", "maxkept", ";", "if", "(", "$", "deletedays", ">", "0", ")", "{", "$", "deletedayssecs", "=", "$", "deletedays", "*", "DAYSECS", ";", "$", "tokeep", "=", "0", ";", "$", "backupfileskeys", "=", "array_keys", "(", "$", "backupfiles", ")", ";", "foreach", "(", "$", "backupfileskeys", "as", "$", "timemodified", ")", "{", "$", "mustdeletebackup", "=", "$", "timemodified", "<", "(", "$", "now", "-", "$", "deletedayssecs", ")", ";", "if", "(", "$", "mustdeletebackup", "||", "$", "tokeep", ">=", "$", "maxkept", ")", "{", "break", ";", "}", "$", "tokeep", "++", ";", "}", "if", "(", "$", "tokeep", "<", "$", "minkept", ")", "{", "$", "tokeep", "=", "$", "minkept", ";", "}", "}", "if", "(", "count", "(", "$", "backupfiles", ")", "<=", "$", "tokeep", ")", "{", "// There are less or equal matching files than the desired number to keep, there is nothing to clean up.", "return", "false", ";", "}", "else", "{", "$", "backupstodelete", "=", "array_splice", "(", "$", "backupfiles", ",", "$", "tokeep", ")", ";", "return", "$", "backupstodelete", ";", "}", "}" ]
Get the list of backup files to delete depending on the automated backup settings. @param array $backupfiles Existing backup files @param int $now Starting time of the process @return array Backup files to delete
[ "Get", "the", "list", "of", "backup", "files", "to", "delete", "depending", "on", "the", "automated", "backup", "settings", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L686-L719
218,974
moodle/moodle
backup/util/helper/backup_cron_helper.class.php
backup_cron_automated_helper.is_course_modified
protected static function is_course_modified($courseid, $since) { $logmang = get_log_manager(); $readers = $logmang->get_readers('core\log\sql_reader'); $params = array('courseid' => $courseid, 'since' => $since); foreach ($readers as $readerpluginname => $reader) { $where = "courseid = :courseid and timecreated > :since and crud <> 'r'"; // Prevent logs of prevous backups causing a false positive. if ($readerpluginname != 'logstore_legacy') { $where .= " and target <> 'course_backup'"; } if ($reader->get_events_select_count($where, $params)) { return true; } } return false; }
php
protected static function is_course_modified($courseid, $since) { $logmang = get_log_manager(); $readers = $logmang->get_readers('core\log\sql_reader'); $params = array('courseid' => $courseid, 'since' => $since); foreach ($readers as $readerpluginname => $reader) { $where = "courseid = :courseid and timecreated > :since and crud <> 'r'"; // Prevent logs of prevous backups causing a false positive. if ($readerpluginname != 'logstore_legacy') { $where .= " and target <> 'course_backup'"; } if ($reader->get_events_select_count($where, $params)) { return true; } } return false; }
[ "protected", "static", "function", "is_course_modified", "(", "$", "courseid", ",", "$", "since", ")", "{", "$", "logmang", "=", "get_log_manager", "(", ")", ";", "$", "readers", "=", "$", "logmang", "->", "get_readers", "(", "'core\\log\\sql_reader'", ")", ";", "$", "params", "=", "array", "(", "'courseid'", "=>", "$", "courseid", ",", "'since'", "=>", "$", "since", ")", ";", "foreach", "(", "$", "readers", "as", "$", "readerpluginname", "=>", "$", "reader", ")", "{", "$", "where", "=", "\"courseid = :courseid and timecreated > :since and crud <> 'r'\"", ";", "// Prevent logs of prevous backups causing a false positive.", "if", "(", "$", "readerpluginname", "!=", "'logstore_legacy'", ")", "{", "$", "where", ".=", "\" and target <> 'course_backup'\"", ";", "}", "if", "(", "$", "reader", "->", "get_events_select_count", "(", "$", "where", ",", "$", "params", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check logs to find out if a course was modified since the given time. @param int $courseid course id to check @param int $since timestamp, from which to check @return bool true if the course was modified, false otherwise. This also returns false if no readers are enabled. This is intentional, since we cannot reliably determine if any modification was made or not.
[ "Check", "logs", "to", "find", "out", "if", "a", "course", "was", "modified", "since", "the", "given", "time", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/helper/backup_cron_helper.class.php#L730-L748
218,975
moodle/moodle
lib/simplepie/library/SimplePie/Content/Type/Sniffer.php
SimplePie_Content_Type_Sniffer.get_type
public function get_type() { if (isset($this->file->headers['content-type'])) { if (!isset($this->file->headers['content-encoding']) && ($this->file->headers['content-type'] === 'text/plain' || $this->file->headers['content-type'] === 'text/plain; charset=ISO-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=iso-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=UTF-8')) { return $this->text_or_binary(); } if (($pos = strpos($this->file->headers['content-type'], ';')) !== false) { $official = substr($this->file->headers['content-type'], 0, $pos); } else { $official = $this->file->headers['content-type']; } $official = trim(strtolower($official)); if ($official === 'unknown/unknown' || $official === 'application/unknown') { return $this->unknown(); } elseif (substr($official, -4) === '+xml' || $official === 'text/xml' || $official === 'application/xml') { return $official; } elseif (substr($official, 0, 6) === 'image/') { if ($return = $this->image()) { return $return; } else { return $official; } } elseif ($official === 'text/html') { return $this->feed_or_html(); } else { return $official; } } else { return $this->unknown(); } }
php
public function get_type() { if (isset($this->file->headers['content-type'])) { if (!isset($this->file->headers['content-encoding']) && ($this->file->headers['content-type'] === 'text/plain' || $this->file->headers['content-type'] === 'text/plain; charset=ISO-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=iso-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=UTF-8')) { return $this->text_or_binary(); } if (($pos = strpos($this->file->headers['content-type'], ';')) !== false) { $official = substr($this->file->headers['content-type'], 0, $pos); } else { $official = $this->file->headers['content-type']; } $official = trim(strtolower($official)); if ($official === 'unknown/unknown' || $official === 'application/unknown') { return $this->unknown(); } elseif (substr($official, -4) === '+xml' || $official === 'text/xml' || $official === 'application/xml') { return $official; } elseif (substr($official, 0, 6) === 'image/') { if ($return = $this->image()) { return $return; } else { return $official; } } elseif ($official === 'text/html') { return $this->feed_or_html(); } else { return $official; } } else { return $this->unknown(); } }
[ "public", "function", "get_type", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "file", "->", "headers", "[", "'content-encoding'", "]", ")", "&&", "(", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", "===", "'text/plain'", "||", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", "===", "'text/plain; charset=ISO-8859-1'", "||", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", "===", "'text/plain; charset=iso-8859-1'", "||", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", "===", "'text/plain; charset=UTF-8'", ")", ")", "{", "return", "$", "this", "->", "text_or_binary", "(", ")", ";", "}", "if", "(", "(", "$", "pos", "=", "strpos", "(", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", ",", "';'", ")", ")", "!==", "false", ")", "{", "$", "official", "=", "substr", "(", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", ",", "0", ",", "$", "pos", ")", ";", "}", "else", "{", "$", "official", "=", "$", "this", "->", "file", "->", "headers", "[", "'content-type'", "]", ";", "}", "$", "official", "=", "trim", "(", "strtolower", "(", "$", "official", ")", ")", ";", "if", "(", "$", "official", "===", "'unknown/unknown'", "||", "$", "official", "===", "'application/unknown'", ")", "{", "return", "$", "this", "->", "unknown", "(", ")", ";", "}", "elseif", "(", "substr", "(", "$", "official", ",", "-", "4", ")", "===", "'+xml'", "||", "$", "official", "===", "'text/xml'", "||", "$", "official", "===", "'application/xml'", ")", "{", "return", "$", "official", ";", "}", "elseif", "(", "substr", "(", "$", "official", ",", "0", ",", "6", ")", "===", "'image/'", ")", "{", "if", "(", "$", "return", "=", "$", "this", "->", "image", "(", ")", ")", "{", "return", "$", "return", ";", "}", "else", "{", "return", "$", "official", ";", "}", "}", "elseif", "(", "$", "official", "===", "'text/html'", ")", "{", "return", "$", "this", "->", "feed_or_html", "(", ")", ";", "}", "else", "{", "return", "$", "official", ";", "}", "}", "else", "{", "return", "$", "this", "->", "unknown", "(", ")", ";", "}", "}" ]
Get the Content-Type of the specified file @return string Actual Content-Type
[ "Get", "the", "Content", "-", "Type", "of", "the", "specified", "file" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Content/Type/Sniffer.php#L83-L141
218,976
moodle/moodle
lib/simplepie/library/SimplePie/Content/Type/Sniffer.php
SimplePie_Content_Type_Sniffer.text_or_binary
public function text_or_binary() { if (substr($this->file->body, 0, 2) === "\xFE\xFF" || substr($this->file->body, 0, 2) === "\xFF\xFE" || substr($this->file->body, 0, 4) === "\x00\x00\xFE\xFF" || substr($this->file->body, 0, 3) === "\xEF\xBB\xBF") { return 'text/plain'; } elseif (preg_match('/[\x00-\x08\x0E-\x1A\x1C-\x1F]/', $this->file->body)) { return 'application/octect-stream'; } else { return 'text/plain'; } }
php
public function text_or_binary() { if (substr($this->file->body, 0, 2) === "\xFE\xFF" || substr($this->file->body, 0, 2) === "\xFF\xFE" || substr($this->file->body, 0, 4) === "\x00\x00\xFE\xFF" || substr($this->file->body, 0, 3) === "\xEF\xBB\xBF") { return 'text/plain'; } elseif (preg_match('/[\x00-\x08\x0E-\x1A\x1C-\x1F]/', $this->file->body)) { return 'application/octect-stream'; } else { return 'text/plain'; } }
[ "public", "function", "text_or_binary", "(", ")", "{", "if", "(", "substr", "(", "$", "this", "->", "file", "->", "body", ",", "0", ",", "2", ")", "===", "\"\\xFE\\xFF\"", "||", "substr", "(", "$", "this", "->", "file", "->", "body", ",", "0", ",", "2", ")", "===", "\"\\xFF\\xFE\"", "||", "substr", "(", "$", "this", "->", "file", "->", "body", ",", "0", ",", "4", ")", "===", "\"\\x00\\x00\\xFE\\xFF\"", "||", "substr", "(", "$", "this", "->", "file", "->", "body", ",", "0", ",", "3", ")", "===", "\"\\xEF\\xBB\\xBF\"", ")", "{", "return", "'text/plain'", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F]/'", ",", "$", "this", "->", "file", "->", "body", ")", ")", "{", "return", "'application/octect-stream'", ";", "}", "else", "{", "return", "'text/plain'", ";", "}", "}" ]
Sniff text or binary @return string Actual Content-Type
[ "Sniff", "text", "or", "binary" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Content/Type/Sniffer.php#L148-L165
218,977
moodle/moodle
search/classes/base_mod.php
base_mod.get_cm
protected function get_cm($modulename, $instanceid, $courseid) { $modinfo = get_fast_modinfo($courseid); // Hopefully not many, they are indexed by cmid. $instances = $modinfo->get_instances_of($modulename); foreach ($instances as $cminfo) { if ($cminfo->instance == $instanceid) { return $cminfo; } } // Nothing found. throw new \dml_missing_record_exception($modulename); }
php
protected function get_cm($modulename, $instanceid, $courseid) { $modinfo = get_fast_modinfo($courseid); // Hopefully not many, they are indexed by cmid. $instances = $modinfo->get_instances_of($modulename); foreach ($instances as $cminfo) { if ($cminfo->instance == $instanceid) { return $cminfo; } } // Nothing found. throw new \dml_missing_record_exception($modulename); }
[ "protected", "function", "get_cm", "(", "$", "modulename", ",", "$", "instanceid", ",", "$", "courseid", ")", "{", "$", "modinfo", "=", "get_fast_modinfo", "(", "$", "courseid", ")", ";", "// Hopefully not many, they are indexed by cmid.", "$", "instances", "=", "$", "modinfo", "->", "get_instances_of", "(", "$", "modulename", ")", ";", "foreach", "(", "$", "instances", "as", "$", "cminfo", ")", "{", "if", "(", "$", "cminfo", "->", "instance", "==", "$", "instanceid", ")", "{", "return", "$", "cminfo", ";", "}", "}", "// Nothing found.", "throw", "new", "\\", "dml_missing_record_exception", "(", "$", "modulename", ")", ";", "}" ]
Gets the course module for the required instanceid + modulename. The returned data depends on the logged user, when calling this through self::get_document the admin user is used so everything would be returned. No need more internal caching here, modinfo is already cached. @throws \dml_missing_record_exception @param string $modulename The module name @param int $instanceid Module instance id (depends on the module) @param int $courseid Helps speeding up things @return \cm_info
[ "Gets", "the", "course", "module", "for", "the", "required", "instanceid", "+", "modulename", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/classes/base_mod.php#L74-L87
218,978
moodle/moodle
search/classes/base_mod.php
base_mod.get_contexts_to_reindex
public function get_contexts_to_reindex() { global $DB; list ($extrajoins, $dborder) = $this->get_contexts_to_reindex_extra_sql(); $contexts = []; $selectcolumns = \context_helper::get_preload_record_columns_sql('x'); $groupbycolumns = ''; foreach (\context_helper::get_preload_record_columns('x') as $column => $thing) { if ($groupbycolumns !== '') { $groupbycolumns .= ','; } $groupbycolumns .= $column; } $rs = $DB->get_recordset_sql(" SELECT $selectcolumns FROM {course_modules} cm JOIN {context} x ON x.instanceid = cm.id AND x.contextlevel = ? $extrajoins WHERE cm.module = (SELECT id FROM {modules} WHERE name = ?) GROUP BY $groupbycolumns ORDER BY $dborder", [CONTEXT_MODULE, $this->get_module_name()]); return new \core\dml\recordset_walk($rs, function($rec) { $id = $rec->ctxid; \context_helper::preload_from_record($rec); return \context::instance_by_id($id); }); }
php
public function get_contexts_to_reindex() { global $DB; list ($extrajoins, $dborder) = $this->get_contexts_to_reindex_extra_sql(); $contexts = []; $selectcolumns = \context_helper::get_preload_record_columns_sql('x'); $groupbycolumns = ''; foreach (\context_helper::get_preload_record_columns('x') as $column => $thing) { if ($groupbycolumns !== '') { $groupbycolumns .= ','; } $groupbycolumns .= $column; } $rs = $DB->get_recordset_sql(" SELECT $selectcolumns FROM {course_modules} cm JOIN {context} x ON x.instanceid = cm.id AND x.contextlevel = ? $extrajoins WHERE cm.module = (SELECT id FROM {modules} WHERE name = ?) GROUP BY $groupbycolumns ORDER BY $dborder", [CONTEXT_MODULE, $this->get_module_name()]); return new \core\dml\recordset_walk($rs, function($rec) { $id = $rec->ctxid; \context_helper::preload_from_record($rec); return \context::instance_by_id($id); }); }
[ "public", "function", "get_contexts_to_reindex", "(", ")", "{", "global", "$", "DB", ";", "list", "(", "$", "extrajoins", ",", "$", "dborder", ")", "=", "$", "this", "->", "get_contexts_to_reindex_extra_sql", "(", ")", ";", "$", "contexts", "=", "[", "]", ";", "$", "selectcolumns", "=", "\\", "context_helper", "::", "get_preload_record_columns_sql", "(", "'x'", ")", ";", "$", "groupbycolumns", "=", "''", ";", "foreach", "(", "\\", "context_helper", "::", "get_preload_record_columns", "(", "'x'", ")", "as", "$", "column", "=>", "$", "thing", ")", "{", "if", "(", "$", "groupbycolumns", "!==", "''", ")", "{", "$", "groupbycolumns", ".=", "','", ";", "}", "$", "groupbycolumns", ".=", "$", "column", ";", "}", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "\"\n SELECT $selectcolumns\n FROM {course_modules} cm\n JOIN {context} x ON x.instanceid = cm.id AND x.contextlevel = ?\n $extrajoins\n WHERE cm.module = (SELECT id FROM {modules} WHERE name = ?)\n GROUP BY $groupbycolumns\n ORDER BY $dborder\"", ",", "[", "CONTEXT_MODULE", ",", "$", "this", "->", "get_module_name", "(", ")", "]", ")", ";", "return", "new", "\\", "core", "\\", "dml", "\\", "recordset_walk", "(", "$", "rs", ",", "function", "(", "$", "rec", ")", "{", "$", "id", "=", "$", "rec", "->", "ctxid", ";", "\\", "context_helper", "::", "preload_from_record", "(", "$", "rec", ")", ";", "return", "\\", "context", "::", "instance_by_id", "(", "$", "id", ")", ";", "}", ")", ";", "}" ]
Gets a list of all contexts to reindex when reindexing this search area. For modules, the default is to return all contexts for modules of that type, in order of time added (most recent first). @return \Iterator Iterator of contexts to reindex @throws \moodle_exception If any DB error
[ "Gets", "a", "list", "of", "all", "contexts", "to", "reindex", "when", "reindexing", "this", "search", "area", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/classes/base_mod.php#L221-L247
218,979
moodle/moodle
lib/horde/framework/Horde/Mail/Transport.php
Horde_Mail_Transport._normalizeEOL
protected function _normalizeEOL($data) { return strtr($data, array( "\r\n" => $this->sep, "\r" => $this->sep, "\n" => $this->sep )); }
php
protected function _normalizeEOL($data) { return strtr($data, array( "\r\n" => $this->sep, "\r" => $this->sep, "\n" => $this->sep )); }
[ "protected", "function", "_normalizeEOL", "(", "$", "data", ")", "{", "return", "strtr", "(", "$", "data", ",", "array", "(", "\"\\r\\n\"", "=>", "$", "this", "->", "sep", ",", "\"\\r\"", "=>", "$", "this", "->", "sep", ",", "\"\\n\"", "=>", "$", "this", "->", "sep", ")", ")", ";", "}" ]
Normalizes EOLs in string data. @param string $data Data. @return string Normalized data.
[ "Normalizes", "EOLs", "in", "string", "data", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Mail/Transport.php#L224-L231
218,980
moodle/moodle
lib/horde/framework/Horde/Mail/Transport.php
Horde_Mail_Transport._getFrom
protected function _getFrom($from, $headers) { /* Since few MTAs are going to allow this header to be forged unless * it's in the MAIL FROM: exchange, we'll use Return-Path instead of * From: if it's set. */ foreach (array_keys($headers) as $hdr) { if (strcasecmp($hdr, 'Return-Path') === 0) { $from = $headers[$hdr]; break; } } if (!strlen($from)) { throw new Horde_Mail_Exception('No from address provided.'); } $from = new Horde_Mail_Rfc822_Address($from); return $from->bare_address_idn; }
php
protected function _getFrom($from, $headers) { /* Since few MTAs are going to allow this header to be forged unless * it's in the MAIL FROM: exchange, we'll use Return-Path instead of * From: if it's set. */ foreach (array_keys($headers) as $hdr) { if (strcasecmp($hdr, 'Return-Path') === 0) { $from = $headers[$hdr]; break; } } if (!strlen($from)) { throw new Horde_Mail_Exception('No from address provided.'); } $from = new Horde_Mail_Rfc822_Address($from); return $from->bare_address_idn; }
[ "protected", "function", "_getFrom", "(", "$", "from", ",", "$", "headers", ")", "{", "/* Since few MTAs are going to allow this header to be forged unless\n * it's in the MAIL FROM: exchange, we'll use Return-Path instead of\n * From: if it's set. */", "foreach", "(", "array_keys", "(", "$", "headers", ")", "as", "$", "hdr", ")", "{", "if", "(", "strcasecmp", "(", "$", "hdr", ",", "'Return-Path'", ")", "===", "0", ")", "{", "$", "from", "=", "$", "headers", "[", "$", "hdr", "]", ";", "break", ";", "}", "}", "if", "(", "!", "strlen", "(", "$", "from", ")", ")", "{", "throw", "new", "Horde_Mail_Exception", "(", "'No from address provided.'", ")", ";", "}", "$", "from", "=", "new", "Horde_Mail_Rfc822_Address", "(", "$", "from", ")", ";", "return", "$", "from", "->", "bare_address_idn", ";", "}" ]
Get the from address. @param string $from From address. @param array $headers Headers array. @return string Address object. @throws Horde_Mail_Exception
[ "Get", "the", "from", "address", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Mail/Transport.php#L242-L261
218,981
moodle/moodle
admin/classes/form/purge_caches.php
purge_caches.definition
public function definition() { $mform = $this->_form; $mform->addElement('hidden', 'returnurl', $this->_customdata['returnurl']); $mform->setType('returnurl', PARAM_LOCALURL); $mform->addElement('submit', 'all', get_string('purgecaches', 'admin')); $mform->addElement('header', 'purgecacheheader', get_string('purgeselectedcaches', 'admin')); $checkboxes = [ $mform->createElement('advcheckbox', 'theme', '', get_string('purgethemecache', 'admin')), $mform->createElement('advcheckbox', 'lang', '', get_string('purgelangcache', 'admin')), $mform->createElement('advcheckbox', 'js', '', get_string('purgejscache', 'admin')), $mform->createElement('advcheckbox', 'filter', '', get_string('purgefiltercache', 'admin')), $mform->createElement('advcheckbox', 'muc', '', get_string('purgemuc', 'admin')), $mform->createElement('advcheckbox', 'other', '', get_string('purgeothercaches', 'admin')) ]; $mform->addGroup($checkboxes, 'purgeselectedoptions'); $mform->addElement('submit', 'purgeselectedcaches', get_string('purgeselectedcaches', 'admin')); }
php
public function definition() { $mform = $this->_form; $mform->addElement('hidden', 'returnurl', $this->_customdata['returnurl']); $mform->setType('returnurl', PARAM_LOCALURL); $mform->addElement('submit', 'all', get_string('purgecaches', 'admin')); $mform->addElement('header', 'purgecacheheader', get_string('purgeselectedcaches', 'admin')); $checkboxes = [ $mform->createElement('advcheckbox', 'theme', '', get_string('purgethemecache', 'admin')), $mform->createElement('advcheckbox', 'lang', '', get_string('purgelangcache', 'admin')), $mform->createElement('advcheckbox', 'js', '', get_string('purgejscache', 'admin')), $mform->createElement('advcheckbox', 'filter', '', get_string('purgefiltercache', 'admin')), $mform->createElement('advcheckbox', 'muc', '', get_string('purgemuc', 'admin')), $mform->createElement('advcheckbox', 'other', '', get_string('purgeothercaches', 'admin')) ]; $mform->addGroup($checkboxes, 'purgeselectedoptions'); $mform->addElement('submit', 'purgeselectedcaches', get_string('purgeselectedcaches', 'admin')); }
[ "public", "function", "definition", "(", ")", "{", "$", "mform", "=", "$", "this", "->", "_form", ";", "$", "mform", "->", "addElement", "(", "'hidden'", ",", "'returnurl'", ",", "$", "this", "->", "_customdata", "[", "'returnurl'", "]", ")", ";", "$", "mform", "->", "setType", "(", "'returnurl'", ",", "PARAM_LOCALURL", ")", ";", "$", "mform", "->", "addElement", "(", "'submit'", ",", "'all'", ",", "get_string", "(", "'purgecaches'", ",", "'admin'", ")", ")", ";", "$", "mform", "->", "addElement", "(", "'header'", ",", "'purgecacheheader'", ",", "get_string", "(", "'purgeselectedcaches'", ",", "'admin'", ")", ")", ";", "$", "checkboxes", "=", "[", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'theme'", ",", "''", ",", "get_string", "(", "'purgethemecache'", ",", "'admin'", ")", ")", ",", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'lang'", ",", "''", ",", "get_string", "(", "'purgelangcache'", ",", "'admin'", ")", ")", ",", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'js'", ",", "''", ",", "get_string", "(", "'purgejscache'", ",", "'admin'", ")", ")", ",", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'filter'", ",", "''", ",", "get_string", "(", "'purgefiltercache'", ",", "'admin'", ")", ")", ",", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'muc'", ",", "''", ",", "get_string", "(", "'purgemuc'", ",", "'admin'", ")", ")", ",", "$", "mform", "->", "createElement", "(", "'advcheckbox'", ",", "'other'", ",", "''", ",", "get_string", "(", "'purgeothercaches'", ",", "'admin'", ")", ")", "]", ";", "$", "mform", "->", "addGroup", "(", "$", "checkboxes", ",", "'purgeselectedoptions'", ")", ";", "$", "mform", "->", "addElement", "(", "'submit'", ",", "'purgeselectedcaches'", ",", "get_string", "(", "'purgeselectedcaches'", ",", "'admin'", ")", ")", ";", "}" ]
Define a "Purge all caches" button, and a fieldset with checkboxes for selectively purging separate caches.
[ "Define", "a", "Purge", "all", "caches", "button", "and", "a", "fieldset", "with", "checkboxes", "for", "selectively", "purging", "separate", "caches", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/classes/form/purge_caches.php#L43-L59
218,982
moodle/moodle
admin/classes/form/purge_caches.php
purge_caches.validation
public function validation($data, $files) { $errors = []; if (isset($data['purgeselectedcaches']) && empty(array_filter($data['purgeselectedoptions']))) { $errors['purgeselectedoptions'] = get_string('purgecachesnoneselected', 'admin'); } return $errors; }
php
public function validation($data, $files) { $errors = []; if (isset($data['purgeselectedcaches']) && empty(array_filter($data['purgeselectedoptions']))) { $errors['purgeselectedoptions'] = get_string('purgecachesnoneselected', 'admin'); } return $errors; }
[ "public", "function", "validation", "(", "$", "data", ",", "$", "files", ")", "{", "$", "errors", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "data", "[", "'purgeselectedcaches'", "]", ")", "&&", "empty", "(", "array_filter", "(", "$", "data", "[", "'purgeselectedoptions'", "]", ")", ")", ")", "{", "$", "errors", "[", "'purgeselectedoptions'", "]", "=", "get_string", "(", "'purgecachesnoneselected'", ",", "'admin'", ")", ";", "}", "return", "$", "errors", ";", "}" ]
If the "Purge selected caches" button was pressed, ensure at least one cache was selected. @param array $data @param array $files @return array Error messages
[ "If", "the", "Purge", "selected", "caches", "button", "was", "pressed", "ensure", "at", "least", "one", "cache", "was", "selected", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/classes/form/purge_caches.php#L68-L74
218,983
moodle/moodle
blocks/quiz_results/backup/moodle2/restore_quiz_results_block_task.class.php
restore_quiz_results_block_task.after_restore
public function after_restore() { global $DB; // Get the blockid. $blockid = $this->get_blockid(); // Extract block configdata and update it to point to the new quiz. $configdata = $DB->get_field('block_instances', 'configdata', array('id' => $blockid)); $newconfigdata = ''; // The block was configured. if (!empty($configdata)) { $config = unserialize(base64_decode($configdata)); $config->activityparent = 'quiz'; $config->activityparentid = 0; $config->gradeformat = isset($config->gradeformat) ? $config->gradeformat : 1; if (!empty($config->quizid) && $quizmap = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $config->quizid)) { $config->activityparentid = $quizmap->newitemid; } // Set the decimal valuue as appropriate. if ($config->gradeformat == 1) { // This block is using percentages, do not display any decimal places. $config->decimalpoints = 0; } else { // Get the decimal value from the corresponding quiz. $config->decimalpoints = $DB->get_field('quiz', 'decimalpoints', array('id' => $config->activityparentid)); } // Get the grade_items record to set the activitygradeitemid. $info = $DB->get_record('grade_items', array('iteminstance' => $config->activityparentid, 'itemmodule' => $config->activityparent)); $config->activitygradeitemid = 0; if ($info) { $config->activitygradeitemid = $info->id; } unset($config->quizid); $newconfigdata = base64_encode(serialize($config)); } // Update the configuration and convert the block. $DB->set_field('block_instances', 'configdata', $newconfigdata, array('id' => $blockid)); $DB->set_field('block_instances', 'blockname', 'activity_results', array('id' => $blockid)); }
php
public function after_restore() { global $DB; // Get the blockid. $blockid = $this->get_blockid(); // Extract block configdata and update it to point to the new quiz. $configdata = $DB->get_field('block_instances', 'configdata', array('id' => $blockid)); $newconfigdata = ''; // The block was configured. if (!empty($configdata)) { $config = unserialize(base64_decode($configdata)); $config->activityparent = 'quiz'; $config->activityparentid = 0; $config->gradeformat = isset($config->gradeformat) ? $config->gradeformat : 1; if (!empty($config->quizid) && $quizmap = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $config->quizid)) { $config->activityparentid = $quizmap->newitemid; } // Set the decimal valuue as appropriate. if ($config->gradeformat == 1) { // This block is using percentages, do not display any decimal places. $config->decimalpoints = 0; } else { // Get the decimal value from the corresponding quiz. $config->decimalpoints = $DB->get_field('quiz', 'decimalpoints', array('id' => $config->activityparentid)); } // Get the grade_items record to set the activitygradeitemid. $info = $DB->get_record('grade_items', array('iteminstance' => $config->activityparentid, 'itemmodule' => $config->activityparent)); $config->activitygradeitemid = 0; if ($info) { $config->activitygradeitemid = $info->id; } unset($config->quizid); $newconfigdata = base64_encode(serialize($config)); } // Update the configuration and convert the block. $DB->set_field('block_instances', 'configdata', $newconfigdata, array('id' => $blockid)); $DB->set_field('block_instances', 'blockname', 'activity_results', array('id' => $blockid)); }
[ "public", "function", "after_restore", "(", ")", "{", "global", "$", "DB", ";", "// Get the blockid.", "$", "blockid", "=", "$", "this", "->", "get_blockid", "(", ")", ";", "// Extract block configdata and update it to point to the new quiz.", "$", "configdata", "=", "$", "DB", "->", "get_field", "(", "'block_instances'", ",", "'configdata'", ",", "array", "(", "'id'", "=>", "$", "blockid", ")", ")", ";", "$", "newconfigdata", "=", "''", ";", "// The block was configured.", "if", "(", "!", "empty", "(", "$", "configdata", ")", ")", "{", "$", "config", "=", "unserialize", "(", "base64_decode", "(", "$", "configdata", ")", ")", ";", "$", "config", "->", "activityparent", "=", "'quiz'", ";", "$", "config", "->", "activityparentid", "=", "0", ";", "$", "config", "->", "gradeformat", "=", "isset", "(", "$", "config", "->", "gradeformat", ")", "?", "$", "config", "->", "gradeformat", ":", "1", ";", "if", "(", "!", "empty", "(", "$", "config", "->", "quizid", ")", "&&", "$", "quizmap", "=", "restore_dbops", "::", "get_backup_ids_record", "(", "$", "this", "->", "get_restoreid", "(", ")", ",", "'quiz'", ",", "$", "config", "->", "quizid", ")", ")", "{", "$", "config", "->", "activityparentid", "=", "$", "quizmap", "->", "newitemid", ";", "}", "// Set the decimal valuue as appropriate.", "if", "(", "$", "config", "->", "gradeformat", "==", "1", ")", "{", "// This block is using percentages, do not display any decimal places.", "$", "config", "->", "decimalpoints", "=", "0", ";", "}", "else", "{", "// Get the decimal value from the corresponding quiz.", "$", "config", "->", "decimalpoints", "=", "$", "DB", "->", "get_field", "(", "'quiz'", ",", "'decimalpoints'", ",", "array", "(", "'id'", "=>", "$", "config", "->", "activityparentid", ")", ")", ";", "}", "// Get the grade_items record to set the activitygradeitemid.", "$", "info", "=", "$", "DB", "->", "get_record", "(", "'grade_items'", ",", "array", "(", "'iteminstance'", "=>", "$", "config", "->", "activityparentid", ",", "'itemmodule'", "=>", "$", "config", "->", "activityparent", ")", ")", ";", "$", "config", "->", "activitygradeitemid", "=", "0", ";", "if", "(", "$", "info", ")", "{", "$", "config", "->", "activitygradeitemid", "=", "$", "info", "->", "id", ";", "}", "unset", "(", "$", "config", "->", "quizid", ")", ";", "$", "newconfigdata", "=", "base64_encode", "(", "serialize", "(", "$", "config", ")", ")", ";", "}", "// Update the configuration and convert the block.", "$", "DB", "->", "set_field", "(", "'block_instances'", ",", "'configdata'", ",", "$", "newconfigdata", ",", "array", "(", "'id'", "=>", "$", "blockid", ")", ")", ";", "$", "DB", "->", "set_field", "(", "'block_instances'", ",", "'blockname'", ",", "'activity_results'", ",", "array", "(", "'id'", "=>", "$", "blockid", ")", ")", ";", "}" ]
This function, executed after all the tasks in the plan have been executed, will perform the recode of the target quiz for the block. This must be done here and not in normal execution steps because the quiz 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", "quiz", "for", "the", "block", ".", "This", "must", "be", "done", "here", "and", "not", "in", "normal", "execution", "steps", "because", "the", "quiz", "can", "be", "restored", "after", "the", "block", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/quiz_results/backup/moodle2/restore_quiz_results_block_task.class.php#L57-L104
218,984
moodle/moodle
blog/renderer.php
core_blog_renderer.render_blog_entry_attachment
public function render_blog_entry_attachment(blog_entry_attachment $attachment) { $syscontext = context_system::instance(); // Image attachments don't get printed as links. if (file_mimetype_in_typegroup($attachment->file->get_mimetype(), 'web_image')) { $attrs = array('src' => $attachment->url, 'alt' => ''); $o = html_writer::empty_tag('img', $attrs); $class = 'attachedimages'; } else { $image = $this->output->pix_icon(file_file_icon($attachment->file), $attachment->filename, 'moodle', array('class' => 'icon')); $o = html_writer::link($attachment->url, $image); $o .= format_text(html_writer::link($attachment->url, $attachment->filename), FORMAT_HTML, array('context' => $syscontext)); $class = 'attachments'; } return $this->output->container($o, $class); }
php
public function render_blog_entry_attachment(blog_entry_attachment $attachment) { $syscontext = context_system::instance(); // Image attachments don't get printed as links. if (file_mimetype_in_typegroup($attachment->file->get_mimetype(), 'web_image')) { $attrs = array('src' => $attachment->url, 'alt' => ''); $o = html_writer::empty_tag('img', $attrs); $class = 'attachedimages'; } else { $image = $this->output->pix_icon(file_file_icon($attachment->file), $attachment->filename, 'moodle', array('class' => 'icon')); $o = html_writer::link($attachment->url, $image); $o .= format_text(html_writer::link($attachment->url, $attachment->filename), FORMAT_HTML, array('context' => $syscontext)); $class = 'attachments'; } return $this->output->container($o, $class); }
[ "public", "function", "render_blog_entry_attachment", "(", "blog_entry_attachment", "$", "attachment", ")", "{", "$", "syscontext", "=", "context_system", "::", "instance", "(", ")", ";", "// Image attachments don't get printed as links.", "if", "(", "file_mimetype_in_typegroup", "(", "$", "attachment", "->", "file", "->", "get_mimetype", "(", ")", ",", "'web_image'", ")", ")", "{", "$", "attrs", "=", "array", "(", "'src'", "=>", "$", "attachment", "->", "url", ",", "'alt'", "=>", "''", ")", ";", "$", "o", "=", "html_writer", "::", "empty_tag", "(", "'img'", ",", "$", "attrs", ")", ";", "$", "class", "=", "'attachedimages'", ";", "}", "else", "{", "$", "image", "=", "$", "this", "->", "output", "->", "pix_icon", "(", "file_file_icon", "(", "$", "attachment", "->", "file", ")", ",", "$", "attachment", "->", "filename", ",", "'moodle'", ",", "array", "(", "'class'", "=>", "'icon'", ")", ")", ";", "$", "o", "=", "html_writer", "::", "link", "(", "$", "attachment", "->", "url", ",", "$", "image", ")", ";", "$", "o", ".=", "format_text", "(", "html_writer", "::", "link", "(", "$", "attachment", "->", "url", ",", "$", "attachment", "->", "filename", ")", ",", "FORMAT_HTML", ",", "array", "(", "'context'", "=>", "$", "syscontext", ")", ")", ";", "$", "class", "=", "'attachments'", ";", "}", "return", "$", "this", "->", "output", "->", "container", "(", "$", "o", ",", "$", "class", ")", ";", "}" ]
Renders an entry attachment Print link for non-images and returns images as HTML @param blog_entry_attachment $attachment @return string List of attachments depending on the $return input
[ "Renders", "an", "entry", "attachment" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blog/renderer.php#L225-L247
218,985
moodle/moodle
completion/criteria/completion_criteria_grade.php
completion_criteria_grade.get_grade
private function get_grade($completion) { $grade = grade_get_course_grade($completion->userid, $this->course); return $grade->grade; }
php
private function get_grade($completion) { $grade = grade_get_course_grade($completion->userid, $this->course); return $grade->grade; }
[ "private", "function", "get_grade", "(", "$", "completion", ")", "{", "$", "grade", "=", "grade_get_course_grade", "(", "$", "completion", "->", "userid", ",", "$", "this", "->", "course", ")", ";", "return", "$", "grade", "->", "grade", ";", "}" ]
Get user's course grade in this course @param completion_completion $completion an instance of completion_completion class @return float
[ "Get", "user", "s", "course", "grade", "in", "this", "course" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/completion/criteria/completion_criteria_grade.php#L102-L105
218,986
moodle/moodle
mod/assign/classes/privacy/useridlist.php
useridlist.add_from_sql
public function add_from_sql($sql, $params) { global $DB; $userids = $DB->get_records_sql($sql, $params); if (!empty($userids)) { $this->userids = array_merge($this->userids, $userids); } }
php
public function add_from_sql($sql, $params) { global $DB; $userids = $DB->get_records_sql($sql, $params); if (!empty($userids)) { $this->userids = array_merge($this->userids, $userids); } }
[ "public", "function", "add_from_sql", "(", "$", "sql", ",", "$", "params", ")", "{", "global", "$", "DB", ";", "$", "userids", "=", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "if", "(", "!", "empty", "(", "$", "userids", ")", ")", "{", "$", "this", "->", "userids", "=", "array_merge", "(", "$", "this", "->", "userids", ",", "$", "userids", ")", ";", "}", "}" ]
Add sql and params to return user IDs. @param string $sql The sql string to return user IDs. @param array $params Parameters for the sql statement.
[ "Add", "sql", "and", "params", "to", "return", "user", "IDs", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/classes/privacy/useridlist.php#L92-L98
218,987
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.get_lineitem
public function get_lineitem($courseid, $itemid, $typeid) { global $DB, $CFG; require_once($CFG->libdir . '/gradelib.php'); $lineitem = \grade_item::fetch(array('id' => $itemid)); if ($lineitem) { $gbs = $this->find_ltiservice_gradebookservice_for_lineitem($itemid); if (!$gbs) { // We will need to check if the activity related belongs to our tool proxy. $ltiactivity = $DB->get_record('lti', array('id' => $lineitem->iteminstance)); if (($ltiactivity) && (isset($ltiactivity->typeid))) { if ($ltiactivity->typeid != 0) { $tool = $DB->get_record('lti_types', array('id' => $ltiactivity->typeid)); } else { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $courseid); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $courseid); } } if (is_null($typeid)) { if (!(($tool) && ($this->get_tool_proxy()->id == $tool->toolproxyid))) { return false; } } else { if (!(($tool) && ($tool->id == $typeid))) { return false; } } } else { return false; } } } return $lineitem; }
php
public function get_lineitem($courseid, $itemid, $typeid) { global $DB, $CFG; require_once($CFG->libdir . '/gradelib.php'); $lineitem = \grade_item::fetch(array('id' => $itemid)); if ($lineitem) { $gbs = $this->find_ltiservice_gradebookservice_for_lineitem($itemid); if (!$gbs) { // We will need to check if the activity related belongs to our tool proxy. $ltiactivity = $DB->get_record('lti', array('id' => $lineitem->iteminstance)); if (($ltiactivity) && (isset($ltiactivity->typeid))) { if ($ltiactivity->typeid != 0) { $tool = $DB->get_record('lti_types', array('id' => $ltiactivity->typeid)); } else { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $courseid); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $courseid); } } if (is_null($typeid)) { if (!(($tool) && ($this->get_tool_proxy()->id == $tool->toolproxyid))) { return false; } } else { if (!(($tool) && ($tool->id == $typeid))) { return false; } } } else { return false; } } } return $lineitem; }
[ "public", "function", "get_lineitem", "(", "$", "courseid", ",", "$", "itemid", ",", "$", "typeid", ")", "{", "global", "$", "DB", ",", "$", "CFG", ";", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/gradelib.php'", ")", ";", "$", "lineitem", "=", "\\", "grade_item", "::", "fetch", "(", "array", "(", "'id'", "=>", "$", "itemid", ")", ")", ";", "if", "(", "$", "lineitem", ")", "{", "$", "gbs", "=", "$", "this", "->", "find_ltiservice_gradebookservice_for_lineitem", "(", "$", "itemid", ")", ";", "if", "(", "!", "$", "gbs", ")", "{", "// We will need to check if the activity related belongs to our tool proxy.", "$", "ltiactivity", "=", "$", "DB", "->", "get_record", "(", "'lti'", ",", "array", "(", "'id'", "=>", "$", "lineitem", "->", "iteminstance", ")", ")", ";", "if", "(", "(", "$", "ltiactivity", ")", "&&", "(", "isset", "(", "$", "ltiactivity", "->", "typeid", ")", ")", ")", "{", "if", "(", "$", "ltiactivity", "->", "typeid", "!=", "0", ")", "{", "$", "tool", "=", "$", "DB", "->", "get_record", "(", "'lti_types'", ",", "array", "(", "'id'", "=>", "$", "ltiactivity", "->", "typeid", ")", ")", ";", "}", "else", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "toolurl", ",", "$", "courseid", ")", ";", "if", "(", "!", "$", "tool", ")", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "securetoolurl", ",", "$", "courseid", ")", ";", "}", "}", "if", "(", "is_null", "(", "$", "typeid", ")", ")", "{", "if", "(", "!", "(", "(", "$", "tool", ")", "&&", "(", "$", "this", "->", "get_tool_proxy", "(", ")", "->", "id", "==", "$", "tool", "->", "toolproxyid", ")", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "if", "(", "!", "(", "(", "$", "tool", ")", "&&", "(", "$", "tool", "->", "id", "==", "$", "typeid", ")", ")", ")", "{", "return", "false", ";", "}", "}", "}", "else", "{", "return", "false", ";", "}", "}", "}", "return", "$", "lineitem", ";", "}" ]
Fetch a lineitem instance. Returns the lineitem instance if found, otherwise false. @param string $courseid ID of course @param string $itemid ID of lineitem @param string $typeid @return \ltiservice_gradebookservices\local\resources\lineitem|bool
[ "Fetch", "a", "lineitem", "instance", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L274-L308
218,988
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.save_score
public static function save_score($gradeitem, $score, $userid) { global $DB, $CFG; $source = 'mod' . self::SERVICE_NAME; if ($DB->get_record('user', array('id' => $userid)) === false) { throw new \Exception(null, 400); } require_once($CFG->libdir . '/gradelib.php'); $finalgrade = null; $timemodified = null; if (isset($score->scoreGiven)) { $finalgrade = grade_floatval($score->scoreGiven); $max = 1; if (isset($score->scoreMaximum)) { $max = $score->scoreMaximum; } if (!is_null($max) && grade_floats_different($max, $gradeitem->grademax) && grade_floats_different($max, 0.0)) { // Rescale to match the grade item maximum. $finalgrade = grade_floatval($finalgrade * $gradeitem->grademax / $max); } if (isset($score->timestamp)) { $timemodified = strtotime($score->timestamp); } else { $timemodified = time(); } } $feedbackformat = FORMAT_MOODLE; $feedback = null; if (isset($score->comment) && !empty($score->comment)) { $feedback = $score->comment; $feedbackformat = FORMAT_PLAIN; } if (!$grade = \grade_grade::fetch(array('itemid' => $gradeitem->id, 'userid' => $userid))) { $grade = new \grade_grade(); $grade->userid = $userid; $grade->itemid = $gradeitem->id; } $grade->rawgrademax = $score->scoreMaximum; $grade->timemodified = $timemodified; $grade->feedbackformat = $feedbackformat; $grade->feedback = $feedback; if ($gradeitem->is_manual_item()) { $grade->finalgrade = $finalgrade; if (empty($grade->id)) { $result = (bool)$grade->insert($source); } else { $result = $grade->update($source); } } else { $grade->rawgrade = $finalgrade; $status = \grade_update($source, $gradeitem->courseid, $gradeitem->itemtype, $gradeitem->itemmodule, $gradeitem->iteminstance, $gradeitem->itemnumber, $grade); $result = ($status == GRADE_UPDATE_OK); } if (!$result) { debugging("failed to save score for item ".$gradeitem->id." and user ".$grade->userid); throw new \Exception(null, 500); } }
php
public static function save_score($gradeitem, $score, $userid) { global $DB, $CFG; $source = 'mod' . self::SERVICE_NAME; if ($DB->get_record('user', array('id' => $userid)) === false) { throw new \Exception(null, 400); } require_once($CFG->libdir . '/gradelib.php'); $finalgrade = null; $timemodified = null; if (isset($score->scoreGiven)) { $finalgrade = grade_floatval($score->scoreGiven); $max = 1; if (isset($score->scoreMaximum)) { $max = $score->scoreMaximum; } if (!is_null($max) && grade_floats_different($max, $gradeitem->grademax) && grade_floats_different($max, 0.0)) { // Rescale to match the grade item maximum. $finalgrade = grade_floatval($finalgrade * $gradeitem->grademax / $max); } if (isset($score->timestamp)) { $timemodified = strtotime($score->timestamp); } else { $timemodified = time(); } } $feedbackformat = FORMAT_MOODLE; $feedback = null; if (isset($score->comment) && !empty($score->comment)) { $feedback = $score->comment; $feedbackformat = FORMAT_PLAIN; } if (!$grade = \grade_grade::fetch(array('itemid' => $gradeitem->id, 'userid' => $userid))) { $grade = new \grade_grade(); $grade->userid = $userid; $grade->itemid = $gradeitem->id; } $grade->rawgrademax = $score->scoreMaximum; $grade->timemodified = $timemodified; $grade->feedbackformat = $feedbackformat; $grade->feedback = $feedback; if ($gradeitem->is_manual_item()) { $grade->finalgrade = $finalgrade; if (empty($grade->id)) { $result = (bool)$grade->insert($source); } else { $result = $grade->update($source); } } else { $grade->rawgrade = $finalgrade; $status = \grade_update($source, $gradeitem->courseid, $gradeitem->itemtype, $gradeitem->itemmodule, $gradeitem->iteminstance, $gradeitem->itemnumber, $grade); $result = ($status == GRADE_UPDATE_OK); } if (!$result) { debugging("failed to save score for item ".$gradeitem->id." and user ".$grade->userid); throw new \Exception(null, 500); } }
[ "public", "static", "function", "save_score", "(", "$", "gradeitem", ",", "$", "score", ",", "$", "userid", ")", "{", "global", "$", "DB", ",", "$", "CFG", ";", "$", "source", "=", "'mod'", ".", "self", "::", "SERVICE_NAME", ";", "if", "(", "$", "DB", "->", "get_record", "(", "'user'", ",", "array", "(", "'id'", "=>", "$", "userid", ")", ")", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "null", ",", "400", ")", ";", "}", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/gradelib.php'", ")", ";", "$", "finalgrade", "=", "null", ";", "$", "timemodified", "=", "null", ";", "if", "(", "isset", "(", "$", "score", "->", "scoreGiven", ")", ")", "{", "$", "finalgrade", "=", "grade_floatval", "(", "$", "score", "->", "scoreGiven", ")", ";", "$", "max", "=", "1", ";", "if", "(", "isset", "(", "$", "score", "->", "scoreMaximum", ")", ")", "{", "$", "max", "=", "$", "score", "->", "scoreMaximum", ";", "}", "if", "(", "!", "is_null", "(", "$", "max", ")", "&&", "grade_floats_different", "(", "$", "max", ",", "$", "gradeitem", "->", "grademax", ")", "&&", "grade_floats_different", "(", "$", "max", ",", "0.0", ")", ")", "{", "// Rescale to match the grade item maximum.", "$", "finalgrade", "=", "grade_floatval", "(", "$", "finalgrade", "*", "$", "gradeitem", "->", "grademax", "/", "$", "max", ")", ";", "}", "if", "(", "isset", "(", "$", "score", "->", "timestamp", ")", ")", "{", "$", "timemodified", "=", "strtotime", "(", "$", "score", "->", "timestamp", ")", ";", "}", "else", "{", "$", "timemodified", "=", "time", "(", ")", ";", "}", "}", "$", "feedbackformat", "=", "FORMAT_MOODLE", ";", "$", "feedback", "=", "null", ";", "if", "(", "isset", "(", "$", "score", "->", "comment", ")", "&&", "!", "empty", "(", "$", "score", "->", "comment", ")", ")", "{", "$", "feedback", "=", "$", "score", "->", "comment", ";", "$", "feedbackformat", "=", "FORMAT_PLAIN", ";", "}", "if", "(", "!", "$", "grade", "=", "\\", "grade_grade", "::", "fetch", "(", "array", "(", "'itemid'", "=>", "$", "gradeitem", "->", "id", ",", "'userid'", "=>", "$", "userid", ")", ")", ")", "{", "$", "grade", "=", "new", "\\", "grade_grade", "(", ")", ";", "$", "grade", "->", "userid", "=", "$", "userid", ";", "$", "grade", "->", "itemid", "=", "$", "gradeitem", "->", "id", ";", "}", "$", "grade", "->", "rawgrademax", "=", "$", "score", "->", "scoreMaximum", ";", "$", "grade", "->", "timemodified", "=", "$", "timemodified", ";", "$", "grade", "->", "feedbackformat", "=", "$", "feedbackformat", ";", "$", "grade", "->", "feedback", "=", "$", "feedback", ";", "if", "(", "$", "gradeitem", "->", "is_manual_item", "(", ")", ")", "{", "$", "grade", "->", "finalgrade", "=", "$", "finalgrade", ";", "if", "(", "empty", "(", "$", "grade", "->", "id", ")", ")", "{", "$", "result", "=", "(", "bool", ")", "$", "grade", "->", "insert", "(", "$", "source", ")", ";", "}", "else", "{", "$", "result", "=", "$", "grade", "->", "update", "(", "$", "source", ")", ";", "}", "}", "else", "{", "$", "grade", "->", "rawgrade", "=", "$", "finalgrade", ";", "$", "status", "=", "\\", "grade_update", "(", "$", "source", ",", "$", "gradeitem", "->", "courseid", ",", "$", "gradeitem", "->", "itemtype", ",", "$", "gradeitem", "->", "itemmodule", ",", "$", "gradeitem", "->", "iteminstance", ",", "$", "gradeitem", "->", "itemnumber", ",", "$", "grade", ")", ";", "$", "result", "=", "(", "$", "status", "==", "GRADE_UPDATE_OK", ")", ";", "}", "if", "(", "!", "$", "result", ")", "{", "debugging", "(", "\"failed to save score for item \"", ".", "$", "gradeitem", "->", "id", ".", "\" and user \"", ".", "$", "grade", "->", "userid", ")", ";", "throw", "new", "\\", "Exception", "(", "null", ",", "500", ")", ";", "}", "}" ]
Set a grade item. @param object $gradeitem Grade Item record @param object $score Result object @param int $userid User ID @throws \Exception
[ "Set", "a", "grade", "item", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L320-L382
218,989
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.item_for_json
public static function item_for_json($item, $endpoint, $typeid) { $lineitem = new \stdClass(); if (is_null($typeid)) { $typeidstring = ""; } else { $typeidstring = "?type_id={$typeid}"; } $lineitem->id = "{$endpoint}/{$item->id}/lineitem" . $typeidstring; $lineitem->label = $item->itemname; $lineitem->scoreMaximum = floatval($item->grademax); $lineitem->resourceId = (!empty($item->idnumber)) ? $item->idnumber : ''; $gbs = self::find_ltiservice_gradebookservice_for_lineitem($item->id); if ($gbs) { $lineitem->tag = (!empty($gbs->tag)) ? $gbs->tag : ''; if (isset($gbs->ltilinkid)) { $lineitem->ltiLinkId = strval($gbs->ltilinkid); } } else { $lineitem->tag = ''; if (isset($item->iteminstance)) { $lineitem->ltiLinkId = strval($item->iteminstance); } } return $lineitem; }
php
public static function item_for_json($item, $endpoint, $typeid) { $lineitem = new \stdClass(); if (is_null($typeid)) { $typeidstring = ""; } else { $typeidstring = "?type_id={$typeid}"; } $lineitem->id = "{$endpoint}/{$item->id}/lineitem" . $typeidstring; $lineitem->label = $item->itemname; $lineitem->scoreMaximum = floatval($item->grademax); $lineitem->resourceId = (!empty($item->idnumber)) ? $item->idnumber : ''; $gbs = self::find_ltiservice_gradebookservice_for_lineitem($item->id); if ($gbs) { $lineitem->tag = (!empty($gbs->tag)) ? $gbs->tag : ''; if (isset($gbs->ltilinkid)) { $lineitem->ltiLinkId = strval($gbs->ltilinkid); } } else { $lineitem->tag = ''; if (isset($item->iteminstance)) { $lineitem->ltiLinkId = strval($item->iteminstance); } } return $lineitem; }
[ "public", "static", "function", "item_for_json", "(", "$", "item", ",", "$", "endpoint", ",", "$", "typeid", ")", "{", "$", "lineitem", "=", "new", "\\", "stdClass", "(", ")", ";", "if", "(", "is_null", "(", "$", "typeid", ")", ")", "{", "$", "typeidstring", "=", "\"\"", ";", "}", "else", "{", "$", "typeidstring", "=", "\"?type_id={$typeid}\"", ";", "}", "$", "lineitem", "->", "id", "=", "\"{$endpoint}/{$item->id}/lineitem\"", ".", "$", "typeidstring", ";", "$", "lineitem", "->", "label", "=", "$", "item", "->", "itemname", ";", "$", "lineitem", "->", "scoreMaximum", "=", "floatval", "(", "$", "item", "->", "grademax", ")", ";", "$", "lineitem", "->", "resourceId", "=", "(", "!", "empty", "(", "$", "item", "->", "idnumber", ")", ")", "?", "$", "item", "->", "idnumber", ":", "''", ";", "$", "gbs", "=", "self", "::", "find_ltiservice_gradebookservice_for_lineitem", "(", "$", "item", "->", "id", ")", ";", "if", "(", "$", "gbs", ")", "{", "$", "lineitem", "->", "tag", "=", "(", "!", "empty", "(", "$", "gbs", "->", "tag", ")", ")", "?", "$", "gbs", "->", "tag", ":", "''", ";", "if", "(", "isset", "(", "$", "gbs", "->", "ltilinkid", ")", ")", "{", "$", "lineitem", "->", "ltiLinkId", "=", "strval", "(", "$", "gbs", "->", "ltilinkid", ")", ";", "}", "}", "else", "{", "$", "lineitem", "->", "tag", "=", "''", ";", "if", "(", "isset", "(", "$", "item", "->", "iteminstance", ")", ")", "{", "$", "lineitem", "->", "ltiLinkId", "=", "strval", "(", "$", "item", "->", "iteminstance", ")", ";", "}", "}", "return", "$", "lineitem", ";", "}" ]
Get the json object representation of the grade item @param object $item Grade Item record @param string $endpoint Endpoint for lineitems container request @param string $typeid @return object
[ "Get", "the", "json", "object", "representation", "of", "the", "grade", "item" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L393-L420
218,990
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.result_for_json
public static function result_for_json($grade, $endpoint, $typeid) { if (is_null($typeid)) { $id = "{$endpoint}/results?user_id={$grade->userid}"; } else { $id = "{$endpoint}/results?type_id={$typeid}&user_id={$grade->userid}"; } $result = new \stdClass(); $result->id = $id; $result->userId = $grade->userid; if (!empty($grade->finalgrade)) { $result->resultScore = floatval($grade->finalgrade); $result->resultMaximum = floatval($grade->rawgrademax); if (!empty($grade->feedback)) { $result->comment = $grade->feedback; } if (is_null($typeid)) { $result->scoreOf = $endpoint; } else { $result->scoreOf = "{$endpoint}?type_id={$typeid}"; } $result->timestamp = date('c', $grade->timemodified); } return $result; }
php
public static function result_for_json($grade, $endpoint, $typeid) { if (is_null($typeid)) { $id = "{$endpoint}/results?user_id={$grade->userid}"; } else { $id = "{$endpoint}/results?type_id={$typeid}&user_id={$grade->userid}"; } $result = new \stdClass(); $result->id = $id; $result->userId = $grade->userid; if (!empty($grade->finalgrade)) { $result->resultScore = floatval($grade->finalgrade); $result->resultMaximum = floatval($grade->rawgrademax); if (!empty($grade->feedback)) { $result->comment = $grade->feedback; } if (is_null($typeid)) { $result->scoreOf = $endpoint; } else { $result->scoreOf = "{$endpoint}?type_id={$typeid}"; } $result->timestamp = date('c', $grade->timemodified); } return $result; }
[ "public", "static", "function", "result_for_json", "(", "$", "grade", ",", "$", "endpoint", ",", "$", "typeid", ")", "{", "if", "(", "is_null", "(", "$", "typeid", ")", ")", "{", "$", "id", "=", "\"{$endpoint}/results?user_id={$grade->userid}\"", ";", "}", "else", "{", "$", "id", "=", "\"{$endpoint}/results?type_id={$typeid}&user_id={$grade->userid}\"", ";", "}", "$", "result", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "result", "->", "id", "=", "$", "id", ";", "$", "result", "->", "userId", "=", "$", "grade", "->", "userid", ";", "if", "(", "!", "empty", "(", "$", "grade", "->", "finalgrade", ")", ")", "{", "$", "result", "->", "resultScore", "=", "floatval", "(", "$", "grade", "->", "finalgrade", ")", ";", "$", "result", "->", "resultMaximum", "=", "floatval", "(", "$", "grade", "->", "rawgrademax", ")", ";", "if", "(", "!", "empty", "(", "$", "grade", "->", "feedback", ")", ")", "{", "$", "result", "->", "comment", "=", "$", "grade", "->", "feedback", ";", "}", "if", "(", "is_null", "(", "$", "typeid", ")", ")", "{", "$", "result", "->", "scoreOf", "=", "$", "endpoint", ";", "}", "else", "{", "$", "result", "->", "scoreOf", "=", "\"{$endpoint}?type_id={$typeid}\"", ";", "}", "$", "result", "->", "timestamp", "=", "date", "(", "'c'", ",", "$", "grade", "->", "timemodified", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get the object matching the JSON representation of the result. @param object $grade Grade record @param string $endpoint Endpoint for lineitem @param int $typeid The id of the type to include in the result url. @return object
[ "Get", "the", "object", "matching", "the", "JSON", "representation", "of", "the", "result", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L431-L455
218,991
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.check_lti_id
public static function check_lti_id($linkid, $course, $toolproxy) { global $DB; // Check if lti type is zero or not (comes from a backup). $sqlparams1 = array(); $sqlparams1['linkid'] = $linkid; $sqlparams1['course'] = $course; $ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course)); if ($ltiactivity->typeid == 0) { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course); } return (($tool) && ($toolproxy == $tool->toolproxyid)); } else { $sqlparams2 = array(); $sqlparams2['linkid'] = $linkid; $sqlparams2['course'] = $course; $sqlparams2['toolproxy'] = $toolproxy; $sql = 'SELECT lti.* FROM {lti} lti INNER JOIN {lti_types} typ ON lti.typeid = typ.id WHERE lti.id = ? AND lti.course = ? AND typ.toolproxyid = ?'; return $DB->record_exists_sql($sql, $sqlparams2); } }
php
public static function check_lti_id($linkid, $course, $toolproxy) { global $DB; // Check if lti type is zero or not (comes from a backup). $sqlparams1 = array(); $sqlparams1['linkid'] = $linkid; $sqlparams1['course'] = $course; $ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course)); if ($ltiactivity->typeid == 0) { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course); } return (($tool) && ($toolproxy == $tool->toolproxyid)); } else { $sqlparams2 = array(); $sqlparams2['linkid'] = $linkid; $sqlparams2['course'] = $course; $sqlparams2['toolproxy'] = $toolproxy; $sql = 'SELECT lti.* FROM {lti} lti INNER JOIN {lti_types} typ ON lti.typeid = typ.id WHERE lti.id = ? AND lti.course = ? AND typ.toolproxyid = ?'; return $DB->record_exists_sql($sql, $sqlparams2); } }
[ "public", "static", "function", "check_lti_id", "(", "$", "linkid", ",", "$", "course", ",", "$", "toolproxy", ")", "{", "global", "$", "DB", ";", "// Check if lti type is zero or not (comes from a backup).", "$", "sqlparams1", "=", "array", "(", ")", ";", "$", "sqlparams1", "[", "'linkid'", "]", "=", "$", "linkid", ";", "$", "sqlparams1", "[", "'course'", "]", "=", "$", "course", ";", "$", "ltiactivity", "=", "$", "DB", "->", "get_record", "(", "'lti'", ",", "array", "(", "'id'", "=>", "$", "linkid", ",", "'course'", "=>", "$", "course", ")", ")", ";", "if", "(", "$", "ltiactivity", "->", "typeid", "==", "0", ")", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "toolurl", ",", "$", "course", ")", ";", "if", "(", "!", "$", "tool", ")", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "securetoolurl", ",", "$", "course", ")", ";", "}", "return", "(", "(", "$", "tool", ")", "&&", "(", "$", "toolproxy", "==", "$", "tool", "->", "toolproxyid", ")", ")", ";", "}", "else", "{", "$", "sqlparams2", "=", "array", "(", ")", ";", "$", "sqlparams2", "[", "'linkid'", "]", "=", "$", "linkid", ";", "$", "sqlparams2", "[", "'course'", "]", "=", "$", "course", ";", "$", "sqlparams2", "[", "'toolproxy'", "]", "=", "$", "toolproxy", ";", "$", "sql", "=", "'SELECT lti.*\n FROM {lti} lti\n INNER JOIN {lti_types} typ ON lti.typeid = typ.id\n WHERE lti.id = ?\n AND lti.course = ?\n AND typ.toolproxyid = ?'", ";", "return", "$", "DB", "->", "record_exists_sql", "(", "$", "sql", ",", "$", "sqlparams2", ")", ";", "}", "}" ]
Check if an LTI id is valid. @param string $linkid The lti id @param string $course The course @param string $toolproxy The tool proxy id @return boolean
[ "Check", "if", "an", "LTI", "id", "is", "valid", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L466-L492
218,992
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.check_lti_1x_id
public static function check_lti_1x_id($linkid, $course, $typeid) { global $DB; // Check if lti type is zero or not (comes from a backup). $sqlparams1 = array(); $sqlparams1['linkid'] = $linkid; $sqlparams1['course'] = $course; $ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course)); if ($ltiactivity) { if ($ltiactivity->typeid == 0) { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course); } return (($tool) && ($typeid == $tool->id)); } else { $sqlparams2 = array(); $sqlparams2['linkid'] = $linkid; $sqlparams2['course'] = $course; $sqlparams2['typeid'] = $typeid; $sql = 'SELECT lti.* FROM {lti} lti INNER JOIN {lti_types} typ ON lti.typeid = typ.id WHERE lti.id = ? AND lti.course = ? AND typ.id = ?'; return $DB->record_exists_sql($sql, $sqlparams2); } } else { return false; } }
php
public static function check_lti_1x_id($linkid, $course, $typeid) { global $DB; // Check if lti type is zero or not (comes from a backup). $sqlparams1 = array(); $sqlparams1['linkid'] = $linkid; $sqlparams1['course'] = $course; $ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course)); if ($ltiactivity) { if ($ltiactivity->typeid == 0) { $tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course); if (!$tool) { $tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course); } return (($tool) && ($typeid == $tool->id)); } else { $sqlparams2 = array(); $sqlparams2['linkid'] = $linkid; $sqlparams2['course'] = $course; $sqlparams2['typeid'] = $typeid; $sql = 'SELECT lti.* FROM {lti} lti INNER JOIN {lti_types} typ ON lti.typeid = typ.id WHERE lti.id = ? AND lti.course = ? AND typ.id = ?'; return $DB->record_exists_sql($sql, $sqlparams2); } } else { return false; } }
[ "public", "static", "function", "check_lti_1x_id", "(", "$", "linkid", ",", "$", "course", ",", "$", "typeid", ")", "{", "global", "$", "DB", ";", "// Check if lti type is zero or not (comes from a backup).", "$", "sqlparams1", "=", "array", "(", ")", ";", "$", "sqlparams1", "[", "'linkid'", "]", "=", "$", "linkid", ";", "$", "sqlparams1", "[", "'course'", "]", "=", "$", "course", ";", "$", "ltiactivity", "=", "$", "DB", "->", "get_record", "(", "'lti'", ",", "array", "(", "'id'", "=>", "$", "linkid", ",", "'course'", "=>", "$", "course", ")", ")", ";", "if", "(", "$", "ltiactivity", ")", "{", "if", "(", "$", "ltiactivity", "->", "typeid", "==", "0", ")", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "toolurl", ",", "$", "course", ")", ";", "if", "(", "!", "$", "tool", ")", "{", "$", "tool", "=", "lti_get_tool_by_url_match", "(", "$", "ltiactivity", "->", "securetoolurl", ",", "$", "course", ")", ";", "}", "return", "(", "(", "$", "tool", ")", "&&", "(", "$", "typeid", "==", "$", "tool", "->", "id", ")", ")", ";", "}", "else", "{", "$", "sqlparams2", "=", "array", "(", ")", ";", "$", "sqlparams2", "[", "'linkid'", "]", "=", "$", "linkid", ";", "$", "sqlparams2", "[", "'course'", "]", "=", "$", "course", ";", "$", "sqlparams2", "[", "'typeid'", "]", "=", "$", "typeid", ";", "$", "sql", "=", "'SELECT lti.*\n FROM {lti} lti\n INNER JOIN {lti_types} typ ON lti.typeid = typ.id\n WHERE lti.id = ?\n AND lti.course = ?\n AND typ.id = ?'", ";", "return", "$", "DB", "->", "record_exists_sql", "(", "$", "sql", ",", "$", "sqlparams2", ")", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check if an LTI id is valid when we are in a LTI 1.x case @param string $linkid The lti id @param string $course The course @param string $typeid The lti type id @return boolean
[ "Check", "if", "an", "LTI", "id", "is", "valid", "when", "we", "are", "in", "a", "LTI", "1", ".", "x", "case" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L503-L533
218,993
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.is_user_gradable_in_course
public static function is_user_gradable_in_course($courseid, $userid) { global $CFG; $gradableuser = false; $coursecontext = \context_course::instance($courseid); if (is_enrolled($coursecontext, $userid, '', false)) { $roles = get_user_roles($coursecontext, $userid); $gradebookroles = explode(',', $CFG->gradebookroles); foreach ($roles as $role) { foreach ($gradebookroles as $gradebookrole) { if ($role->roleid = $gradebookrole) { $gradableuser = true; } } } } return $gradableuser; }
php
public static function is_user_gradable_in_course($courseid, $userid) { global $CFG; $gradableuser = false; $coursecontext = \context_course::instance($courseid); if (is_enrolled($coursecontext, $userid, '', false)) { $roles = get_user_roles($coursecontext, $userid); $gradebookroles = explode(',', $CFG->gradebookroles); foreach ($roles as $role) { foreach ($gradebookroles as $gradebookrole) { if ($role->roleid = $gradebookrole) { $gradableuser = true; } } } } return $gradableuser; }
[ "public", "static", "function", "is_user_gradable_in_course", "(", "$", "courseid", ",", "$", "userid", ")", "{", "global", "$", "CFG", ";", "$", "gradableuser", "=", "false", ";", "$", "coursecontext", "=", "\\", "context_course", "::", "instance", "(", "$", "courseid", ")", ";", "if", "(", "is_enrolled", "(", "$", "coursecontext", ",", "$", "userid", ",", "''", ",", "false", ")", ")", "{", "$", "roles", "=", "get_user_roles", "(", "$", "coursecontext", ",", "$", "userid", ")", ";", "$", "gradebookroles", "=", "explode", "(", "','", ",", "$", "CFG", "->", "gradebookroles", ")", ";", "foreach", "(", "$", "roles", "as", "$", "role", ")", "{", "foreach", "(", "$", "gradebookroles", "as", "$", "gradebookrole", ")", "{", "if", "(", "$", "role", "->", "roleid", "=", "$", "gradebookrole", ")", "{", "$", "gradableuser", "=", "true", ";", "}", "}", "}", "}", "return", "$", "gradableuser", ";", "}" ]
Check if a user can be graded in a course @param int $courseid The course @param int $userid The user @return bool
[ "Check", "if", "a", "user", "can", "be", "graded", "in", "a", "course" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L560-L578
218,994
moodle/moodle
mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php
gradebookservices.find_ltiservice_gradebookservice_for_lineitem
public static function find_ltiservice_gradebookservice_for_lineitem($lineitemid) { global $DB; if (!$lineitemid) { return false; } $gradeitem = $DB->get_record('grade_items', array('id' => $lineitemid)); if ($gradeitem) { $gbs = $DB->get_record('ltiservice_gradebookservices', array('gradeitemid' => $gradeitem->id, 'courseid' => $gradeitem->courseid)); if ($gbs) { return $gbs; } else { return false; } } else { return false; } }
php
public static function find_ltiservice_gradebookservice_for_lineitem($lineitemid) { global $DB; if (!$lineitemid) { return false; } $gradeitem = $DB->get_record('grade_items', array('id' => $lineitemid)); if ($gradeitem) { $gbs = $DB->get_record('ltiservice_gradebookservices', array('gradeitemid' => $gradeitem->id, 'courseid' => $gradeitem->courseid)); if ($gbs) { return $gbs; } else { return false; } } else { return false; } }
[ "public", "static", "function", "find_ltiservice_gradebookservice_for_lineitem", "(", "$", "lineitemid", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "$", "lineitemid", ")", "{", "return", "false", ";", "}", "$", "gradeitem", "=", "$", "DB", "->", "get_record", "(", "'grade_items'", ",", "array", "(", "'id'", "=>", "$", "lineitemid", ")", ")", ";", "if", "(", "$", "gradeitem", ")", "{", "$", "gbs", "=", "$", "DB", "->", "get_record", "(", "'ltiservice_gradebookservices'", ",", "array", "(", "'gradeitemid'", "=>", "$", "gradeitem", "->", "id", ",", "'courseid'", "=>", "$", "gradeitem", "->", "courseid", ")", ")", ";", "if", "(", "$", "gbs", ")", "{", "return", "$", "gbs", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Find the right element in the ltiservice_gradebookservice table for a lineitem @param string $lineitemid The lineitem @return object|bool gradebookservice id or false if none
[ "Find", "the", "right", "element", "in", "the", "ltiservice_gradebookservice", "table", "for", "a", "lineitem" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/lti/service/gradebookservices/classes/local/service/gradebookservices.php#L586-L604
218,995
moodle/moodle
backup/moodle2/restore_activity_task.class.php
restore_activity_task.define_settings
protected function define_settings() { // All the settings related to this activity will include this prefix $settingprefix = $this->info->modulename . '_' . $this->info->moduleid . '_'; // All these are common settings to be shared by all activities // Define activity_include (to decide if the whole task must be really executed) // Dependent of: // - activities root setting // - section_included setting (if exists) $settingname = $settingprefix . 'included'; $activity_included = new restore_activity_generic_setting($settingname, base_setting::IS_BOOLEAN, true); $activity_included->get_ui()->set_icon(new image_icon('icon', get_string('pluginname', $this->modulename), $this->modulename, array('class' => 'iconlarge icon-post'))); $this->add_setting($activity_included); // Look for "activities" root setting $activities = $this->plan->get_setting('activities'); $activities->add_dependency($activity_included); // Look for "section_included" section setting (if exists) $settingname = 'section_' . $this->info->sectionid . '_included'; if ($this->plan->setting_exists($settingname)) { $section_included = $this->plan->get_setting($settingname); $section_included->add_dependency($activity_included); } // Define activity_userinfo. Dependent of: // - users root setting // - section_userinfo setting (if exists) // - activity_included setting. $settingname = $settingprefix . 'userinfo'; $defaultvalue = false; if (isset($this->info->settings[$settingname]) && $this->info->settings[$settingname]) { // Only enabled when available $defaultvalue = true; } $activity_userinfo = new restore_activity_userinfo_setting($settingname, base_setting::IS_BOOLEAN, $defaultvalue); if (!$defaultvalue) { // This is a bit hacky, but if there is no user data to restore, then // we replace the standard check-box with a select menu with the // single choice 'No', and the select menu is clever enough that if // there is only one choice, it just displays a static string. // // It would probably be better design to have a special UI class // setting_ui_checkbox_or_no, rather than this hack, but I am not // going to do that today. $activity_userinfo->set_ui(new backup_setting_ui_select($activity_userinfo, '-', array(0 => get_string('no')))); } else { $activity_userinfo->get_ui()->set_label('-'); } $this->add_setting($activity_userinfo); // Look for "users" root setting $users = $this->plan->get_setting('users'); $users->add_dependency($activity_userinfo); // Look for "section_userinfo" section setting (if exists) $settingname = 'section_' . $this->info->sectionid . '_userinfo'; if ($this->plan->setting_exists($settingname)) { $section_userinfo = $this->plan->get_setting($settingname); $section_userinfo->add_dependency($activity_userinfo); } // Look for "activity_included" setting. $activity_included->add_dependency($activity_userinfo); // End of common activity settings, let's add the particular ones. $this->define_my_settings(); }
php
protected function define_settings() { // All the settings related to this activity will include this prefix $settingprefix = $this->info->modulename . '_' . $this->info->moduleid . '_'; // All these are common settings to be shared by all activities // Define activity_include (to decide if the whole task must be really executed) // Dependent of: // - activities root setting // - section_included setting (if exists) $settingname = $settingprefix . 'included'; $activity_included = new restore_activity_generic_setting($settingname, base_setting::IS_BOOLEAN, true); $activity_included->get_ui()->set_icon(new image_icon('icon', get_string('pluginname', $this->modulename), $this->modulename, array('class' => 'iconlarge icon-post'))); $this->add_setting($activity_included); // Look for "activities" root setting $activities = $this->plan->get_setting('activities'); $activities->add_dependency($activity_included); // Look for "section_included" section setting (if exists) $settingname = 'section_' . $this->info->sectionid . '_included'; if ($this->plan->setting_exists($settingname)) { $section_included = $this->plan->get_setting($settingname); $section_included->add_dependency($activity_included); } // Define activity_userinfo. Dependent of: // - users root setting // - section_userinfo setting (if exists) // - activity_included setting. $settingname = $settingprefix . 'userinfo'; $defaultvalue = false; if (isset($this->info->settings[$settingname]) && $this->info->settings[$settingname]) { // Only enabled when available $defaultvalue = true; } $activity_userinfo = new restore_activity_userinfo_setting($settingname, base_setting::IS_BOOLEAN, $defaultvalue); if (!$defaultvalue) { // This is a bit hacky, but if there is no user data to restore, then // we replace the standard check-box with a select menu with the // single choice 'No', and the select menu is clever enough that if // there is only one choice, it just displays a static string. // // It would probably be better design to have a special UI class // setting_ui_checkbox_or_no, rather than this hack, but I am not // going to do that today. $activity_userinfo->set_ui(new backup_setting_ui_select($activity_userinfo, '-', array(0 => get_string('no')))); } else { $activity_userinfo->get_ui()->set_label('-'); } $this->add_setting($activity_userinfo); // Look for "users" root setting $users = $this->plan->get_setting('users'); $users->add_dependency($activity_userinfo); // Look for "section_userinfo" section setting (if exists) $settingname = 'section_' . $this->info->sectionid . '_userinfo'; if ($this->plan->setting_exists($settingname)) { $section_userinfo = $this->plan->get_setting($settingname); $section_userinfo->add_dependency($activity_userinfo); } // Look for "activity_included" setting. $activity_included->add_dependency($activity_userinfo); // End of common activity settings, let's add the particular ones. $this->define_my_settings(); }
[ "protected", "function", "define_settings", "(", ")", "{", "// All the settings related to this activity will include this prefix", "$", "settingprefix", "=", "$", "this", "->", "info", "->", "modulename", ".", "'_'", ".", "$", "this", "->", "info", "->", "moduleid", ".", "'_'", ";", "// All these are common settings to be shared by all activities", "// Define activity_include (to decide if the whole task must be really executed)", "// Dependent of:", "// - activities root setting", "// - section_included setting (if exists)", "$", "settingname", "=", "$", "settingprefix", ".", "'included'", ";", "$", "activity_included", "=", "new", "restore_activity_generic_setting", "(", "$", "settingname", ",", "base_setting", "::", "IS_BOOLEAN", ",", "true", ")", ";", "$", "activity_included", "->", "get_ui", "(", ")", "->", "set_icon", "(", "new", "image_icon", "(", "'icon'", ",", "get_string", "(", "'pluginname'", ",", "$", "this", "->", "modulename", ")", ",", "$", "this", "->", "modulename", ",", "array", "(", "'class'", "=>", "'iconlarge icon-post'", ")", ")", ")", ";", "$", "this", "->", "add_setting", "(", "$", "activity_included", ")", ";", "// Look for \"activities\" root setting", "$", "activities", "=", "$", "this", "->", "plan", "->", "get_setting", "(", "'activities'", ")", ";", "$", "activities", "->", "add_dependency", "(", "$", "activity_included", ")", ";", "// Look for \"section_included\" section setting (if exists)", "$", "settingname", "=", "'section_'", ".", "$", "this", "->", "info", "->", "sectionid", ".", "'_included'", ";", "if", "(", "$", "this", "->", "plan", "->", "setting_exists", "(", "$", "settingname", ")", ")", "{", "$", "section_included", "=", "$", "this", "->", "plan", "->", "get_setting", "(", "$", "settingname", ")", ";", "$", "section_included", "->", "add_dependency", "(", "$", "activity_included", ")", ";", "}", "// Define activity_userinfo. Dependent of:", "// - users root setting", "// - section_userinfo setting (if exists)", "// - activity_included setting.", "$", "settingname", "=", "$", "settingprefix", ".", "'userinfo'", ";", "$", "defaultvalue", "=", "false", ";", "if", "(", "isset", "(", "$", "this", "->", "info", "->", "settings", "[", "$", "settingname", "]", ")", "&&", "$", "this", "->", "info", "->", "settings", "[", "$", "settingname", "]", ")", "{", "// Only enabled when available", "$", "defaultvalue", "=", "true", ";", "}", "$", "activity_userinfo", "=", "new", "restore_activity_userinfo_setting", "(", "$", "settingname", ",", "base_setting", "::", "IS_BOOLEAN", ",", "$", "defaultvalue", ")", ";", "if", "(", "!", "$", "defaultvalue", ")", "{", "// This is a bit hacky, but if there is no user data to restore, then", "// we replace the standard check-box with a select menu with the", "// single choice 'No', and the select menu is clever enough that if", "// there is only one choice, it just displays a static string.", "//", "// It would probably be better design to have a special UI class", "// setting_ui_checkbox_or_no, rather than this hack, but I am not", "// going to do that today.", "$", "activity_userinfo", "->", "set_ui", "(", "new", "backup_setting_ui_select", "(", "$", "activity_userinfo", ",", "'-'", ",", "array", "(", "0", "=>", "get_string", "(", "'no'", ")", ")", ")", ")", ";", "}", "else", "{", "$", "activity_userinfo", "->", "get_ui", "(", ")", "->", "set_label", "(", "'-'", ")", ";", "}", "$", "this", "->", "add_setting", "(", "$", "activity_userinfo", ")", ";", "// Look for \"users\" root setting", "$", "users", "=", "$", "this", "->", "plan", "->", "get_setting", "(", "'users'", ")", ";", "$", "users", "->", "add_dependency", "(", "$", "activity_userinfo", ")", ";", "// Look for \"section_userinfo\" section setting (if exists)", "$", "settingname", "=", "'section_'", ".", "$", "this", "->", "info", "->", "sectionid", ".", "'_userinfo'", ";", "if", "(", "$", "this", "->", "plan", "->", "setting_exists", "(", "$", "settingname", ")", ")", "{", "$", "section_userinfo", "=", "$", "this", "->", "plan", "->", "get_setting", "(", "$", "settingname", ")", ";", "$", "section_userinfo", "->", "add_dependency", "(", "$", "activity_userinfo", ")", ";", "}", "// Look for \"activity_included\" setting.", "$", "activity_included", "->", "add_dependency", "(", "$", "activity_userinfo", ")", ";", "// End of common activity settings, let's add the particular ones.", "$", "this", "->", "define_my_settings", "(", ")", ";", "}" ]
Define the common setting that any restore activity will have
[ "Define", "the", "common", "setting", "that", "any", "restore", "activity", "will", "have" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/moodle2/restore_activity_task.class.php#L286-L356
218,996
moodle/moodle
lib/dtl/xml_database_importer.php
xml_database_importer.get_parser
protected function get_parser() { $parser = xml_parser_create(); xml_set_object($parser, $this); xml_set_element_handler($parser, 'tag_open', 'tag_close'); xml_set_character_data_handler($parser, 'cdata'); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false); return $parser; }
php
protected function get_parser() { $parser = xml_parser_create(); xml_set_object($parser, $this); xml_set_element_handler($parser, 'tag_open', 'tag_close'); xml_set_character_data_handler($parser, 'cdata'); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false); return $parser; }
[ "protected", "function", "get_parser", "(", ")", "{", "$", "parser", "=", "xml_parser_create", "(", ")", ";", "xml_set_object", "(", "$", "parser", ",", "$", "this", ")", ";", "xml_set_element_handler", "(", "$", "parser", ",", "'tag_open'", ",", "'tag_close'", ")", ";", "xml_set_character_data_handler", "(", "$", "parser", ",", "'cdata'", ")", ";", "xml_parser_set_option", "(", "$", "parser", ",", "XML_OPTION_CASE_FOLDING", ",", "false", ")", ";", "return", "$", "parser", ";", "}" ]
Creates and setups a SAX parser. Subclasses should use this method to create the XML parser. @return resource XML parser resource.
[ "Creates", "and", "setups", "a", "SAX", "parser", ".", "Subclasses", "should", "use", "this", "method", "to", "create", "the", "XML", "parser", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dtl/xml_database_importer.php#L45-L52
218,997
moodle/moodle
lib/dtl/xml_database_importer.php
xml_database_importer.tag_open
protected function tag_open($parser, $tag, $attributes) { switch ($tag) { case 'moodle_database' : if (empty($attributes['version']) || empty($attributes['timestamp'])) { throw new dbtransfer_exception('malformedxmlexception'); } $this->begin_database_import($attributes['version'], $attributes['timestamp']); break; case 'table' : if (isset($this->current_table)) { throw new dbtransfer_exception('malformedxmlexception'); } if (empty($attributes['name']) || empty($attributes['schemaHash'])) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_table = $attributes['name']; $this->begin_table_import($this->current_table, $attributes['schemaHash']); break; case 'record' : if (isset($this->current_row) || !isset($this->current_table)) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_row = new stdClass(); break; case 'field' : if (isset($this->current_field) || !isset($this->current_row)) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_field = $attributes['name']; $this->current_data = ''; if (isset($attributes['value']) and $attributes['value'] === 'null') { $this->current_data_is_null = true; } else { $this->current_data_is_null = false; } break; default : throw new dbtransfer_exception('malformedxmlexception'); } }
php
protected function tag_open($parser, $tag, $attributes) { switch ($tag) { case 'moodle_database' : if (empty($attributes['version']) || empty($attributes['timestamp'])) { throw new dbtransfer_exception('malformedxmlexception'); } $this->begin_database_import($attributes['version'], $attributes['timestamp']); break; case 'table' : if (isset($this->current_table)) { throw new dbtransfer_exception('malformedxmlexception'); } if (empty($attributes['name']) || empty($attributes['schemaHash'])) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_table = $attributes['name']; $this->begin_table_import($this->current_table, $attributes['schemaHash']); break; case 'record' : if (isset($this->current_row) || !isset($this->current_table)) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_row = new stdClass(); break; case 'field' : if (isset($this->current_field) || !isset($this->current_row)) { throw new dbtransfer_exception('malformedxmlexception'); } $this->current_field = $attributes['name']; $this->current_data = ''; if (isset($attributes['value']) and $attributes['value'] === 'null') { $this->current_data_is_null = true; } else { $this->current_data_is_null = false; } break; default : throw new dbtransfer_exception('malformedxmlexception'); } }
[ "protected", "function", "tag_open", "(", "$", "parser", ",", "$", "tag", ",", "$", "attributes", ")", "{", "switch", "(", "$", "tag", ")", "{", "case", "'moodle_database'", ":", "if", "(", "empty", "(", "$", "attributes", "[", "'version'", "]", ")", "||", "empty", "(", "$", "attributes", "[", "'timestamp'", "]", ")", ")", "{", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "$", "this", "->", "begin_database_import", "(", "$", "attributes", "[", "'version'", "]", ",", "$", "attributes", "[", "'timestamp'", "]", ")", ";", "break", ";", "case", "'table'", ":", "if", "(", "isset", "(", "$", "this", "->", "current_table", ")", ")", "{", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "if", "(", "empty", "(", "$", "attributes", "[", "'name'", "]", ")", "||", "empty", "(", "$", "attributes", "[", "'schemaHash'", "]", ")", ")", "{", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "$", "this", "->", "current_table", "=", "$", "attributes", "[", "'name'", "]", ";", "$", "this", "->", "begin_table_import", "(", "$", "this", "->", "current_table", ",", "$", "attributes", "[", "'schemaHash'", "]", ")", ";", "break", ";", "case", "'record'", ":", "if", "(", "isset", "(", "$", "this", "->", "current_row", ")", "||", "!", "isset", "(", "$", "this", "->", "current_table", ")", ")", "{", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "$", "this", "->", "current_row", "=", "new", "stdClass", "(", ")", ";", "break", ";", "case", "'field'", ":", "if", "(", "isset", "(", "$", "this", "->", "current_field", ")", "||", "!", "isset", "(", "$", "this", "->", "current_row", ")", ")", "{", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "$", "this", "->", "current_field", "=", "$", "attributes", "[", "'name'", "]", ";", "$", "this", "->", "current_data", "=", "''", ";", "if", "(", "isset", "(", "$", "attributes", "[", "'value'", "]", ")", "and", "$", "attributes", "[", "'value'", "]", "===", "'null'", ")", "{", "$", "this", "->", "current_data_is_null", "=", "true", ";", "}", "else", "{", "$", "this", "->", "current_data_is_null", "=", "false", ";", "}", "break", ";", "default", ":", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "}" ]
Callback function. Called by the XML parser for opening tags processing. @param resource $parser XML parser resource. @param string $tag name of opening tag @param array $attributes set of opening tag XML attributes @return void
[ "Callback", "function", ".", "Called", "by", "the", "XML", "parser", "for", "opening", "tags", "processing", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dtl/xml_database_importer.php#L62-L101
218,998
moodle/moodle
lib/dtl/xml_database_importer.php
xml_database_importer.tag_close
protected function tag_close($parser, $tag) { switch ($tag) { case 'moodle_database' : $this->finish_database_import(); break; case 'table' : $this->finish_table_import($this->current_table); $this->current_table = null; break; case 'record' : $this->import_table_data($this->current_table, $this->current_row); $this->current_row = null; break; case 'field' : $field = $this->current_field; if ($this->current_data_is_null) { $this->current_row->$field = null; } else { $this->current_row->$field = $this->current_data; } $this->current_field = null; $this->current_data = null; $this->current_data_is_null = null; break; default : throw new dbtransfer_exception('malformedxmlexception'); } }
php
protected function tag_close($parser, $tag) { switch ($tag) { case 'moodle_database' : $this->finish_database_import(); break; case 'table' : $this->finish_table_import($this->current_table); $this->current_table = null; break; case 'record' : $this->import_table_data($this->current_table, $this->current_row); $this->current_row = null; break; case 'field' : $field = $this->current_field; if ($this->current_data_is_null) { $this->current_row->$field = null; } else { $this->current_row->$field = $this->current_data; } $this->current_field = null; $this->current_data = null; $this->current_data_is_null = null; break; default : throw new dbtransfer_exception('malformedxmlexception'); } }
[ "protected", "function", "tag_close", "(", "$", "parser", ",", "$", "tag", ")", "{", "switch", "(", "$", "tag", ")", "{", "case", "'moodle_database'", ":", "$", "this", "->", "finish_database_import", "(", ")", ";", "break", ";", "case", "'table'", ":", "$", "this", "->", "finish_table_import", "(", "$", "this", "->", "current_table", ")", ";", "$", "this", "->", "current_table", "=", "null", ";", "break", ";", "case", "'record'", ":", "$", "this", "->", "import_table_data", "(", "$", "this", "->", "current_table", ",", "$", "this", "->", "current_row", ")", ";", "$", "this", "->", "current_row", "=", "null", ";", "break", ";", "case", "'field'", ":", "$", "field", "=", "$", "this", "->", "current_field", ";", "if", "(", "$", "this", "->", "current_data_is_null", ")", "{", "$", "this", "->", "current_row", "->", "$", "field", "=", "null", ";", "}", "else", "{", "$", "this", "->", "current_row", "->", "$", "field", "=", "$", "this", "->", "current_data", ";", "}", "$", "this", "->", "current_field", "=", "null", ";", "$", "this", "->", "current_data", "=", "null", ";", "$", "this", "->", "current_data_is_null", "=", "null", ";", "break", ";", "default", ":", "throw", "new", "dbtransfer_exception", "(", "'malformedxmlexception'", ")", ";", "}", "}" ]
Callback function. Called by the XML parser for closing tags processing. @param resource $parser XML parser resource. @param string $tag name of opening tag @return void
[ "Callback", "function", ".", "Called", "by", "the", "XML", "parser", "for", "closing", "tags", "processing", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/dtl/xml_database_importer.php#L110-L141
218,999
moodle/moodle
admin/tool/dataprivacy/classes/purpose.php
purpose.after_create
protected function after_create() { $cache = \cache::make('tool_dataprivacy', 'purpose'); $cache->set($this->get('id'), $this->to_record()); }
php
protected function after_create() { $cache = \cache::make('tool_dataprivacy', 'purpose'); $cache->set($this->get('id'), $this->to_record()); }
[ "protected", "function", "after_create", "(", ")", "{", "$", "cache", "=", "\\", "cache", "::", "make", "(", "'tool_dataprivacy'", ",", "'purpose'", ")", ";", "$", "cache", "->", "set", "(", "$", "this", "->", "get", "(", "'id'", ")", ",", "$", "this", "->", "to_record", "(", ")", ")", ";", "}" ]
Adds the new record to the cache. @return null
[ "Adds", "the", "new", "record", "to", "the", "cache", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/dataprivacy/classes/purpose.php#L133-L136