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
220,200
moodle/moodle
admin/tool/uploadcourse/classes/tracker.php
tool_uploadcourse_tracker.output
public function output($line, $outcome, $status, $data) { global $OUTPUT; if ($this->outputmode == self::NO_OUTPUT) { return; } if ($this->outputmode == self::OUTPUT_PLAIN) { $message = array( $line, $outcome ? 'OK' : 'NOK', isset($data['id']) ? $data['id'] : '', isset($data['shortname']) ? $data['shortname'] : '', isset($data['fullname']) ? $data['fullname'] : '', isset($data['idnumber']) ? $data['idnumber'] : '' ); $this->buffer->output(implode("\t", $message)); if (!empty($status)) { foreach ($status as $st) { $this->buffer->output($st, 1); } } } else if ($this->outputmode == self::OUTPUT_HTML) { $ci = 0; $this->rownb++; if (is_array($status)) { $status = implode(html_writer::empty_tag('br'), $status); } if ($outcome) { $outcome = $OUTPUT->pix_icon('i/valid', ''); } else { $outcome = $OUTPUT->pix_icon('i/invalid', ''); } echo html_writer::start_tag('tr', array('class' => 'r' . $this->rownb % 2)); echo html_writer::tag('td', $line, array('class' => 'c' . $ci++)); echo html_writer::tag('td', $outcome, array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['id']) ? $data['id'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['shortname']) ? $data['shortname'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['fullname']) ? $data['fullname'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['idnumber']) ? $data['idnumber'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', $status, array('class' => 'c' . $ci++)); echo html_writer::end_tag('tr'); } }
php
public function output($line, $outcome, $status, $data) { global $OUTPUT; if ($this->outputmode == self::NO_OUTPUT) { return; } if ($this->outputmode == self::OUTPUT_PLAIN) { $message = array( $line, $outcome ? 'OK' : 'NOK', isset($data['id']) ? $data['id'] : '', isset($data['shortname']) ? $data['shortname'] : '', isset($data['fullname']) ? $data['fullname'] : '', isset($data['idnumber']) ? $data['idnumber'] : '' ); $this->buffer->output(implode("\t", $message)); if (!empty($status)) { foreach ($status as $st) { $this->buffer->output($st, 1); } } } else if ($this->outputmode == self::OUTPUT_HTML) { $ci = 0; $this->rownb++; if (is_array($status)) { $status = implode(html_writer::empty_tag('br'), $status); } if ($outcome) { $outcome = $OUTPUT->pix_icon('i/valid', ''); } else { $outcome = $OUTPUT->pix_icon('i/invalid', ''); } echo html_writer::start_tag('tr', array('class' => 'r' . $this->rownb % 2)); echo html_writer::tag('td', $line, array('class' => 'c' . $ci++)); echo html_writer::tag('td', $outcome, array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['id']) ? $data['id'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['shortname']) ? $data['shortname'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['fullname']) ? $data['fullname'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', isset($data['idnumber']) ? $data['idnumber'] : '', array('class' => 'c' . $ci++)); echo html_writer::tag('td', $status, array('class' => 'c' . $ci++)); echo html_writer::end_tag('tr'); } }
[ "public", "function", "output", "(", "$", "line", ",", "$", "outcome", ",", "$", "status", ",", "$", "data", ")", "{", "global", "$", "OUTPUT", ";", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "NO_OUTPUT", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "OUTPUT_PLAIN", ")", "{", "$", "message", "=", "array", "(", "$", "line", ",", "$", "outcome", "?", "'OK'", ":", "'NOK'", ",", "isset", "(", "$", "data", "[", "'id'", "]", ")", "?", "$", "data", "[", "'id'", "]", ":", "''", ",", "isset", "(", "$", "data", "[", "'shortname'", "]", ")", "?", "$", "data", "[", "'shortname'", "]", ":", "''", ",", "isset", "(", "$", "data", "[", "'fullname'", "]", ")", "?", "$", "data", "[", "'fullname'", "]", ":", "''", ",", "isset", "(", "$", "data", "[", "'idnumber'", "]", ")", "?", "$", "data", "[", "'idnumber'", "]", ":", "''", ")", ";", "$", "this", "->", "buffer", "->", "output", "(", "implode", "(", "\"\\t\"", ",", "$", "message", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "status", ")", ")", "{", "foreach", "(", "$", "status", "as", "$", "st", ")", "{", "$", "this", "->", "buffer", "->", "output", "(", "$", "st", ",", "1", ")", ";", "}", "}", "}", "else", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "OUTPUT_HTML", ")", "{", "$", "ci", "=", "0", ";", "$", "this", "->", "rownb", "++", ";", "if", "(", "is_array", "(", "$", "status", ")", ")", "{", "$", "status", "=", "implode", "(", "html_writer", "::", "empty_tag", "(", "'br'", ")", ",", "$", "status", ")", ";", "}", "if", "(", "$", "outcome", ")", "{", "$", "outcome", "=", "$", "OUTPUT", "->", "pix_icon", "(", "'i/valid'", ",", "''", ")", ";", "}", "else", "{", "$", "outcome", "=", "$", "OUTPUT", "->", "pix_icon", "(", "'i/invalid'", ",", "''", ")", ";", "}", "echo", "html_writer", "::", "start_tag", "(", "'tr'", ",", "array", "(", "'class'", "=>", "'r'", ".", "$", "this", "->", "rownb", "%", "2", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "$", "line", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "$", "outcome", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "isset", "(", "$", "data", "[", "'id'", "]", ")", "?", "$", "data", "[", "'id'", "]", ":", "''", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "isset", "(", "$", "data", "[", "'shortname'", "]", ")", "?", "$", "data", "[", "'shortname'", "]", ":", "''", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "isset", "(", "$", "data", "[", "'fullname'", "]", ")", "?", "$", "data", "[", "'fullname'", "]", ":", "''", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "isset", "(", "$", "data", "[", "'idnumber'", "]", ")", "?", "$", "data", "[", "'idnumber'", "]", ":", "''", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'td'", ",", "$", "status", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ")", ")", ";", "echo", "html_writer", "::", "end_tag", "(", "'tr'", ")", ";", "}", "}" ]
Output one more line. @param int $line line number. @param bool $outcome success or not? @param array $status array of statuses. @param array $data extra data to display. @return void
[ "Output", "one", "more", "line", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/tracker.php#L144-L186
220,201
moodle/moodle
admin/tool/uploadcourse/classes/tracker.php
tool_uploadcourse_tracker.start
public function start() { if ($this->outputmode == self::NO_OUTPUT) { return; } if ($this->outputmode == self::OUTPUT_PLAIN) { $columns = array_flip($this->columns); unset($columns['status']); $columns = array_flip($columns); $this->buffer->output(implode("\t", $columns)); } else if ($this->outputmode == self::OUTPUT_HTML) { $ci = 0; echo html_writer::start_tag('table', array('class' => 'generaltable boxaligncenter flexible-wrap', 'summary' => get_string('uploadcoursesresult', 'tool_uploadcourse'))); echo html_writer::start_tag('tr', array('class' => 'heading r' . $this->rownb)); echo html_writer::tag('th', get_string('csvline', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('result', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('id', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('shortname'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('fullname'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('idnumber'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('status'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::end_tag('tr'); } }
php
public function start() { if ($this->outputmode == self::NO_OUTPUT) { return; } if ($this->outputmode == self::OUTPUT_PLAIN) { $columns = array_flip($this->columns); unset($columns['status']); $columns = array_flip($columns); $this->buffer->output(implode("\t", $columns)); } else if ($this->outputmode == self::OUTPUT_HTML) { $ci = 0; echo html_writer::start_tag('table', array('class' => 'generaltable boxaligncenter flexible-wrap', 'summary' => get_string('uploadcoursesresult', 'tool_uploadcourse'))); echo html_writer::start_tag('tr', array('class' => 'heading r' . $this->rownb)); echo html_writer::tag('th', get_string('csvline', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('result', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('id', 'tool_uploadcourse'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('shortname'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('fullname'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('idnumber'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::tag('th', get_string('status'), array('class' => 'c' . $ci++, 'scope' => 'col')); echo html_writer::end_tag('tr'); } }
[ "public", "function", "start", "(", ")", "{", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "NO_OUTPUT", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "OUTPUT_PLAIN", ")", "{", "$", "columns", "=", "array_flip", "(", "$", "this", "->", "columns", ")", ";", "unset", "(", "$", "columns", "[", "'status'", "]", ")", ";", "$", "columns", "=", "array_flip", "(", "$", "columns", ")", ";", "$", "this", "->", "buffer", "->", "output", "(", "implode", "(", "\"\\t\"", ",", "$", "columns", ")", ")", ";", "}", "else", "if", "(", "$", "this", "->", "outputmode", "==", "self", "::", "OUTPUT_HTML", ")", "{", "$", "ci", "=", "0", ";", "echo", "html_writer", "::", "start_tag", "(", "'table'", ",", "array", "(", "'class'", "=>", "'generaltable boxaligncenter flexible-wrap'", ",", "'summary'", "=>", "get_string", "(", "'uploadcoursesresult'", ",", "'tool_uploadcourse'", ")", ")", ")", ";", "echo", "html_writer", "::", "start_tag", "(", "'tr'", ",", "array", "(", "'class'", "=>", "'heading r'", ".", "$", "this", "->", "rownb", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'csvline'", ",", "'tool_uploadcourse'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'result'", ",", "'tool_uploadcourse'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'id'", ",", "'tool_uploadcourse'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'shortname'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'fullname'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'idnumber'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "tag", "(", "'th'", ",", "get_string", "(", "'status'", ")", ",", "array", "(", "'class'", "=>", "'c'", ".", "$", "ci", "++", ",", "'scope'", "=>", "'col'", ")", ")", ";", "echo", "html_writer", "::", "end_tag", "(", "'tr'", ")", ";", "}", "}" ]
Start the output. @return void
[ "Start", "the", "output", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/uploadcourse/classes/tracker.php#L193-L218
220,202
moodle/moodle
cache/stores/mongodb/MongoDB/GridFS/WritableStream.php
WritableStream.close
public function close() { if ($this->isClosed) { // TODO: Should this be an error condition? e.g. BadMethodCallException return; } if (strlen($this->buffer) > 0) { $this->insertChunkFromBuffer(); } $this->fileCollectionInsert(); $this->isClosed = true; }
php
public function close() { if ($this->isClosed) { // TODO: Should this be an error condition? e.g. BadMethodCallException return; } if (strlen($this->buffer) > 0) { $this->insertChunkFromBuffer(); } $this->fileCollectionInsert(); $this->isClosed = true; }
[ "public", "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "isClosed", ")", "{", "// TODO: Should this be an error condition? e.g. BadMethodCallException", "return", ";", "}", "if", "(", "strlen", "(", "$", "this", "->", "buffer", ")", ">", "0", ")", "{", "$", "this", "->", "insertChunkFromBuffer", "(", ")", ";", "}", "$", "this", "->", "fileCollectionInsert", "(", ")", ";", "$", "this", "->", "isClosed", "=", "true", ";", "}" ]
Closes an active stream and flushes all buffered data to GridFS.
[ "Closes", "an", "active", "stream", "and", "flushes", "all", "buffered", "data", "to", "GridFS", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/cache/stores/mongodb/MongoDB/GridFS/WritableStream.php#L139-L152
220,203
moodle/moodle
cache/stores/mongodb/MongoDB/GridFS/WritableStream.php
WritableStream.writeBytes
public function writeBytes($data) { if ($this->isClosed) { // TODO: Should this be an error condition? e.g. BadMethodCallException return; } $bytesRead = 0; while ($bytesRead != strlen($data)) { $initialBufferLength = strlen($this->buffer); $this->buffer .= substr($data, $bytesRead, $this->chunkSize - $initialBufferLength); $bytesRead += strlen($this->buffer) - $initialBufferLength; if (strlen($this->buffer) == $this->chunkSize) { $this->insertChunkFromBuffer(); } } return $bytesRead; }
php
public function writeBytes($data) { if ($this->isClosed) { // TODO: Should this be an error condition? e.g. BadMethodCallException return; } $bytesRead = 0; while ($bytesRead != strlen($data)) { $initialBufferLength = strlen($this->buffer); $this->buffer .= substr($data, $bytesRead, $this->chunkSize - $initialBufferLength); $bytesRead += strlen($this->buffer) - $initialBufferLength; if (strlen($this->buffer) == $this->chunkSize) { $this->insertChunkFromBuffer(); } } return $bytesRead; }
[ "public", "function", "writeBytes", "(", "$", "data", ")", "{", "if", "(", "$", "this", "->", "isClosed", ")", "{", "// TODO: Should this be an error condition? e.g. BadMethodCallException", "return", ";", "}", "$", "bytesRead", "=", "0", ";", "while", "(", "$", "bytesRead", "!=", "strlen", "(", "$", "data", ")", ")", "{", "$", "initialBufferLength", "=", "strlen", "(", "$", "this", "->", "buffer", ")", ";", "$", "this", "->", "buffer", ".=", "substr", "(", "$", "data", ",", "$", "bytesRead", ",", "$", "this", "->", "chunkSize", "-", "$", "initialBufferLength", ")", ";", "$", "bytesRead", "+=", "strlen", "(", "$", "this", "->", "buffer", ")", "-", "$", "initialBufferLength", ";", "if", "(", "strlen", "(", "$", "this", "->", "buffer", ")", "==", "$", "this", "->", "chunkSize", ")", "{", "$", "this", "->", "insertChunkFromBuffer", "(", ")", ";", "}", "}", "return", "$", "bytesRead", ";", "}" ]
Inserts binary data into GridFS via chunks. Data will be buffered internally until chunkSizeBytes are accumulated, at which point a chunk document will be inserted and the buffer reset. @param string $data Binary data to write @return integer
[ "Inserts", "binary", "data", "into", "GridFS", "via", "chunks", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/cache/stores/mongodb/MongoDB/GridFS/WritableStream.php#L200-L220
220,204
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.init
protected function init() { if (isset($this->stores)) { // Do not bother checking readers and writers here // because everything is init here. return; } $this->stores = array(); $this->readers = array(); $this->writers = array(); // Register shutdown handler - this may be useful for buffering, file handle closing, etc. \core_shutdown_manager::register_function(array($this, 'dispose')); $plugins = get_config('tool_log', 'enabled_stores'); if (empty($plugins)) { return; } $plugins = explode(',', $plugins); foreach ($plugins as $plugin) { $classname = "\\$plugin\\log\\store"; if (class_exists($classname)) { $store = new $classname($this); $this->stores[$plugin] = $store; if ($store instanceof \tool_log\log\writer) { $this->writers[$plugin] = $store; } if ($store instanceof \core\log\reader) { $this->readers[$plugin] = $store; } } } }
php
protected function init() { if (isset($this->stores)) { // Do not bother checking readers and writers here // because everything is init here. return; } $this->stores = array(); $this->readers = array(); $this->writers = array(); // Register shutdown handler - this may be useful for buffering, file handle closing, etc. \core_shutdown_manager::register_function(array($this, 'dispose')); $plugins = get_config('tool_log', 'enabled_stores'); if (empty($plugins)) { return; } $plugins = explode(',', $plugins); foreach ($plugins as $plugin) { $classname = "\\$plugin\\log\\store"; if (class_exists($classname)) { $store = new $classname($this); $this->stores[$plugin] = $store; if ($store instanceof \tool_log\log\writer) { $this->writers[$plugin] = $store; } if ($store instanceof \core\log\reader) { $this->readers[$plugin] = $store; } } } }
[ "protected", "function", "init", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "stores", ")", ")", "{", "// Do not bother checking readers and writers here", "// because everything is init here.", "return", ";", "}", "$", "this", "->", "stores", "=", "array", "(", ")", ";", "$", "this", "->", "readers", "=", "array", "(", ")", ";", "$", "this", "->", "writers", "=", "array", "(", ")", ";", "// Register shutdown handler - this may be useful for buffering, file handle closing, etc.", "\\", "core_shutdown_manager", "::", "register_function", "(", "array", "(", "$", "this", ",", "'dispose'", ")", ")", ";", "$", "plugins", "=", "get_config", "(", "'tool_log'", ",", "'enabled_stores'", ")", ";", "if", "(", "empty", "(", "$", "plugins", ")", ")", "{", "return", ";", "}", "$", "plugins", "=", "explode", "(", "','", ",", "$", "plugins", ")", ";", "foreach", "(", "$", "plugins", "as", "$", "plugin", ")", "{", "$", "classname", "=", "\"\\\\$plugin\\\\log\\\\store\"", ";", "if", "(", "class_exists", "(", "$", "classname", ")", ")", "{", "$", "store", "=", "new", "$", "classname", "(", "$", "this", ")", ";", "$", "this", "->", "stores", "[", "$", "plugin", "]", "=", "$", "store", ";", "if", "(", "$", "store", "instanceof", "\\", "tool_log", "\\", "log", "\\", "writer", ")", "{", "$", "this", "->", "writers", "[", "$", "plugin", "]", "=", "$", "store", ";", "}", "if", "(", "$", "store", "instanceof", "\\", "core", "\\", "log", "\\", "reader", ")", "{", "$", "this", "->", "readers", "[", "$", "plugin", "]", "=", "$", "store", ";", "}", "}", "}", "}" ]
Delayed initialisation of singleton.
[ "Delayed", "initialisation", "of", "singleton", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L42-L74
220,205
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.process
public function process(\core\event\base $event) { $this->init(); foreach ($this->writers as $plugin => $writer) { try { $writer->write($event, $this); } catch (\Exception $e) { debugging('Exception detected when logging event ' . $event->eventname . ' in ' . $plugin . ': ' . $e->getMessage(), DEBUG_NORMAL, $e->getTrace()); } } }
php
public function process(\core\event\base $event) { $this->init(); foreach ($this->writers as $plugin => $writer) { try { $writer->write($event, $this); } catch (\Exception $e) { debugging('Exception detected when logging event ' . $event->eventname . ' in ' . $plugin . ': ' . $e->getMessage(), DEBUG_NORMAL, $e->getTrace()); } } }
[ "public", "function", "process", "(", "\\", "core", "\\", "event", "\\", "base", "$", "event", ")", "{", "$", "this", "->", "init", "(", ")", ";", "foreach", "(", "$", "this", "->", "writers", "as", "$", "plugin", "=>", "$", "writer", ")", "{", "try", "{", "$", "writer", "->", "write", "(", "$", "event", ",", "$", "this", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "debugging", "(", "'Exception detected when logging event '", ".", "$", "event", "->", "eventname", ".", "' in '", ".", "$", "plugin", ".", "': '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "DEBUG_NORMAL", ",", "$", "e", "->", "getTrace", "(", ")", ")", ";", "}", "}", "}" ]
Called from the observer only. @param \core\event\base $event
[ "Called", "from", "the", "observer", "only", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L81-L91
220,206
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.get_readers
public function get_readers($interface = null) { $this->init(); $return = array(); foreach ($this->readers as $plugin => $reader) { if (empty($interface) || ($reader instanceof $interface)) { $return[$plugin] = $reader; } } return $return; }
php
public function get_readers($interface = null) { $this->init(); $return = array(); foreach ($this->readers as $plugin => $reader) { if (empty($interface) || ($reader instanceof $interface)) { $return[$plugin] = $reader; } } return $return; }
[ "public", "function", "get_readers", "(", "$", "interface", "=", "null", ")", "{", "$", "this", "->", "init", "(", ")", ";", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "readers", "as", "$", "plugin", "=>", "$", "reader", ")", "{", "if", "(", "empty", "(", "$", "interface", ")", "||", "(", "$", "reader", "instanceof", "$", "interface", ")", ")", "{", "$", "return", "[", "$", "plugin", "]", "=", "$", "reader", ";", "}", "}", "return", "$", "return", ";", "}" ]
Returns list of available log readers. This way the reports find out available sources of data. @param string $interface Returned stores must implement this interface. @return \core\log\reader[] list of available log data readers
[ "Returns", "list", "of", "available", "log", "readers", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L102-L112
220,207
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.get_supported_reports
public function get_supported_reports($logstore) { $allstores = self::get_store_plugins(); if (empty($allstores[$logstore])) { // Store doesn't exist. return array(); } $reports = get_plugin_list_with_function('report', 'supports_logstore', 'lib.php'); $enabled = $this->stores; if (empty($enabled[$logstore])) { // Store is not enabled, init an instance. $classname = '\\' . $logstore . '\log\store'; $instance = new $classname($this); } else { $instance = $enabled[$logstore]; } $return = array(); foreach ($reports as $report => $fulldir) { if (component_callback($report, 'supports_logstore', array($instance), false)) { $return[$report] = get_string('pluginname', $report); } } return $return; }
php
public function get_supported_reports($logstore) { $allstores = self::get_store_plugins(); if (empty($allstores[$logstore])) { // Store doesn't exist. return array(); } $reports = get_plugin_list_with_function('report', 'supports_logstore', 'lib.php'); $enabled = $this->stores; if (empty($enabled[$logstore])) { // Store is not enabled, init an instance. $classname = '\\' . $logstore . '\log\store'; $instance = new $classname($this); } else { $instance = $enabled[$logstore]; } $return = array(); foreach ($reports as $report => $fulldir) { if (component_callback($report, 'supports_logstore', array($instance), false)) { $return[$report] = get_string('pluginname', $report); } } return $return; }
[ "public", "function", "get_supported_reports", "(", "$", "logstore", ")", "{", "$", "allstores", "=", "self", "::", "get_store_plugins", "(", ")", ";", "if", "(", "empty", "(", "$", "allstores", "[", "$", "logstore", "]", ")", ")", "{", "// Store doesn't exist.", "return", "array", "(", ")", ";", "}", "$", "reports", "=", "get_plugin_list_with_function", "(", "'report'", ",", "'supports_logstore'", ",", "'lib.php'", ")", ";", "$", "enabled", "=", "$", "this", "->", "stores", ";", "if", "(", "empty", "(", "$", "enabled", "[", "$", "logstore", "]", ")", ")", "{", "// Store is not enabled, init an instance.", "$", "classname", "=", "'\\\\'", ".", "$", "logstore", ".", "'\\log\\store'", ";", "$", "instance", "=", "new", "$", "classname", "(", "$", "this", ")", ";", "}", "else", "{", "$", "instance", "=", "$", "enabled", "[", "$", "logstore", "]", ";", "}", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "reports", "as", "$", "report", "=>", "$", "fulldir", ")", "{", "if", "(", "component_callback", "(", "$", "report", ",", "'supports_logstore'", ",", "array", "(", "$", "instance", ")", ",", "false", ")", ")", "{", "$", "return", "[", "$", "report", "]", "=", "get_string", "(", "'pluginname'", ",", "$", "report", ")", ";", "}", "}", "return", "$", "return", ";", "}" ]
Get a list of reports that support the given store instance. @param string $logstore Name of the store. @return array List of supported reports
[ "Get", "a", "list", "of", "reports", "that", "support", "the", "given", "store", "instance", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L121-L148
220,208
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.get_supported_logstores
public function get_supported_logstores($component) { $allstores = self::get_store_plugins(); $enabled = $this->stores; $function = component_callback_exists($component, 'supports_logstore'); if (!$function) { // The report doesn't define the callback, most probably it doesn't need log stores. return false; } $return = array(); foreach ($allstores as $store => $logclass) { $instance = empty($enabled[$store]) ? new $logclass($this) : $enabled[$store]; if ($function($instance)) { $return[$store] = get_string('pluginname', $store); } } return $return; }
php
public function get_supported_logstores($component) { $allstores = self::get_store_plugins(); $enabled = $this->stores; $function = component_callback_exists($component, 'supports_logstore'); if (!$function) { // The report doesn't define the callback, most probably it doesn't need log stores. return false; } $return = array(); foreach ($allstores as $store => $logclass) { $instance = empty($enabled[$store]) ? new $logclass($this) : $enabled[$store]; if ($function($instance)) { $return[$store] = get_string('pluginname', $store); } } return $return; }
[ "public", "function", "get_supported_logstores", "(", "$", "component", ")", "{", "$", "allstores", "=", "self", "::", "get_store_plugins", "(", ")", ";", "$", "enabled", "=", "$", "this", "->", "stores", ";", "$", "function", "=", "component_callback_exists", "(", "$", "component", ",", "'supports_logstore'", ")", ";", "if", "(", "!", "$", "function", ")", "{", "// The report doesn't define the callback, most probably it doesn't need log stores.", "return", "false", ";", "}", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "allstores", "as", "$", "store", "=>", "$", "logclass", ")", "{", "$", "instance", "=", "empty", "(", "$", "enabled", "[", "$", "store", "]", ")", "?", "new", "$", "logclass", "(", "$", "this", ")", ":", "$", "enabled", "[", "$", "store", "]", ";", "if", "(", "$", "function", "(", "$", "instance", ")", ")", "{", "$", "return", "[", "$", "store", "]", "=", "get_string", "(", "'pluginname'", ",", "$", "store", ")", ";", "}", "}", "return", "$", "return", ";", "}" ]
For a given report, returns a list of log stores that are supported. @param string $component component. @return false|array list of logstores that support the given report. It returns false if the given $component doesn't require logstores.
[ "For", "a", "given", "report", "returns", "a", "list", "of", "log", "stores", "that", "are", "supported", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L158-L177
220,209
moodle/moodle
admin/tool/log/classes/log/manager.php
manager.dispose
public function dispose() { if ($this->stores) { foreach ($this->stores as $store) { $store->dispose(); } } $this->stores = null; $this->readers = null; $this->writers = null; }
php
public function dispose() { if ($this->stores) { foreach ($this->stores as $store) { $store->dispose(); } } $this->stores = null; $this->readers = null; $this->writers = null; }
[ "public", "function", "dispose", "(", ")", "{", "if", "(", "$", "this", "->", "stores", ")", "{", "foreach", "(", "$", "this", "->", "stores", "as", "$", "store", ")", "{", "$", "store", "->", "dispose", "(", ")", ";", "}", "}", "$", "this", "->", "stores", "=", "null", ";", "$", "this", "->", "readers", "=", "null", ";", "$", "this", "->", "writers", "=", "null", ";", "}" ]
Usually called automatically from shutdown manager, this allows us to implement buffering of write operations.
[ "Usually", "called", "automatically", "from", "shutdown", "manager", "this", "allows", "us", "to", "implement", "buffering", "of", "write", "operations", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/log/classes/log/manager.php#L192-L201
220,210
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_badge_assertion
public function get_badge_assertion() { global $CFG; $assertion = array(); if ($this->_data) { $hash = $this->_data->uniquehash; $email = empty($this->_data->backpackemail) ? $this->_data->email : $this->_data->backpackemail; $assertionurl = new moodle_url('/badges/assertion.php', array('b' => $hash)); $classurl = new moodle_url('/badges/assertion.php', array('b' => $hash, 'action' => 1)); // Required. $assertion['uid'] = $hash; $assertion['recipient'] = array(); $assertion['recipient']['identity'] = 'sha256$' . hash('sha256', $email . $CFG->badges_badgesalt); $assertion['recipient']['type'] = 'email'; // Currently the only supported type. $assertion['recipient']['hashed'] = true; // We are always hashing recipient. $assertion['recipient']['salt'] = $CFG->badges_badgesalt; $assertion['badge'] = $classurl->out(false); $assertion['verify'] = array(); $assertion['verify']['type'] = 'hosted'; // 'Signed' is not implemented yet. $assertion['verify']['url'] = $assertionurl->out(false); $assertion['issuedOn'] = $this->_data->dateissued; // Optional. $assertion['evidence'] = $this->_url->out(false); // Currently issued badge URL. if (!empty($this->_data->dateexpire)) { $assertion['expires'] = $this->_data->dateexpire; } $this->embed_data_badge_version2($assertion, OPEN_BADGES_V2_TYPE_ASSERTION); } return $assertion; }
php
public function get_badge_assertion() { global $CFG; $assertion = array(); if ($this->_data) { $hash = $this->_data->uniquehash; $email = empty($this->_data->backpackemail) ? $this->_data->email : $this->_data->backpackemail; $assertionurl = new moodle_url('/badges/assertion.php', array('b' => $hash)); $classurl = new moodle_url('/badges/assertion.php', array('b' => $hash, 'action' => 1)); // Required. $assertion['uid'] = $hash; $assertion['recipient'] = array(); $assertion['recipient']['identity'] = 'sha256$' . hash('sha256', $email . $CFG->badges_badgesalt); $assertion['recipient']['type'] = 'email'; // Currently the only supported type. $assertion['recipient']['hashed'] = true; // We are always hashing recipient. $assertion['recipient']['salt'] = $CFG->badges_badgesalt; $assertion['badge'] = $classurl->out(false); $assertion['verify'] = array(); $assertion['verify']['type'] = 'hosted'; // 'Signed' is not implemented yet. $assertion['verify']['url'] = $assertionurl->out(false); $assertion['issuedOn'] = $this->_data->dateissued; // Optional. $assertion['evidence'] = $this->_url->out(false); // Currently issued badge URL. if (!empty($this->_data->dateexpire)) { $assertion['expires'] = $this->_data->dateexpire; } $this->embed_data_badge_version2($assertion, OPEN_BADGES_V2_TYPE_ASSERTION); } return $assertion; }
[ "public", "function", "get_badge_assertion", "(", ")", "{", "global", "$", "CFG", ";", "$", "assertion", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "_data", ")", "{", "$", "hash", "=", "$", "this", "->", "_data", "->", "uniquehash", ";", "$", "email", "=", "empty", "(", "$", "this", "->", "_data", "->", "backpackemail", ")", "?", "$", "this", "->", "_data", "->", "email", ":", "$", "this", "->", "_data", "->", "backpackemail", ";", "$", "assertionurl", "=", "new", "moodle_url", "(", "'/badges/assertion.php'", ",", "array", "(", "'b'", "=>", "$", "hash", ")", ")", ";", "$", "classurl", "=", "new", "moodle_url", "(", "'/badges/assertion.php'", ",", "array", "(", "'b'", "=>", "$", "hash", ",", "'action'", "=>", "1", ")", ")", ";", "// Required.", "$", "assertion", "[", "'uid'", "]", "=", "$", "hash", ";", "$", "assertion", "[", "'recipient'", "]", "=", "array", "(", ")", ";", "$", "assertion", "[", "'recipient'", "]", "[", "'identity'", "]", "=", "'sha256$'", ".", "hash", "(", "'sha256'", ",", "$", "email", ".", "$", "CFG", "->", "badges_badgesalt", ")", ";", "$", "assertion", "[", "'recipient'", "]", "[", "'type'", "]", "=", "'email'", ";", "// Currently the only supported type.", "$", "assertion", "[", "'recipient'", "]", "[", "'hashed'", "]", "=", "true", ";", "// We are always hashing recipient.", "$", "assertion", "[", "'recipient'", "]", "[", "'salt'", "]", "=", "$", "CFG", "->", "badges_badgesalt", ";", "$", "assertion", "[", "'badge'", "]", "=", "$", "classurl", "->", "out", "(", "false", ")", ";", "$", "assertion", "[", "'verify'", "]", "=", "array", "(", ")", ";", "$", "assertion", "[", "'verify'", "]", "[", "'type'", "]", "=", "'hosted'", ";", "// 'Signed' is not implemented yet.", "$", "assertion", "[", "'verify'", "]", "[", "'url'", "]", "=", "$", "assertionurl", "->", "out", "(", "false", ")", ";", "$", "assertion", "[", "'issuedOn'", "]", "=", "$", "this", "->", "_data", "->", "dateissued", ";", "// Optional.", "$", "assertion", "[", "'evidence'", "]", "=", "$", "this", "->", "_url", "->", "out", "(", "false", ")", ";", "// Currently issued badge URL.", "if", "(", "!", "empty", "(", "$", "this", "->", "_data", "->", "dateexpire", ")", ")", "{", "$", "assertion", "[", "'expires'", "]", "=", "$", "this", "->", "_data", "->", "dateexpire", ";", "}", "$", "this", "->", "embed_data_badge_version2", "(", "$", "assertion", ",", "OPEN_BADGES_V2_TYPE_ASSERTION", ")", ";", "}", "return", "$", "assertion", ";", "}" ]
Get badge assertion. @return array Badge assertion.
[ "Get", "badge", "assertion", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L95-L124
220,211
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_badge_class
public function get_badge_class() { $class = array(); if ($this->_data) { if (empty($this->_data->courseid)) { $context = context_system::instance(); } else { $context = context_course::instance($this->_data->courseid); } $issuerurl = new moodle_url('/badges/assertion.php', array('b' => $this->_data->uniquehash, 'action' => 0)); // Required. $class['name'] = $this->_data->name; $class['description'] = $this->_data->description; $class['image'] = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $this->_data->id, '/', 'f1')->out(false); $class['criteria'] = $this->_url->out(false); // Currently issued badge URL. $class['issuer'] = $issuerurl->out(false); $this->embed_data_badge_version2($class, OPEN_BADGES_V2_TYPE_BADGE); } return $class; }
php
public function get_badge_class() { $class = array(); if ($this->_data) { if (empty($this->_data->courseid)) { $context = context_system::instance(); } else { $context = context_course::instance($this->_data->courseid); } $issuerurl = new moodle_url('/badges/assertion.php', array('b' => $this->_data->uniquehash, 'action' => 0)); // Required. $class['name'] = $this->_data->name; $class['description'] = $this->_data->description; $class['image'] = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $this->_data->id, '/', 'f1')->out(false); $class['criteria'] = $this->_url->out(false); // Currently issued badge URL. $class['issuer'] = $issuerurl->out(false); $this->embed_data_badge_version2($class, OPEN_BADGES_V2_TYPE_BADGE); } return $class; }
[ "public", "function", "get_badge_class", "(", ")", "{", "$", "class", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "_data", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "_data", "->", "courseid", ")", ")", "{", "$", "context", "=", "context_system", "::", "instance", "(", ")", ";", "}", "else", "{", "$", "context", "=", "context_course", "::", "instance", "(", "$", "this", "->", "_data", "->", "courseid", ")", ";", "}", "$", "issuerurl", "=", "new", "moodle_url", "(", "'/badges/assertion.php'", ",", "array", "(", "'b'", "=>", "$", "this", "->", "_data", "->", "uniquehash", ",", "'action'", "=>", "0", ")", ")", ";", "// Required.", "$", "class", "[", "'name'", "]", "=", "$", "this", "->", "_data", "->", "name", ";", "$", "class", "[", "'description'", "]", "=", "$", "this", "->", "_data", "->", "description", ";", "$", "class", "[", "'image'", "]", "=", "moodle_url", "::", "make_pluginfile_url", "(", "$", "context", "->", "id", ",", "'badges'", ",", "'badgeimage'", ",", "$", "this", "->", "_data", "->", "id", ",", "'/'", ",", "'f1'", ")", "->", "out", "(", "false", ")", ";", "$", "class", "[", "'criteria'", "]", "=", "$", "this", "->", "_url", "->", "out", "(", "false", ")", ";", "// Currently issued badge URL.", "$", "class", "[", "'issuer'", "]", "=", "$", "issuerurl", "->", "out", "(", "false", ")", ";", "$", "this", "->", "embed_data_badge_version2", "(", "$", "class", ",", "OPEN_BADGES_V2_TYPE_BADGE", ")", ";", "}", "return", "$", "class", ";", "}" ]
Get badge class information. @return array Badge Class information.
[ "Get", "badge", "class", "information", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L131-L150
220,212
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_issuer
public function get_issuer() { $issuer = array(); if ($this->_data) { // Required. $issuer['name'] = $this->_data->issuername; $issuer['url'] = $this->_data->issuerurl; // Optional. if (!empty($this->_data->issuercontact)) { $issuer['email'] = $this->_data->issuercontact; } } $this->embed_data_badge_version2($issuer, OPEN_BADGES_V2_TYPE_ISSUER); return $issuer; }
php
public function get_issuer() { $issuer = array(); if ($this->_data) { // Required. $issuer['name'] = $this->_data->issuername; $issuer['url'] = $this->_data->issuerurl; // Optional. if (!empty($this->_data->issuercontact)) { $issuer['email'] = $this->_data->issuercontact; } } $this->embed_data_badge_version2($issuer, OPEN_BADGES_V2_TYPE_ISSUER); return $issuer; }
[ "public", "function", "get_issuer", "(", ")", "{", "$", "issuer", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "_data", ")", "{", "// Required.", "$", "issuer", "[", "'name'", "]", "=", "$", "this", "->", "_data", "->", "issuername", ";", "$", "issuer", "[", "'url'", "]", "=", "$", "this", "->", "_data", "->", "issuerurl", ";", "// Optional.", "if", "(", "!", "empty", "(", "$", "this", "->", "_data", "->", "issuercontact", ")", ")", "{", "$", "issuer", "[", "'email'", "]", "=", "$", "this", "->", "_data", "->", "issuercontact", ";", "}", "}", "$", "this", "->", "embed_data_badge_version2", "(", "$", "issuer", ",", "OPEN_BADGES_V2_TYPE_ISSUER", ")", ";", "return", "$", "issuer", ";", "}" ]
Get badge issuer information. @return array Issuer information.
[ "Get", "badge", "issuer", "information", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L157-L170
220,213
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_related_badges
public function get_related_badges(badge $badge) { global $DB; $arraybadges = array(); $relatedbadges = $badge->get_related_badges(true); if ($relatedbadges) { foreach ($relatedbadges as $rb) { $url = new moodle_url('/badges/badge_json.php', array('id' => $rb->id)); $arraybadges[] = array( 'id' => $url->out(false), 'version' => $rb->version, '@language' => $rb->language ); } } return $arraybadges; }
php
public function get_related_badges(badge $badge) { global $DB; $arraybadges = array(); $relatedbadges = $badge->get_related_badges(true); if ($relatedbadges) { foreach ($relatedbadges as $rb) { $url = new moodle_url('/badges/badge_json.php', array('id' => $rb->id)); $arraybadges[] = array( 'id' => $url->out(false), 'version' => $rb->version, '@language' => $rb->language ); } } return $arraybadges; }
[ "public", "function", "get_related_badges", "(", "badge", "$", "badge", ")", "{", "global", "$", "DB", ";", "$", "arraybadges", "=", "array", "(", ")", ";", "$", "relatedbadges", "=", "$", "badge", "->", "get_related_badges", "(", "true", ")", ";", "if", "(", "$", "relatedbadges", ")", "{", "foreach", "(", "$", "relatedbadges", "as", "$", "rb", ")", "{", "$", "url", "=", "new", "moodle_url", "(", "'/badges/badge_json.php'", ",", "array", "(", "'id'", "=>", "$", "rb", "->", "id", ")", ")", ";", "$", "arraybadges", "[", "]", "=", "array", "(", "'id'", "=>", "$", "url", "->", "out", "(", "false", ")", ",", "'version'", "=>", "$", "rb", "->", "version", ",", "'@language'", "=>", "$", "rb", "->", "language", ")", ";", "}", "}", "return", "$", "arraybadges", ";", "}" ]
Get related badges of the badge. @param badge $badge Badge object. @return array|bool List related badges.
[ "Get", "related", "badges", "of", "the", "badge", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L178-L193
220,214
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_endorsement
public function get_endorsement() { global $DB; $endorsement = array(); $record = $DB->get_record_select('badge_endorsement', 'badgeid = ?', array($this->_data->id)); return $record; }
php
public function get_endorsement() { global $DB; $endorsement = array(); $record = $DB->get_record_select('badge_endorsement', 'badgeid = ?', array($this->_data->id)); return $record; }
[ "public", "function", "get_endorsement", "(", ")", "{", "global", "$", "DB", ";", "$", "endorsement", "=", "array", "(", ")", ";", "$", "record", "=", "$", "DB", "->", "get_record_select", "(", "'badge_endorsement'", ",", "'badgeid = ?'", ",", "array", "(", "$", "this", "->", "_data", "->", "id", ")", ")", ";", "return", "$", "record", ";", "}" ]
Get endorsement of the badge. @return false|stdClass Endorsement information.
[ "Get", "endorsement", "of", "the", "badge", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L200-L205
220,215
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_criteria_badge_class
public function get_criteria_badge_class() { $badge = new badge($this->_data->id); $narrative = $badge->markdown_badge_criteria(); if (!empty($narrative)) { $criteria = array(); $criteria['id'] = $this->_url->out(false); $criteria['narrative'] = $narrative; return $criteria; } else { return $this->_url->out(false); } }
php
public function get_criteria_badge_class() { $badge = new badge($this->_data->id); $narrative = $badge->markdown_badge_criteria(); if (!empty($narrative)) { $criteria = array(); $criteria['id'] = $this->_url->out(false); $criteria['narrative'] = $narrative; return $criteria; } else { return $this->_url->out(false); } }
[ "public", "function", "get_criteria_badge_class", "(", ")", "{", "$", "badge", "=", "new", "badge", "(", "$", "this", "->", "_data", "->", "id", ")", ";", "$", "narrative", "=", "$", "badge", "->", "markdown_badge_criteria", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "narrative", ")", ")", "{", "$", "criteria", "=", "array", "(", ")", ";", "$", "criteria", "[", "'id'", "]", "=", "$", "this", "->", "_url", "->", "out", "(", "false", ")", ";", "$", "criteria", "[", "'narrative'", "]", "=", "$", "narrative", ";", "return", "$", "criteria", ";", "}", "else", "{", "return", "$", "this", "->", "_url", "->", "out", "(", "false", ")", ";", "}", "}" ]
Get criteria of badge class. @return array|string Criteria information.
[ "Get", "criteria", "of", "badge", "class", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L212-L223
220,216
moodle/moodle
badges/classes/assertion.php
core_badges_assertion.get_alignments
public function get_alignments() { global $DB; $badgeid = $this->_data->id; $alignments = array(); $items = $DB->get_records_select('badge_alignment', 'badgeid = ?', array($badgeid)); foreach ($items as $item) { $alignment = array('targetName' => $item->targetname, 'targetUrl' => $item->targeturl); if ($item->targetdescription) { $alignment['targetDescription'] = $item->targetdescription; } if ($item->targetframework) { $alignment['targetFramework'] = $item->targetframework; } if ($item->targetcode) { $alignment['targetCode'] = $item->targetcode; } $alignments[] = $alignment; } return $alignments; }
php
public function get_alignments() { global $DB; $badgeid = $this->_data->id; $alignments = array(); $items = $DB->get_records_select('badge_alignment', 'badgeid = ?', array($badgeid)); foreach ($items as $item) { $alignment = array('targetName' => $item->targetname, 'targetUrl' => $item->targeturl); if ($item->targetdescription) { $alignment['targetDescription'] = $item->targetdescription; } if ($item->targetframework) { $alignment['targetFramework'] = $item->targetframework; } if ($item->targetcode) { $alignment['targetCode'] = $item->targetcode; } $alignments[] = $alignment; } return $alignments; }
[ "public", "function", "get_alignments", "(", ")", "{", "global", "$", "DB", ";", "$", "badgeid", "=", "$", "this", "->", "_data", "->", "id", ";", "$", "alignments", "=", "array", "(", ")", ";", "$", "items", "=", "$", "DB", "->", "get_records_select", "(", "'badge_alignment'", ",", "'badgeid = ?'", ",", "array", "(", "$", "badgeid", ")", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "alignment", "=", "array", "(", "'targetName'", "=>", "$", "item", "->", "targetname", ",", "'targetUrl'", "=>", "$", "item", "->", "targeturl", ")", ";", "if", "(", "$", "item", "->", "targetdescription", ")", "{", "$", "alignment", "[", "'targetDescription'", "]", "=", "$", "item", "->", "targetdescription", ";", "}", "if", "(", "$", "item", "->", "targetframework", ")", "{", "$", "alignment", "[", "'targetFramework'", "]", "=", "$", "item", "->", "targetframework", ";", "}", "if", "(", "$", "item", "->", "targetcode", ")", "{", "$", "alignment", "[", "'targetCode'", "]", "=", "$", "item", "->", "targetcode", ";", "}", "$", "alignments", "[", "]", "=", "$", "alignment", ";", "}", "return", "$", "alignments", ";", "}" ]
Get alignment of the badge. @return array information.
[ "Get", "alignment", "of", "the", "badge", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/badges/classes/assertion.php#L230-L249
220,217
moodle/moodle
competency/classes/course_module_competency.php
course_module_competency.get_ruleoutcome_name
public static function get_ruleoutcome_name($ruleoutcome) { switch ($ruleoutcome) { case self::OUTCOME_NONE: $strname = 'none'; break; case self::OUTCOME_EVIDENCE: $strname = 'evidence'; break; case self::OUTCOME_RECOMMEND: $strname = 'recommend'; break; case self::OUTCOME_COMPLETE: $strname = 'complete'; break; default: throw new \moodle_exception('errorcompetencyrule', 'core_competency', '', $ruleoutcome); break; } return new lang_string('coursemodulecompetencyoutcome_' . $strname, 'core_competency'); }
php
public static function get_ruleoutcome_name($ruleoutcome) { switch ($ruleoutcome) { case self::OUTCOME_NONE: $strname = 'none'; break; case self::OUTCOME_EVIDENCE: $strname = 'evidence'; break; case self::OUTCOME_RECOMMEND: $strname = 'recommend'; break; case self::OUTCOME_COMPLETE: $strname = 'complete'; break; default: throw new \moodle_exception('errorcompetencyrule', 'core_competency', '', $ruleoutcome); break; } return new lang_string('coursemodulecompetencyoutcome_' . $strname, 'core_competency'); }
[ "public", "static", "function", "get_ruleoutcome_name", "(", "$", "ruleoutcome", ")", "{", "switch", "(", "$", "ruleoutcome", ")", "{", "case", "self", "::", "OUTCOME_NONE", ":", "$", "strname", "=", "'none'", ";", "break", ";", "case", "self", "::", "OUTCOME_EVIDENCE", ":", "$", "strname", "=", "'evidence'", ";", "break", ";", "case", "self", "::", "OUTCOME_RECOMMEND", ":", "$", "strname", "=", "'recommend'", ";", "break", ";", "case", "self", "::", "OUTCOME_COMPLETE", ":", "$", "strname", "=", "'complete'", ";", "break", ";", "default", ":", "throw", "new", "\\", "moodle_exception", "(", "'errorcompetencyrule'", ",", "'core_competency'", ",", "''", ",", "$", "ruleoutcome", ")", ";", "break", ";", "}", "return", "new", "lang_string", "(", "'coursemodulecompetencyoutcome_'", ".", "$", "strname", ",", "'core_competency'", ")", ";", "}" ]
Human readable rule name. @param int $ruleoutcome The value of ruleoutcome. @return lang_string
[ "Human", "readable", "rule", "name", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/course_module_competency.php#L113-L134
220,218
moodle/moodle
competency/classes/course_module_competency.php
course_module_competency.list_course_modules
public static function list_course_modules($competencyid, $courseid) { global $DB; $results = $DB->get_records_sql('SELECT coursemodules.id as id FROM {' . self::TABLE . '} modcomp JOIN {course_modules} coursemodules ON modcomp.cmid = coursemodules.id WHERE modcomp.competencyid = ? AND coursemodules.course = ?', array($competencyid, $courseid)); return array_keys($results); }
php
public static function list_course_modules($competencyid, $courseid) { global $DB; $results = $DB->get_records_sql('SELECT coursemodules.id as id FROM {' . self::TABLE . '} modcomp JOIN {course_modules} coursemodules ON modcomp.cmid = coursemodules.id WHERE modcomp.competencyid = ? AND coursemodules.course = ?', array($competencyid, $courseid)); return array_keys($results); }
[ "public", "static", "function", "list_course_modules", "(", "$", "competencyid", ",", "$", "courseid", ")", "{", "global", "$", "DB", ";", "$", "results", "=", "$", "DB", "->", "get_records_sql", "(", "'SELECT coursemodules.id as id\n FROM {'", ".", "self", "::", "TABLE", ".", "'} modcomp\n JOIN {course_modules} coursemodules\n ON modcomp.cmid = coursemodules.id\n WHERE modcomp.competencyid = ? AND coursemodules.course = ?'", ",", "array", "(", "$", "competencyid", ",", "$", "courseid", ")", ")", ";", "return", "array_keys", "(", "$", "results", ")", ";", "}" ]
Return the module IDs and visible flags that include this competency in a single course. @param int $competencyid The competency id @param int $courseid The course ID. @return array of ints (cmids)
[ "Return", "the", "module", "IDs", "and", "visible", "flags", "that", "include", "this", "competency", "in", "a", "single", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/course_module_competency.php#L170-L181
220,219
moodle/moodle
competency/classes/course_module_competency.php
course_module_competency.list_course_module_competencies
public static function list_course_module_competencies($cmid) { global $DB; $sql = 'SELECT coursemodcomp.* FROM {' . self::TABLE . '} coursemodcomp JOIN {' . competency::TABLE . '} comp ON coursemodcomp.competencyid = comp.id WHERE coursemodcomp.cmid = ? ORDER BY coursemodcomp.sortorder ASC'; $params = array($cmid); $results = $DB->get_recordset_sql($sql, $params); $instances = array(); foreach ($results as $result) { array_push($instances, new course_module_competency(0, $result)); } $results->close(); return $instances; }
php
public static function list_course_module_competencies($cmid) { global $DB; $sql = 'SELECT coursemodcomp.* FROM {' . self::TABLE . '} coursemodcomp JOIN {' . competency::TABLE . '} comp ON coursemodcomp.competencyid = comp.id WHERE coursemodcomp.cmid = ? ORDER BY coursemodcomp.sortorder ASC'; $params = array($cmid); $results = $DB->get_recordset_sql($sql, $params); $instances = array(); foreach ($results as $result) { array_push($instances, new course_module_competency(0, $result)); } $results->close(); return $instances; }
[ "public", "static", "function", "list_course_module_competencies", "(", "$", "cmid", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "'SELECT coursemodcomp.*\n FROM {'", ".", "self", "::", "TABLE", ".", "'} coursemodcomp\n JOIN {'", ".", "competency", "::", "TABLE", ".", "'} comp\n ON coursemodcomp.competencyid = comp.id\n WHERE coursemodcomp.cmid = ?\n ORDER BY coursemodcomp.sortorder ASC'", ";", "$", "params", "=", "array", "(", "$", "cmid", ")", ";", "$", "results", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "$", "instances", "=", "array", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "array_push", "(", "$", "instances", ",", "new", "course_module_competency", "(", "0", ",", "$", "result", ")", ")", ";", "}", "$", "results", "->", "close", "(", ")", ";", "return", "$", "instances", ";", "}" ]
List the course_module_competencies in this course module. @param int $cmid The course module id @return course_module_competency[]
[ "List", "the", "course_module_competencies", "in", "this", "course", "module", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/course_module_competency.php#L280-L299
220,220
moodle/moodle
competency/classes/course_module_competency.php
course_module_competency.get_records_by_competencyid_in_course
public static function get_records_by_competencyid_in_course($competencyid, $courseid) { global $DB; $sql = 'SELECT cmc.* FROM {' . self::TABLE . '} cmc JOIN {course_modules} cm ON cm.course = ? AND cmc.cmid = cm.id WHERE cmc.competencyid = ? ORDER BY cmc.sortorder ASC'; $params = array($courseid, $competencyid); $results = $DB->get_recordset_sql($sql, $params); $instances = array(); foreach ($results as $result) { $instances[$result->id] = new course_module_competency(0, $result); } $results->close(); return $instances; }
php
public static function get_records_by_competencyid_in_course($competencyid, $courseid) { global $DB; $sql = 'SELECT cmc.* FROM {' . self::TABLE . '} cmc JOIN {course_modules} cm ON cm.course = ? AND cmc.cmid = cm.id WHERE cmc.competencyid = ? ORDER BY cmc.sortorder ASC'; $params = array($courseid, $competencyid); $results = $DB->get_recordset_sql($sql, $params); $instances = array(); foreach ($results as $result) { $instances[$result->id] = new course_module_competency(0, $result); } $results->close(); return $instances; }
[ "public", "static", "function", "get_records_by_competencyid_in_course", "(", "$", "competencyid", ",", "$", "courseid", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "'SELECT cmc.*\n FROM {'", ".", "self", "::", "TABLE", ".", "'} cmc\n JOIN {course_modules} cm\n ON cm.course = ?\n AND cmc.cmid = cm.id\n WHERE cmc.competencyid = ?\n ORDER BY cmc.sortorder ASC'", ";", "$", "params", "=", "array", "(", "$", "courseid", ",", "$", "competencyid", ")", ";", "$", "results", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "$", "instances", "=", "array", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "instances", "[", "$", "result", "->", "id", "]", "=", "new", "course_module_competency", "(", "0", ",", "$", "result", ")", ";", "}", "$", "results", "->", "close", "(", ")", ";", "return", "$", "instances", ";", "}" ]
List the relationship objects for a competency in a course. @param int $competencyid The competency ID. @param int $courseid The course ID. @return course_module_competency[]
[ "List", "the", "relationship", "objects", "for", "a", "competency", "in", "a", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/course_module_competency.php#L308-L328
220,221
moodle/moodle
cache/stores/mongodb/addinstanceform.php
cachestore_mongodb_addinstance_form.configuration_definition
protected function configuration_definition() { global $OUTPUT; $form = $this->_form; if (!version_compare(phpversion('mongodb'), '1.5', 'ge')) { $form->addElement('html', $OUTPUT->notification(get_string('pleaseupgrademongo', 'cachestore_mongodb'))); } $form->addElement('text', 'server', get_string('server', 'cachestore_mongodb'), array('size' => 72)); $form->addHelpButton('server', 'server', 'cachestore_mongodb'); $form->addRule('server', get_string('required'), 'required'); $form->setDefault('server', 'mongodb://127.0.0.1:27017'); $form->setType('server', PARAM_RAW); $form->addElement('text', 'database', get_string('database', 'cachestore_mongodb')); $form->addHelpButton('database', 'database', 'cachestore_mongodb'); $form->addRule('database', get_string('required'), 'required'); $form->setType('database', PARAM_ALPHANUMEXT); $form->setDefault('database', 'mcache'); $form->addElement('text', 'username', get_string('username', 'cachestore_mongodb')); $form->addHelpButton('username', 'username', 'cachestore_mongodb'); $form->setType('username', PARAM_ALPHANUMEXT); $form->addElement('passwordunmask', 'password', get_string('password', 'cachestore_mongodb')); $form->addHelpButton('password', 'password', 'cachestore_mongodb'); $form->setType('password', PARAM_TEXT); $form->addElement('text', 'replicaset', get_string('replicaset', 'cachestore_mongodb')); $form->addHelpButton('replicaset', 'replicaset', 'cachestore_mongodb'); $form->setType('replicaset', PARAM_ALPHANUMEXT); $form->setAdvanced('replicaset'); $form->addElement('checkbox', 'usesafe', get_string('usesafe', 'cachestore_mongodb')); $form->addHelpButton('usesafe', 'usesafe', 'cachestore_mongodb'); $form->setDefault('usesafe', 1); $form->setAdvanced('usesafe'); $form->setType('usesafe', PARAM_BOOL); $form->addElement('text', 'usesafevalue', get_string('usesafevalue', 'cachestore_mongodb')); $form->addHelpButton('usesafevalue', 'usesafevalue', 'cachestore_mongodb'); $form->disabledIf('usesafevalue', 'usesafe', 'notchecked'); $form->setType('usesafevalue', PARAM_INT); $form->setAdvanced('usesafevalue'); $form->addElement('checkbox', 'extendedmode', get_string('extendedmode', 'cachestore_mongodb')); $form->addHelpButton('extendedmode', 'extendedmode', 'cachestore_mongodb'); $form->setDefault('extendedmode', 0); $form->setAdvanced('extendedmode'); $form->setType('extendedmode', PARAM_BOOL); }
php
protected function configuration_definition() { global $OUTPUT; $form = $this->_form; if (!version_compare(phpversion('mongodb'), '1.5', 'ge')) { $form->addElement('html', $OUTPUT->notification(get_string('pleaseupgrademongo', 'cachestore_mongodb'))); } $form->addElement('text', 'server', get_string('server', 'cachestore_mongodb'), array('size' => 72)); $form->addHelpButton('server', 'server', 'cachestore_mongodb'); $form->addRule('server', get_string('required'), 'required'); $form->setDefault('server', 'mongodb://127.0.0.1:27017'); $form->setType('server', PARAM_RAW); $form->addElement('text', 'database', get_string('database', 'cachestore_mongodb')); $form->addHelpButton('database', 'database', 'cachestore_mongodb'); $form->addRule('database', get_string('required'), 'required'); $form->setType('database', PARAM_ALPHANUMEXT); $form->setDefault('database', 'mcache'); $form->addElement('text', 'username', get_string('username', 'cachestore_mongodb')); $form->addHelpButton('username', 'username', 'cachestore_mongodb'); $form->setType('username', PARAM_ALPHANUMEXT); $form->addElement('passwordunmask', 'password', get_string('password', 'cachestore_mongodb')); $form->addHelpButton('password', 'password', 'cachestore_mongodb'); $form->setType('password', PARAM_TEXT); $form->addElement('text', 'replicaset', get_string('replicaset', 'cachestore_mongodb')); $form->addHelpButton('replicaset', 'replicaset', 'cachestore_mongodb'); $form->setType('replicaset', PARAM_ALPHANUMEXT); $form->setAdvanced('replicaset'); $form->addElement('checkbox', 'usesafe', get_string('usesafe', 'cachestore_mongodb')); $form->addHelpButton('usesafe', 'usesafe', 'cachestore_mongodb'); $form->setDefault('usesafe', 1); $form->setAdvanced('usesafe'); $form->setType('usesafe', PARAM_BOOL); $form->addElement('text', 'usesafevalue', get_string('usesafevalue', 'cachestore_mongodb')); $form->addHelpButton('usesafevalue', 'usesafevalue', 'cachestore_mongodb'); $form->disabledIf('usesafevalue', 'usesafe', 'notchecked'); $form->setType('usesafevalue', PARAM_INT); $form->setAdvanced('usesafevalue'); $form->addElement('checkbox', 'extendedmode', get_string('extendedmode', 'cachestore_mongodb')); $form->addHelpButton('extendedmode', 'extendedmode', 'cachestore_mongodb'); $form->setDefault('extendedmode', 0); $form->setAdvanced('extendedmode'); $form->setType('extendedmode', PARAM_BOOL); }
[ "protected", "function", "configuration_definition", "(", ")", "{", "global", "$", "OUTPUT", ";", "$", "form", "=", "$", "this", "->", "_form", ";", "if", "(", "!", "version_compare", "(", "phpversion", "(", "'mongodb'", ")", ",", "'1.5'", ",", "'ge'", ")", ")", "{", "$", "form", "->", "addElement", "(", "'html'", ",", "$", "OUTPUT", "->", "notification", "(", "get_string", "(", "'pleaseupgrademongo'", ",", "'cachestore_mongodb'", ")", ")", ")", ";", "}", "$", "form", "->", "addElement", "(", "'text'", ",", "'server'", ",", "get_string", "(", "'server'", ",", "'cachestore_mongodb'", ")", ",", "array", "(", "'size'", "=>", "72", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'server'", ",", "'server'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "addRule", "(", "'server'", ",", "get_string", "(", "'required'", ")", ",", "'required'", ")", ";", "$", "form", "->", "setDefault", "(", "'server'", ",", "'mongodb://127.0.0.1:27017'", ")", ";", "$", "form", "->", "setType", "(", "'server'", ",", "PARAM_RAW", ")", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'database'", ",", "get_string", "(", "'database'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'database'", ",", "'database'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "addRule", "(", "'database'", ",", "get_string", "(", "'required'", ")", ",", "'required'", ")", ";", "$", "form", "->", "setType", "(", "'database'", ",", "PARAM_ALPHANUMEXT", ")", ";", "$", "form", "->", "setDefault", "(", "'database'", ",", "'mcache'", ")", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'username'", ",", "get_string", "(", "'username'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'username'", ",", "'username'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "setType", "(", "'username'", ",", "PARAM_ALPHANUMEXT", ")", ";", "$", "form", "->", "addElement", "(", "'passwordunmask'", ",", "'password'", ",", "get_string", "(", "'password'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'password'", ",", "'password'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "setType", "(", "'password'", ",", "PARAM_TEXT", ")", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'replicaset'", ",", "get_string", "(", "'replicaset'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'replicaset'", ",", "'replicaset'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "setType", "(", "'replicaset'", ",", "PARAM_ALPHANUMEXT", ")", ";", "$", "form", "->", "setAdvanced", "(", "'replicaset'", ")", ";", "$", "form", "->", "addElement", "(", "'checkbox'", ",", "'usesafe'", ",", "get_string", "(", "'usesafe'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'usesafe'", ",", "'usesafe'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "setDefault", "(", "'usesafe'", ",", "1", ")", ";", "$", "form", "->", "setAdvanced", "(", "'usesafe'", ")", ";", "$", "form", "->", "setType", "(", "'usesafe'", ",", "PARAM_BOOL", ")", ";", "$", "form", "->", "addElement", "(", "'text'", ",", "'usesafevalue'", ",", "get_string", "(", "'usesafevalue'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'usesafevalue'", ",", "'usesafevalue'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "disabledIf", "(", "'usesafevalue'", ",", "'usesafe'", ",", "'notchecked'", ")", ";", "$", "form", "->", "setType", "(", "'usesafevalue'", ",", "PARAM_INT", ")", ";", "$", "form", "->", "setAdvanced", "(", "'usesafevalue'", ")", ";", "$", "form", "->", "addElement", "(", "'checkbox'", ",", "'extendedmode'", ",", "get_string", "(", "'extendedmode'", ",", "'cachestore_mongodb'", ")", ")", ";", "$", "form", "->", "addHelpButton", "(", "'extendedmode'", ",", "'extendedmode'", ",", "'cachestore_mongodb'", ")", ";", "$", "form", "->", "setDefault", "(", "'extendedmode'", ",", "0", ")", ";", "$", "form", "->", "setAdvanced", "(", "'extendedmode'", ")", ";", "$", "form", "->", "setType", "(", "'extendedmode'", ",", "PARAM_BOOL", ")", ";", "}" ]
The forms custom definitions.
[ "The", "forms", "custom", "definitions", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/cache/stores/mongodb/addinstanceform.php#L50-L100
220,222
moodle/moodle
lib/classes/session/manager.php
manager.start
public static function start() { global $CFG, $DB, $PERF; if (isset(self::$sessionactive)) { debugging('Session was already started!', DEBUG_DEVELOPER); return; } // Grab the time before session lock starts. $PERF->sessionlock['start'] = microtime(true); self::load_handler(); // Init the session handler only if everything initialised properly in lib/setup.php file // and the session is actually required. if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) { self::$sessionactive = false; self::init_empty_session(); return; } try { self::$handler->init(); self::prepare_cookies(); $isnewsession = empty($_COOKIE[session_name()]); if (!self::$handler->start()) { // Could not successfully start/recover session. throw new \core\session\exception(get_string('servererror')); } // Grab the time when session lock starts. $PERF->sessionlock['gained'] = microtime(true); $PERF->sessionlock['wait'] = $PERF->sessionlock['gained'] - $PERF->sessionlock['start']; self::initialise_user_session($isnewsession); self::$sessionactive = true; // Set here, so the session can be cleared if the security check fails. self::check_security(); // Link global $USER and $SESSION, // this is tricky because PHP does not allow references to references // and global keyword uses internally once reference to the $GLOBALS array. // The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION'] // as the main storage of data and put references to $_SESSION. $GLOBALS['USER'] = $_SESSION['USER']; $_SESSION['USER'] =& $GLOBALS['USER']; $GLOBALS['SESSION'] = $_SESSION['SESSION']; $_SESSION['SESSION'] =& $GLOBALS['SESSION']; } catch (\Exception $ex) { self::init_empty_session(); self::$sessionactive = false; throw $ex; } }
php
public static function start() { global $CFG, $DB, $PERF; if (isset(self::$sessionactive)) { debugging('Session was already started!', DEBUG_DEVELOPER); return; } // Grab the time before session lock starts. $PERF->sessionlock['start'] = microtime(true); self::load_handler(); // Init the session handler only if everything initialised properly in lib/setup.php file // and the session is actually required. if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) { self::$sessionactive = false; self::init_empty_session(); return; } try { self::$handler->init(); self::prepare_cookies(); $isnewsession = empty($_COOKIE[session_name()]); if (!self::$handler->start()) { // Could not successfully start/recover session. throw new \core\session\exception(get_string('servererror')); } // Grab the time when session lock starts. $PERF->sessionlock['gained'] = microtime(true); $PERF->sessionlock['wait'] = $PERF->sessionlock['gained'] - $PERF->sessionlock['start']; self::initialise_user_session($isnewsession); self::$sessionactive = true; // Set here, so the session can be cleared if the security check fails. self::check_security(); // Link global $USER and $SESSION, // this is tricky because PHP does not allow references to references // and global keyword uses internally once reference to the $GLOBALS array. // The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION'] // as the main storage of data and put references to $_SESSION. $GLOBALS['USER'] = $_SESSION['USER']; $_SESSION['USER'] =& $GLOBALS['USER']; $GLOBALS['SESSION'] = $_SESSION['SESSION']; $_SESSION['SESSION'] =& $GLOBALS['SESSION']; } catch (\Exception $ex) { self::init_empty_session(); self::$sessionactive = false; throw $ex; } }
[ "public", "static", "function", "start", "(", ")", "{", "global", "$", "CFG", ",", "$", "DB", ",", "$", "PERF", ";", "if", "(", "isset", "(", "self", "::", "$", "sessionactive", ")", ")", "{", "debugging", "(", "'Session was already started!'", ",", "DEBUG_DEVELOPER", ")", ";", "return", ";", "}", "// Grab the time before session lock starts.", "$", "PERF", "->", "sessionlock", "[", "'start'", "]", "=", "microtime", "(", "true", ")", ";", "self", "::", "load_handler", "(", ")", ";", "// Init the session handler only if everything initialised properly in lib/setup.php file", "// and the session is actually required.", "if", "(", "empty", "(", "$", "DB", ")", "or", "empty", "(", "$", "CFG", "->", "version", ")", "or", "!", "defined", "(", "'NO_MOODLE_COOKIES'", ")", "or", "NO_MOODLE_COOKIES", "or", "CLI_SCRIPT", ")", "{", "self", "::", "$", "sessionactive", "=", "false", ";", "self", "::", "init_empty_session", "(", ")", ";", "return", ";", "}", "try", "{", "self", "::", "$", "handler", "->", "init", "(", ")", ";", "self", "::", "prepare_cookies", "(", ")", ";", "$", "isnewsession", "=", "empty", "(", "$", "_COOKIE", "[", "session_name", "(", ")", "]", ")", ";", "if", "(", "!", "self", "::", "$", "handler", "->", "start", "(", ")", ")", "{", "// Could not successfully start/recover session.", "throw", "new", "\\", "core", "\\", "session", "\\", "exception", "(", "get_string", "(", "'servererror'", ")", ")", ";", "}", "// Grab the time when session lock starts.", "$", "PERF", "->", "sessionlock", "[", "'gained'", "]", "=", "microtime", "(", "true", ")", ";", "$", "PERF", "->", "sessionlock", "[", "'wait'", "]", "=", "$", "PERF", "->", "sessionlock", "[", "'gained'", "]", "-", "$", "PERF", "->", "sessionlock", "[", "'start'", "]", ";", "self", "::", "initialise_user_session", "(", "$", "isnewsession", ")", ";", "self", "::", "$", "sessionactive", "=", "true", ";", "// Set here, so the session can be cleared if the security check fails.", "self", "::", "check_security", "(", ")", ";", "// Link global $USER and $SESSION,", "// this is tricky because PHP does not allow references to references", "// and global keyword uses internally once reference to the $GLOBALS array.", "// The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION']", "// as the main storage of data and put references to $_SESSION.", "$", "GLOBALS", "[", "'USER'", "]", "=", "$", "_SESSION", "[", "'USER'", "]", ";", "$", "_SESSION", "[", "'USER'", "]", "=", "&", "$", "GLOBALS", "[", "'USER'", "]", ";", "$", "GLOBALS", "[", "'SESSION'", "]", "=", "$", "_SESSION", "[", "'SESSION'", "]", ";", "$", "_SESSION", "[", "'SESSION'", "]", "=", "&", "$", "GLOBALS", "[", "'SESSION'", "]", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "self", "::", "init_empty_session", "(", ")", ";", "self", "::", "$", "sessionactive", "=", "false", ";", "throw", "$", "ex", ";", "}", "}" ]
Start user session. Note: This is intended to be called only from lib/setup.php!
[ "Start", "user", "session", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L59-L111
220,223
moodle/moodle
lib/classes/session/manager.php
manager.get_performance_info
public static function get_performance_info() { global $CFG, $PERF; if (!session_id()) { return array(); } self::load_handler(); $size = display_size(strlen(session_encode())); $handler = get_class(self::$handler); $info = array(); $info['size'] = $size; $info['html'] = html_writer::div("Session ($handler): $size", "sessionsize"); $info['txt'] = "Session ($handler): $size "; if (!empty($CFG->debugsessionlock)) { $sessionlock = self::get_session_lock_info(); if (!empty($sessionlock['held'])) { // The page displays the footer and the session has been closed. $sessionlocktext = "Session lock held: ".number_format($sessionlock['held'], 3)." secs"; } else { // The session hasn't yet been closed and so we assume now with microtime. $sessionlockheld = microtime(true) - $PERF->sessionlock['gained']; $sessionlocktext = "Session lock open: ".number_format($sessionlockheld, 3)." secs"; } $info['txt'] .= $sessionlocktext; $info['html'] .= html_writer::div($sessionlocktext, "sessionlockstart"); $sessionlockwaittext = "Session lock wait: ".number_format($sessionlock['wait'], 3)." secs"; $info['txt'] .= $sessionlockwaittext; $info['html'] .= html_writer::div($sessionlockwaittext, "sessionlockwait"); } return $info; }
php
public static function get_performance_info() { global $CFG, $PERF; if (!session_id()) { return array(); } self::load_handler(); $size = display_size(strlen(session_encode())); $handler = get_class(self::$handler); $info = array(); $info['size'] = $size; $info['html'] = html_writer::div("Session ($handler): $size", "sessionsize"); $info['txt'] = "Session ($handler): $size "; if (!empty($CFG->debugsessionlock)) { $sessionlock = self::get_session_lock_info(); if (!empty($sessionlock['held'])) { // The page displays the footer and the session has been closed. $sessionlocktext = "Session lock held: ".number_format($sessionlock['held'], 3)." secs"; } else { // The session hasn't yet been closed and so we assume now with microtime. $sessionlockheld = microtime(true) - $PERF->sessionlock['gained']; $sessionlocktext = "Session lock open: ".number_format($sessionlockheld, 3)." secs"; } $info['txt'] .= $sessionlocktext; $info['html'] .= html_writer::div($sessionlocktext, "sessionlockstart"); $sessionlockwaittext = "Session lock wait: ".number_format($sessionlock['wait'], 3)." secs"; $info['txt'] .= $sessionlockwaittext; $info['html'] .= html_writer::div($sessionlockwaittext, "sessionlockwait"); } return $info; }
[ "public", "static", "function", "get_performance_info", "(", ")", "{", "global", "$", "CFG", ",", "$", "PERF", ";", "if", "(", "!", "session_id", "(", ")", ")", "{", "return", "array", "(", ")", ";", "}", "self", "::", "load_handler", "(", ")", ";", "$", "size", "=", "display_size", "(", "strlen", "(", "session_encode", "(", ")", ")", ")", ";", "$", "handler", "=", "get_class", "(", "self", "::", "$", "handler", ")", ";", "$", "info", "=", "array", "(", ")", ";", "$", "info", "[", "'size'", "]", "=", "$", "size", ";", "$", "info", "[", "'html'", "]", "=", "html_writer", "::", "div", "(", "\"Session ($handler): $size\"", ",", "\"sessionsize\"", ")", ";", "$", "info", "[", "'txt'", "]", "=", "\"Session ($handler): $size \"", ";", "if", "(", "!", "empty", "(", "$", "CFG", "->", "debugsessionlock", ")", ")", "{", "$", "sessionlock", "=", "self", "::", "get_session_lock_info", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "sessionlock", "[", "'held'", "]", ")", ")", "{", "// The page displays the footer and the session has been closed.", "$", "sessionlocktext", "=", "\"Session lock held: \"", ".", "number_format", "(", "$", "sessionlock", "[", "'held'", "]", ",", "3", ")", ".", "\" secs\"", ";", "}", "else", "{", "// The session hasn't yet been closed and so we assume now with microtime.", "$", "sessionlockheld", "=", "microtime", "(", "true", ")", "-", "$", "PERF", "->", "sessionlock", "[", "'gained'", "]", ";", "$", "sessionlocktext", "=", "\"Session lock open: \"", ".", "number_format", "(", "$", "sessionlockheld", ",", "3", ")", ".", "\" secs\"", ";", "}", "$", "info", "[", "'txt'", "]", ".=", "$", "sessionlocktext", ";", "$", "info", "[", "'html'", "]", ".=", "html_writer", "::", "div", "(", "$", "sessionlocktext", ",", "\"sessionlockstart\"", ")", ";", "$", "sessionlockwaittext", "=", "\"Session lock wait: \"", ".", "number_format", "(", "$", "sessionlock", "[", "'wait'", "]", ",", "3", ")", ".", "\" secs\"", ";", "$", "info", "[", "'txt'", "]", ".=", "$", "sessionlockwaittext", ";", "$", "info", "[", "'html'", "]", ".=", "html_writer", "::", "div", "(", "$", "sessionlockwaittext", ",", "\"sessionlockwait\"", ")", ";", "}", "return", "$", "info", ";", "}" ]
Returns current page performance info. @return array perf info
[ "Returns", "current", "page", "performance", "info", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L118-L152
220,224
moodle/moodle
lib/classes/session/manager.php
manager.get_handler_class
public static function get_handler_class() { global $CFG, $DB; if (PHPUNIT_TEST) { return '\core\session\file'; } else if (!empty($CFG->session_handler_class)) { return $CFG->session_handler_class; } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) { return '\core\session\database'; } return '\core\session\file'; }
php
public static function get_handler_class() { global $CFG, $DB; if (PHPUNIT_TEST) { return '\core\session\file'; } else if (!empty($CFG->session_handler_class)) { return $CFG->session_handler_class; } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) { return '\core\session\database'; } return '\core\session\file'; }
[ "public", "static", "function", "get_handler_class", "(", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "if", "(", "PHPUNIT_TEST", ")", "{", "return", "'\\core\\session\\file'", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "CFG", "->", "session_handler_class", ")", ")", "{", "return", "$", "CFG", "->", "session_handler_class", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "CFG", "->", "dbsessions", ")", "and", "$", "DB", "->", "session_lock_supported", "(", ")", ")", "{", "return", "'\\core\\session\\database'", ";", "}", "return", "'\\core\\session\\file'", ";", "}" ]
Get fully qualified name of session handler class. @return string The name of the handler class
[ "Get", "fully", "qualified", "name", "of", "session", "handler", "class", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L159-L171
220,225
moodle/moodle
lib/classes/session/manager.php
manager.init_empty_session
public static function init_empty_session() { global $CFG; if (isset($GLOBALS['SESSION']->notifications)) { // Backup notifications. These should be preserved across session changes until the user fetches and clears them. $notifications = $GLOBALS['SESSION']->notifications; } $GLOBALS['SESSION'] = new \stdClass(); $GLOBALS['USER'] = new \stdClass(); $GLOBALS['USER']->id = 0; if (!empty($notifications)) { // Restore notifications. $GLOBALS['SESSION']->notifications = $notifications; } if (isset($CFG->mnet_localhost_id)) { $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id; } else { // Not installed yet, the future host id will be most probably 1. $GLOBALS['USER']->mnethostid = 1; } // Link global $USER and $SESSION. $_SESSION = array(); $_SESSION['USER'] =& $GLOBALS['USER']; $_SESSION['SESSION'] =& $GLOBALS['SESSION']; }
php
public static function init_empty_session() { global $CFG; if (isset($GLOBALS['SESSION']->notifications)) { // Backup notifications. These should be preserved across session changes until the user fetches and clears them. $notifications = $GLOBALS['SESSION']->notifications; } $GLOBALS['SESSION'] = new \stdClass(); $GLOBALS['USER'] = new \stdClass(); $GLOBALS['USER']->id = 0; if (!empty($notifications)) { // Restore notifications. $GLOBALS['SESSION']->notifications = $notifications; } if (isset($CFG->mnet_localhost_id)) { $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id; } else { // Not installed yet, the future host id will be most probably 1. $GLOBALS['USER']->mnethostid = 1; } // Link global $USER and $SESSION. $_SESSION = array(); $_SESSION['USER'] =& $GLOBALS['USER']; $_SESSION['SESSION'] =& $GLOBALS['SESSION']; }
[ "public", "static", "function", "init_empty_session", "(", ")", "{", "global", "$", "CFG", ";", "if", "(", "isset", "(", "$", "GLOBALS", "[", "'SESSION'", "]", "->", "notifications", ")", ")", "{", "// Backup notifications. These should be preserved across session changes until the user fetches and clears them.", "$", "notifications", "=", "$", "GLOBALS", "[", "'SESSION'", "]", "->", "notifications", ";", "}", "$", "GLOBALS", "[", "'SESSION'", "]", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "GLOBALS", "[", "'USER'", "]", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "GLOBALS", "[", "'USER'", "]", "->", "id", "=", "0", ";", "if", "(", "!", "empty", "(", "$", "notifications", ")", ")", "{", "// Restore notifications.", "$", "GLOBALS", "[", "'SESSION'", "]", "->", "notifications", "=", "$", "notifications", ";", "}", "if", "(", "isset", "(", "$", "CFG", "->", "mnet_localhost_id", ")", ")", "{", "$", "GLOBALS", "[", "'USER'", "]", "->", "mnethostid", "=", "$", "CFG", "->", "mnet_localhost_id", ";", "}", "else", "{", "// Not installed yet, the future host id will be most probably 1.", "$", "GLOBALS", "[", "'USER'", "]", "->", "mnethostid", "=", "1", ";", "}", "// Link global $USER and $SESSION.", "$", "_SESSION", "=", "array", "(", ")", ";", "$", "_SESSION", "[", "'USER'", "]", "=", "&", "$", "GLOBALS", "[", "'USER'", "]", ";", "$", "_SESSION", "[", "'SESSION'", "]", "=", "&", "$", "GLOBALS", "[", "'SESSION'", "]", ";", "}" ]
Empty current session, fill it with not-logged-in user info. This is intended for installation scripts, unit tests and other special areas. Do NOT use for logout and session termination in normal requests!
[ "Empty", "current", "session", "fill", "it", "with", "not", "-", "logged", "-", "in", "user", "info", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L193-L220
220,226
moodle/moodle
lib/classes/session/manager.php
manager.prepare_cookies
protected static function prepare_cookies() { global $CFG; $cookiesecure = is_moodle_cookie_secure(); if (!isset($CFG->cookiehttponly)) { $CFG->cookiehttponly = 0; } // Set sessioncookie variable if it isn't already. if (!isset($CFG->sessioncookie)) { $CFG->sessioncookie = ''; } $sessionname = 'MoodleSession'.$CFG->sessioncookie; // Make sure cookie domain makes sense for this wwwroot. if (!isset($CFG->sessioncookiedomain)) { $CFG->sessioncookiedomain = ''; } else if ($CFG->sessioncookiedomain !== '') { $host = parse_url($CFG->wwwroot, PHP_URL_HOST); if ($CFG->sessioncookiedomain !== $host) { if (substr($CFG->sessioncookiedomain, 0, 1) === '.') { if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) { // Invalid domain - it must be end part of host. $CFG->sessioncookiedomain = ''; } } else { if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) { // Invalid domain - it must be end part of host. $CFG->sessioncookiedomain = ''; } } } } // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified. if (!isset($CFG->sessioncookiepath)) { $CFG->sessioncookiepath = ''; } if ($CFG->sessioncookiepath !== '/') { $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/'; if ($CFG->sessioncookiepath === '') { $CFG->sessioncookiepath = $path; } else { if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') { $CFG->sessioncookiepath = $path; } } } // Discard session ID from POST, GET and globals to tighten security, // this is session fixation prevention. unset($GLOBALS[$sessionname]); unset($_GET[$sessionname]); unset($_POST[$sessionname]); unset($_REQUEST[$sessionname]); // Compatibility hack for non-browser access to our web interface. if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") { unset($_COOKIE[$sessionname]); } // Set configuration. session_name($sessionname); session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $cookiesecure, $CFG->cookiehttponly); ini_set('session.use_trans_sid', '0'); ini_set('session.use_only_cookies', '1'); ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table. ini_set('session.use_strict_mode', '0'); // We have custom protection in session init. ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle. // Moodle does normal session timeouts, this is for leftovers only. ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 1000); ini_set('session.gc_maxlifetime', 60*60*24*4); }
php
protected static function prepare_cookies() { global $CFG; $cookiesecure = is_moodle_cookie_secure(); if (!isset($CFG->cookiehttponly)) { $CFG->cookiehttponly = 0; } // Set sessioncookie variable if it isn't already. if (!isset($CFG->sessioncookie)) { $CFG->sessioncookie = ''; } $sessionname = 'MoodleSession'.$CFG->sessioncookie; // Make sure cookie domain makes sense for this wwwroot. if (!isset($CFG->sessioncookiedomain)) { $CFG->sessioncookiedomain = ''; } else if ($CFG->sessioncookiedomain !== '') { $host = parse_url($CFG->wwwroot, PHP_URL_HOST); if ($CFG->sessioncookiedomain !== $host) { if (substr($CFG->sessioncookiedomain, 0, 1) === '.') { if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) { // Invalid domain - it must be end part of host. $CFG->sessioncookiedomain = ''; } } else { if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) { // Invalid domain - it must be end part of host. $CFG->sessioncookiedomain = ''; } } } } // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified. if (!isset($CFG->sessioncookiepath)) { $CFG->sessioncookiepath = ''; } if ($CFG->sessioncookiepath !== '/') { $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/'; if ($CFG->sessioncookiepath === '') { $CFG->sessioncookiepath = $path; } else { if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') { $CFG->sessioncookiepath = $path; } } } // Discard session ID from POST, GET and globals to tighten security, // this is session fixation prevention. unset($GLOBALS[$sessionname]); unset($_GET[$sessionname]); unset($_POST[$sessionname]); unset($_REQUEST[$sessionname]); // Compatibility hack for non-browser access to our web interface. if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") { unset($_COOKIE[$sessionname]); } // Set configuration. session_name($sessionname); session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $cookiesecure, $CFG->cookiehttponly); ini_set('session.use_trans_sid', '0'); ini_set('session.use_only_cookies', '1'); ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table. ini_set('session.use_strict_mode', '0'); // We have custom protection in session init. ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle. // Moodle does normal session timeouts, this is for leftovers only. ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 1000); ini_set('session.gc_maxlifetime', 60*60*24*4); }
[ "protected", "static", "function", "prepare_cookies", "(", ")", "{", "global", "$", "CFG", ";", "$", "cookiesecure", "=", "is_moodle_cookie_secure", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "CFG", "->", "cookiehttponly", ")", ")", "{", "$", "CFG", "->", "cookiehttponly", "=", "0", ";", "}", "// Set sessioncookie variable if it isn't already.", "if", "(", "!", "isset", "(", "$", "CFG", "->", "sessioncookie", ")", ")", "{", "$", "CFG", "->", "sessioncookie", "=", "''", ";", "}", "$", "sessionname", "=", "'MoodleSession'", ".", "$", "CFG", "->", "sessioncookie", ";", "// Make sure cookie domain makes sense for this wwwroot.", "if", "(", "!", "isset", "(", "$", "CFG", "->", "sessioncookiedomain", ")", ")", "{", "$", "CFG", "->", "sessioncookiedomain", "=", "''", ";", "}", "else", "if", "(", "$", "CFG", "->", "sessioncookiedomain", "!==", "''", ")", "{", "$", "host", "=", "parse_url", "(", "$", "CFG", "->", "wwwroot", ",", "PHP_URL_HOST", ")", ";", "if", "(", "$", "CFG", "->", "sessioncookiedomain", "!==", "$", "host", ")", "{", "if", "(", "substr", "(", "$", "CFG", "->", "sessioncookiedomain", ",", "0", ",", "1", ")", "===", "'.'", ")", "{", "if", "(", "!", "preg_match", "(", "'|^.*'", ".", "preg_quote", "(", "$", "CFG", "->", "sessioncookiedomain", ",", "'|'", ")", ".", "'$|'", ",", "$", "host", ")", ")", "{", "// Invalid domain - it must be end part of host.", "$", "CFG", "->", "sessioncookiedomain", "=", "''", ";", "}", "}", "else", "{", "if", "(", "!", "preg_match", "(", "'|^.*\\.'", ".", "preg_quote", "(", "$", "CFG", "->", "sessioncookiedomain", ",", "'|'", ")", ".", "'$|'", ",", "$", "host", ")", ")", "{", "// Invalid domain - it must be end part of host.", "$", "CFG", "->", "sessioncookiedomain", "=", "''", ";", "}", "}", "}", "}", "// Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.", "if", "(", "!", "isset", "(", "$", "CFG", "->", "sessioncookiepath", ")", ")", "{", "$", "CFG", "->", "sessioncookiepath", "=", "''", ";", "}", "if", "(", "$", "CFG", "->", "sessioncookiepath", "!==", "'/'", ")", "{", "$", "path", "=", "parse_url", "(", "$", "CFG", "->", "wwwroot", ",", "PHP_URL_PATH", ")", ".", "'/'", ";", "if", "(", "$", "CFG", "->", "sessioncookiepath", "===", "''", ")", "{", "$", "CFG", "->", "sessioncookiepath", "=", "$", "path", ";", "}", "else", "{", "if", "(", "strpos", "(", "$", "path", ",", "$", "CFG", "->", "sessioncookiepath", ")", "!==", "0", "or", "substr", "(", "$", "CFG", "->", "sessioncookiepath", ",", "-", "1", ")", "!==", "'/'", ")", "{", "$", "CFG", "->", "sessioncookiepath", "=", "$", "path", ";", "}", "}", "}", "// Discard session ID from POST, GET and globals to tighten security,", "// this is session fixation prevention.", "unset", "(", "$", "GLOBALS", "[", "$", "sessionname", "]", ")", ";", "unset", "(", "$", "_GET", "[", "$", "sessionname", "]", ")", ";", "unset", "(", "$", "_POST", "[", "$", "sessionname", "]", ")", ";", "unset", "(", "$", "_REQUEST", "[", "$", "sessionname", "]", ")", ";", "// Compatibility hack for non-browser access to our web interface.", "if", "(", "!", "empty", "(", "$", "_COOKIE", "[", "$", "sessionname", "]", ")", "&&", "$", "_COOKIE", "[", "$", "sessionname", "]", "==", "\"deleted\"", ")", "{", "unset", "(", "$", "_COOKIE", "[", "$", "sessionname", "]", ")", ";", "}", "// Set configuration.", "session_name", "(", "$", "sessionname", ")", ";", "session_set_cookie_params", "(", "0", ",", "$", "CFG", "->", "sessioncookiepath", ",", "$", "CFG", "->", "sessioncookiedomain", ",", "$", "cookiesecure", ",", "$", "CFG", "->", "cookiehttponly", ")", ";", "ini_set", "(", "'session.use_trans_sid'", ",", "'0'", ")", ";", "ini_set", "(", "'session.use_only_cookies'", ",", "'1'", ")", ";", "ini_set", "(", "'session.hash_function'", ",", "'0'", ")", ";", "// For now MD5 - we do not have room for sha-1 in sessions table.", "ini_set", "(", "'session.use_strict_mode'", ",", "'0'", ")", ";", "// We have custom protection in session init.", "ini_set", "(", "'session.serialize_handler'", ",", "'php'", ")", ";", "// We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.", "// Moodle does normal session timeouts, this is for leftovers only.", "ini_set", "(", "'session.gc_probability'", ",", "1", ")", ";", "ini_set", "(", "'session.gc_divisor'", ",", "1000", ")", ";", "ini_set", "(", "'session.gc_maxlifetime'", ",", "60", "*", "60", "*", "24", "*", "4", ")", ";", "}" ]
Make sure all cookie and session related stuff is configured properly before session start.
[ "Make", "sure", "all", "cookie", "and", "session", "related", "stuff", "is", "configured", "properly", "before", "session", "start", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L225-L300
220,227
moodle/moodle
lib/classes/session/manager.php
manager.add_session_record
protected static function add_session_record($userid) { global $DB; $record = new \stdClass(); $record->state = 0; $record->sid = session_id(); $record->sessdata = null; $record->userid = $userid; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); $record->id = $DB->insert_record('sessions', $record); return $record; }
php
protected static function add_session_record($userid) { global $DB; $record = new \stdClass(); $record->state = 0; $record->sid = session_id(); $record->sessdata = null; $record->userid = $userid; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); $record->id = $DB->insert_record('sessions', $record); return $record; }
[ "protected", "static", "function", "add_session_record", "(", "$", "userid", ")", "{", "global", "$", "DB", ";", "$", "record", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "record", "->", "state", "=", "0", ";", "$", "record", "->", "sid", "=", "session_id", "(", ")", ";", "$", "record", "->", "sessdata", "=", "null", ";", "$", "record", "->", "userid", "=", "$", "userid", ";", "$", "record", "->", "timecreated", "=", "$", "record", "->", "timemodified", "=", "time", "(", ")", ";", "$", "record", "->", "firstip", "=", "$", "record", "->", "lastip", "=", "getremoteaddr", "(", ")", ";", "$", "record", "->", "id", "=", "$", "DB", "->", "insert_record", "(", "'sessions'", ",", "$", "record", ")", ";", "return", "$", "record", ";", "}" ]
Insert new empty session record. @param int $userid @return \stdClass the new record
[ "Insert", "new", "empty", "session", "record", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L456-L469
220,228
moodle/moodle
lib/classes/session/manager.php
manager.check_security
protected static function check_security() { global $CFG; if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) { // Make sure current IP matches the one for this session. $remoteaddr = getremoteaddr(); if (empty($_SESSION['USER']->sessionip)) { $_SESSION['USER']->sessionip = $remoteaddr; } if ($_SESSION['USER']->sessionip != $remoteaddr) { // This is a security feature - terminate the session in case of any doubt. self::terminate_current(); throw new exception('sessionipnomatch2', 'error'); } } }
php
protected static function check_security() { global $CFG; if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) { // Make sure current IP matches the one for this session. $remoteaddr = getremoteaddr(); if (empty($_SESSION['USER']->sessionip)) { $_SESSION['USER']->sessionip = $remoteaddr; } if ($_SESSION['USER']->sessionip != $remoteaddr) { // This is a security feature - terminate the session in case of any doubt. self::terminate_current(); throw new exception('sessionipnomatch2', 'error'); } } }
[ "protected", "static", "function", "check_security", "(", ")", "{", "global", "$", "CFG", ";", "if", "(", "!", "empty", "(", "$", "_SESSION", "[", "'USER'", "]", "->", "id", ")", "and", "!", "empty", "(", "$", "CFG", "->", "tracksessionip", ")", ")", "{", "// Make sure current IP matches the one for this session.", "$", "remoteaddr", "=", "getremoteaddr", "(", ")", ";", "if", "(", "empty", "(", "$", "_SESSION", "[", "'USER'", "]", "->", "sessionip", ")", ")", "{", "$", "_SESSION", "[", "'USER'", "]", "->", "sessionip", "=", "$", "remoteaddr", ";", "}", "if", "(", "$", "_SESSION", "[", "'USER'", "]", "->", "sessionip", "!=", "$", "remoteaddr", ")", "{", "// This is a security feature - terminate the session in case of any doubt.", "self", "::", "terminate_current", "(", ")", ";", "throw", "new", "exception", "(", "'sessionipnomatch2'", ",", "'error'", ")", ";", "}", "}", "}" ]
Do various session security checks. WARNING: $USER and $SESSION are set up later, do not use them yet! @throws \core\session\exception
[ "Do", "various", "session", "security", "checks", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L477-L494
220,229
moodle/moodle
lib/classes/session/manager.php
manager.terminate_current
public static function terminate_current() { global $DB; if (!self::$sessionactive) { self::init_empty_session(); self::$sessionactive = false; return; } try { $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED)); } catch (\Exception $ignored) { // Probably install/upgrade - ignore this problem. } // Initialize variable to pass-by-reference to headers_sent(&$file, &$line). $file = null; $line = null; if (headers_sent($file, $line)) { error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line); } // Write new empty session and make sure the old one is deleted. $sid = session_id(); session_regenerate_id(true); $DB->delete_records('sessions', array('sid'=>$sid)); self::init_empty_session(); self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet. session_write_close(); self::$sessionactive = false; }
php
public static function terminate_current() { global $DB; if (!self::$sessionactive) { self::init_empty_session(); self::$sessionactive = false; return; } try { $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED)); } catch (\Exception $ignored) { // Probably install/upgrade - ignore this problem. } // Initialize variable to pass-by-reference to headers_sent(&$file, &$line). $file = null; $line = null; if (headers_sent($file, $line)) { error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line); } // Write new empty session and make sure the old one is deleted. $sid = session_id(); session_regenerate_id(true); $DB->delete_records('sessions', array('sid'=>$sid)); self::init_empty_session(); self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet. session_write_close(); self::$sessionactive = false; }
[ "public", "static", "function", "terminate_current", "(", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "self", "::", "$", "sessionactive", ")", "{", "self", "::", "init_empty_session", "(", ")", ";", "self", "::", "$", "sessionactive", "=", "false", ";", "return", ";", "}", "try", "{", "$", "DB", "->", "delete_records", "(", "'external_tokens'", ",", "array", "(", "'sid'", "=>", "session_id", "(", ")", ",", "'tokentype'", "=>", "EXTERNAL_TOKEN_EMBEDDED", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ignored", ")", "{", "// Probably install/upgrade - ignore this problem.", "}", "// Initialize variable to pass-by-reference to headers_sent(&$file, &$line).", "$", "file", "=", "null", ";", "$", "line", "=", "null", ";", "if", "(", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ")", "{", "error_log", "(", "'Cannot terminate session properly - headers were already sent in file: '", ".", "$", "file", ".", "' on line '", ".", "$", "line", ")", ";", "}", "// Write new empty session and make sure the old one is deleted.", "$", "sid", "=", "session_id", "(", ")", ";", "session_regenerate_id", "(", "true", ")", ";", "$", "DB", "->", "delete_records", "(", "'sessions'", ",", "array", "(", "'sid'", "=>", "$", "sid", ")", ")", ";", "self", "::", "init_empty_session", "(", ")", ";", "self", "::", "add_session_record", "(", "$", "_SESSION", "[", "'USER'", "]", "->", "id", ")", ";", "// Do not use $USER here because it may not be set up yet.", "session_write_close", "(", ")", ";", "self", "::", "$", "sessionactive", "=", "false", ";", "}" ]
Terminate current user session. @return void
[ "Terminate", "current", "user", "session", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L522-L552
220,230
moodle/moodle
lib/classes/session/manager.php
manager.write_close
public static function write_close() { global $PERF; if (self::$sessionactive) { // Grab the time when session lock is released. $PERF->sessionlock['released'] = microtime(true); if (!empty($PERF->sessionlock['gained'])) { $PERF->sessionlock['held'] = $PERF->sessionlock['released'] - $PERF->sessionlock['gained']; } $PERF->sessionlock['url'] = me(); self::update_recent_session_locks($PERF->sessionlock); self::sessionlock_debugging(); } if (version_compare(PHP_VERSION, '5.6.0', '>=')) { // More control over whether session data // is persisted or not. if (self::$sessionactive && session_id()) { // Write session and release lock only if // indication session start was clean. session_write_close(); } else { // Otherwise, if possibile lock exists want // to clear it, but do not write session. @session_abort(); } } else { // Any indication session was started, attempt // to close it. if (self::$sessionactive || session_id()) { session_write_close(); } } self::$sessionactive = false; }
php
public static function write_close() { global $PERF; if (self::$sessionactive) { // Grab the time when session lock is released. $PERF->sessionlock['released'] = microtime(true); if (!empty($PERF->sessionlock['gained'])) { $PERF->sessionlock['held'] = $PERF->sessionlock['released'] - $PERF->sessionlock['gained']; } $PERF->sessionlock['url'] = me(); self::update_recent_session_locks($PERF->sessionlock); self::sessionlock_debugging(); } if (version_compare(PHP_VERSION, '5.6.0', '>=')) { // More control over whether session data // is persisted or not. if (self::$sessionactive && session_id()) { // Write session and release lock only if // indication session start was clean. session_write_close(); } else { // Otherwise, if possibile lock exists want // to clear it, but do not write session. @session_abort(); } } else { // Any indication session was started, attempt // to close it. if (self::$sessionactive || session_id()) { session_write_close(); } } self::$sessionactive = false; }
[ "public", "static", "function", "write_close", "(", ")", "{", "global", "$", "PERF", ";", "if", "(", "self", "::", "$", "sessionactive", ")", "{", "// Grab the time when session lock is released.", "$", "PERF", "->", "sessionlock", "[", "'released'", "]", "=", "microtime", "(", "true", ")", ";", "if", "(", "!", "empty", "(", "$", "PERF", "->", "sessionlock", "[", "'gained'", "]", ")", ")", "{", "$", "PERF", "->", "sessionlock", "[", "'held'", "]", "=", "$", "PERF", "->", "sessionlock", "[", "'released'", "]", "-", "$", "PERF", "->", "sessionlock", "[", "'gained'", "]", ";", "}", "$", "PERF", "->", "sessionlock", "[", "'url'", "]", "=", "me", "(", ")", ";", "self", "::", "update_recent_session_locks", "(", "$", "PERF", "->", "sessionlock", ")", ";", "self", "::", "sessionlock_debugging", "(", ")", ";", "}", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'5.6.0'", ",", "'>='", ")", ")", "{", "// More control over whether session data", "// is persisted or not.", "if", "(", "self", "::", "$", "sessionactive", "&&", "session_id", "(", ")", ")", "{", "// Write session and release lock only if", "// indication session start was clean.", "session_write_close", "(", ")", ";", "}", "else", "{", "// Otherwise, if possibile lock exists want", "// to clear it, but do not write session.", "@", "session_abort", "(", ")", ";", "}", "}", "else", "{", "// Any indication session was started, attempt", "// to close it.", "if", "(", "self", "::", "$", "sessionactive", "||", "session_id", "(", ")", ")", "{", "session_write_close", "(", ")", ";", "}", "}", "self", "::", "$", "sessionactive", "=", "false", ";", "}" ]
No more changes in session expected. Unblocks the sessions, other scripts may start executing in parallel.
[ "No", "more", "changes", "in", "session", "expected", ".", "Unblocks", "the", "sessions", "other", "scripts", "may", "start", "executing", "in", "parallel", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L558-L592
220,231
moodle/moodle
lib/classes/session/manager.php
manager.session_exists
public static function session_exists($sid) { global $DB, $CFG; if (empty($CFG->version)) { // Not installed yet, do not try to access database. return false; } // Note: add sessions->state checking here if it gets implemented. if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) { return false; } if (empty($record->userid) or isguestuser($record->userid)) { // Ignore guest and not-logged-in timeouts, there is very little risk here. } else if ($record->timemodified < time() - $CFG->sessiontimeout) { return false; } // There is no need the existence of handler storage in public API. self::load_handler(); return self::$handler->session_exists($sid); }
php
public static function session_exists($sid) { global $DB, $CFG; if (empty($CFG->version)) { // Not installed yet, do not try to access database. return false; } // Note: add sessions->state checking here if it gets implemented. if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) { return false; } if (empty($record->userid) or isguestuser($record->userid)) { // Ignore guest and not-logged-in timeouts, there is very little risk here. } else if ($record->timemodified < time() - $CFG->sessiontimeout) { return false; } // There is no need the existence of handler storage in public API. self::load_handler(); return self::$handler->session_exists($sid); }
[ "public", "static", "function", "session_exists", "(", "$", "sid", ")", "{", "global", "$", "DB", ",", "$", "CFG", ";", "if", "(", "empty", "(", "$", "CFG", "->", "version", ")", ")", "{", "// Not installed yet, do not try to access database.", "return", "false", ";", "}", "// Note: add sessions->state checking here if it gets implemented.", "if", "(", "!", "$", "record", "=", "$", "DB", "->", "get_record", "(", "'sessions'", ",", "array", "(", "'sid'", "=>", "$", "sid", ")", ",", "'id, userid, timemodified'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "empty", "(", "$", "record", "->", "userid", ")", "or", "isguestuser", "(", "$", "record", "->", "userid", ")", ")", "{", "// Ignore guest and not-logged-in timeouts, there is very little risk here.", "}", "else", "if", "(", "$", "record", "->", "timemodified", "<", "time", "(", ")", "-", "$", "CFG", "->", "sessiontimeout", ")", "{", "return", "false", ";", "}", "// There is no need the existence of handler storage in public API.", "self", "::", "load_handler", "(", ")", ";", "return", "self", "::", "$", "handler", "->", "session_exists", "(", "$", "sid", ")", ";", "}" ]
Does the PHP session with given id exist? The session must exist both in session table and actual session backend and the session must not be timed out. Timeout evaluation is simplified, the auth hooks are not executed. @param string $sid @return bool
[ "Does", "the", "PHP", "session", "with", "given", "id", "exist?" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L605-L627
220,232
moodle/moodle
lib/classes/session/manager.php
manager.kill_all_sessions
public static function kill_all_sessions() { global $DB; self::terminate_current(); self::load_handler(); self::$handler->kill_all_sessions(); try { $DB->delete_records('sessions'); } catch (\dml_exception $ignored) { // Do not show any warnings - might be during upgrade/installation. } }
php
public static function kill_all_sessions() { global $DB; self::terminate_current(); self::load_handler(); self::$handler->kill_all_sessions(); try { $DB->delete_records('sessions'); } catch (\dml_exception $ignored) { // Do not show any warnings - might be during upgrade/installation. } }
[ "public", "static", "function", "kill_all_sessions", "(", ")", "{", "global", "$", "DB", ";", "self", "::", "terminate_current", "(", ")", ";", "self", "::", "load_handler", "(", ")", ";", "self", "::", "$", "handler", "->", "kill_all_sessions", "(", ")", ";", "try", "{", "$", "DB", "->", "delete_records", "(", "'sessions'", ")", ";", "}", "catch", "(", "\\", "dml_exception", "$", "ignored", ")", "{", "// Do not show any warnings - might be during upgrade/installation.", "}", "}" ]
Terminate all sessions unconditionally.
[ "Terminate", "all", "sessions", "unconditionally", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L645-L658
220,233
moodle/moodle
lib/classes/session/manager.php
manager.kill_session
public static function kill_session($sid) { global $DB; self::load_handler(); if ($sid === session_id()) { self::write_close(); } self::$handler->kill_session($sid); $DB->delete_records('sessions', array('sid'=>$sid)); }
php
public static function kill_session($sid) { global $DB; self::load_handler(); if ($sid === session_id()) { self::write_close(); } self::$handler->kill_session($sid); $DB->delete_records('sessions', array('sid'=>$sid)); }
[ "public", "static", "function", "kill_session", "(", "$", "sid", ")", "{", "global", "$", "DB", ";", "self", "::", "load_handler", "(", ")", ";", "if", "(", "$", "sid", "===", "session_id", "(", ")", ")", "{", "self", "::", "write_close", "(", ")", ";", "}", "self", "::", "$", "handler", "->", "kill_session", "(", "$", "sid", ")", ";", "$", "DB", "->", "delete_records", "(", "'sessions'", ",", "array", "(", "'sid'", "=>", "$", "sid", ")", ")", ";", "}" ]
Terminate give session unconditionally. @param string $sid
[ "Terminate", "give", "session", "unconditionally", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L664-L676
220,234
moodle/moodle
lib/classes/session/manager.php
manager.kill_user_sessions
public static function kill_user_sessions($userid, $keepsid = null) { global $DB; $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid'); foreach ($sessions as $session) { if ($keepsid and $keepsid === $session->sid) { continue; } self::kill_session($session->sid); } }
php
public static function kill_user_sessions($userid, $keepsid = null) { global $DB; $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid'); foreach ($sessions as $session) { if ($keepsid and $keepsid === $session->sid) { continue; } self::kill_session($session->sid); } }
[ "public", "static", "function", "kill_user_sessions", "(", "$", "userid", ",", "$", "keepsid", "=", "null", ")", "{", "global", "$", "DB", ";", "$", "sessions", "=", "$", "DB", "->", "get_records", "(", "'sessions'", ",", "array", "(", "'userid'", "=>", "$", "userid", ")", ",", "'id DESC'", ",", "'id, sid'", ")", ";", "foreach", "(", "$", "sessions", "as", "$", "session", ")", "{", "if", "(", "$", "keepsid", "and", "$", "keepsid", "===", "$", "session", "->", "sid", ")", "{", "continue", ";", "}", "self", "::", "kill_session", "(", "$", "session", "->", "sid", ")", ";", "}", "}" ]
Terminate all sessions of given user unconditionally. @param int $userid @param string $keepsid keep this sid if present
[ "Terminate", "all", "sessions", "of", "given", "user", "unconditionally", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L683-L693
220,235
moodle/moodle
lib/classes/session/manager.php
manager.loginas
public static function loginas($userid, \context $context, $generateevent = true) { global $USER; if (self::is_loggedinas()) { return; } // Switch to fresh new $_SESSION. $_SESSION = array(); $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']); $GLOBALS['SESSION'] = new \stdClass(); $_SESSION['SESSION'] =& $GLOBALS['SESSION']; // Create the new $USER object with all details and reload needed capabilities. $_SESSION['REALUSER'] = clone($GLOBALS['USER']); $user = get_complete_user_data('id', $userid); $user->realuser = $_SESSION['REALUSER']->id; $user->loginascontext = $context; // Let enrol plugins deal with new enrolments if necessary. enrol_check_plugins($user); if ($generateevent) { // Create event before $USER is updated. $event = \core\event\user_loggedinas::create( array( 'objectid' => $USER->id, 'context' => $context, 'relateduserid' => $userid, 'other' => array( 'originalusername' => fullname($USER, true), 'loggedinasusername' => fullname($user, true) ) ) ); } // Set up global $USER. \core\session\manager::set_user($user); if ($generateevent) { $event->trigger(); } }
php
public static function loginas($userid, \context $context, $generateevent = true) { global $USER; if (self::is_loggedinas()) { return; } // Switch to fresh new $_SESSION. $_SESSION = array(); $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']); $GLOBALS['SESSION'] = new \stdClass(); $_SESSION['SESSION'] =& $GLOBALS['SESSION']; // Create the new $USER object with all details and reload needed capabilities. $_SESSION['REALUSER'] = clone($GLOBALS['USER']); $user = get_complete_user_data('id', $userid); $user->realuser = $_SESSION['REALUSER']->id; $user->loginascontext = $context; // Let enrol plugins deal with new enrolments if necessary. enrol_check_plugins($user); if ($generateevent) { // Create event before $USER is updated. $event = \core\event\user_loggedinas::create( array( 'objectid' => $USER->id, 'context' => $context, 'relateduserid' => $userid, 'other' => array( 'originalusername' => fullname($USER, true), 'loggedinasusername' => fullname($user, true) ) ) ); } // Set up global $USER. \core\session\manager::set_user($user); if ($generateevent) { $event->trigger(); } }
[ "public", "static", "function", "loginas", "(", "$", "userid", ",", "\\", "context", "$", "context", ",", "$", "generateevent", "=", "true", ")", "{", "global", "$", "USER", ";", "if", "(", "self", "::", "is_loggedinas", "(", ")", ")", "{", "return", ";", "}", "// Switch to fresh new $_SESSION.", "$", "_SESSION", "=", "array", "(", ")", ";", "$", "_SESSION", "[", "'REALSESSION'", "]", "=", "clone", "(", "$", "GLOBALS", "[", "'SESSION'", "]", ")", ";", "$", "GLOBALS", "[", "'SESSION'", "]", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "_SESSION", "[", "'SESSION'", "]", "=", "&", "$", "GLOBALS", "[", "'SESSION'", "]", ";", "// Create the new $USER object with all details and reload needed capabilities.", "$", "_SESSION", "[", "'REALUSER'", "]", "=", "clone", "(", "$", "GLOBALS", "[", "'USER'", "]", ")", ";", "$", "user", "=", "get_complete_user_data", "(", "'id'", ",", "$", "userid", ")", ";", "$", "user", "->", "realuser", "=", "$", "_SESSION", "[", "'REALUSER'", "]", "->", "id", ";", "$", "user", "->", "loginascontext", "=", "$", "context", ";", "// Let enrol plugins deal with new enrolments if necessary.", "enrol_check_plugins", "(", "$", "user", ")", ";", "if", "(", "$", "generateevent", ")", "{", "// Create event before $USER is updated.", "$", "event", "=", "\\", "core", "\\", "event", "\\", "user_loggedinas", "::", "create", "(", "array", "(", "'objectid'", "=>", "$", "USER", "->", "id", ",", "'context'", "=>", "$", "context", ",", "'relateduserid'", "=>", "$", "userid", ",", "'other'", "=>", "array", "(", "'originalusername'", "=>", "fullname", "(", "$", "USER", ",", "true", ")", ",", "'loggedinasusername'", "=>", "fullname", "(", "$", "user", ",", "true", ")", ")", ")", ")", ";", "}", "// Set up global $USER.", "\\", "core", "\\", "session", "\\", "manager", "::", "set_user", "(", "$", "user", ")", ";", "if", "(", "$", "generateevent", ")", "{", "$", "event", "->", "trigger", "(", ")", ";", "}", "}" ]
Login as another user - no security checks here. @param int $userid @param \context $context @param bool $generateevent Set to false to prevent the loginas event to be generated @return void
[ "Login", "as", "another", "user", "-", "no", "security", "checks", "here", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L887-L930
220,236
moodle/moodle
lib/classes/session/manager.php
manager.keepalive
public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null) { global $CFG, $PAGE; if ($frequency) { if ($frequency > $CFG->sessiontimeout) { // Sanity check the frequency. throw new \coding_exception('Keepalive frequency is longer than the session lifespan.'); } } else { // A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session. $frequency = $CFG->sessiontimeout / 3; } // Add the session keepalive script to the list of page output requirements. $sessionkeepaliveurl = new \moodle_url('/lib/sessionkeepalive_ajax.php'); $PAGE->requires->string_for_js($identifier, $component); $PAGE->requires->yui_module('moodle-core-checknet', 'M.core.checknet.init', array(array( // The JS config takes this is milliseconds rather than seconds. 'frequency' => $frequency * 1000, 'message' => array($identifier, $component), 'uri' => $sessionkeepaliveurl->out(), ))); }
php
public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null) { global $CFG, $PAGE; if ($frequency) { if ($frequency > $CFG->sessiontimeout) { // Sanity check the frequency. throw new \coding_exception('Keepalive frequency is longer than the session lifespan.'); } } else { // A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session. $frequency = $CFG->sessiontimeout / 3; } // Add the session keepalive script to the list of page output requirements. $sessionkeepaliveurl = new \moodle_url('/lib/sessionkeepalive_ajax.php'); $PAGE->requires->string_for_js($identifier, $component); $PAGE->requires->yui_module('moodle-core-checknet', 'M.core.checknet.init', array(array( // The JS config takes this is milliseconds rather than seconds. 'frequency' => $frequency * 1000, 'message' => array($identifier, $component), 'uri' => $sessionkeepaliveurl->out(), ))); }
[ "public", "static", "function", "keepalive", "(", "$", "identifier", "=", "'sessionerroruser'", ",", "$", "component", "=", "'error'", ",", "$", "frequency", "=", "null", ")", "{", "global", "$", "CFG", ",", "$", "PAGE", ";", "if", "(", "$", "frequency", ")", "{", "if", "(", "$", "frequency", ">", "$", "CFG", "->", "sessiontimeout", ")", "{", "// Sanity check the frequency.", "throw", "new", "\\", "coding_exception", "(", "'Keepalive frequency is longer than the session lifespan.'", ")", ";", "}", "}", "else", "{", "// A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session.", "$", "frequency", "=", "$", "CFG", "->", "sessiontimeout", "/", "3", ";", "}", "// Add the session keepalive script to the list of page output requirements.", "$", "sessionkeepaliveurl", "=", "new", "\\", "moodle_url", "(", "'/lib/sessionkeepalive_ajax.php'", ")", ";", "$", "PAGE", "->", "requires", "->", "string_for_js", "(", "$", "identifier", ",", "$", "component", ")", ";", "$", "PAGE", "->", "requires", "->", "yui_module", "(", "'moodle-core-checknet'", ",", "'M.core.checknet.init'", ",", "array", "(", "array", "(", "// The JS config takes this is milliseconds rather than seconds.", "'frequency'", "=>", "$", "frequency", "*", "1000", ",", "'message'", "=>", "array", "(", "$", "identifier", ",", "$", "component", ")", ",", "'uri'", "=>", "$", "sessionkeepaliveurl", "->", "out", "(", ")", ",", ")", ")", ")", ";", "}" ]
Add a JS session keepalive to the page. A JS session keepalive script will be called to update the session modification time every $frequency seconds. Upon failure, the specified error message will be shown to the user. @param string $identifier The string identifier for the message to show on failure. @param string $component The string component for the message to show on failure. @param int $frequency The update frequency in seconds. @throws coding_exception IF the frequency is longer than the session lifetime.
[ "Add", "a", "JS", "session", "keepalive", "to", "the", "page", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L944-L966
220,237
moodle/moodle
lib/classes/session/manager.php
manager.create_login_token
private static function create_login_token() { global $SESSION; $state = [ 'token' => random_string(32), 'created' => time() // Server time - not user time. ]; if (!isset($SESSION->logintoken)) { $SESSION->logintoken = []; } // Overwrite any previous values. $SESSION->logintoken[self::$logintokenkey] = $state; return $state; }
php
private static function create_login_token() { global $SESSION; $state = [ 'token' => random_string(32), 'created' => time() // Server time - not user time. ]; if (!isset($SESSION->logintoken)) { $SESSION->logintoken = []; } // Overwrite any previous values. $SESSION->logintoken[self::$logintokenkey] = $state; return $state; }
[ "private", "static", "function", "create_login_token", "(", ")", "{", "global", "$", "SESSION", ";", "$", "state", "=", "[", "'token'", "=>", "random_string", "(", "32", ")", ",", "'created'", "=>", "time", "(", ")", "// Server time - not user time.", "]", ";", "if", "(", "!", "isset", "(", "$", "SESSION", "->", "logintoken", ")", ")", "{", "$", "SESSION", "->", "logintoken", "=", "[", "]", ";", "}", "// Overwrite any previous values.", "$", "SESSION", "->", "logintoken", "[", "self", "::", "$", "logintokenkey", "]", "=", "$", "state", ";", "return", "$", "state", ";", "}" ]
Generate a new login token and store it in the session. @return array The current login state.
[ "Generate", "a", "new", "login", "token", "and", "store", "it", "in", "the", "session", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L973-L989
220,238
moodle/moodle
lib/classes/session/manager.php
manager.get_login_token
public static function get_login_token() { global $CFG, $SESSION; $state = false; if (!isset($SESSION->logintoken)) { $SESSION->logintoken = []; } if (array_key_exists(self::$logintokenkey, $SESSION->logintoken)) { $state = $SESSION->logintoken[self::$logintokenkey]; } if (empty($state)) { $state = self::create_login_token(); } // Check token lifespan. if ($state['created'] < (time() - $CFG->sessiontimeout)) { $state = self::create_login_token(); } // Return the current session login token. if (array_key_exists('token', $state)) { return $state['token']; } else { return false; } }
php
public static function get_login_token() { global $CFG, $SESSION; $state = false; if (!isset($SESSION->logintoken)) { $SESSION->logintoken = []; } if (array_key_exists(self::$logintokenkey, $SESSION->logintoken)) { $state = $SESSION->logintoken[self::$logintokenkey]; } if (empty($state)) { $state = self::create_login_token(); } // Check token lifespan. if ($state['created'] < (time() - $CFG->sessiontimeout)) { $state = self::create_login_token(); } // Return the current session login token. if (array_key_exists('token', $state)) { return $state['token']; } else { return false; } }
[ "public", "static", "function", "get_login_token", "(", ")", "{", "global", "$", "CFG", ",", "$", "SESSION", ";", "$", "state", "=", "false", ";", "if", "(", "!", "isset", "(", "$", "SESSION", "->", "logintoken", ")", ")", "{", "$", "SESSION", "->", "logintoken", "=", "[", "]", ";", "}", "if", "(", "array_key_exists", "(", "self", "::", "$", "logintokenkey", ",", "$", "SESSION", "->", "logintoken", ")", ")", "{", "$", "state", "=", "$", "SESSION", "->", "logintoken", "[", "self", "::", "$", "logintokenkey", "]", ";", "}", "if", "(", "empty", "(", "$", "state", ")", ")", "{", "$", "state", "=", "self", "::", "create_login_token", "(", ")", ";", "}", "// Check token lifespan.", "if", "(", "$", "state", "[", "'created'", "]", "<", "(", "time", "(", ")", "-", "$", "CFG", "->", "sessiontimeout", ")", ")", "{", "$", "state", "=", "self", "::", "create_login_token", "(", ")", ";", "}", "// Return the current session login token.", "if", "(", "array_key_exists", "(", "'token'", ",", "$", "state", ")", ")", "{", "return", "$", "state", "[", "'token'", "]", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Get the current login token or generate a new one. All login forms generated from Moodle must include a login token named "logintoken" with the value being the result of this function. Logins will be rejected if they do not include this token as well as the username and password fields. @return string The current login token.
[ "Get", "the", "current", "login", "token", "or", "generate", "a", "new", "one", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1001-L1028
220,239
moodle/moodle
lib/classes/session/manager.php
manager.validate_login_token
public static function validate_login_token($token = false) { global $CFG; if (!empty($CFG->alternateloginurl) || !empty($CFG->disablelogintoken)) { // An external login page cannot generate the login token we need to protect CSRF on // login requests. // Other custom login workflows may skip this check by setting disablelogintoken in config. return true; } if ($token === false) { // authenticate_user_login is a core function was extended to validate tokens. // For existing uses other than the login form it does not // validate that a token was generated. // Some uses that do not validate the token are login/token.php, // or an auth plugin like auth/ldap/auth.php. return true; } $currenttoken = self::get_login_token(); // We need to clean the login token so the old one is not valid again. self::create_login_token(); if ($currenttoken !== $token) { // Fail the login. return false; } return true; }
php
public static function validate_login_token($token = false) { global $CFG; if (!empty($CFG->alternateloginurl) || !empty($CFG->disablelogintoken)) { // An external login page cannot generate the login token we need to protect CSRF on // login requests. // Other custom login workflows may skip this check by setting disablelogintoken in config. return true; } if ($token === false) { // authenticate_user_login is a core function was extended to validate tokens. // For existing uses other than the login form it does not // validate that a token was generated. // Some uses that do not validate the token are login/token.php, // or an auth plugin like auth/ldap/auth.php. return true; } $currenttoken = self::get_login_token(); // We need to clean the login token so the old one is not valid again. self::create_login_token(); if ($currenttoken !== $token) { // Fail the login. return false; } return true; }
[ "public", "static", "function", "validate_login_token", "(", "$", "token", "=", "false", ")", "{", "global", "$", "CFG", ";", "if", "(", "!", "empty", "(", "$", "CFG", "->", "alternateloginurl", ")", "||", "!", "empty", "(", "$", "CFG", "->", "disablelogintoken", ")", ")", "{", "// An external login page cannot generate the login token we need to protect CSRF on", "// login requests.", "// Other custom login workflows may skip this check by setting disablelogintoken in config.", "return", "true", ";", "}", "if", "(", "$", "token", "===", "false", ")", "{", "// authenticate_user_login is a core function was extended to validate tokens.", "// For existing uses other than the login form it does not", "// validate that a token was generated.", "// Some uses that do not validate the token are login/token.php,", "// or an auth plugin like auth/ldap/auth.php.", "return", "true", ";", "}", "$", "currenttoken", "=", "self", "::", "get_login_token", "(", ")", ";", "// We need to clean the login token so the old one is not valid again.", "self", "::", "create_login_token", "(", ")", ";", "if", "(", "$", "currenttoken", "!==", "$", "token", ")", "{", "// Fail the login.", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check the submitted value against the stored login token. @param mixed $token The value submitted in the login form that we are validating. If false is passed for the token, this function will always return true. @return boolean If the submitted token is valid.
[ "Check", "the", "submitted", "value", "against", "the", "stored", "login", "token", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1037-L1065
220,240
moodle/moodle
lib/classes/session/manager.php
manager.update_recent_session_locks
public static function update_recent_session_locks($sessionlock) { global $CFG, $SESSION; if (empty($CFG->debugsessionlock)) { return; } $SESSION->recentsessionlocks = self::get_recent_session_locks(); array_push($SESSION->recentsessionlocks, $sessionlock); self::cleanup_recent_session_locks(); }
php
public static function update_recent_session_locks($sessionlock) { global $CFG, $SESSION; if (empty($CFG->debugsessionlock)) { return; } $SESSION->recentsessionlocks = self::get_recent_session_locks(); array_push($SESSION->recentsessionlocks, $sessionlock); self::cleanup_recent_session_locks(); }
[ "public", "static", "function", "update_recent_session_locks", "(", "$", "sessionlock", ")", "{", "global", "$", "CFG", ",", "$", "SESSION", ";", "if", "(", "empty", "(", "$", "CFG", "->", "debugsessionlock", ")", ")", "{", "return", ";", "}", "$", "SESSION", "->", "recentsessionlocks", "=", "self", "::", "get_recent_session_locks", "(", ")", ";", "array_push", "(", "$", "SESSION", "->", "recentsessionlocks", ",", "$", "sessionlock", ")", ";", "self", "::", "cleanup_recent_session_locks", "(", ")", ";", "}" ]
Updates the recent session locks. This function will store session lock info of all the pages visited. @param array $sessionlock Session lock array.
[ "Updates", "the", "recent", "session", "locks", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1090-L1101
220,241
moodle/moodle
lib/classes/session/manager.php
manager.cleanup_recent_session_locks
public static function cleanup_recent_session_locks() { global $SESSION; $locks = self::get_recent_session_locks(); if (count($locks) > 2) { for ($i = count($locks) - 1; $i > 0; $i--) { // Calculate the gap between session locks. $gap = $locks[$i]['released'] - $locks[$i - 1]['start']; if ($gap >= 10) { // Remove previous locks if the gap is 10 seconds or more. $SESSION->recentsessionlocks = array_slice($locks, $i); break; } } } }
php
public static function cleanup_recent_session_locks() { global $SESSION; $locks = self::get_recent_session_locks(); if (count($locks) > 2) { for ($i = count($locks) - 1; $i > 0; $i--) { // Calculate the gap between session locks. $gap = $locks[$i]['released'] - $locks[$i - 1]['start']; if ($gap >= 10) { // Remove previous locks if the gap is 10 seconds or more. $SESSION->recentsessionlocks = array_slice($locks, $i); break; } } } }
[ "public", "static", "function", "cleanup_recent_session_locks", "(", ")", "{", "global", "$", "SESSION", ";", "$", "locks", "=", "self", "::", "get_recent_session_locks", "(", ")", ";", "if", "(", "count", "(", "$", "locks", ")", ">", "2", ")", "{", "for", "(", "$", "i", "=", "count", "(", "$", "locks", ")", "-", "1", ";", "$", "i", ">", "0", ";", "$", "i", "--", ")", "{", "// Calculate the gap between session locks.", "$", "gap", "=", "$", "locks", "[", "$", "i", "]", "[", "'released'", "]", "-", "$", "locks", "[", "$", "i", "-", "1", "]", "[", "'start'", "]", ";", "if", "(", "$", "gap", ">=", "10", ")", "{", "// Remove previous locks if the gap is 10 seconds or more.", "$", "SESSION", "->", "recentsessionlocks", "=", "array_slice", "(", "$", "locks", ",", "$", "i", ")", ";", "break", ";", "}", "}", "}", "}" ]
Reset recent session locks array if there is a 10 seconds time gap. @return array Recent session locks array.
[ "Reset", "recent", "session", "locks", "array", "if", "there", "is", "a", "10", "seconds", "time", "gap", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1108-L1123
220,242
moodle/moodle
lib/classes/session/manager.php
manager.get_locked_page_at
public static function get_locked_page_at($time) { $recentsessionlocks = self::get_recent_session_locks(); foreach ($recentsessionlocks as $recentsessionlock) { if ($time >= $recentsessionlock['gained'] && $time <= $recentsessionlock['released']) { return $recentsessionlock; } } }
php
public static function get_locked_page_at($time) { $recentsessionlocks = self::get_recent_session_locks(); foreach ($recentsessionlocks as $recentsessionlock) { if ($time >= $recentsessionlock['gained'] && $time <= $recentsessionlock['released']) { return $recentsessionlock; } } }
[ "public", "static", "function", "get_locked_page_at", "(", "$", "time", ")", "{", "$", "recentsessionlocks", "=", "self", "::", "get_recent_session_locks", "(", ")", ";", "foreach", "(", "$", "recentsessionlocks", "as", "$", "recentsessionlock", ")", "{", "if", "(", "$", "time", ">=", "$", "recentsessionlock", "[", "'gained'", "]", "&&", "$", "time", "<=", "$", "recentsessionlock", "[", "'released'", "]", ")", "{", "return", "$", "recentsessionlock", ";", "}", "}", "}" ]
Get the page that blocks other pages at a specific timestamp. Look for a page whose lock was gained before that timestamp, and released after that timestamp. @param float $time Time before session lock starts. @return array|null
[ "Get", "the", "page", "that", "blocks", "other", "pages", "at", "a", "specific", "timestamp", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1133-L1141
220,243
moodle/moodle
lib/classes/session/manager.php
manager.display_blocking_page
public static function display_blocking_page() { global $PERF; $page = self::get_locked_page_at($PERF->sessionlock['start']); $output = "Script ".me()." was blocked for "; $output .= number_format($PERF->sessionlock['wait'], 3); if ($page != null) { $output .= " second(s) by script: "; $output .= $page['url']; } else { $output .= " second(s) by an unknown script."; } return $output; }
php
public static function display_blocking_page() { global $PERF; $page = self::get_locked_page_at($PERF->sessionlock['start']); $output = "Script ".me()." was blocked for "; $output .= number_format($PERF->sessionlock['wait'], 3); if ($page != null) { $output .= " second(s) by script: "; $output .= $page['url']; } else { $output .= " second(s) by an unknown script."; } return $output; }
[ "public", "static", "function", "display_blocking_page", "(", ")", "{", "global", "$", "PERF", ";", "$", "page", "=", "self", "::", "get_locked_page_at", "(", "$", "PERF", "->", "sessionlock", "[", "'start'", "]", ")", ";", "$", "output", "=", "\"Script \"", ".", "me", "(", ")", ".", "\" was blocked for \"", ";", "$", "output", ".=", "number_format", "(", "$", "PERF", "->", "sessionlock", "[", "'wait'", "]", ",", "3", ")", ";", "if", "(", "$", "page", "!=", "null", ")", "{", "$", "output", ".=", "\" second(s) by script: \"", ";", "$", "output", ".=", "$", "page", "[", "'url'", "]", ";", "}", "else", "{", "$", "output", ".=", "\" second(s) by an unknown script.\"", ";", "}", "return", "$", "output", ";", "}" ]
Display the page which blocks other pages. @return string
[ "Display", "the", "page", "which", "blocks", "other", "pages", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1148-L1162
220,244
moodle/moodle
lib/classes/session/manager.php
manager.sessionlock_debugging
public static function sessionlock_debugging() { global $CFG, $PERF; if (!empty($CFG->debugsessionlock)) { if (isset($PERF->sessionlock['held']) && $PERF->sessionlock['held'] > $CFG->debugsessionlock) { debugging("Script ".me()." locked the session for ".number_format($PERF->sessionlock['held'], 3) ." seconds, it should close the session using \core\session\manager::write_close().", DEBUG_NORMAL); } if (isset($PERF->sessionlock['wait']) && $PERF->sessionlock['wait'] > $CFG->debugsessionlock) { $output = self::display_blocking_page(); debugging($output, DEBUG_DEVELOPER); } } }
php
public static function sessionlock_debugging() { global $CFG, $PERF; if (!empty($CFG->debugsessionlock)) { if (isset($PERF->sessionlock['held']) && $PERF->sessionlock['held'] > $CFG->debugsessionlock) { debugging("Script ".me()." locked the session for ".number_format($PERF->sessionlock['held'], 3) ." seconds, it should close the session using \core\session\manager::write_close().", DEBUG_NORMAL); } if (isset($PERF->sessionlock['wait']) && $PERF->sessionlock['wait'] > $CFG->debugsessionlock) { $output = self::display_blocking_page(); debugging($output, DEBUG_DEVELOPER); } } }
[ "public", "static", "function", "sessionlock_debugging", "(", ")", "{", "global", "$", "CFG", ",", "$", "PERF", ";", "if", "(", "!", "empty", "(", "$", "CFG", "->", "debugsessionlock", ")", ")", "{", "if", "(", "isset", "(", "$", "PERF", "->", "sessionlock", "[", "'held'", "]", ")", "&&", "$", "PERF", "->", "sessionlock", "[", "'held'", "]", ">", "$", "CFG", "->", "debugsessionlock", ")", "{", "debugging", "(", "\"Script \"", ".", "me", "(", ")", ".", "\" locked the session for \"", ".", "number_format", "(", "$", "PERF", "->", "sessionlock", "[", "'held'", "]", ",", "3", ")", ".", "\" seconds, it should close the session using \\core\\session\\manager::write_close().\"", ",", "DEBUG_NORMAL", ")", ";", "}", "if", "(", "isset", "(", "$", "PERF", "->", "sessionlock", "[", "'wait'", "]", ")", "&&", "$", "PERF", "->", "sessionlock", "[", "'wait'", "]", ">", "$", "CFG", "->", "debugsessionlock", ")", "{", "$", "output", "=", "self", "::", "display_blocking_page", "(", ")", ";", "debugging", "(", "$", "output", ",", "DEBUG_DEVELOPER", ")", ";", "}", "}", "}" ]
Display debugging info about slow and blocked script.
[ "Display", "debugging", "info", "about", "slow", "and", "blocked", "script", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/session/manager.php#L1181-L1195
220,245
moodle/moodle
question/type/randomsamatch/questiontype.php
qtype_randomsamatch.get_available_saquestions_from_category
public function get_available_saquestions_from_category($categoryid, $subcategories) { if (isset($this->availablesaquestionsbycategory[$categoryid][$subcategories])) { return $this->availablesaquestionsbycategory[$categoryid][$subcategories]; } if ($subcategories) { $categoryids = question_categorylist($categoryid); } else { $categoryids = array($categoryid); } $questionids = question_bank::get_finder()->get_questions_from_categories( $categoryids, "qtype = 'shortanswer'"); $this->availablesaquestionsbycategory[$categoryid][$subcategories] = $questionids; return $questionids; }
php
public function get_available_saquestions_from_category($categoryid, $subcategories) { if (isset($this->availablesaquestionsbycategory[$categoryid][$subcategories])) { return $this->availablesaquestionsbycategory[$categoryid][$subcategories]; } if ($subcategories) { $categoryids = question_categorylist($categoryid); } else { $categoryids = array($categoryid); } $questionids = question_bank::get_finder()->get_questions_from_categories( $categoryids, "qtype = 'shortanswer'"); $this->availablesaquestionsbycategory[$categoryid][$subcategories] = $questionids; return $questionids; }
[ "public", "function", "get_available_saquestions_from_category", "(", "$", "categoryid", ",", "$", "subcategories", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "availablesaquestionsbycategory", "[", "$", "categoryid", "]", "[", "$", "subcategories", "]", ")", ")", "{", "return", "$", "this", "->", "availablesaquestionsbycategory", "[", "$", "categoryid", "]", "[", "$", "subcategories", "]", ";", "}", "if", "(", "$", "subcategories", ")", "{", "$", "categoryids", "=", "question_categorylist", "(", "$", "categoryid", ")", ";", "}", "else", "{", "$", "categoryids", "=", "array", "(", "$", "categoryid", ")", ";", "}", "$", "questionids", "=", "question_bank", "::", "get_finder", "(", ")", "->", "get_questions_from_categories", "(", "$", "categoryids", ",", "\"qtype = 'shortanswer'\"", ")", ";", "$", "this", "->", "availablesaquestionsbycategory", "[", "$", "categoryid", "]", "[", "$", "subcategories", "]", "=", "$", "questionids", ";", "return", "$", "questionids", ";", "}" ]
Get all the usable shortanswer questions from a particular question category. @param integer $categoryid the id of a question category. @param bool $subcategories whether to include questions from subcategories. @return array of question records.
[ "Get", "all", "the", "usable", "shortanswer", "questions", "from", "a", "particular", "question", "category", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/randomsamatch/questiontype.php#L145-L160
220,246
moodle/moodle
question/type/randomsamatch/questiontype.php
qtype_randomsamatch.import_from_xml
public function import_from_xml($xml, $fromform, qformat_xml $format, $extra=null) { // Return if data type is not our own one. if (!isset($xml['@']['type']) || $xml['@']['type'] != $this->name()) { return false; } // Import the common question headers and set the corresponding field. $fromform = $format->import_headers($xml); $fromform->qtype = $this->name(); $format->import_combined_feedback($fromform, $xml, true); $format->import_hints($fromform, $xml, true); $extras = $this->extra_question_fields(); array_shift($extras); foreach ($extras as $extra) { $fromform->$extra = $format->getpath($xml, array('#', $extra, 0, '#'), '', true); } return $fromform; }
php
public function import_from_xml($xml, $fromform, qformat_xml $format, $extra=null) { // Return if data type is not our own one. if (!isset($xml['@']['type']) || $xml['@']['type'] != $this->name()) { return false; } // Import the common question headers and set the corresponding field. $fromform = $format->import_headers($xml); $fromform->qtype = $this->name(); $format->import_combined_feedback($fromform, $xml, true); $format->import_hints($fromform, $xml, true); $extras = $this->extra_question_fields(); array_shift($extras); foreach ($extras as $extra) { $fromform->$extra = $format->getpath($xml, array('#', $extra, 0, '#'), '', true); } return $fromform; }
[ "public", "function", "import_from_xml", "(", "$", "xml", ",", "$", "fromform", ",", "qformat_xml", "$", "format", ",", "$", "extra", "=", "null", ")", "{", "// Return if data type is not our own one.", "if", "(", "!", "isset", "(", "$", "xml", "[", "'@'", "]", "[", "'type'", "]", ")", "||", "$", "xml", "[", "'@'", "]", "[", "'type'", "]", "!=", "$", "this", "->", "name", "(", ")", ")", "{", "return", "false", ";", "}", "// Import the common question headers and set the corresponding field.", "$", "fromform", "=", "$", "format", "->", "import_headers", "(", "$", "xml", ")", ";", "$", "fromform", "->", "qtype", "=", "$", "this", "->", "name", "(", ")", ";", "$", "format", "->", "import_combined_feedback", "(", "$", "fromform", ",", "$", "xml", ",", "true", ")", ";", "$", "format", "->", "import_hints", "(", "$", "fromform", ",", "$", "xml", ",", "true", ")", ";", "$", "extras", "=", "$", "this", "->", "extra_question_fields", "(", ")", ";", "array_shift", "(", "$", "extras", ")", ";", "foreach", "(", "$", "extras", "as", "$", "extra", ")", "{", "$", "fromform", "->", "$", "extra", "=", "$", "format", "->", "getpath", "(", "$", "xml", ",", "array", "(", "'#'", ",", "$", "extra", ",", "0", ",", "'#'", ")", ",", "''", ",", "true", ")", ";", "}", "return", "$", "fromform", ";", "}" ]
Imports the question from Moodle XML format. @param array $xml structure containing the XML data @param object $fromform question object to fill: ignored by this function (assumed to be null) @param qformat_xml $format format class exporting the question @param object $extra extra information (not required for importing this question in this format) @return object question object
[ "Imports", "the", "question", "from", "Moodle", "XML", "format", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/randomsamatch/questiontype.php#L194-L213
220,247
moodle/moodle
question/type/randomsamatch/questiontype.php
qtype_randomsamatch.export_to_xml
public function export_to_xml($question, qformat_xml $format, $extra=null) { $expout = ''; $expout .= $format->write_combined_feedback($question->options, $question->id, $question->contextid); $extraquestionfields = $this->extra_question_fields(); array_shift($extraquestionfields); foreach ($extraquestionfields as $extra) { $expout .= " <{$extra}>" . $question->options->$extra . "</{$extra}>\n"; } return $expout; }
php
public function export_to_xml($question, qformat_xml $format, $extra=null) { $expout = ''; $expout .= $format->write_combined_feedback($question->options, $question->id, $question->contextid); $extraquestionfields = $this->extra_question_fields(); array_shift($extraquestionfields); foreach ($extraquestionfields as $extra) { $expout .= " <{$extra}>" . $question->options->$extra . "</{$extra}>\n"; } return $expout; }
[ "public", "function", "export_to_xml", "(", "$", "question", ",", "qformat_xml", "$", "format", ",", "$", "extra", "=", "null", ")", "{", "$", "expout", "=", "''", ";", "$", "expout", ".=", "$", "format", "->", "write_combined_feedback", "(", "$", "question", "->", "options", ",", "$", "question", "->", "id", ",", "$", "question", "->", "contextid", ")", ";", "$", "extraquestionfields", "=", "$", "this", "->", "extra_question_fields", "(", ")", ";", "array_shift", "(", "$", "extraquestionfields", ")", ";", "foreach", "(", "$", "extraquestionfields", "as", "$", "extra", ")", "{", "$", "expout", ".=", "\" <{$extra}>\"", ".", "$", "question", "->", "options", "->", "$", "extra", ".", "\"</{$extra}>\\n\"", ";", "}", "return", "$", "expout", ";", "}" ]
Exports the question to Moodle XML format. @param object $question question to be exported into XML format @param qformat_xml $format format class exporting the question @param object $extra extra information (not required for exporting this question in this format) @return string containing the question data in XML format
[ "Exports", "the", "question", "to", "Moodle", "XML", "format", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/randomsamatch/questiontype.php#L223-L234
220,248
moodle/moodle
mod/forum/classes/output/email/renderer.php
renderer.format_message_text
public function format_message_text($cm, $post) { $context = \context_module::instance($cm->id); $message = file_rewrite_pluginfile_urls( $post->message, 'pluginfile.php', $context->id, 'mod_forum', 'post', $post->id, [ 'includetoken' => true, ]); $options = new \stdClass(); $options->para = true; $options->context = $context; return format_text($message, $post->messageformat, $options); }
php
public function format_message_text($cm, $post) { $context = \context_module::instance($cm->id); $message = file_rewrite_pluginfile_urls( $post->message, 'pluginfile.php', $context->id, 'mod_forum', 'post', $post->id, [ 'includetoken' => true, ]); $options = new \stdClass(); $options->para = true; $options->context = $context; return format_text($message, $post->messageformat, $options); }
[ "public", "function", "format_message_text", "(", "$", "cm", ",", "$", "post", ")", "{", "$", "context", "=", "\\", "context_module", "::", "instance", "(", "$", "cm", "->", "id", ")", ";", "$", "message", "=", "file_rewrite_pluginfile_urls", "(", "$", "post", "->", "message", ",", "'pluginfile.php'", ",", "$", "context", "->", "id", ",", "'mod_forum'", ",", "'post'", ",", "$", "post", "->", "id", ",", "[", "'includetoken'", "=>", "true", ",", "]", ")", ";", "$", "options", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "options", "->", "para", "=", "true", ";", "$", "options", "->", "context", "=", "$", "context", ";", "return", "format_text", "(", "$", "message", ",", "$", "post", "->", "messageformat", ",", "$", "options", ")", ";", "}" ]
The HTML version of the e-mail message. @param \stdClass $cm @param \stdClass $post @return string
[ "The", "HTML", "version", "of", "the", "e", "-", "mail", "message", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/forum/classes/output/email/renderer.php#L57-L73
220,249
moodle/moodle
user/edit_form.php
user_edit_form.validation
public function validation($usernew, $files) { global $CFG, $DB; $errors = parent::validation($usernew, $files); $usernew = (object)$usernew; $user = $DB->get_record('user', array('id' => $usernew->id)); // Validate email. if (!isset($usernew->email)) { // Mail not confirmed yet. } else if (!validate_email($usernew->email)) { $errors['email'] = get_string('invalidemail'); } else if (($usernew->email !== $user->email) and empty($CFG->allowaccountssameemail) and $DB->record_exists('user', array('email' => $usernew->email, 'mnethostid' => $CFG->mnet_localhost_id))) { $errors['email'] = get_string('emailexists'); } if (isset($usernew->email) and $usernew->email === $user->email and over_bounce_threshold($user)) { $errors['email'] = get_string('toomanybounces'); } if (isset($usernew->email) and !empty($CFG->verifychangedemail) and !isset($errors['email']) and !has_capability('moodle/user:update', context_system::instance())) { $errorstr = email_is_not_allowed($usernew->email); if ($errorstr !== false) { $errors['email'] = $errorstr; } } // Next the customisable profile fields. $errors += profile_validation($usernew, $files); return $errors; }
php
public function validation($usernew, $files) { global $CFG, $DB; $errors = parent::validation($usernew, $files); $usernew = (object)$usernew; $user = $DB->get_record('user', array('id' => $usernew->id)); // Validate email. if (!isset($usernew->email)) { // Mail not confirmed yet. } else if (!validate_email($usernew->email)) { $errors['email'] = get_string('invalidemail'); } else if (($usernew->email !== $user->email) and empty($CFG->allowaccountssameemail) and $DB->record_exists('user', array('email' => $usernew->email, 'mnethostid' => $CFG->mnet_localhost_id))) { $errors['email'] = get_string('emailexists'); } if (isset($usernew->email) and $usernew->email === $user->email and over_bounce_threshold($user)) { $errors['email'] = get_string('toomanybounces'); } if (isset($usernew->email) and !empty($CFG->verifychangedemail) and !isset($errors['email']) and !has_capability('moodle/user:update', context_system::instance())) { $errorstr = email_is_not_allowed($usernew->email); if ($errorstr !== false) { $errors['email'] = $errorstr; } } // Next the customisable profile fields. $errors += profile_validation($usernew, $files); return $errors; }
[ "public", "function", "validation", "(", "$", "usernew", ",", "$", "files", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "$", "errors", "=", "parent", "::", "validation", "(", "$", "usernew", ",", "$", "files", ")", ";", "$", "usernew", "=", "(", "object", ")", "$", "usernew", ";", "$", "user", "=", "$", "DB", "->", "get_record", "(", "'user'", ",", "array", "(", "'id'", "=>", "$", "usernew", "->", "id", ")", ")", ";", "// Validate email.", "if", "(", "!", "isset", "(", "$", "usernew", "->", "email", ")", ")", "{", "// Mail not confirmed yet.", "}", "else", "if", "(", "!", "validate_email", "(", "$", "usernew", "->", "email", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "get_string", "(", "'invalidemail'", ")", ";", "}", "else", "if", "(", "(", "$", "usernew", "->", "email", "!==", "$", "user", "->", "email", ")", "and", "empty", "(", "$", "CFG", "->", "allowaccountssameemail", ")", "and", "$", "DB", "->", "record_exists", "(", "'user'", ",", "array", "(", "'email'", "=>", "$", "usernew", "->", "email", ",", "'mnethostid'", "=>", "$", "CFG", "->", "mnet_localhost_id", ")", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "get_string", "(", "'emailexists'", ")", ";", "}", "if", "(", "isset", "(", "$", "usernew", "->", "email", ")", "and", "$", "usernew", "->", "email", "===", "$", "user", "->", "email", "and", "over_bounce_threshold", "(", "$", "user", ")", ")", "{", "$", "errors", "[", "'email'", "]", "=", "get_string", "(", "'toomanybounces'", ")", ";", "}", "if", "(", "isset", "(", "$", "usernew", "->", "email", ")", "and", "!", "empty", "(", "$", "CFG", "->", "verifychangedemail", ")", "and", "!", "isset", "(", "$", "errors", "[", "'email'", "]", ")", "and", "!", "has_capability", "(", "'moodle/user:update'", ",", "context_system", "::", "instance", "(", ")", ")", ")", "{", "$", "errorstr", "=", "email_is_not_allowed", "(", "$", "usernew", "->", "email", ")", ";", "if", "(", "$", "errorstr", "!==", "false", ")", "{", "$", "errors", "[", "'email'", "]", "=", "$", "errorstr", ";", "}", "}", "// Next the customisable profile fields.", "$", "errors", "+=", "profile_validation", "(", "$", "usernew", ",", "$", "files", ")", ";", "return", "$", "errors", ";", "}" ]
Validate incoming form data. @param array $usernew @param array $files @return array
[ "Validate", "incoming", "form", "data", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/user/edit_form.php#L200-L234
220,250
moodle/moodle
message/output/email/classes/task/send_email_task.php
send_email_task.execute
public function execute() { global $DB, $PAGE; // Get the maximum id we are going to use. // We use this as records may be added to the table while this task runs. $this->maxid = $DB->get_field_sql("SELECT MAX(id) FROM {message_email_messages}"); // We are going to send these emails from 'noreplyaddress'. $noreplyuser = \core_user::get_noreply_user(); // The renderers used for sending emails. $htmlrenderer = $PAGE->get_renderer('message_email', 'email', 'htmlemail'); $textrenderer = $PAGE->get_renderer('message_email', 'email', 'textemail'); // Keep track of which emails failed to send. $users = $this->get_unique_users(); foreach ($users as $user) { cron_setup_user($user); $hascontent = false; $renderable = new \message_email\output\email_digest($user); $conversations = $this->get_conversations_for_user($user->id); foreach ($conversations as $conversation) { $renderable->add_conversation($conversation); $messages = $this->get_users_messages_for_conversation($conversation->id, $user->id); if ($messages->valid()) { $hascontent = true; foreach ($messages as $message) { $renderable->add_message($message); } } $messages->close(); } $conversations->close(); if ($hascontent) { $subject = get_string('emaildigestsubject', 'message_email'); $message = $textrenderer->render($renderable); $messagehtml = $htmlrenderer->render($renderable); if (email_to_user($user, $noreplyuser, $subject, $message, $messagehtml)) { $DB->delete_records_select('message_email_messages', 'useridto = ? AND id <= ?', [$user->id, $this->maxid]); } } } cron_setup_user(); $users->close(); }
php
public function execute() { global $DB, $PAGE; // Get the maximum id we are going to use. // We use this as records may be added to the table while this task runs. $this->maxid = $DB->get_field_sql("SELECT MAX(id) FROM {message_email_messages}"); // We are going to send these emails from 'noreplyaddress'. $noreplyuser = \core_user::get_noreply_user(); // The renderers used for sending emails. $htmlrenderer = $PAGE->get_renderer('message_email', 'email', 'htmlemail'); $textrenderer = $PAGE->get_renderer('message_email', 'email', 'textemail'); // Keep track of which emails failed to send. $users = $this->get_unique_users(); foreach ($users as $user) { cron_setup_user($user); $hascontent = false; $renderable = new \message_email\output\email_digest($user); $conversations = $this->get_conversations_for_user($user->id); foreach ($conversations as $conversation) { $renderable->add_conversation($conversation); $messages = $this->get_users_messages_for_conversation($conversation->id, $user->id); if ($messages->valid()) { $hascontent = true; foreach ($messages as $message) { $renderable->add_message($message); } } $messages->close(); } $conversations->close(); if ($hascontent) { $subject = get_string('emaildigestsubject', 'message_email'); $message = $textrenderer->render($renderable); $messagehtml = $htmlrenderer->render($renderable); if (email_to_user($user, $noreplyuser, $subject, $message, $messagehtml)) { $DB->delete_records_select('message_email_messages', 'useridto = ? AND id <= ?', [$user->id, $this->maxid]); } } } cron_setup_user(); $users->close(); }
[ "public", "function", "execute", "(", ")", "{", "global", "$", "DB", ",", "$", "PAGE", ";", "// Get the maximum id we are going to use.", "// We use this as records may be added to the table while this task runs.", "$", "this", "->", "maxid", "=", "$", "DB", "->", "get_field_sql", "(", "\"SELECT MAX(id) FROM {message_email_messages}\"", ")", ";", "// We are going to send these emails from 'noreplyaddress'.", "$", "noreplyuser", "=", "\\", "core_user", "::", "get_noreply_user", "(", ")", ";", "// The renderers used for sending emails.", "$", "htmlrenderer", "=", "$", "PAGE", "->", "get_renderer", "(", "'message_email'", ",", "'email'", ",", "'htmlemail'", ")", ";", "$", "textrenderer", "=", "$", "PAGE", "->", "get_renderer", "(", "'message_email'", ",", "'email'", ",", "'textemail'", ")", ";", "// Keep track of which emails failed to send.", "$", "users", "=", "$", "this", "->", "get_unique_users", "(", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "cron_setup_user", "(", "$", "user", ")", ";", "$", "hascontent", "=", "false", ";", "$", "renderable", "=", "new", "\\", "message_email", "\\", "output", "\\", "email_digest", "(", "$", "user", ")", ";", "$", "conversations", "=", "$", "this", "->", "get_conversations_for_user", "(", "$", "user", "->", "id", ")", ";", "foreach", "(", "$", "conversations", "as", "$", "conversation", ")", "{", "$", "renderable", "->", "add_conversation", "(", "$", "conversation", ")", ";", "$", "messages", "=", "$", "this", "->", "get_users_messages_for_conversation", "(", "$", "conversation", "->", "id", ",", "$", "user", "->", "id", ")", ";", "if", "(", "$", "messages", "->", "valid", "(", ")", ")", "{", "$", "hascontent", "=", "true", ";", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "$", "renderable", "->", "add_message", "(", "$", "message", ")", ";", "}", "}", "$", "messages", "->", "close", "(", ")", ";", "}", "$", "conversations", "->", "close", "(", ")", ";", "if", "(", "$", "hascontent", ")", "{", "$", "subject", "=", "get_string", "(", "'emaildigestsubject'", ",", "'message_email'", ")", ";", "$", "message", "=", "$", "textrenderer", "->", "render", "(", "$", "renderable", ")", ";", "$", "messagehtml", "=", "$", "htmlrenderer", "->", "render", "(", "$", "renderable", ")", ";", "if", "(", "email_to_user", "(", "$", "user", ",", "$", "noreplyuser", ",", "$", "subject", ",", "$", "message", ",", "$", "messagehtml", ")", ")", "{", "$", "DB", "->", "delete_records_select", "(", "'message_email_messages'", ",", "'useridto = ? AND id <= ?'", ",", "[", "$", "user", "->", "id", ",", "$", "this", "->", "maxid", "]", ")", ";", "}", "}", "}", "cron_setup_user", "(", ")", ";", "$", "users", "->", "close", "(", ")", ";", "}" ]
Send out emails.
[ "Send", "out", "emails", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/message/output/email/classes/task/send_email_task.php#L59-L104
220,251
moodle/moodle
message/output/email/classes/task/send_email_task.php
send_email_task.get_unique_users
private function get_unique_users() : moodle_recordset { global $DB; $subsql = 'SELECT DISTINCT(useridto) as id FROM {message_email_messages} WHERE id <= ?'; $sql = "SELECT * FROM {user} u WHERE id IN ($subsql)"; return $DB->get_recordset_sql($sql, [$this->maxid]); }
php
private function get_unique_users() : moodle_recordset { global $DB; $subsql = 'SELECT DISTINCT(useridto) as id FROM {message_email_messages} WHERE id <= ?'; $sql = "SELECT * FROM {user} u WHERE id IN ($subsql)"; return $DB->get_recordset_sql($sql, [$this->maxid]); }
[ "private", "function", "get_unique_users", "(", ")", ":", "moodle_recordset", "{", "global", "$", "DB", ";", "$", "subsql", "=", "'SELECT DISTINCT(useridto) as id\n FROM {message_email_messages}\n WHERE id <= ?'", ";", "$", "sql", "=", "\"SELECT *\n FROM {user} u\n WHERE id IN ($subsql)\"", ";", "return", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "[", "$", "this", "->", "maxid", "]", ")", ";", "}" ]
Returns an array of users in the given conversation. @return moodle_recordset A moodle_recordset instance.
[ "Returns", "an", "array", "of", "users", "in", "the", "given", "conversation", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/message/output/email/classes/task/send_email_task.php#L111-L123
220,252
moodle/moodle
message/output/email/classes/task/send_email_task.php
send_email_task.get_conversations_for_user
private function get_conversations_for_user(int $userid) : moodle_recordset { global $DB; // We shouldn't be joining directly on the group table as group // conversations may (in the future) be something created that // isn't related to an actual group in a course. However, for // now this will have to do before 3.7 code freeze. // See related MDL-63814. $sql = "SELECT DISTINCT mc.id, mc.name, c.id as courseid, c.fullname as coursename, g.id as groupid, g.picture, g.hidepicture FROM {message_conversations} mc JOIN {groups} g ON mc.itemid = g.id JOIN {course} c ON g.courseid = c.id JOIN {message_email_messages} mem ON mem.conversationid = mc.id WHERE mem.useridto = ? AND mem.id <= ?"; return $DB->get_recordset_sql($sql, [$userid, $this->maxid]); }
php
private function get_conversations_for_user(int $userid) : moodle_recordset { global $DB; // We shouldn't be joining directly on the group table as group // conversations may (in the future) be something created that // isn't related to an actual group in a course. However, for // now this will have to do before 3.7 code freeze. // See related MDL-63814. $sql = "SELECT DISTINCT mc.id, mc.name, c.id as courseid, c.fullname as coursename, g.id as groupid, g.picture, g.hidepicture FROM {message_conversations} mc JOIN {groups} g ON mc.itemid = g.id JOIN {course} c ON g.courseid = c.id JOIN {message_email_messages} mem ON mem.conversationid = mc.id WHERE mem.useridto = ? AND mem.id <= ?"; return $DB->get_recordset_sql($sql, [$userid, $this->maxid]); }
[ "private", "function", "get_conversations_for_user", "(", "int", "$", "userid", ")", ":", "moodle_recordset", "{", "global", "$", "DB", ";", "// We shouldn't be joining directly on the group table as group", "// conversations may (in the future) be something created that", "// isn't related to an actual group in a course. However, for", "// now this will have to do before 3.7 code freeze.", "// See related MDL-63814.", "$", "sql", "=", "\"SELECT DISTINCT mc.id, mc.name, c.id as courseid, c.fullname as coursename, g.id as groupid,\n g.picture, g.hidepicture\n FROM {message_conversations} mc\n JOIN {groups} g\n ON mc.itemid = g.id\n JOIN {course} c\n ON g.courseid = c.id\n JOIN {message_email_messages} mem\n ON mem.conversationid = mc.id\n WHERE mem.useridto = ?\n AND mem.id <= ?\"", ";", "return", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "[", "$", "userid", ",", "$", "this", "->", "maxid", "]", ")", ";", "}" ]
Returns an array of unique conversations that require processing. @param int $userid The ID of the user we are sending a digest to. @return moodle_recordset A moodle_recordset instance.
[ "Returns", "an", "array", "of", "unique", "conversations", "that", "require", "processing", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/message/output/email/classes/task/send_email_task.php#L131-L152
220,253
moodle/moodle
message/output/email/classes/task/send_email_task.php
send_email_task.get_users_messages_for_conversation
protected function get_users_messages_for_conversation(int $conversationid, int $userid) : moodle_recordset { global $DB; $usernamefields = \user_picture::fields('u'); $sql = "SELECT $usernamefields, m.* FROM {messages} m JOIN {user} u ON u.id = m.useridfrom JOIN {message_email_messages} mem ON mem.messageid = m.id WHERE mem.useridto = ? AND mem.conversationid = ? AND mem.id <= ?"; return $DB->get_recordset_sql($sql, [$userid, $conversationid, $this->maxid]); }
php
protected function get_users_messages_for_conversation(int $conversationid, int $userid) : moodle_recordset { global $DB; $usernamefields = \user_picture::fields('u'); $sql = "SELECT $usernamefields, m.* FROM {messages} m JOIN {user} u ON u.id = m.useridfrom JOIN {message_email_messages} mem ON mem.messageid = m.id WHERE mem.useridto = ? AND mem.conversationid = ? AND mem.id <= ?"; return $DB->get_recordset_sql($sql, [$userid, $conversationid, $this->maxid]); }
[ "protected", "function", "get_users_messages_for_conversation", "(", "int", "$", "conversationid", ",", "int", "$", "userid", ")", ":", "moodle_recordset", "{", "global", "$", "DB", ";", "$", "usernamefields", "=", "\\", "user_picture", "::", "fields", "(", "'u'", ")", ";", "$", "sql", "=", "\"SELECT $usernamefields, m.*\n FROM {messages} m\n JOIN {user} u\n ON u.id = m.useridfrom\n JOIN {message_email_messages} mem\n ON mem.messageid = m.id\n WHERE mem.useridto = ?\n AND mem.conversationid = ?\n AND mem.id <= ?\"", ";", "return", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "[", "$", "userid", ",", "$", "conversationid", ",", "$", "this", "->", "maxid", "]", ")", ";", "}" ]
Returns the messages to send to a user for a given conversation @param int $conversationid @param int $userid @return moodle_recordset A moodle_recordset instance.
[ "Returns", "the", "messages", "to", "send", "to", "a", "user", "for", "a", "given", "conversation" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/message/output/email/classes/task/send_email_task.php#L161-L176
220,254
moodle/moodle
lib/adodb/perf/perf-db2.inc.php
perf_db2.Tables
function Tables($throwaway=0) { $rs = $this->conn->Execute("select tabschema,tabname,card as rows, npages pages_used,fpages pages_allocated, tbspace tablespace from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2"); return rs2html($rs,false,false,false,false); }
php
function Tables($throwaway=0) { $rs = $this->conn->Execute("select tabschema,tabname,card as rows, npages pages_used,fpages pages_allocated, tbspace tablespace from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2"); return rs2html($rs,false,false,false,false); }
[ "function", "Tables", "(", "$", "throwaway", "=", "0", ")", "{", "$", "rs", "=", "$", "this", "->", "conn", "->", "Execute", "(", "\"select tabschema,tabname,card as rows,\n\t\t\tnpages pages_used,fpages pages_allocated, tbspace tablespace\n\t\t\tfrom syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2\"", ")", ";", "return", "rs2html", "(", "$", "rs", ",", "false", ",", "false", ",", "false", ",", "false", ")", ";", "}" ]
Gets a list of tables @param int $throwaway discarded variable to match the parent method @return string The formatted table list
[ "Gets", "a", "list", "of", "tables" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/adodb/perf/perf-db2.inc.php#L101-L107
220,255
moodle/moodle
lib/form/group.php
MoodleQuickForm_group.setElements
function setElements($elements){ parent::setElements($elements); foreach ($this->_elements as $element){ if (method_exists($element, 'setHiddenLabel')){ $element->setHiddenLabel(true); } } }
php
function setElements($elements){ parent::setElements($elements); foreach ($this->_elements as $element){ if (method_exists($element, 'setHiddenLabel')){ $element->setHiddenLabel(true); } } }
[ "function", "setElements", "(", "$", "elements", ")", "{", "parent", "::", "setElements", "(", "$", "elements", ")", ";", "foreach", "(", "$", "this", "->", "_elements", "as", "$", "element", ")", "{", "if", "(", "method_exists", "(", "$", "element", ",", "'setHiddenLabel'", ")", ")", "{", "$", "element", "->", "setHiddenLabel", "(", "true", ")", ";", "}", "}", "}" ]
Sets the grouped elements and hides label @param array $elements
[ "Sets", "the", "grouped", "elements", "and", "hides", "label" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/form/group.php#L112-L119
220,256
moodle/moodle
lib/form/group.php
MoodleQuickForm_group.validateSubmitValue
public function validateSubmitValue($values) { foreach ($this->_elements as $element) { if (method_exists($element, 'validateSubmitValue')) { $value = $values[$element->getName()] ?? null; $result = $element->validateSubmitValue($value); if (!empty($result) && is_string($result)) { return $result; } } } }
php
public function validateSubmitValue($values) { foreach ($this->_elements as $element) { if (method_exists($element, 'validateSubmitValue')) { $value = $values[$element->getName()] ?? null; $result = $element->validateSubmitValue($value); if (!empty($result) && is_string($result)) { return $result; } } } }
[ "public", "function", "validateSubmitValue", "(", "$", "values", ")", "{", "foreach", "(", "$", "this", "->", "_elements", "as", "$", "element", ")", "{", "if", "(", "method_exists", "(", "$", "element", ",", "'validateSubmitValue'", ")", ")", "{", "$", "value", "=", "$", "values", "[", "$", "element", "->", "getName", "(", ")", "]", "??", "null", ";", "$", "result", "=", "$", "element", "->", "validateSubmitValue", "(", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "result", ")", "&&", "is_string", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "}", "}", "}" ]
Calls the validateSubmitValue function for the containing elements and returns an error string as soon as it finds one. @param array $values Values of the containing elements. @return string|null Validation error message or null.
[ "Calls", "the", "validateSubmitValue", "function", "for", "the", "containing", "elements", "and", "returns", "an", "error", "string", "as", "soon", "as", "it", "finds", "one", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/form/group.php#L267-L277
220,257
moodle/moodle
admin/tool/messageinbound/classes/edit_handler_form.php
tool_messageinbound_edit_handler_form.get_defaultexpiration_text
protected function get_defaultexpiration_text(\core\message\inbound\handler $handler) { switch($handler->defaultexpiration) { case HOURSECS : return get_string('onehour', 'tool_messageinbound'); case DAYSECS : return get_string('oneday', 'tool_messageinbound'); case WEEKSECS : return get_string('oneweek', 'tool_messageinbound'); case YEARSECS : return get_string('oneyear', 'tool_messageinbound'); case 0: return get_string('noexpiry', 'tool_messageinbound'); default: return ''; // Should never happen. } }
php
protected function get_defaultexpiration_text(\core\message\inbound\handler $handler) { switch($handler->defaultexpiration) { case HOURSECS : return get_string('onehour', 'tool_messageinbound'); case DAYSECS : return get_string('oneday', 'tool_messageinbound'); case WEEKSECS : return get_string('oneweek', 'tool_messageinbound'); case YEARSECS : return get_string('oneyear', 'tool_messageinbound'); case 0: return get_string('noexpiry', 'tool_messageinbound'); default: return ''; // Should never happen. } }
[ "protected", "function", "get_defaultexpiration_text", "(", "\\", "core", "\\", "message", "\\", "inbound", "\\", "handler", "$", "handler", ")", "{", "switch", "(", "$", "handler", "->", "defaultexpiration", ")", "{", "case", "HOURSECS", ":", "return", "get_string", "(", "'onehour'", ",", "'tool_messageinbound'", ")", ";", "case", "DAYSECS", ":", "return", "get_string", "(", "'oneday'", ",", "'tool_messageinbound'", ")", ";", "case", "WEEKSECS", ":", "return", "get_string", "(", "'oneweek'", ",", "'tool_messageinbound'", ")", ";", "case", "YEARSECS", ":", "return", "get_string", "(", "'oneyear'", ",", "'tool_messageinbound'", ")", ";", "case", "0", ":", "return", "get_string", "(", "'noexpiry'", ",", "'tool_messageinbound'", ")", ";", "default", ":", "return", "''", ";", "// Should never happen.", "}", "}" ]
Return a text string representing the selected default expiration for the handler. @param \core\message\inbound\handler $handler handler instance. @return string localised text string.
[ "Return", "a", "text", "string", "representing", "the", "selected", "default", "expiration", "for", "the", "handler", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/messageinbound/classes/edit_handler_form.php#L127-L142
220,258
moodle/moodle
lib/horde/framework/Horde/Imap/Client/Data/Acl.php
Horde_Imap_Client_Data_Acl.diff
public function diff($rights) { $rlist = array_diff(str_split($rights), array_keys($this->_virtual)); return array( 'added' => implode('', array_diff($rlist, $this->_rights)), 'removed' => implode('', array_diff($this->_rights, $rlist)) ); }
php
public function diff($rights) { $rlist = array_diff(str_split($rights), array_keys($this->_virtual)); return array( 'added' => implode('', array_diff($rlist, $this->_rights)), 'removed' => implode('', array_diff($this->_rights, $rlist)) ); }
[ "public", "function", "diff", "(", "$", "rights", ")", "{", "$", "rlist", "=", "array_diff", "(", "str_split", "(", "$", "rights", ")", ",", "array_keys", "(", "$", "this", "->", "_virtual", ")", ")", ";", "return", "array", "(", "'added'", "=>", "implode", "(", "''", ",", "array_diff", "(", "$", "rlist", ",", "$", "this", "->", "_rights", ")", ")", ",", "'removed'", "=>", "implode", "(", "''", ",", "array_diff", "(", "$", "this", "->", "_rights", ",", "$", "rlist", ")", ")", ")", ";", "}" ]
Computes the difference to another rights string. Virtual rights are ignored. @param string $rights The rights to compute against. @return array Two element array: added and removed.
[ "Computes", "the", "difference", "to", "another", "rights", "string", ".", "Virtual", "rights", "are", "ignored", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Imap/Client/Data/Acl.php#L61-L69
220,259
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.get_status
public function get_status() { if ($this->combinedfile) { // The combined file exists. Report success. return self::STATUS_COMPLETE; } if (empty($this->sourcefiles)) { // There are no source files to combine. return self::STATUS_FAILED; } if (!empty($this->combinationstatus)) { // The combination is in progress and has set a status. // Return it instead. return $this->combinationstatus; } $pending = false; $partial = false; foreach ($this->sourcefiles as $file) { // The combined file has not yet been generated. // Check the status of each source file. if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); switch ($status) { case \core_files\conversion::STATUS_IN_PROGRESS: case \core_files\conversion::STATUS_PENDING: $pending = true; break; // There are 4 status flags, so the only remaining one is complete which is fine. case \core_files\conversion::STATUS_FAILED: $partial = true; break; } } } if ($pending) { return self::STATUS_PENDING_INPUT; } else { if ($partial) { return self::STATUS_READY_PARTIAL; } return self::STATUS_READY; } }
php
public function get_status() { if ($this->combinedfile) { // The combined file exists. Report success. return self::STATUS_COMPLETE; } if (empty($this->sourcefiles)) { // There are no source files to combine. return self::STATUS_FAILED; } if (!empty($this->combinationstatus)) { // The combination is in progress and has set a status. // Return it instead. return $this->combinationstatus; } $pending = false; $partial = false; foreach ($this->sourcefiles as $file) { // The combined file has not yet been generated. // Check the status of each source file. if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); switch ($status) { case \core_files\conversion::STATUS_IN_PROGRESS: case \core_files\conversion::STATUS_PENDING: $pending = true; break; // There are 4 status flags, so the only remaining one is complete which is fine. case \core_files\conversion::STATUS_FAILED: $partial = true; break; } } } if ($pending) { return self::STATUS_PENDING_INPUT; } else { if ($partial) { return self::STATUS_READY_PARTIAL; } return self::STATUS_READY; } }
[ "public", "function", "get_status", "(", ")", "{", "if", "(", "$", "this", "->", "combinedfile", ")", "{", "// The combined file exists. Report success.", "return", "self", "::", "STATUS_COMPLETE", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "sourcefiles", ")", ")", "{", "// There are no source files to combine.", "return", "self", "::", "STATUS_FAILED", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "combinationstatus", ")", ")", "{", "// The combination is in progress and has set a status.", "// Return it instead.", "return", "$", "this", "->", "combinationstatus", ";", "}", "$", "pending", "=", "false", ";", "$", "partial", "=", "false", ";", "foreach", "(", "$", "this", "->", "sourcefiles", "as", "$", "file", ")", "{", "// The combined file has not yet been generated.", "// Check the status of each source file.", "if", "(", "is_a", "(", "$", "file", ",", "\\", "core_files", "\\", "conversion", "::", "class", ")", ")", "{", "$", "status", "=", "$", "file", "->", "get", "(", "'status'", ")", ";", "switch", "(", "$", "status", ")", "{", "case", "\\", "core_files", "\\", "conversion", "::", "STATUS_IN_PROGRESS", ":", "case", "\\", "core_files", "\\", "conversion", "::", "STATUS_PENDING", ":", "$", "pending", "=", "true", ";", "break", ";", "// There are 4 status flags, so the only remaining one is complete which is fine.", "case", "\\", "core_files", "\\", "conversion", "::", "STATUS_FAILED", ":", "$", "partial", "=", "true", ";", "break", ";", "}", "}", "}", "if", "(", "$", "pending", ")", "{", "return", "self", "::", "STATUS_PENDING_INPUT", ";", "}", "else", "{", "if", "(", "$", "partial", ")", "{", "return", "self", "::", "STATUS_READY_PARTIAL", ";", "}", "return", "self", "::", "STATUS_READY", ";", "}", "}" ]
Check the current status of the document combination. Note that the combined document may not contain all the source files if some of the source files were not able to be converted. An example is an audio file with a pdf cover sheet. Only the cover sheet will be included in the combined document. @return int
[ "Check", "the", "current", "status", "of", "the", "document", "combination", ".", "Note", "that", "the", "combined", "document", "may", "not", "contain", "all", "the", "source", "files", "if", "some", "of", "the", "source", "files", "were", "not", "able", "to", "be", "converted", ".", "An", "example", "is", "an", "audio", "file", "with", "a", "pdf", "cover", "sheet", ".", "Only", "the", "cover", "sheet", "will", "be", "included", "in", "the", "combined", "document", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L90-L135
220,260
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.is_partial_conversion
public function is_partial_conversion() { $combinedfile = $this->get_combined_file(); if (empty($combinedfile)) { return false; } $filearea = $combinedfile->get_filearea(); return $filearea == document_services::PARTIAL_PDF_FILEAREA; }
php
public function is_partial_conversion() { $combinedfile = $this->get_combined_file(); if (empty($combinedfile)) { return false; } $filearea = $combinedfile->get_filearea(); return $filearea == document_services::PARTIAL_PDF_FILEAREA; }
[ "public", "function", "is_partial_conversion", "(", ")", "{", "$", "combinedfile", "=", "$", "this", "->", "get_combined_file", "(", ")", ";", "if", "(", "empty", "(", "$", "combinedfile", ")", ")", "{", "return", "false", ";", "}", "$", "filearea", "=", "$", "combinedfile", "->", "get_filearea", "(", ")", ";", "return", "$", "filearea", "==", "document_services", "::", "PARTIAL_PDF_FILEAREA", ";", "}" ]
Return true of the combined file contained only some of the submission files. @return boolean
[ "Return", "true", "of", "the", "combined", "file", "contained", "only", "some", "of", "the", "submission", "files", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L153-L160
220,261
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.refresh_files
public function refresh_files() { $converter = new \core_files\converter(); foreach ($this->sourcefiles as $file) { if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); switch ($status) { case \core_files\conversion::STATUS_COMPLETE: continue 2; break; default: $converter->poll_conversion($conversion); } } } return $this; }
php
public function refresh_files() { $converter = new \core_files\converter(); foreach ($this->sourcefiles as $file) { if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); switch ($status) { case \core_files\conversion::STATUS_COMPLETE: continue 2; break; default: $converter->poll_conversion($conversion); } } } return $this; }
[ "public", "function", "refresh_files", "(", ")", "{", "$", "converter", "=", "new", "\\", "core_files", "\\", "converter", "(", ")", ";", "foreach", "(", "$", "this", "->", "sourcefiles", "as", "$", "file", ")", "{", "if", "(", "is_a", "(", "$", "file", ",", "\\", "core_files", "\\", "conversion", "::", "class", ")", ")", "{", "$", "status", "=", "$", "file", "->", "get", "(", "'status'", ")", ";", "switch", "(", "$", "status", ")", "{", "case", "\\", "core_files", "\\", "conversion", "::", "STATUS_COMPLETE", ":", "continue", "2", ";", "break", ";", "default", ":", "$", "converter", "->", "poll_conversion", "(", "$", "conversion", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Refresh the files. This includes polling any pending conversions to see if they are complete. @return $this
[ "Refresh", "the", "files", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L211-L227
220,262
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.combine_files
public function combine_files($contextid, $itemid) { global $CFG; $currentstatus = $this->get_status(); $readystatuslist = [self::STATUS_READY, self::STATUS_READY_PARTIAL]; if ($currentstatus === self::STATUS_FAILED) { $this->store_empty_document($contextid, $itemid); return $this; } else if (!in_array($currentstatus, $readystatuslist)) { // The document is either: // * already combined; or // * pending input being fully converted; or // * unable to continue due to an issue with the input documents. // // Exit early as we cannot continue. return $this; } require_once($CFG->libdir . '/pdflib.php'); $pdf = new pdf(); $files = $this->get_source_files(); $compatiblepdfs = []; foreach ($files as $file) { // Check that each file is compatible and add it to the list. // Note: We drop non-compatible files. $compatiblepdf = false; if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); if ($status == \core_files\conversion::STATUS_COMPLETE) { $compatiblepdf = pdf::ensure_pdf_compatible($file->get_destfile()); } } else { $compatiblepdf = pdf::ensure_pdf_compatible($file); } if ($compatiblepdf) { $compatiblepdfs[] = $compatiblepdf; } } $tmpdir = make_request_directory(); $tmpfile = $tmpdir . '/' . document_services::COMBINED_PDF_FILENAME; try { $pagecount = $pdf->combine_pdfs($compatiblepdfs, $tmpfile); $pdf->Close(); } catch (\Exception $e) { // Unable to combine the PDF. debugging('TCPDF could not process the pdf files:' . $e->getMessage(), DEBUG_DEVELOPER); $pdf->Close(); return $this->mark_combination_failed(); } // Verify the PDF. $verifypdf = new pdf(); $verifypagecount = $verifypdf->load_pdf($tmpfile); $verifypdf->Close(); if ($verifypagecount <= 0) { // No pages were found in the combined PDF. return $this->mark_combination_failed(); } // Store the newly created file as a stored_file. $this->store_combined_file($tmpfile, $contextid, $itemid, ($currentstatus == self::STATUS_READY_PARTIAL)); // Note the verified page count. $this->pagecount = $verifypagecount; return $this; }
php
public function combine_files($contextid, $itemid) { global $CFG; $currentstatus = $this->get_status(); $readystatuslist = [self::STATUS_READY, self::STATUS_READY_PARTIAL]; if ($currentstatus === self::STATUS_FAILED) { $this->store_empty_document($contextid, $itemid); return $this; } else if (!in_array($currentstatus, $readystatuslist)) { // The document is either: // * already combined; or // * pending input being fully converted; or // * unable to continue due to an issue with the input documents. // // Exit early as we cannot continue. return $this; } require_once($CFG->libdir . '/pdflib.php'); $pdf = new pdf(); $files = $this->get_source_files(); $compatiblepdfs = []; foreach ($files as $file) { // Check that each file is compatible and add it to the list. // Note: We drop non-compatible files. $compatiblepdf = false; if (is_a($file, \core_files\conversion::class)) { $status = $file->get('status'); if ($status == \core_files\conversion::STATUS_COMPLETE) { $compatiblepdf = pdf::ensure_pdf_compatible($file->get_destfile()); } } else { $compatiblepdf = pdf::ensure_pdf_compatible($file); } if ($compatiblepdf) { $compatiblepdfs[] = $compatiblepdf; } } $tmpdir = make_request_directory(); $tmpfile = $tmpdir . '/' . document_services::COMBINED_PDF_FILENAME; try { $pagecount = $pdf->combine_pdfs($compatiblepdfs, $tmpfile); $pdf->Close(); } catch (\Exception $e) { // Unable to combine the PDF. debugging('TCPDF could not process the pdf files:' . $e->getMessage(), DEBUG_DEVELOPER); $pdf->Close(); return $this->mark_combination_failed(); } // Verify the PDF. $verifypdf = new pdf(); $verifypagecount = $verifypdf->load_pdf($tmpfile); $verifypdf->Close(); if ($verifypagecount <= 0) { // No pages were found in the combined PDF. return $this->mark_combination_failed(); } // Store the newly created file as a stored_file. $this->store_combined_file($tmpfile, $contextid, $itemid, ($currentstatus == self::STATUS_READY_PARTIAL)); // Note the verified page count. $this->pagecount = $verifypagecount; return $this; }
[ "public", "function", "combine_files", "(", "$", "contextid", ",", "$", "itemid", ")", "{", "global", "$", "CFG", ";", "$", "currentstatus", "=", "$", "this", "->", "get_status", "(", ")", ";", "$", "readystatuslist", "=", "[", "self", "::", "STATUS_READY", ",", "self", "::", "STATUS_READY_PARTIAL", "]", ";", "if", "(", "$", "currentstatus", "===", "self", "::", "STATUS_FAILED", ")", "{", "$", "this", "->", "store_empty_document", "(", "$", "contextid", ",", "$", "itemid", ")", ";", "return", "$", "this", ";", "}", "else", "if", "(", "!", "in_array", "(", "$", "currentstatus", ",", "$", "readystatuslist", ")", ")", "{", "// The document is either:", "// * already combined; or", "// * pending input being fully converted; or", "// * unable to continue due to an issue with the input documents.", "//", "// Exit early as we cannot continue.", "return", "$", "this", ";", "}", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/pdflib.php'", ")", ";", "$", "pdf", "=", "new", "pdf", "(", ")", ";", "$", "files", "=", "$", "this", "->", "get_source_files", "(", ")", ";", "$", "compatiblepdfs", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "// Check that each file is compatible and add it to the list.", "// Note: We drop non-compatible files.", "$", "compatiblepdf", "=", "false", ";", "if", "(", "is_a", "(", "$", "file", ",", "\\", "core_files", "\\", "conversion", "::", "class", ")", ")", "{", "$", "status", "=", "$", "file", "->", "get", "(", "'status'", ")", ";", "if", "(", "$", "status", "==", "\\", "core_files", "\\", "conversion", "::", "STATUS_COMPLETE", ")", "{", "$", "compatiblepdf", "=", "pdf", "::", "ensure_pdf_compatible", "(", "$", "file", "->", "get_destfile", "(", ")", ")", ";", "}", "}", "else", "{", "$", "compatiblepdf", "=", "pdf", "::", "ensure_pdf_compatible", "(", "$", "file", ")", ";", "}", "if", "(", "$", "compatiblepdf", ")", "{", "$", "compatiblepdfs", "[", "]", "=", "$", "compatiblepdf", ";", "}", "}", "$", "tmpdir", "=", "make_request_directory", "(", ")", ";", "$", "tmpfile", "=", "$", "tmpdir", ".", "'/'", ".", "document_services", "::", "COMBINED_PDF_FILENAME", ";", "try", "{", "$", "pagecount", "=", "$", "pdf", "->", "combine_pdfs", "(", "$", "compatiblepdfs", ",", "$", "tmpfile", ")", ";", "$", "pdf", "->", "Close", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Unable to combine the PDF.", "debugging", "(", "'TCPDF could not process the pdf files:'", ".", "$", "e", "->", "getMessage", "(", ")", ",", "DEBUG_DEVELOPER", ")", ";", "$", "pdf", "->", "Close", "(", ")", ";", "return", "$", "this", "->", "mark_combination_failed", "(", ")", ";", "}", "// Verify the PDF.", "$", "verifypdf", "=", "new", "pdf", "(", ")", ";", "$", "verifypagecount", "=", "$", "verifypdf", "->", "load_pdf", "(", "$", "tmpfile", ")", ";", "$", "verifypdf", "->", "Close", "(", ")", ";", "if", "(", "$", "verifypagecount", "<=", "0", ")", "{", "// No pages were found in the combined PDF.", "return", "$", "this", "->", "mark_combination_failed", "(", ")", ";", "}", "// Store the newly created file as a stored_file.", "$", "this", "->", "store_combined_file", "(", "$", "tmpfile", ",", "$", "contextid", ",", "$", "itemid", ",", "(", "$", "currentstatus", "==", "self", "::", "STATUS_READY_PARTIAL", ")", ")", ";", "// Note the verified page count.", "$", "this", "->", "pagecount", "=", "$", "verifypagecount", ";", "return", "$", "this", ";", "}" ]
Combine all source files into a single PDF and store it in the file_storage API using the supplied contextid and itemid. @param int $contextid The contextid for the file to be stored under @param int $itemid The itemid for the file to be stored under @return $this
[ "Combine", "all", "source", "files", "into", "a", "single", "PDF", "and", "store", "it", "in", "the", "file_storage", "API", "using", "the", "supplied", "contextid", "and", "itemid", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L237-L311
220,263
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.store_combined_file
protected function store_combined_file($tmpfile, $contextid, $itemid, $partial = false) { // Store the file. $record = $this->get_stored_file_record($contextid, $itemid, $partial); $fs = get_file_storage(); // Delete existing files first. $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid); // This was a combined pdf. $file = $fs->create_file_from_pathname($record, $tmpfile); $this->set_combined_file($file); return $this; }
php
protected function store_combined_file($tmpfile, $contextid, $itemid, $partial = false) { // Store the file. $record = $this->get_stored_file_record($contextid, $itemid, $partial); $fs = get_file_storage(); // Delete existing files first. $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid); // This was a combined pdf. $file = $fs->create_file_from_pathname($record, $tmpfile); $this->set_combined_file($file); return $this; }
[ "protected", "function", "store_combined_file", "(", "$", "tmpfile", ",", "$", "contextid", ",", "$", "itemid", ",", "$", "partial", "=", "false", ")", "{", "// Store the file.", "$", "record", "=", "$", "this", "->", "get_stored_file_record", "(", "$", "contextid", ",", "$", "itemid", ",", "$", "partial", ")", ";", "$", "fs", "=", "get_file_storage", "(", ")", ";", "// Delete existing files first.", "$", "fs", "->", "delete_area_files", "(", "$", "record", "->", "contextid", ",", "$", "record", "->", "component", ",", "$", "record", "->", "filearea", ",", "$", "record", "->", "itemid", ")", ";", "// This was a combined pdf.", "$", "file", "=", "$", "fs", "->", "create_file_from_pathname", "(", "$", "record", ",", "$", "tmpfile", ")", ";", "$", "this", "->", "set_combined_file", "(", "$", "file", ")", ";", "return", "$", "this", ";", "}" ]
Store the combined file in the file_storage API. @param string $tmpfile The path to the file on disk to be stored. @param int $contextid The contextid for the file to be stored under @param int $itemid The itemid for the file to be stored under @param boolean $partial The combined pdf contains only some of the source files. @return $this
[ "Store", "the", "combined", "file", "in", "the", "file_storage", "API", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L333-L347
220,264
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.store_empty_document
protected function store_empty_document($contextid, $itemid) { // Store the file. $record = $this->get_stored_file_record($contextid, $itemid); $fs = get_file_storage(); // Delete existing files first. $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid); $file = $fs->create_file_from_string($record, base64_decode(document_services::BLANK_PDF_BASE64)); $this->pagecount = 1; $this->set_combined_file($file); return $this; }
php
protected function store_empty_document($contextid, $itemid) { // Store the file. $record = $this->get_stored_file_record($contextid, $itemid); $fs = get_file_storage(); // Delete existing files first. $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid); $file = $fs->create_file_from_string($record, base64_decode(document_services::BLANK_PDF_BASE64)); $this->pagecount = 1; $this->set_combined_file($file); return $this; }
[ "protected", "function", "store_empty_document", "(", "$", "contextid", ",", "$", "itemid", ")", "{", "// Store the file.", "$", "record", "=", "$", "this", "->", "get_stored_file_record", "(", "$", "contextid", ",", "$", "itemid", ")", ";", "$", "fs", "=", "get_file_storage", "(", ")", ";", "// Delete existing files first.", "$", "fs", "->", "delete_area_files", "(", "$", "record", "->", "contextid", ",", "$", "record", "->", "component", ",", "$", "record", "->", "filearea", ",", "$", "record", "->", "itemid", ")", ";", "$", "file", "=", "$", "fs", "->", "create_file_from_string", "(", "$", "record", ",", "base64_decode", "(", "document_services", "::", "BLANK_PDF_BASE64", ")", ")", ";", "$", "this", "->", "pagecount", "=", "1", ";", "$", "this", "->", "set_combined_file", "(", "$", "file", ")", ";", "return", "$", "this", ";", "}" ]
Store the empty document file in the file_storage API. @param int $contextid The contextid for the file to be stored under @param int $itemid The itemid for the file to be stored under @return $this
[ "Store", "the", "empty", "document", "file", "in", "the", "file_storage", "API", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L356-L370
220,265
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.get_page_count
public function get_page_count() { if ($this->pagecount) { return $this->pagecount; } $status = $this->get_status(); if ($status === self::STATUS_FAILED) { // The empty document will be returned. return 1; } if ($status !== self::STATUS_COMPLETE) { // No pages yet. return 0; } // Load the PDF to determine the page count. $temparea = make_request_directory(); $tempsrc = $temparea . "/source.pdf"; $this->get_combined_file()->copy_content_to($tempsrc); $pdf = new pdf(); $pagecount = $pdf->load_pdf($tempsrc); $pdf->Close(); if ($pagecount <= 0) { // Something went wrong. Return an empty page count again. return 0; } $this->pagecount = $pagecount; return $this->pagecount; }
php
public function get_page_count() { if ($this->pagecount) { return $this->pagecount; } $status = $this->get_status(); if ($status === self::STATUS_FAILED) { // The empty document will be returned. return 1; } if ($status !== self::STATUS_COMPLETE) { // No pages yet. return 0; } // Load the PDF to determine the page count. $temparea = make_request_directory(); $tempsrc = $temparea . "/source.pdf"; $this->get_combined_file()->copy_content_to($tempsrc); $pdf = new pdf(); $pagecount = $pdf->load_pdf($tempsrc); $pdf->Close(); if ($pagecount <= 0) { // Something went wrong. Return an empty page count again. return 0; } $this->pagecount = $pagecount; return $this->pagecount; }
[ "public", "function", "get_page_count", "(", ")", "{", "if", "(", "$", "this", "->", "pagecount", ")", "{", "return", "$", "this", "->", "pagecount", ";", "}", "$", "status", "=", "$", "this", "->", "get_status", "(", ")", ";", "if", "(", "$", "status", "===", "self", "::", "STATUS_FAILED", ")", "{", "// The empty document will be returned.", "return", "1", ";", "}", "if", "(", "$", "status", "!==", "self", "::", "STATUS_COMPLETE", ")", "{", "// No pages yet.", "return", "0", ";", "}", "// Load the PDF to determine the page count.", "$", "temparea", "=", "make_request_directory", "(", ")", ";", "$", "tempsrc", "=", "$", "temparea", ".", "\"/source.pdf\"", ";", "$", "this", "->", "get_combined_file", "(", ")", "->", "copy_content_to", "(", "$", "tempsrc", ")", ";", "$", "pdf", "=", "new", "pdf", "(", ")", ";", "$", "pagecount", "=", "$", "pdf", "->", "load_pdf", "(", "$", "tempsrc", ")", ";", "$", "pdf", "->", "Close", "(", ")", ";", "if", "(", "$", "pagecount", "<=", "0", ")", "{", "// Something went wrong. Return an empty page count again.", "return", "0", ";", "}", "$", "this", "->", "pagecount", "=", "$", "pagecount", ";", "return", "$", "this", "->", "pagecount", ";", "}" ]
Get the total number of pages in the combined document. If there are no pages, or it is not yet possible to count them a value of 0 is returned. @return int
[ "Get", "the", "total", "number", "of", "pages", "in", "the", "combined", "document", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L380-L413
220,266
moodle/moodle
mod/assign/feedback/editpdf/classes/combined_document.php
combined_document.get_stored_file_record
protected function get_stored_file_record($contextid, $itemid, $partial = false) { $filearea = document_services::COMBINED_PDF_FILEAREA; if ($partial) { $filearea = document_services::PARTIAL_PDF_FILEAREA; } return (object) [ 'contextid' => $contextid, 'component' => 'assignfeedback_editpdf', 'filearea' => $filearea, 'itemid' => $itemid, 'filepath' => '/', 'filename' => document_services::COMBINED_PDF_FILENAME, ]; }
php
protected function get_stored_file_record($contextid, $itemid, $partial = false) { $filearea = document_services::COMBINED_PDF_FILEAREA; if ($partial) { $filearea = document_services::PARTIAL_PDF_FILEAREA; } return (object) [ 'contextid' => $contextid, 'component' => 'assignfeedback_editpdf', 'filearea' => $filearea, 'itemid' => $itemid, 'filepath' => '/', 'filename' => document_services::COMBINED_PDF_FILENAME, ]; }
[ "protected", "function", "get_stored_file_record", "(", "$", "contextid", ",", "$", "itemid", ",", "$", "partial", "=", "false", ")", "{", "$", "filearea", "=", "document_services", "::", "COMBINED_PDF_FILEAREA", ";", "if", "(", "$", "partial", ")", "{", "$", "filearea", "=", "document_services", "::", "PARTIAL_PDF_FILEAREA", ";", "}", "return", "(", "object", ")", "[", "'contextid'", "=>", "$", "contextid", ",", "'component'", "=>", "'assignfeedback_editpdf'", ",", "'filearea'", "=>", "$", "filearea", ",", "'itemid'", "=>", "$", "itemid", ",", "'filepath'", "=>", "'/'", ",", "'filename'", "=>", "document_services", "::", "COMBINED_PDF_FILENAME", ",", "]", ";", "}" ]
Helper to fetch the stored_file record. @param int $contextid The contextid for the file to be stored under @param int $itemid The itemid for the file to be stored under @param boolean $partial The combined file contains only some of the source files. @return stdClass
[ "Helper", "to", "fetch", "the", "stored_file", "record", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/classes/combined_document.php#L432-L445
220,267
moodle/moodle
lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php
LDA.calculateMeans
protected function calculateMeans(array $data, array $classes) : array { $means = []; $counts= []; $overallMean = array_fill(0, count($data[0]), 0.0); foreach ($data as $index => $row) { $label = array_search($classes[$index], $this->labels); foreach ($row as $col => $val) { if (!isset($means[$label][$col])) { $means[$label][$col] = 0.0; } $means[$label][$col] += $val; $overallMean[$col] += $val; } if (!isset($counts[$label])) { $counts[$label] = 0; } ++$counts[$label]; } foreach ($means as $index => $row) { foreach ($row as $col => $sum) { $means[$index][$col] = $sum / $counts[$index]; } } // Calculate overall mean of the dataset for each column $numElements = array_sum($counts); $map = function ($el) use ($numElements) { return $el / $numElements; }; $this->overallMean = array_map($map, $overallMean); $this->counts = $counts; return $means; }
php
protected function calculateMeans(array $data, array $classes) : array { $means = []; $counts= []; $overallMean = array_fill(0, count($data[0]), 0.0); foreach ($data as $index => $row) { $label = array_search($classes[$index], $this->labels); foreach ($row as $col => $val) { if (!isset($means[$label][$col])) { $means[$label][$col] = 0.0; } $means[$label][$col] += $val; $overallMean[$col] += $val; } if (!isset($counts[$label])) { $counts[$label] = 0; } ++$counts[$label]; } foreach ($means as $index => $row) { foreach ($row as $col => $sum) { $means[$index][$col] = $sum / $counts[$index]; } } // Calculate overall mean of the dataset for each column $numElements = array_sum($counts); $map = function ($el) use ($numElements) { return $el / $numElements; }; $this->overallMean = array_map($map, $overallMean); $this->counts = $counts; return $means; }
[ "protected", "function", "calculateMeans", "(", "array", "$", "data", ",", "array", "$", "classes", ")", ":", "array", "{", "$", "means", "=", "[", "]", ";", "$", "counts", "=", "[", "]", ";", "$", "overallMean", "=", "array_fill", "(", "0", ",", "count", "(", "$", "data", "[", "0", "]", ")", ",", "0.0", ")", ";", "foreach", "(", "$", "data", "as", "$", "index", "=>", "$", "row", ")", "{", "$", "label", "=", "array_search", "(", "$", "classes", "[", "$", "index", "]", ",", "$", "this", "->", "labels", ")", ";", "foreach", "(", "$", "row", "as", "$", "col", "=>", "$", "val", ")", "{", "if", "(", "!", "isset", "(", "$", "means", "[", "$", "label", "]", "[", "$", "col", "]", ")", ")", "{", "$", "means", "[", "$", "label", "]", "[", "$", "col", "]", "=", "0.0", ";", "}", "$", "means", "[", "$", "label", "]", "[", "$", "col", "]", "+=", "$", "val", ";", "$", "overallMean", "[", "$", "col", "]", "+=", "$", "val", ";", "}", "if", "(", "!", "isset", "(", "$", "counts", "[", "$", "label", "]", ")", ")", "{", "$", "counts", "[", "$", "label", "]", "=", "0", ";", "}", "++", "$", "counts", "[", "$", "label", "]", ";", "}", "foreach", "(", "$", "means", "as", "$", "index", "=>", "$", "row", ")", "{", "foreach", "(", "$", "row", "as", "$", "col", "=>", "$", "sum", ")", "{", "$", "means", "[", "$", "index", "]", "[", "$", "col", "]", "=", "$", "sum", "/", "$", "counts", "[", "$", "index", "]", ";", "}", "}", "// Calculate overall mean of the dataset for each column", "$", "numElements", "=", "array_sum", "(", "$", "counts", ")", ";", "$", "map", "=", "function", "(", "$", "el", ")", "use", "(", "$", "numElements", ")", "{", "return", "$", "el", "/", "$", "numElements", ";", "}", ";", "$", "this", "->", "overallMean", "=", "array_map", "(", "$", "map", ",", "$", "overallMean", ")", ";", "$", "this", "->", "counts", "=", "$", "counts", ";", "return", "$", "means", ";", "}" ]
Calculates mean of each column for each class and returns n by m matrix where n is number of labels and m is number of columns @param array $data @param array $classes @return array
[ "Calculates", "mean", "of", "each", "column", "for", "each", "class", "and", "returns", "n", "by", "m", "matrix", "where", "n", "is", "number", "of", "labels", "and", "m", "is", "number", "of", "columns" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php#L118-L157
220,268
moodle/moodle
lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php
LDA.calculateClassVar
protected function calculateClassVar($data, $classes) { // s is an n (number of classes) by m (number of column) matrix $s = array_fill(0, count($data[0]), array_fill(0, count($data[0]), 0)); $sW = new Matrix($s, false); foreach ($data as $index => $row) { $label = array_search($classes[$index], $this->labels); $means = $this->means[$label]; $row = $this->calculateVar($row, $means); $sW = $sW->add($row); } return $sW; }
php
protected function calculateClassVar($data, $classes) { // s is an n (number of classes) by m (number of column) matrix $s = array_fill(0, count($data[0]), array_fill(0, count($data[0]), 0)); $sW = new Matrix($s, false); foreach ($data as $index => $row) { $label = array_search($classes[$index], $this->labels); $means = $this->means[$label]; $row = $this->calculateVar($row, $means); $sW = $sW->add($row); } return $sW; }
[ "protected", "function", "calculateClassVar", "(", "$", "data", ",", "$", "classes", ")", "{", "// s is an n (number of classes) by m (number of column) matrix", "$", "s", "=", "array_fill", "(", "0", ",", "count", "(", "$", "data", "[", "0", "]", ")", ",", "array_fill", "(", "0", ",", "count", "(", "$", "data", "[", "0", "]", ")", ",", "0", ")", ")", ";", "$", "sW", "=", "new", "Matrix", "(", "$", "s", ",", "false", ")", ";", "foreach", "(", "$", "data", "as", "$", "index", "=>", "$", "row", ")", "{", "$", "label", "=", "array_search", "(", "$", "classes", "[", "$", "index", "]", ",", "$", "this", "->", "labels", ")", ";", "$", "means", "=", "$", "this", "->", "means", "[", "$", "label", "]", ";", "$", "row", "=", "$", "this", "->", "calculateVar", "(", "$", "row", ",", "$", "means", ")", ";", "$", "sW", "=", "$", "sW", "->", "add", "(", "$", "row", ")", ";", "}", "return", "$", "sW", ";", "}" ]
Returns in-class scatter matrix for each class, which is a n by m matrix where n is number of classes and m is number of columns @param array $data @param array $classes @return Matrix
[ "Returns", "in", "-", "class", "scatter", "matrix", "for", "each", "class", "which", "is", "a", "n", "by", "m", "matrix", "where", "n", "is", "number", "of", "classes", "and", "m", "is", "number", "of", "columns" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php#L170-L186
220,269
moodle/moodle
lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php
LDA.calculateClassCov
protected function calculateClassCov() { // s is an n (number of classes) by m (number of column) matrix $s = array_fill(0, count($this->overallMean), array_fill(0, count($this->overallMean), 0)); $sB = new Matrix($s, false); foreach ($this->means as $index => $classMeans) { $row = $this->calculateVar($classMeans, $this->overallMean); $N = $this->counts[$index]; $sB = $sB->add($row->multiplyByScalar($N)); } return $sB; }
php
protected function calculateClassCov() { // s is an n (number of classes) by m (number of column) matrix $s = array_fill(0, count($this->overallMean), array_fill(0, count($this->overallMean), 0)); $sB = new Matrix($s, false); foreach ($this->means as $index => $classMeans) { $row = $this->calculateVar($classMeans, $this->overallMean); $N = $this->counts[$index]; $sB = $sB->add($row->multiplyByScalar($N)); } return $sB; }
[ "protected", "function", "calculateClassCov", "(", ")", "{", "// s is an n (number of classes) by m (number of column) matrix", "$", "s", "=", "array_fill", "(", "0", ",", "count", "(", "$", "this", "->", "overallMean", ")", ",", "array_fill", "(", "0", ",", "count", "(", "$", "this", "->", "overallMean", ")", ",", "0", ")", ")", ";", "$", "sB", "=", "new", "Matrix", "(", "$", "s", ",", "false", ")", ";", "foreach", "(", "$", "this", "->", "means", "as", "$", "index", "=>", "$", "classMeans", ")", "{", "$", "row", "=", "$", "this", "->", "calculateVar", "(", "$", "classMeans", ",", "$", "this", "->", "overallMean", ")", ";", "$", "N", "=", "$", "this", "->", "counts", "[", "$", "index", "]", ";", "$", "sB", "=", "$", "sB", "->", "add", "(", "$", "row", "->", "multiplyByScalar", "(", "$", "N", ")", ")", ";", "}", "return", "$", "sB", ";", "}" ]
Returns between-class scatter matrix for each class, which is an n by m matrix where n is number of classes and m is number of columns @return Matrix
[ "Returns", "between", "-", "class", "scatter", "matrix", "for", "each", "class", "which", "is", "an", "n", "by", "m", "matrix", "where", "n", "is", "number", "of", "classes", "and", "m", "is", "number", "of", "columns" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/mlbackend/php/phpml/src/Phpml/DimensionReduction/LDA.php#L195-L208
220,270
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.cm_updated
public static function cm_updated(\core\event\course_module_updated $event) { if ($event->other['modulename'] !== 'glossary') { return; } // We do not know what changed exactly, so let's reset everything that might be affected. concept_cache::reset_course_muc($event->courseid); concept_cache::reset_global_muc(); }
php
public static function cm_updated(\core\event\course_module_updated $event) { if ($event->other['modulename'] !== 'glossary') { return; } // We do not know what changed exactly, so let's reset everything that might be affected. concept_cache::reset_course_muc($event->courseid); concept_cache::reset_global_muc(); }
[ "public", "static", "function", "cm_updated", "(", "\\", "core", "\\", "event", "\\", "course_module_updated", "$", "event", ")", "{", "if", "(", "$", "event", "->", "other", "[", "'modulename'", "]", "!==", "'glossary'", ")", "{", "return", ";", "}", "// We do not know what changed exactly, so let's reset everything that might be affected.", "concept_cache", "::", "reset_course_muc", "(", "$", "event", "->", "courseid", ")", ";", "concept_cache", "::", "reset_global_muc", "(", ")", ";", "}" ]
Event observer, do not call directly. @param \core\event\course_module_updated $event
[ "Event", "observer", "do", "not", "call", "directly", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L40-L47
220,271
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.reset_course_muc
public static function reset_course_muc($courseid) { if (empty($courseid)) { return; } $cache = \cache::make('mod_glossary', 'concepts'); $cache->delete((int)$courseid); }
php
public static function reset_course_muc($courseid) { if (empty($courseid)) { return; } $cache = \cache::make('mod_glossary', 'concepts'); $cache->delete((int)$courseid); }
[ "public", "static", "function", "reset_course_muc", "(", "$", "courseid", ")", "{", "if", "(", "empty", "(", "$", "courseid", ")", ")", "{", "return", ";", "}", "$", "cache", "=", "\\", "cache", "::", "make", "(", "'mod_glossary'", ",", "'concepts'", ")", ";", "$", "cache", "->", "delete", "(", "(", "int", ")", "$", "courseid", ")", ";", "}" ]
Reset the cache for course concepts. @param int $courseid
[ "Reset", "the", "cache", "for", "course", "concepts", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L65-L71
220,272
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.reset_glossary
public static function reset_glossary($glossary) { if (!$glossary->usedynalink) { return; } self::reset_course_muc($glossary->course); if ($glossary->globalglossary) { self::reset_global_muc(); } }
php
public static function reset_glossary($glossary) { if (!$glossary->usedynalink) { return; } self::reset_course_muc($glossary->course); if ($glossary->globalglossary) { self::reset_global_muc(); } }
[ "public", "static", "function", "reset_glossary", "(", "$", "glossary", ")", "{", "if", "(", "!", "$", "glossary", "->", "usedynalink", ")", "{", "return", ";", "}", "self", "::", "reset_course_muc", "(", "$", "glossary", "->", "course", ")", ";", "if", "(", "$", "glossary", "->", "globalglossary", ")", "{", "self", "::", "reset_global_muc", "(", ")", ";", "}", "}" ]
Utility method to purge caches related to given glossary. @param \stdClass $glossary
[ "Utility", "method", "to", "purge", "caches", "related", "to", "given", "glossary", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L85-L93
220,273
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.fetch_concepts
protected static function fetch_concepts(array $glossaries) { global $DB; $glossarylist = implode(',', $glossaries); $sql = "SELECT id, glossaryid, concept, casesensitive, 0 AS category, fullmatch FROM {glossary_entries} WHERE glossaryid IN ($glossarylist) AND usedynalink = 1 AND approved = 1 UNION SELECT id, glossaryid, name AS concept, 1 AS casesensitive, 1 AS category, 1 AS fullmatch FROM {glossary_categories} WHERE glossaryid IN ($glossarylist) AND usedynalink = 1 UNION SELECT ge.id, ge.glossaryid, ga.alias AS concept, ge.casesensitive, 0 AS category, ge.fullmatch FROM {glossary_alias} ga JOIN {glossary_entries} ge ON (ga.entryid = ge.id) WHERE ge.glossaryid IN ($glossarylist) AND ge.usedynalink = 1 AND ge.approved = 1"; $concepts = array(); $rs = $DB->get_recordset_sql($sql); foreach ($rs as $concept) { $currentconcept = trim(strip_tags($concept->concept)); // Concept must be HTML-escaped, so do the same as format_string to turn ampersands into &amp;. $currentconcept = replace_ampersands_not_followed_by_entity($currentconcept); if (empty($currentconcept)) { continue; } // Rule out any small integers, see MDL-1446. if (is_number($currentconcept) and $currentconcept < 1000) { continue; } $concept->concept = $currentconcept; $concepts[$concept->glossaryid][] = $concept; } $rs->close(); return $concepts; }
php
protected static function fetch_concepts(array $glossaries) { global $DB; $glossarylist = implode(',', $glossaries); $sql = "SELECT id, glossaryid, concept, casesensitive, 0 AS category, fullmatch FROM {glossary_entries} WHERE glossaryid IN ($glossarylist) AND usedynalink = 1 AND approved = 1 UNION SELECT id, glossaryid, name AS concept, 1 AS casesensitive, 1 AS category, 1 AS fullmatch FROM {glossary_categories} WHERE glossaryid IN ($glossarylist) AND usedynalink = 1 UNION SELECT ge.id, ge.glossaryid, ga.alias AS concept, ge.casesensitive, 0 AS category, ge.fullmatch FROM {glossary_alias} ga JOIN {glossary_entries} ge ON (ga.entryid = ge.id) WHERE ge.glossaryid IN ($glossarylist) AND ge.usedynalink = 1 AND ge.approved = 1"; $concepts = array(); $rs = $DB->get_recordset_sql($sql); foreach ($rs as $concept) { $currentconcept = trim(strip_tags($concept->concept)); // Concept must be HTML-escaped, so do the same as format_string to turn ampersands into &amp;. $currentconcept = replace_ampersands_not_followed_by_entity($currentconcept); if (empty($currentconcept)) { continue; } // Rule out any small integers, see MDL-1446. if (is_number($currentconcept) and $currentconcept < 1000) { continue; } $concept->concept = $currentconcept; $concepts[$concept->glossaryid][] = $concept; } $rs->close(); return $concepts; }
[ "protected", "static", "function", "fetch_concepts", "(", "array", "$", "glossaries", ")", "{", "global", "$", "DB", ";", "$", "glossarylist", "=", "implode", "(", "','", ",", "$", "glossaries", ")", ";", "$", "sql", "=", "\"SELECT id, glossaryid, concept, casesensitive, 0 AS category, fullmatch\n FROM {glossary_entries}\n WHERE glossaryid IN ($glossarylist) AND usedynalink = 1 AND approved = 1\n\n UNION\n\n SELECT id, glossaryid, name AS concept, 1 AS casesensitive, 1 AS category, 1 AS fullmatch\n FROM {glossary_categories}\n WHERE glossaryid IN ($glossarylist) AND usedynalink = 1\n\n UNION\n\n SELECT ge.id, ge.glossaryid, ga.alias AS concept, ge.casesensitive, 0 AS category, ge.fullmatch\n FROM {glossary_alias} ga\n JOIN {glossary_entries} ge ON (ga.entryid = ge.id)\n WHERE ge.glossaryid IN ($glossarylist) AND ge.usedynalink = 1 AND ge.approved = 1\"", ";", "$", "concepts", "=", "array", "(", ")", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ")", ";", "foreach", "(", "$", "rs", "as", "$", "concept", ")", "{", "$", "currentconcept", "=", "trim", "(", "strip_tags", "(", "$", "concept", "->", "concept", ")", ")", ";", "// Concept must be HTML-escaped, so do the same as format_string to turn ampersands into &amp;.", "$", "currentconcept", "=", "replace_ampersands_not_followed_by_entity", "(", "$", "currentconcept", ")", ";", "if", "(", "empty", "(", "$", "currentconcept", ")", ")", "{", "continue", ";", "}", "// Rule out any small integers, see MDL-1446.", "if", "(", "is_number", "(", "$", "currentconcept", ")", "and", "$", "currentconcept", "<", "1000", ")", "{", "continue", ";", "}", "$", "concept", "->", "concept", "=", "$", "currentconcept", ";", "$", "concepts", "[", "$", "concept", "->", "glossaryid", "]", "[", "]", "=", "$", "concept", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "return", "$", "concepts", ";", "}" ]
Fetch concepts for given glossaries. @param int[] $glossaries @return array
[ "Fetch", "concepts", "for", "given", "glossaries", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L100-L146
220,274
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.get_course_concepts
protected static function get_course_concepts($courseid) { global $DB; if (empty($courseid)) { return array(array(), array()); } $courseid = (int)$courseid; // Get info on any glossaries in this course. $modinfo = get_fast_modinfo($courseid); $cminfos = $modinfo->get_instances_of('glossary'); if (!$cminfos) { // No glossaries in this course, so don't do any work. return array(array(), array()); } $cache = \cache::make('mod_glossary', 'concepts'); $data = $cache->get($courseid); if (is_array($data)) { list($glossaries, $allconcepts) = $data; } else { // Find all course glossaries. $sql = "SELECT g.id, g.name FROM {glossary} g JOIN {course_modules} cm ON (cm.instance = g.id) JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module) WHERE g.usedynalink = 1 AND g.course = :course AND cm.visible = 1 AND m.visible = 1 ORDER BY g.globalglossary, g.id"; $glossaries = $DB->get_records_sql_menu($sql, array('course' => $courseid)); if (!$glossaries) { $data = array(array(), array()); $cache->set($courseid, $data); return $data; } foreach ($glossaries as $id => $name) { $name = str_replace(':', '-', $name); $glossaries[$id] = replace_ampersands_not_followed_by_entity(strip_tags($name)); } $allconcepts = self::fetch_concepts(array_keys($glossaries)); foreach ($glossaries as $gid => $unused) { if (!isset($allconcepts[$gid])) { unset($glossaries[$gid]); } } if (!$glossaries) { // This means there are no interesting concepts in the existing glossaries. $data = array(array(), array()); $cache->set($courseid, $data); return $data; } $cache->set($courseid, array($glossaries, $allconcepts)); } $concepts = $allconcepts; // Verify access control to glossary instances. foreach ($concepts as $modid => $unused) { if (!isset($cminfos[$modid])) { // This should not happen. unset($concepts[$modid]); unset($glossaries[$modid]); continue; } if (!$cminfos[$modid]->uservisible) { unset($concepts[$modid]); unset($glossaries[$modid]); continue; } } return array($glossaries, $concepts); }
php
protected static function get_course_concepts($courseid) { global $DB; if (empty($courseid)) { return array(array(), array()); } $courseid = (int)$courseid; // Get info on any glossaries in this course. $modinfo = get_fast_modinfo($courseid); $cminfos = $modinfo->get_instances_of('glossary'); if (!$cminfos) { // No glossaries in this course, so don't do any work. return array(array(), array()); } $cache = \cache::make('mod_glossary', 'concepts'); $data = $cache->get($courseid); if (is_array($data)) { list($glossaries, $allconcepts) = $data; } else { // Find all course glossaries. $sql = "SELECT g.id, g.name FROM {glossary} g JOIN {course_modules} cm ON (cm.instance = g.id) JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module) WHERE g.usedynalink = 1 AND g.course = :course AND cm.visible = 1 AND m.visible = 1 ORDER BY g.globalglossary, g.id"; $glossaries = $DB->get_records_sql_menu($sql, array('course' => $courseid)); if (!$glossaries) { $data = array(array(), array()); $cache->set($courseid, $data); return $data; } foreach ($glossaries as $id => $name) { $name = str_replace(':', '-', $name); $glossaries[$id] = replace_ampersands_not_followed_by_entity(strip_tags($name)); } $allconcepts = self::fetch_concepts(array_keys($glossaries)); foreach ($glossaries as $gid => $unused) { if (!isset($allconcepts[$gid])) { unset($glossaries[$gid]); } } if (!$glossaries) { // This means there are no interesting concepts in the existing glossaries. $data = array(array(), array()); $cache->set($courseid, $data); return $data; } $cache->set($courseid, array($glossaries, $allconcepts)); } $concepts = $allconcepts; // Verify access control to glossary instances. foreach ($concepts as $modid => $unused) { if (!isset($cminfos[$modid])) { // This should not happen. unset($concepts[$modid]); unset($glossaries[$modid]); continue; } if (!$cminfos[$modid]->uservisible) { unset($concepts[$modid]); unset($glossaries[$modid]); continue; } } return array($glossaries, $concepts); }
[ "protected", "static", "function", "get_course_concepts", "(", "$", "courseid", ")", "{", "global", "$", "DB", ";", "if", "(", "empty", "(", "$", "courseid", ")", ")", "{", "return", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "}", "$", "courseid", "=", "(", "int", ")", "$", "courseid", ";", "// Get info on any glossaries in this course.", "$", "modinfo", "=", "get_fast_modinfo", "(", "$", "courseid", ")", ";", "$", "cminfos", "=", "$", "modinfo", "->", "get_instances_of", "(", "'glossary'", ")", ";", "if", "(", "!", "$", "cminfos", ")", "{", "// No glossaries in this course, so don't do any work.", "return", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "}", "$", "cache", "=", "\\", "cache", "::", "make", "(", "'mod_glossary'", ",", "'concepts'", ")", ";", "$", "data", "=", "$", "cache", "->", "get", "(", "$", "courseid", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "list", "(", "$", "glossaries", ",", "$", "allconcepts", ")", "=", "$", "data", ";", "}", "else", "{", "// Find all course glossaries.", "$", "sql", "=", "\"SELECT g.id, g.name\n FROM {glossary} g\n JOIN {course_modules} cm ON (cm.instance = g.id)\n JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module)\n WHERE g.usedynalink = 1 AND g.course = :course AND cm.visible = 1 AND m.visible = 1\n ORDER BY g.globalglossary, g.id\"", ";", "$", "glossaries", "=", "$", "DB", "->", "get_records_sql_menu", "(", "$", "sql", ",", "array", "(", "'course'", "=>", "$", "courseid", ")", ")", ";", "if", "(", "!", "$", "glossaries", ")", "{", "$", "data", "=", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "$", "cache", "->", "set", "(", "$", "courseid", ",", "$", "data", ")", ";", "return", "$", "data", ";", "}", "foreach", "(", "$", "glossaries", "as", "$", "id", "=>", "$", "name", ")", "{", "$", "name", "=", "str_replace", "(", "':'", ",", "'-'", ",", "$", "name", ")", ";", "$", "glossaries", "[", "$", "id", "]", "=", "replace_ampersands_not_followed_by_entity", "(", "strip_tags", "(", "$", "name", ")", ")", ";", "}", "$", "allconcepts", "=", "self", "::", "fetch_concepts", "(", "array_keys", "(", "$", "glossaries", ")", ")", ";", "foreach", "(", "$", "glossaries", "as", "$", "gid", "=>", "$", "unused", ")", "{", "if", "(", "!", "isset", "(", "$", "allconcepts", "[", "$", "gid", "]", ")", ")", "{", "unset", "(", "$", "glossaries", "[", "$", "gid", "]", ")", ";", "}", "}", "if", "(", "!", "$", "glossaries", ")", "{", "// This means there are no interesting concepts in the existing glossaries.", "$", "data", "=", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "$", "cache", "->", "set", "(", "$", "courseid", ",", "$", "data", ")", ";", "return", "$", "data", ";", "}", "$", "cache", "->", "set", "(", "$", "courseid", ",", "array", "(", "$", "glossaries", ",", "$", "allconcepts", ")", ")", ";", "}", "$", "concepts", "=", "$", "allconcepts", ";", "// Verify access control to glossary instances.", "foreach", "(", "$", "concepts", "as", "$", "modid", "=>", "$", "unused", ")", "{", "if", "(", "!", "isset", "(", "$", "cminfos", "[", "$", "modid", "]", ")", ")", "{", "// This should not happen.", "unset", "(", "$", "concepts", "[", "$", "modid", "]", ")", ";", "unset", "(", "$", "glossaries", "[", "$", "modid", "]", ")", ";", "continue", ";", "}", "if", "(", "!", "$", "cminfos", "[", "$", "modid", "]", "->", "uservisible", ")", "{", "unset", "(", "$", "concepts", "[", "$", "modid", "]", ")", ";", "unset", "(", "$", "glossaries", "[", "$", "modid", "]", ")", ";", "continue", ";", "}", "}", "return", "array", "(", "$", "glossaries", ",", "$", "concepts", ")", ";", "}" ]
Get all linked concepts from course. @param int $courseid @return array
[ "Get", "all", "linked", "concepts", "from", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L153-L227
220,275
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.get_global_concepts
protected static function get_global_concepts() { global $DB; $cache = \cache::make('mod_glossary', 'concepts'); $data = $cache->get(0); if (is_array($data)) { list($glossaries, $allconcepts) = $data; } else { // Find all global glossaries - no access control here. $sql = "SELECT g.id, g.name FROM {glossary} g JOIN {course_modules} cm ON (cm.instance = g.id) JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module) WHERE g.usedynalink = 1 AND g.globalglossary = 1 AND cm.visible = 1 AND m.visible = 1 ORDER BY g.globalglossary, g.id"; $glossaries = $DB->get_records_sql_menu($sql); if (!$glossaries) { $data = array(array(), array()); $cache->set(0, $data); return $data; } foreach ($glossaries as $id => $name) { $name = str_replace(':', '-', $name); $glossaries[$id] = replace_ampersands_not_followed_by_entity(strip_tags($name)); } $allconcepts = self::fetch_concepts(array_keys($glossaries)); foreach ($glossaries as $gid => $unused) { if (!isset($allconcepts[$gid])) { unset($glossaries[$gid]); } } $cache->set(0, array($glossaries, $allconcepts)); } // NOTE: no access control is here because it would be way too expensive to check access // to all courses that contain the global glossaries. return array($glossaries, $allconcepts); }
php
protected static function get_global_concepts() { global $DB; $cache = \cache::make('mod_glossary', 'concepts'); $data = $cache->get(0); if (is_array($data)) { list($glossaries, $allconcepts) = $data; } else { // Find all global glossaries - no access control here. $sql = "SELECT g.id, g.name FROM {glossary} g JOIN {course_modules} cm ON (cm.instance = g.id) JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module) WHERE g.usedynalink = 1 AND g.globalglossary = 1 AND cm.visible = 1 AND m.visible = 1 ORDER BY g.globalglossary, g.id"; $glossaries = $DB->get_records_sql_menu($sql); if (!$glossaries) { $data = array(array(), array()); $cache->set(0, $data); return $data; } foreach ($glossaries as $id => $name) { $name = str_replace(':', '-', $name); $glossaries[$id] = replace_ampersands_not_followed_by_entity(strip_tags($name)); } $allconcepts = self::fetch_concepts(array_keys($glossaries)); foreach ($glossaries as $gid => $unused) { if (!isset($allconcepts[$gid])) { unset($glossaries[$gid]); } } $cache->set(0, array($glossaries, $allconcepts)); } // NOTE: no access control is here because it would be way too expensive to check access // to all courses that contain the global glossaries. return array($glossaries, $allconcepts); }
[ "protected", "static", "function", "get_global_concepts", "(", ")", "{", "global", "$", "DB", ";", "$", "cache", "=", "\\", "cache", "::", "make", "(", "'mod_glossary'", ",", "'concepts'", ")", ";", "$", "data", "=", "$", "cache", "->", "get", "(", "0", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "list", "(", "$", "glossaries", ",", "$", "allconcepts", ")", "=", "$", "data", ";", "}", "else", "{", "// Find all global glossaries - no access control here.", "$", "sql", "=", "\"SELECT g.id, g.name\n FROM {glossary} g\n JOIN {course_modules} cm ON (cm.instance = g.id)\n JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module)\n WHERE g.usedynalink = 1 AND g.globalglossary = 1 AND cm.visible = 1 AND m.visible = 1\n ORDER BY g.globalglossary, g.id\"", ";", "$", "glossaries", "=", "$", "DB", "->", "get_records_sql_menu", "(", "$", "sql", ")", ";", "if", "(", "!", "$", "glossaries", ")", "{", "$", "data", "=", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "$", "cache", "->", "set", "(", "0", ",", "$", "data", ")", ";", "return", "$", "data", ";", "}", "foreach", "(", "$", "glossaries", "as", "$", "id", "=>", "$", "name", ")", "{", "$", "name", "=", "str_replace", "(", "':'", ",", "'-'", ",", "$", "name", ")", ";", "$", "glossaries", "[", "$", "id", "]", "=", "replace_ampersands_not_followed_by_entity", "(", "strip_tags", "(", "$", "name", ")", ")", ";", "}", "$", "allconcepts", "=", "self", "::", "fetch_concepts", "(", "array_keys", "(", "$", "glossaries", ")", ")", ";", "foreach", "(", "$", "glossaries", "as", "$", "gid", "=>", "$", "unused", ")", "{", "if", "(", "!", "isset", "(", "$", "allconcepts", "[", "$", "gid", "]", ")", ")", "{", "unset", "(", "$", "glossaries", "[", "$", "gid", "]", ")", ";", "}", "}", "$", "cache", "->", "set", "(", "0", ",", "array", "(", "$", "glossaries", ",", "$", "allconcepts", ")", ")", ";", "}", "// NOTE: no access control is here because it would be way too expensive to check access", "// to all courses that contain the global glossaries.", "return", "array", "(", "$", "glossaries", ",", "$", "allconcepts", ")", ";", "}" ]
Get all linked global concepts. @return array
[ "Get", "all", "linked", "global", "concepts", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L233-L271
220,276
moodle/moodle
mod/glossary/classes/local/concept_cache.php
concept_cache.get_concepts
public static function get_concepts($courseid) { list($glossaries, $concepts) = self::get_course_concepts($courseid); list($globalglossaries, $globalconcepts) = self::get_global_concepts(); foreach ($globalconcepts as $gid => $cs) { if (!isset($concepts[$gid])) { $concepts[$gid] = $cs; } } foreach ($globalglossaries as $gid => $name) { if (!isset($glossaries[$gid])) { $glossaries[$gid] = $name; } } return array($glossaries, $concepts); }
php
public static function get_concepts($courseid) { list($glossaries, $concepts) = self::get_course_concepts($courseid); list($globalglossaries, $globalconcepts) = self::get_global_concepts(); foreach ($globalconcepts as $gid => $cs) { if (!isset($concepts[$gid])) { $concepts[$gid] = $cs; } } foreach ($globalglossaries as $gid => $name) { if (!isset($glossaries[$gid])) { $glossaries[$gid] = $name; } } return array($glossaries, $concepts); }
[ "public", "static", "function", "get_concepts", "(", "$", "courseid", ")", "{", "list", "(", "$", "glossaries", ",", "$", "concepts", ")", "=", "self", "::", "get_course_concepts", "(", "$", "courseid", ")", ";", "list", "(", "$", "globalglossaries", ",", "$", "globalconcepts", ")", "=", "self", "::", "get_global_concepts", "(", ")", ";", "foreach", "(", "$", "globalconcepts", "as", "$", "gid", "=>", "$", "cs", ")", "{", "if", "(", "!", "isset", "(", "$", "concepts", "[", "$", "gid", "]", ")", ")", "{", "$", "concepts", "[", "$", "gid", "]", "=", "$", "cs", ";", "}", "}", "foreach", "(", "$", "globalglossaries", "as", "$", "gid", "=>", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "glossaries", "[", "$", "gid", "]", ")", ")", "{", "$", "glossaries", "[", "$", "gid", "]", "=", "$", "name", ";", "}", "}", "return", "array", "(", "$", "glossaries", ",", "$", "concepts", ")", ";", "}" ]
Get all concepts that should be linked in the given course. @param int $courseid @return array with two elements - array of glossaries and concepts for each glossary
[ "Get", "all", "concepts", "that", "should", "be", "linked", "in", "the", "given", "course", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/glossary/classes/local/concept_cache.php#L278-L294
220,277
moodle/moodle
lib/pear/HTML/QuickForm/Rule/Regex.php
HTML_QuickForm_Rule_Regex.validate
function validate($value, $regex = null) { if (isset($this->_data[$this->name])) { if (!preg_match($this->_data[$this->name], $value)) { return false; } } else { if (!preg_match($regex, $value)) { return false; } } return true; }
php
function validate($value, $regex = null) { if (isset($this->_data[$this->name])) { if (!preg_match($this->_data[$this->name], $value)) { return false; } } else { if (!preg_match($regex, $value)) { return false; } } return true; }
[ "function", "validate", "(", "$", "value", ",", "$", "regex", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_data", "[", "$", "this", "->", "name", "]", ")", ")", "{", "if", "(", "!", "preg_match", "(", "$", "this", "->", "_data", "[", "$", "this", "->", "name", "]", ",", "$", "value", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "if", "(", "!", "preg_match", "(", "$", "regex", ",", "$", "value", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Validates a value using a regular expression @param string $value Value to be checked @param string $regex Regular expression @access public @return boolean true if value is valid
[ "Validates", "a", "value", "using", "a", "regular", "expression" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/pear/HTML/QuickForm/Rule/Regex.php#L54-L66
220,278
moodle/moodle
admin/tool/dataprivacy/classes/form/contextlevel.php
contextlevel.get_contextlevel_customdata
public static function get_contextlevel_customdata($contextlevel) { $persistent = \tool_dataprivacy\contextlevel::get_record_by_contextlevel($contextlevel, false); if (!$persistent) { $persistent = new \tool_dataprivacy\contextlevel(); $persistent->set('contextlevel', $contextlevel); } $includeinherit = true; if ($contextlevel == CONTEXT_SYSTEM) { // Nothing to inherit from Site level. $includeinherit = false; } $includenotset = true; if ($contextlevel == CONTEXT_SYSTEM || $contextlevel == CONTEXT_USER) { // No 'not set' value for system and user because we do not have defaults for them. $includenotset = false; } $purposeoptions = \tool_dataprivacy\output\data_registry_page::purpose_options( api::get_purposes(), $includenotset, $includeinherit); $categoryoptions = \tool_dataprivacy\output\data_registry_page::category_options( api::get_categories(), $includenotset, $includeinherit); $customdata = [ 'contextlevel' => $contextlevel, 'contextlevelname' => get_string('contextlevelname' . $contextlevel, 'tool_dataprivacy'), 'persistent' => $persistent, 'purposes' => $purposeoptions, 'categories' => $categoryoptions, ]; $effectivepurpose = api::get_effective_contextlevel_purpose($contextlevel); if ($effectivepurpose) { $customdata['currentretentionperiod'] = self::get_retention_display_text($effectivepurpose, $contextlevel, \context_system::instance()); $customdata['purposeretentionperiods'] = []; foreach ($purposeoptions as $optionvalue => $unused) { // Get the effective purpose if $optionvalue would be the selected value. list($purposeid, $unused) = data_registry::get_effective_default_contextlevel_purpose_and_category($contextlevel, $optionvalue); $purpose = new \tool_dataprivacy\purpose($purposeid); $retentionperiod = self::get_retention_display_text( $purpose, $contextlevel, \context_system::instance() ); $customdata['purposeretentionperiods'][$optionvalue] = $retentionperiod; } } return $customdata; }
php
public static function get_contextlevel_customdata($contextlevel) { $persistent = \tool_dataprivacy\contextlevel::get_record_by_contextlevel($contextlevel, false); if (!$persistent) { $persistent = new \tool_dataprivacy\contextlevel(); $persistent->set('contextlevel', $contextlevel); } $includeinherit = true; if ($contextlevel == CONTEXT_SYSTEM) { // Nothing to inherit from Site level. $includeinherit = false; } $includenotset = true; if ($contextlevel == CONTEXT_SYSTEM || $contextlevel == CONTEXT_USER) { // No 'not set' value for system and user because we do not have defaults for them. $includenotset = false; } $purposeoptions = \tool_dataprivacy\output\data_registry_page::purpose_options( api::get_purposes(), $includenotset, $includeinherit); $categoryoptions = \tool_dataprivacy\output\data_registry_page::category_options( api::get_categories(), $includenotset, $includeinherit); $customdata = [ 'contextlevel' => $contextlevel, 'contextlevelname' => get_string('contextlevelname' . $contextlevel, 'tool_dataprivacy'), 'persistent' => $persistent, 'purposes' => $purposeoptions, 'categories' => $categoryoptions, ]; $effectivepurpose = api::get_effective_contextlevel_purpose($contextlevel); if ($effectivepurpose) { $customdata['currentretentionperiod'] = self::get_retention_display_text($effectivepurpose, $contextlevel, \context_system::instance()); $customdata['purposeretentionperiods'] = []; foreach ($purposeoptions as $optionvalue => $unused) { // Get the effective purpose if $optionvalue would be the selected value. list($purposeid, $unused) = data_registry::get_effective_default_contextlevel_purpose_and_category($contextlevel, $optionvalue); $purpose = new \tool_dataprivacy\purpose($purposeid); $retentionperiod = self::get_retention_display_text( $purpose, $contextlevel, \context_system::instance() ); $customdata['purposeretentionperiods'][$optionvalue] = $retentionperiod; } } return $customdata; }
[ "public", "static", "function", "get_contextlevel_customdata", "(", "$", "contextlevel", ")", "{", "$", "persistent", "=", "\\", "tool_dataprivacy", "\\", "contextlevel", "::", "get_record_by_contextlevel", "(", "$", "contextlevel", ",", "false", ")", ";", "if", "(", "!", "$", "persistent", ")", "{", "$", "persistent", "=", "new", "\\", "tool_dataprivacy", "\\", "contextlevel", "(", ")", ";", "$", "persistent", "->", "set", "(", "'contextlevel'", ",", "$", "contextlevel", ")", ";", "}", "$", "includeinherit", "=", "true", ";", "if", "(", "$", "contextlevel", "==", "CONTEXT_SYSTEM", ")", "{", "// Nothing to inherit from Site level.", "$", "includeinherit", "=", "false", ";", "}", "$", "includenotset", "=", "true", ";", "if", "(", "$", "contextlevel", "==", "CONTEXT_SYSTEM", "||", "$", "contextlevel", "==", "CONTEXT_USER", ")", "{", "// No 'not set' value for system and user because we do not have defaults for them.", "$", "includenotset", "=", "false", ";", "}", "$", "purposeoptions", "=", "\\", "tool_dataprivacy", "\\", "output", "\\", "data_registry_page", "::", "purpose_options", "(", "api", "::", "get_purposes", "(", ")", ",", "$", "includenotset", ",", "$", "includeinherit", ")", ";", "$", "categoryoptions", "=", "\\", "tool_dataprivacy", "\\", "output", "\\", "data_registry_page", "::", "category_options", "(", "api", "::", "get_categories", "(", ")", ",", "$", "includenotset", ",", "$", "includeinherit", ")", ";", "$", "customdata", "=", "[", "'contextlevel'", "=>", "$", "contextlevel", ",", "'contextlevelname'", "=>", "get_string", "(", "'contextlevelname'", ".", "$", "contextlevel", ",", "'tool_dataprivacy'", ")", ",", "'persistent'", "=>", "$", "persistent", ",", "'purposes'", "=>", "$", "purposeoptions", ",", "'categories'", "=>", "$", "categoryoptions", ",", "]", ";", "$", "effectivepurpose", "=", "api", "::", "get_effective_contextlevel_purpose", "(", "$", "contextlevel", ")", ";", "if", "(", "$", "effectivepurpose", ")", "{", "$", "customdata", "[", "'currentretentionperiod'", "]", "=", "self", "::", "get_retention_display_text", "(", "$", "effectivepurpose", ",", "$", "contextlevel", ",", "\\", "context_system", "::", "instance", "(", ")", ")", ";", "$", "customdata", "[", "'purposeretentionperiods'", "]", "=", "[", "]", ";", "foreach", "(", "$", "purposeoptions", "as", "$", "optionvalue", "=>", "$", "unused", ")", "{", "// Get the effective purpose if $optionvalue would be the selected value.", "list", "(", "$", "purposeid", ",", "$", "unused", ")", "=", "data_registry", "::", "get_effective_default_contextlevel_purpose_and_category", "(", "$", "contextlevel", ",", "$", "optionvalue", ")", ";", "$", "purpose", "=", "new", "\\", "tool_dataprivacy", "\\", "purpose", "(", "$", "purposeid", ")", ";", "$", "retentionperiod", "=", "self", "::", "get_retention_display_text", "(", "$", "purpose", ",", "$", "contextlevel", ",", "\\", "context_system", "::", "instance", "(", ")", ")", ";", "$", "customdata", "[", "'purposeretentionperiods'", "]", "[", "$", "optionvalue", "]", "=", "$", "retentionperiod", ";", "}", "}", "return", "$", "customdata", ";", "}" ]
Returns the customdata array for the provided context level. @param int $contextlevel @return array
[ "Returns", "the", "customdata", "array", "for", "the", "provided", "context", "level", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/dataprivacy/classes/form/contextlevel.php#L68-L123
220,279
moodle/moodle
mod/assign/feedback/editpdf/backup/moodle2/restore_assignfeedback_editpdf_subplugin.class.php
restore_assignfeedback_editpdf_subplugin.process_assignfeedback_editpdf_files
public function process_assignfeedback_editpdf_files($data) { $data = (object)$data; // In this case the id is the old gradeid which will be mapped. $this->add_related_files('assignfeedback_editpdf', \assignfeedback_editpdf\document_services::FINAL_PDF_FILEAREA, 'grade', null, $data->gradeid); $this->add_related_files('assignfeedback_editpdf', \assignfeedback_editpdf\document_services::PAGE_IMAGE_READONLY_FILEAREA, 'grade', null, $data->gradeid); $this->add_related_files('assignfeedback_editpdf', 'stamps', 'grade', null, $data->gradeid); }
php
public function process_assignfeedback_editpdf_files($data) { $data = (object)$data; // In this case the id is the old gradeid which will be mapped. $this->add_related_files('assignfeedback_editpdf', \assignfeedback_editpdf\document_services::FINAL_PDF_FILEAREA, 'grade', null, $data->gradeid); $this->add_related_files('assignfeedback_editpdf', \assignfeedback_editpdf\document_services::PAGE_IMAGE_READONLY_FILEAREA, 'grade', null, $data->gradeid); $this->add_related_files('assignfeedback_editpdf', 'stamps', 'grade', null, $data->gradeid); }
[ "public", "function", "process_assignfeedback_editpdf_files", "(", "$", "data", ")", "{", "$", "data", "=", "(", "object", ")", "$", "data", ";", "// In this case the id is the old gradeid which will be mapped.", "$", "this", "->", "add_related_files", "(", "'assignfeedback_editpdf'", ",", "\\", "assignfeedback_editpdf", "\\", "document_services", "::", "FINAL_PDF_FILEAREA", ",", "'grade'", ",", "null", ",", "$", "data", "->", "gradeid", ")", ";", "$", "this", "->", "add_related_files", "(", "'assignfeedback_editpdf'", ",", "\\", "assignfeedback_editpdf", "\\", "document_services", "::", "PAGE_IMAGE_READONLY_FILEAREA", ",", "'grade'", ",", "null", ",", "$", "data", "->", "gradeid", ")", ";", "$", "this", "->", "add_related_files", "(", "'assignfeedback_editpdf'", ",", "'stamps'", ",", "'grade'", ",", "null", ",", "$", "data", "->", "gradeid", ")", ";", "}" ]
Processes one feedback_editpdf_files element @param mixed $data
[ "Processes", "one", "feedback_editpdf_files", "element" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/assign/feedback/editpdf/backup/moodle2/restore_assignfeedback_editpdf_subplugin.class.php#L72-L81
220,280
moodle/moodle
lib/horde/framework/Horde/Array.php
Horde_Array.arraySort
public static function arraySort(array &$array, $key = null, $dir = 0, $assoc = true) { /* Return if the array is empty. */ if (empty($array)) { return; } /* If no key to sort by is specified, use the first key of the * first element. */ if (is_null($key)) { $keys = array_keys(reset($array)); $key = array_shift($keys); } /* Call the appropriate sort function. */ $helper = new Horde_Array_Sort_Helper(); $helper->key = $key; $function = $dir ? 'reverseCompare' : 'compare'; if ($assoc) { uasort($array, array($helper, $function)); } else { usort($array, array($helper, $function)); } }
php
public static function arraySort(array &$array, $key = null, $dir = 0, $assoc = true) { /* Return if the array is empty. */ if (empty($array)) { return; } /* If no key to sort by is specified, use the first key of the * first element. */ if (is_null($key)) { $keys = array_keys(reset($array)); $key = array_shift($keys); } /* Call the appropriate sort function. */ $helper = new Horde_Array_Sort_Helper(); $helper->key = $key; $function = $dir ? 'reverseCompare' : 'compare'; if ($assoc) { uasort($array, array($helper, $function)); } else { usort($array, array($helper, $function)); } }
[ "public", "static", "function", "arraySort", "(", "array", "&", "$", "array", ",", "$", "key", "=", "null", ",", "$", "dir", "=", "0", ",", "$", "assoc", "=", "true", ")", "{", "/* Return if the array is empty. */", "if", "(", "empty", "(", "$", "array", ")", ")", "{", "return", ";", "}", "/* If no key to sort by is specified, use the first key of the\n * first element. */", "if", "(", "is_null", "(", "$", "key", ")", ")", "{", "$", "keys", "=", "array_keys", "(", "reset", "(", "$", "array", ")", ")", ";", "$", "key", "=", "array_shift", "(", "$", "keys", ")", ";", "}", "/* Call the appropriate sort function. */", "$", "helper", "=", "new", "Horde_Array_Sort_Helper", "(", ")", ";", "$", "helper", "->", "key", "=", "$", "key", ";", "$", "function", "=", "$", "dir", "?", "'reverseCompare'", ":", "'compare'", ";", "if", "(", "$", "assoc", ")", "{", "uasort", "(", "$", "array", ",", "array", "(", "$", "helper", ",", "$", "function", ")", ")", ";", "}", "else", "{", "usort", "(", "$", "array", ",", "array", "(", "$", "helper", ",", "$", "function", ")", ")", ";", "}", "}" ]
Sorts an array on a specified key. If the key does not exist, defaults to the first key of the array. @param array &$array The array to be sorted, passed by reference. @param string $key The key by which to sort. If not specified then the first key is used. @param integer $dir Sort direction: 0 = ascending (default) 1 = descending @param boolean $assoc Keep key value association?
[ "Sorts", "an", "array", "on", "a", "specified", "key", ".", "If", "the", "key", "does", "not", "exist", "defaults", "to", "the", "first", "key", "of", "the", "array", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Array.php#L31-L55
220,281
moodle/moodle
lib/horde/framework/Horde/Array.php
Horde_Array.getElement
public static function getElement(&$array, array &$keys, $value = null) { if (count($keys)) { $key = array_shift($keys); return isset($array[$key]) ? self::getElement($array[$key], $keys, $value) : false; } if (!is_null($value)) { $array = $value; } return $array; }
php
public static function getElement(&$array, array &$keys, $value = null) { if (count($keys)) { $key = array_shift($keys); return isset($array[$key]) ? self::getElement($array[$key], $keys, $value) : false; } if (!is_null($value)) { $array = $value; } return $array; }
[ "public", "static", "function", "getElement", "(", "&", "$", "array", ",", "array", "&", "$", "keys", ",", "$", "value", "=", "null", ")", "{", "if", "(", "count", "(", "$", "keys", ")", ")", "{", "$", "key", "=", "array_shift", "(", "$", "keys", ")", ";", "return", "isset", "(", "$", "array", "[", "$", "key", "]", ")", "?", "self", "::", "getElement", "(", "$", "array", "[", "$", "key", "]", ",", "$", "keys", ",", "$", "value", ")", ":", "false", ";", "}", "if", "(", "!", "is_null", "(", "$", "value", ")", ")", "{", "$", "array", "=", "$", "value", ";", "}", "return", "$", "array", ";", "}" ]
Using an array of keys iterate through the array following the keys to find the final key value. If a value is passed then set that value. @param array &$array The array to be used. @param array &$keys The key path to follow as an array. @param array $value If set the target element will have this value set to it. @return mixed The final value of the key path.
[ "Using", "an", "array", "of", "keys", "iterate", "through", "the", "array", "following", "the", "keys", "to", "find", "the", "final", "key", "value", ".", "If", "a", "value", "is", "passed", "then", "set", "that", "value", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Array.php#L92-L106
220,282
moodle/moodle
lib/horde/framework/Horde/Array.php
Horde_Array.getRectangle
public static function getRectangle(array $array, $row, $col, $height, $width) { $rec = array(); for ($y = $row; $y < $row + $height; $y++) { $rec[] = array_slice($array[$y], $col, $width); } return $rec; }
php
public static function getRectangle(array $array, $row, $col, $height, $width) { $rec = array(); for ($y = $row; $y < $row + $height; $y++) { $rec[] = array_slice($array[$y], $col, $width); } return $rec; }
[ "public", "static", "function", "getRectangle", "(", "array", "$", "array", ",", "$", "row", ",", "$", "col", ",", "$", "height", ",", "$", "width", ")", "{", "$", "rec", "=", "array", "(", ")", ";", "for", "(", "$", "y", "=", "$", "row", ";", "$", "y", "<", "$", "row", "+", "$", "height", ";", "$", "y", "++", ")", "{", "$", "rec", "[", "]", "=", "array_slice", "(", "$", "array", "[", "$", "y", "]", ",", "$", "col", ",", "$", "width", ")", ";", "}", "return", "$", "rec", ";", "}" ]
Returns a rectangle of a two-dimensional array. @param array $array The array to extract the rectangle from. @param integer $row The start row of the rectangle. @param integer $col The start column of the rectangle. @param integer $height The height of the rectangle. @param integer $width The width of the rectangle. @return array The extracted rectangle.
[ "Returns", "a", "rectangle", "of", "a", "two", "-", "dimensional", "array", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Array.php#L119-L127
220,283
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.process
final public function process($data) { if (!array_key_exists($data['path'], $this->pathelements)) { // Incorrect path, must not happen throw new restore_step_exception('restore_structure_step_missing_path', $data['path']); } $element = $this->pathelements[$data['path']]; $object = $element->get_processing_object(); $method = $element->get_processing_method(); $rdata = null; if (empty($object)) { // No processing object defined throw new restore_step_exception('restore_structure_step_missing_pobject', $object); } // Release the lock if we aren't anymore within children of it if (!is_null($this->pathlock) and strpos($data['path'], $this->pathlock) === false) { $this->pathlock = null; } if (is_null($this->pathlock)) { // Only dispatch if there isn't any lock $rdata = $object->$method($data['tags']); // Dispatch to proper object/method } // If the dispatched method returns SKIP_ALL_CHILDREN, we grab current path in order to // lock dispatching to any children if ($rdata === self::SKIP_ALL_CHILDREN) { // Check we haven't any previous lock if (!is_null($this->pathlock)) { throw new restore_step_exception('restore_structure_step_already_skipping', $data['path']); } // Set the lock $this->pathlock = $data['path'] . '/'; // Lock everything below current path // Continue with normal processing of return values } else if ($rdata !== null) { // If the method has returned any info, set element data to it $element->set_data($rdata); } else { // Else, put the original parsed data $element->set_data($data); } }
php
final public function process($data) { if (!array_key_exists($data['path'], $this->pathelements)) { // Incorrect path, must not happen throw new restore_step_exception('restore_structure_step_missing_path', $data['path']); } $element = $this->pathelements[$data['path']]; $object = $element->get_processing_object(); $method = $element->get_processing_method(); $rdata = null; if (empty($object)) { // No processing object defined throw new restore_step_exception('restore_structure_step_missing_pobject', $object); } // Release the lock if we aren't anymore within children of it if (!is_null($this->pathlock) and strpos($data['path'], $this->pathlock) === false) { $this->pathlock = null; } if (is_null($this->pathlock)) { // Only dispatch if there isn't any lock $rdata = $object->$method($data['tags']); // Dispatch to proper object/method } // If the dispatched method returns SKIP_ALL_CHILDREN, we grab current path in order to // lock dispatching to any children if ($rdata === self::SKIP_ALL_CHILDREN) { // Check we haven't any previous lock if (!is_null($this->pathlock)) { throw new restore_step_exception('restore_structure_step_already_skipping', $data['path']); } // Set the lock $this->pathlock = $data['path'] . '/'; // Lock everything below current path // Continue with normal processing of return values } else if ($rdata !== null) { // If the method has returned any info, set element data to it $element->set_data($rdata); } else { // Else, put the original parsed data $element->set_data($data); } }
[ "final", "public", "function", "process", "(", "$", "data", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "data", "[", "'path'", "]", ",", "$", "this", "->", "pathelements", ")", ")", "{", "// Incorrect path, must not happen", "throw", "new", "restore_step_exception", "(", "'restore_structure_step_missing_path'", ",", "$", "data", "[", "'path'", "]", ")", ";", "}", "$", "element", "=", "$", "this", "->", "pathelements", "[", "$", "data", "[", "'path'", "]", "]", ";", "$", "object", "=", "$", "element", "->", "get_processing_object", "(", ")", ";", "$", "method", "=", "$", "element", "->", "get_processing_method", "(", ")", ";", "$", "rdata", "=", "null", ";", "if", "(", "empty", "(", "$", "object", ")", ")", "{", "// No processing object defined", "throw", "new", "restore_step_exception", "(", "'restore_structure_step_missing_pobject'", ",", "$", "object", ")", ";", "}", "// Release the lock if we aren't anymore within children of it", "if", "(", "!", "is_null", "(", "$", "this", "->", "pathlock", ")", "and", "strpos", "(", "$", "data", "[", "'path'", "]", ",", "$", "this", "->", "pathlock", ")", "===", "false", ")", "{", "$", "this", "->", "pathlock", "=", "null", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "pathlock", ")", ")", "{", "// Only dispatch if there isn't any lock", "$", "rdata", "=", "$", "object", "->", "$", "method", "(", "$", "data", "[", "'tags'", "]", ")", ";", "// Dispatch to proper object/method", "}", "// If the dispatched method returns SKIP_ALL_CHILDREN, we grab current path in order to", "// lock dispatching to any children", "if", "(", "$", "rdata", "===", "self", "::", "SKIP_ALL_CHILDREN", ")", "{", "// Check we haven't any previous lock", "if", "(", "!", "is_null", "(", "$", "this", "->", "pathlock", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'restore_structure_step_already_skipping'", ",", "$", "data", "[", "'path'", "]", ")", ";", "}", "// Set the lock", "$", "this", "->", "pathlock", "=", "$", "data", "[", "'path'", "]", ".", "'/'", ";", "// Lock everything below current path", "// Continue with normal processing of return values", "}", "else", "if", "(", "$", "rdata", "!==", "null", ")", "{", "// If the method has returned any info, set element data to it", "$", "element", "->", "set_data", "(", "$", "rdata", ")", ";", "}", "else", "{", "// Else, put the original parsed data", "$", "element", "->", "set_data", "(", "$", "data", ")", ";", "}", "}" ]
Receive one chunk of information form the xml parser processor and dispatch it, following the naming rules
[ "Receive", "one", "chunk", "of", "information", "form", "the", "xml", "parser", "processor", "and", "dispatch", "it", "following", "the", "naming", "rules" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L121-L156
220,284
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.add_plugin_structure
protected function add_plugin_structure($plugintype, $element) { global $CFG; // Check the requested plugintype is a valid one if (!array_key_exists($plugintype, core_component::get_plugin_types($plugintype))) { throw new restore_step_exception('incorrect_plugin_type', $plugintype); } // Get all the restore path elements, looking across all the plugin dirs $pluginsdirs = core_component::get_plugin_list($plugintype); foreach ($pluginsdirs as $name => $pluginsdir) { // We need to add also backup plugin classes on restore, they may contain // some stuff used both in backup & restore $backupclassname = 'backup_' . $plugintype . '_' . $name . '_plugin'; $backupfile = $pluginsdir . '/backup/moodle2/' . $backupclassname . '.class.php'; if (file_exists($backupfile)) { require_once($backupfile); } // Now add restore plugin classes and prepare stuff $restoreclassname = 'restore_' . $plugintype . '_' . $name . '_plugin'; $restorefile = $pluginsdir . '/backup/moodle2/' . $restoreclassname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoreplugin = new $restoreclassname($plugintype, $name, $this); // Add plugin paths to the step $this->prepare_pathelements($restoreplugin->define_plugin_structure($element)); } } }
php
protected function add_plugin_structure($plugintype, $element) { global $CFG; // Check the requested plugintype is a valid one if (!array_key_exists($plugintype, core_component::get_plugin_types($plugintype))) { throw new restore_step_exception('incorrect_plugin_type', $plugintype); } // Get all the restore path elements, looking across all the plugin dirs $pluginsdirs = core_component::get_plugin_list($plugintype); foreach ($pluginsdirs as $name => $pluginsdir) { // We need to add also backup plugin classes on restore, they may contain // some stuff used both in backup & restore $backupclassname = 'backup_' . $plugintype . '_' . $name . '_plugin'; $backupfile = $pluginsdir . '/backup/moodle2/' . $backupclassname . '.class.php'; if (file_exists($backupfile)) { require_once($backupfile); } // Now add restore plugin classes and prepare stuff $restoreclassname = 'restore_' . $plugintype . '_' . $name . '_plugin'; $restorefile = $pluginsdir . '/backup/moodle2/' . $restoreclassname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoreplugin = new $restoreclassname($plugintype, $name, $this); // Add plugin paths to the step $this->prepare_pathelements($restoreplugin->define_plugin_structure($element)); } } }
[ "protected", "function", "add_plugin_structure", "(", "$", "plugintype", ",", "$", "element", ")", "{", "global", "$", "CFG", ";", "// Check the requested plugintype is a valid one", "if", "(", "!", "array_key_exists", "(", "$", "plugintype", ",", "core_component", "::", "get_plugin_types", "(", "$", "plugintype", ")", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'incorrect_plugin_type'", ",", "$", "plugintype", ")", ";", "}", "// Get all the restore path elements, looking across all the plugin dirs", "$", "pluginsdirs", "=", "core_component", "::", "get_plugin_list", "(", "$", "plugintype", ")", ";", "foreach", "(", "$", "pluginsdirs", "as", "$", "name", "=>", "$", "pluginsdir", ")", "{", "// We need to add also backup plugin classes on restore, they may contain", "// some stuff used both in backup & restore", "$", "backupclassname", "=", "'backup_'", ".", "$", "plugintype", ".", "'_'", ".", "$", "name", ".", "'_plugin'", ";", "$", "backupfile", "=", "$", "pluginsdir", ".", "'/backup/moodle2/'", ".", "$", "backupclassname", ".", "'.class.php'", ";", "if", "(", "file_exists", "(", "$", "backupfile", ")", ")", "{", "require_once", "(", "$", "backupfile", ")", ";", "}", "// Now add restore plugin classes and prepare stuff", "$", "restoreclassname", "=", "'restore_'", ".", "$", "plugintype", ".", "'_'", ".", "$", "name", ".", "'_plugin'", ";", "$", "restorefile", "=", "$", "pluginsdir", ".", "'/backup/moodle2/'", ".", "$", "restoreclassname", ".", "'.class.php'", ";", "if", "(", "file_exists", "(", "$", "restorefile", ")", ")", "{", "require_once", "(", "$", "restorefile", ")", ";", "$", "restoreplugin", "=", "new", "$", "restoreclassname", "(", "$", "plugintype", ",", "$", "name", ",", "$", "this", ")", ";", "// Add plugin paths to the step", "$", "this", "->", "prepare_pathelements", "(", "$", "restoreplugin", "->", "define_plugin_structure", "(", "$", "element", ")", ")", ";", "}", "}", "}" ]
Add plugin structure to any element in the structure restore tree @param string $plugintype type of plugin as defined by core_component::get_plugin_types() @param restore_path_element $element element in the structure restore tree that we are going to add plugin information to
[ "Add", "plugin", "structure", "to", "any", "element", "in", "the", "structure", "restore", "tree" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L266-L295
220,285
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.add_subplugin_structure
protected function add_subplugin_structure($subplugintype, $element, $plugintype = null, $pluginname = null) { global $CFG; // This global declaration is required, because where we do require_once($backupfile); // That file may in turn try to do require_once($CFG->dirroot ...). // That worked in the past, we should keep it working. // Verify if this is a BC call for an activity restore. See NOTE above for this special case. if ($plugintype === null and $pluginname === null) { $plugintype = 'mod'; $pluginname = $this->task->get_modulename(); // TODO: Once all the calls have been changed to add both not null plugintype and pluginname, add a debugging here. } // Check the requested plugintype is a valid one. if (!array_key_exists($plugintype, core_component::get_plugin_types())) { throw new restore_step_exception('incorrect_plugin_type', $plugintype); } // Check the requested pluginname, for the specified plugintype, is a valid one. if (!array_key_exists($pluginname, core_component::get_plugin_list($plugintype))) { throw new restore_step_exception('incorrect_plugin_name', array($plugintype, $pluginname)); } // Check the requested subplugintype is a valid one. $subpluginsfile = core_component::get_component_directory($plugintype . '_' . $pluginname) . '/db/subplugins.php'; if (!file_exists($subpluginsfile)) { throw new restore_step_exception('plugin_missing_subplugins_php_file', array($plugintype, $pluginname)); } include($subpluginsfile); if (!array_key_exists($subplugintype, $subplugins)) { throw new restore_step_exception('incorrect_subplugin_type', $subplugintype); } // Every subplugin optionally can have a common/parent subplugin // class for shared stuff. $parentclass = 'restore_' . $plugintype . '_' . $pluginname . '_' . $subplugintype . '_subplugin'; $parentfile = core_component::get_component_directory($plugintype . '_' . $pluginname) . '/backup/moodle2/' . $parentclass . '.class.php'; if (file_exists($parentfile)) { require_once($parentfile); } // Get all the restore path elements, looking across all the subplugin dirs. $subpluginsdirs = core_component::get_plugin_list($subplugintype); foreach ($subpluginsdirs as $name => $subpluginsdir) { $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin'; $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoresubplugin = new $classname($subplugintype, $name, $this); // Add subplugin paths to the step. $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element)); } } }
php
protected function add_subplugin_structure($subplugintype, $element, $plugintype = null, $pluginname = null) { global $CFG; // This global declaration is required, because where we do require_once($backupfile); // That file may in turn try to do require_once($CFG->dirroot ...). // That worked in the past, we should keep it working. // Verify if this is a BC call for an activity restore. See NOTE above for this special case. if ($plugintype === null and $pluginname === null) { $plugintype = 'mod'; $pluginname = $this->task->get_modulename(); // TODO: Once all the calls have been changed to add both not null plugintype and pluginname, add a debugging here. } // Check the requested plugintype is a valid one. if (!array_key_exists($plugintype, core_component::get_plugin_types())) { throw new restore_step_exception('incorrect_plugin_type', $plugintype); } // Check the requested pluginname, for the specified plugintype, is a valid one. if (!array_key_exists($pluginname, core_component::get_plugin_list($plugintype))) { throw new restore_step_exception('incorrect_plugin_name', array($plugintype, $pluginname)); } // Check the requested subplugintype is a valid one. $subpluginsfile = core_component::get_component_directory($plugintype . '_' . $pluginname) . '/db/subplugins.php'; if (!file_exists($subpluginsfile)) { throw new restore_step_exception('plugin_missing_subplugins_php_file', array($plugintype, $pluginname)); } include($subpluginsfile); if (!array_key_exists($subplugintype, $subplugins)) { throw new restore_step_exception('incorrect_subplugin_type', $subplugintype); } // Every subplugin optionally can have a common/parent subplugin // class for shared stuff. $parentclass = 'restore_' . $plugintype . '_' . $pluginname . '_' . $subplugintype . '_subplugin'; $parentfile = core_component::get_component_directory($plugintype . '_' . $pluginname) . '/backup/moodle2/' . $parentclass . '.class.php'; if (file_exists($parentfile)) { require_once($parentfile); } // Get all the restore path elements, looking across all the subplugin dirs. $subpluginsdirs = core_component::get_plugin_list($subplugintype); foreach ($subpluginsdirs as $name => $subpluginsdir) { $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin'; $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoresubplugin = new $classname($subplugintype, $name, $this); // Add subplugin paths to the step. $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element)); } } }
[ "protected", "function", "add_subplugin_structure", "(", "$", "subplugintype", ",", "$", "element", ",", "$", "plugintype", "=", "null", ",", "$", "pluginname", "=", "null", ")", "{", "global", "$", "CFG", ";", "// This global declaration is required, because where we do require_once($backupfile);", "// That file may in turn try to do require_once($CFG->dirroot ...).", "// That worked in the past, we should keep it working.", "// Verify if this is a BC call for an activity restore. See NOTE above for this special case.", "if", "(", "$", "plugintype", "===", "null", "and", "$", "pluginname", "===", "null", ")", "{", "$", "plugintype", "=", "'mod'", ";", "$", "pluginname", "=", "$", "this", "->", "task", "->", "get_modulename", "(", ")", ";", "// TODO: Once all the calls have been changed to add both not null plugintype and pluginname, add a debugging here.", "}", "// Check the requested plugintype is a valid one.", "if", "(", "!", "array_key_exists", "(", "$", "plugintype", ",", "core_component", "::", "get_plugin_types", "(", ")", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'incorrect_plugin_type'", ",", "$", "plugintype", ")", ";", "}", "// Check the requested pluginname, for the specified plugintype, is a valid one.", "if", "(", "!", "array_key_exists", "(", "$", "pluginname", ",", "core_component", "::", "get_plugin_list", "(", "$", "plugintype", ")", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'incorrect_plugin_name'", ",", "array", "(", "$", "plugintype", ",", "$", "pluginname", ")", ")", ";", "}", "// Check the requested subplugintype is a valid one.", "$", "subpluginsfile", "=", "core_component", "::", "get_component_directory", "(", "$", "plugintype", ".", "'_'", ".", "$", "pluginname", ")", ".", "'/db/subplugins.php'", ";", "if", "(", "!", "file_exists", "(", "$", "subpluginsfile", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'plugin_missing_subplugins_php_file'", ",", "array", "(", "$", "plugintype", ",", "$", "pluginname", ")", ")", ";", "}", "include", "(", "$", "subpluginsfile", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "subplugintype", ",", "$", "subplugins", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'incorrect_subplugin_type'", ",", "$", "subplugintype", ")", ";", "}", "// Every subplugin optionally can have a common/parent subplugin", "// class for shared stuff.", "$", "parentclass", "=", "'restore_'", ".", "$", "plugintype", ".", "'_'", ".", "$", "pluginname", ".", "'_'", ".", "$", "subplugintype", ".", "'_subplugin'", ";", "$", "parentfile", "=", "core_component", "::", "get_component_directory", "(", "$", "plugintype", ".", "'_'", ".", "$", "pluginname", ")", ".", "'/backup/moodle2/'", ".", "$", "parentclass", ".", "'.class.php'", ";", "if", "(", "file_exists", "(", "$", "parentfile", ")", ")", "{", "require_once", "(", "$", "parentfile", ")", ";", "}", "// Get all the restore path elements, looking across all the subplugin dirs.", "$", "subpluginsdirs", "=", "core_component", "::", "get_plugin_list", "(", "$", "subplugintype", ")", ";", "foreach", "(", "$", "subpluginsdirs", "as", "$", "name", "=>", "$", "subpluginsdir", ")", "{", "$", "classname", "=", "'restore_'", ".", "$", "subplugintype", ".", "'_'", ".", "$", "name", ".", "'_subplugin'", ";", "$", "restorefile", "=", "$", "subpluginsdir", ".", "'/backup/moodle2/'", ".", "$", "classname", ".", "'.class.php'", ";", "if", "(", "file_exists", "(", "$", "restorefile", ")", ")", "{", "require_once", "(", "$", "restorefile", ")", ";", "$", "restoresubplugin", "=", "new", "$", "classname", "(", "$", "subplugintype", ",", "$", "name", ",", "$", "this", ")", ";", "// Add subplugin paths to the step.", "$", "this", "->", "prepare_pathelements", "(", "$", "restoresubplugin", "->", "define_subplugin_structure", "(", "$", "element", ")", ")", ";", "}", "}", "}" ]
Add subplugin structure for a given plugin to any element in the structure restore tree This method allows the injection of subplugins (of a specific plugin) parsing and proccessing to any element in the restore structure. NOTE: Initially subplugins were only available for activities (mod), so only the {@link restore_activity_structure_step} class had support for them, always looking for /mod/modulenanme subplugins. This new method is a generalization of the existing one for activities, supporting all subplugins injecting information everywhere. @param string $subplugintype type of subplugin as defined in plugin's db/subplugins.php. @param restore_path_element $element element in the structure restore tree that we are going to add subplugin information to. @param string $plugintype type of the plugin. @param string $pluginname name of the plugin. @return void
[ "Add", "subplugin", "structure", "for", "a", "given", "plugin", "to", "any", "element", "in", "the", "structure", "restore", "tree" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L315-L369
220,286
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.launch_after_execute_methods
protected function launch_after_execute_methods() { $alreadylaunched = array(); // To avoid multiple executions foreach ($this->pathelements as $key => $pathelement) { // Get the processing object $pobject = $pathelement->get_processing_object(); // Skip null processors (child of grouped ones for sure) if (is_null($pobject)) { continue; } // Skip restore structure step processors (this) if ($pobject instanceof restore_structure_step) { continue; } // Skip already launched processing objects if (in_array($pobject, $alreadylaunched, true)) { continue; } // Add processing object to array of launched ones $alreadylaunched[] = $pobject; // If the processing object has support for // launching after_execute methods, use it if (method_exists($pobject, 'launch_after_execute_methods')) { $pobject->launch_after_execute_methods(); } } // Finally execute own (restore_structure_step) after_execute method $this->after_execute(); }
php
protected function launch_after_execute_methods() { $alreadylaunched = array(); // To avoid multiple executions foreach ($this->pathelements as $key => $pathelement) { // Get the processing object $pobject = $pathelement->get_processing_object(); // Skip null processors (child of grouped ones for sure) if (is_null($pobject)) { continue; } // Skip restore structure step processors (this) if ($pobject instanceof restore_structure_step) { continue; } // Skip already launched processing objects if (in_array($pobject, $alreadylaunched, true)) { continue; } // Add processing object to array of launched ones $alreadylaunched[] = $pobject; // If the processing object has support for // launching after_execute methods, use it if (method_exists($pobject, 'launch_after_execute_methods')) { $pobject->launch_after_execute_methods(); } } // Finally execute own (restore_structure_step) after_execute method $this->after_execute(); }
[ "protected", "function", "launch_after_execute_methods", "(", ")", "{", "$", "alreadylaunched", "=", "array", "(", ")", ";", "// To avoid multiple executions", "foreach", "(", "$", "this", "->", "pathelements", "as", "$", "key", "=>", "$", "pathelement", ")", "{", "// Get the processing object", "$", "pobject", "=", "$", "pathelement", "->", "get_processing_object", "(", ")", ";", "// Skip null processors (child of grouped ones for sure)", "if", "(", "is_null", "(", "$", "pobject", ")", ")", "{", "continue", ";", "}", "// Skip restore structure step processors (this)", "if", "(", "$", "pobject", "instanceof", "restore_structure_step", ")", "{", "continue", ";", "}", "// Skip already launched processing objects", "if", "(", "in_array", "(", "$", "pobject", ",", "$", "alreadylaunched", ",", "true", ")", ")", "{", "continue", ";", "}", "// Add processing object to array of launched ones", "$", "alreadylaunched", "[", "]", "=", "$", "pobject", ";", "// If the processing object has support for", "// launching after_execute methods, use it", "if", "(", "method_exists", "(", "$", "pobject", ",", "'launch_after_execute_methods'", ")", ")", "{", "$", "pobject", "->", "launch_after_execute_methods", "(", ")", ";", "}", "}", "// Finally execute own (restore_structure_step) after_execute method", "$", "this", "->", "after_execute", "(", ")", ";", "}" ]
Launch all the after_execute methods present in all the processing objects This method will launch all the after_execute methods that can be defined both in restore_plugin and restore_structure_step classes For restore_plugin classes the name of the method to be executed will be "after_execute_" + connection point (as far as can be multiple connection points in the same class) For restore_structure_step classes is will be, simply, "after_execute". Note that this is executed *after* the plugin ones
[ "Launch", "all", "the", "after_execute", "methods", "present", "in", "all", "the", "processing", "objects" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L384-L412
220,287
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.launch_after_restore_methods
public function launch_after_restore_methods() { $alreadylaunched = array(); // To avoid multiple executions foreach ($this->pathelements as $pathelement) { // Get the processing object $pobject = $pathelement->get_processing_object(); // Skip null processors (child of grouped ones for sure) if (is_null($pobject)) { continue; } // Skip restore structure step processors (this) if ($pobject instanceof restore_structure_step) { continue; } // Skip already launched processing objects if (in_array($pobject, $alreadylaunched, true)) { continue; } // Add processing object to array of launched ones $alreadylaunched[] = $pobject; // If the processing object has support for // launching after_restore methods, use it if (method_exists($pobject, 'launch_after_restore_methods')) { $pobject->launch_after_restore_methods(); } } // Finally execute own (restore_structure_step) after_restore method $this->after_restore(); }
php
public function launch_after_restore_methods() { $alreadylaunched = array(); // To avoid multiple executions foreach ($this->pathelements as $pathelement) { // Get the processing object $pobject = $pathelement->get_processing_object(); // Skip null processors (child of grouped ones for sure) if (is_null($pobject)) { continue; } // Skip restore structure step processors (this) if ($pobject instanceof restore_structure_step) { continue; } // Skip already launched processing objects if (in_array($pobject, $alreadylaunched, true)) { continue; } // Add processing object to array of launched ones $alreadylaunched[] = $pobject; // If the processing object has support for // launching after_restore methods, use it if (method_exists($pobject, 'launch_after_restore_methods')) { $pobject->launch_after_restore_methods(); } } // Finally execute own (restore_structure_step) after_restore method $this->after_restore(); }
[ "public", "function", "launch_after_restore_methods", "(", ")", "{", "$", "alreadylaunched", "=", "array", "(", ")", ";", "// To avoid multiple executions", "foreach", "(", "$", "this", "->", "pathelements", "as", "$", "pathelement", ")", "{", "// Get the processing object", "$", "pobject", "=", "$", "pathelement", "->", "get_processing_object", "(", ")", ";", "// Skip null processors (child of grouped ones for sure)", "if", "(", "is_null", "(", "$", "pobject", ")", ")", "{", "continue", ";", "}", "// Skip restore structure step processors (this)", "if", "(", "$", "pobject", "instanceof", "restore_structure_step", ")", "{", "continue", ";", "}", "// Skip already launched processing objects", "if", "(", "in_array", "(", "$", "pobject", ",", "$", "alreadylaunched", ",", "true", ")", ")", "{", "continue", ";", "}", "// Add processing object to array of launched ones", "$", "alreadylaunched", "[", "]", "=", "$", "pobject", ";", "// If the processing object has support for", "// launching after_restore methods, use it", "if", "(", "method_exists", "(", "$", "pobject", ",", "'launch_after_restore_methods'", ")", ")", "{", "$", "pobject", "->", "launch_after_restore_methods", "(", ")", ";", "}", "}", "// Finally execute own (restore_structure_step) after_restore method", "$", "this", "->", "after_restore", "(", ")", ";", "}" ]
Launch all the after_restore methods present in all the processing objects This method will launch all the after_restore methods that can be defined both in restore_plugin class For restore_plugin classes the name of the method to be executed will be "after_restore_" + connection point (as far as can be multiple connection points in the same class)
[ "Launch", "all", "the", "after_restore", "methods", "present", "in", "all", "the", "processing", "objects" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L424-L451
220,288
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.prepare_pathelements
protected function prepare_pathelements($elementsarr) { // First iteration, push them to new array, indexed by name // detecting duplicates in names or paths $names = array(); $paths = array(); foreach($elementsarr as $element) { if (!$element instanceof restore_path_element) { throw new restore_step_exception('restore_path_element_wrong_class', get_class($element)); } if (array_key_exists($element->get_name(), $names)) { throw new restore_step_exception('restore_path_element_name_alreadyexists', $element->get_name()); } if (array_key_exists($element->get_path(), $paths)) { throw new restore_step_exception('restore_path_element_path_alreadyexists', $element->get_path()); } $names[$element->get_name()] = true; $paths[$element->get_path()] = $element; } // Now, for each element not having one processing object, if // not child of grouped element, assign $this (the step itself) as processing element // Note method must exist or we'll get one @restore_path_element_exception foreach($paths as $key => $pelement) { if ($pelement->get_processing_object() === null && !$this->grouped_parent_exists($pelement, $paths)) { $paths[$key]->set_processing_object($this); } // Populate $elementsoldid and $elementsoldid based on available pathelements $this->elementsoldid[$pelement->get_name()] = null; $this->elementsnewid[$pelement->get_name()] = null; } // Done, add them to pathelements (dupes by key - path - are discarded) $this->pathelements = array_merge($this->pathelements, $paths); }
php
protected function prepare_pathelements($elementsarr) { // First iteration, push them to new array, indexed by name // detecting duplicates in names or paths $names = array(); $paths = array(); foreach($elementsarr as $element) { if (!$element instanceof restore_path_element) { throw new restore_step_exception('restore_path_element_wrong_class', get_class($element)); } if (array_key_exists($element->get_name(), $names)) { throw new restore_step_exception('restore_path_element_name_alreadyexists', $element->get_name()); } if (array_key_exists($element->get_path(), $paths)) { throw new restore_step_exception('restore_path_element_path_alreadyexists', $element->get_path()); } $names[$element->get_name()] = true; $paths[$element->get_path()] = $element; } // Now, for each element not having one processing object, if // not child of grouped element, assign $this (the step itself) as processing element // Note method must exist or we'll get one @restore_path_element_exception foreach($paths as $key => $pelement) { if ($pelement->get_processing_object() === null && !$this->grouped_parent_exists($pelement, $paths)) { $paths[$key]->set_processing_object($this); } // Populate $elementsoldid and $elementsoldid based on available pathelements $this->elementsoldid[$pelement->get_name()] = null; $this->elementsnewid[$pelement->get_name()] = null; } // Done, add them to pathelements (dupes by key - path - are discarded) $this->pathelements = array_merge($this->pathelements, $paths); }
[ "protected", "function", "prepare_pathelements", "(", "$", "elementsarr", ")", "{", "// First iteration, push them to new array, indexed by name", "// detecting duplicates in names or paths", "$", "names", "=", "array", "(", ")", ";", "$", "paths", "=", "array", "(", ")", ";", "foreach", "(", "$", "elementsarr", "as", "$", "element", ")", "{", "if", "(", "!", "$", "element", "instanceof", "restore_path_element", ")", "{", "throw", "new", "restore_step_exception", "(", "'restore_path_element_wrong_class'", ",", "get_class", "(", "$", "element", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "element", "->", "get_name", "(", ")", ",", "$", "names", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'restore_path_element_name_alreadyexists'", ",", "$", "element", "->", "get_name", "(", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "element", "->", "get_path", "(", ")", ",", "$", "paths", ")", ")", "{", "throw", "new", "restore_step_exception", "(", "'restore_path_element_path_alreadyexists'", ",", "$", "element", "->", "get_path", "(", ")", ")", ";", "}", "$", "names", "[", "$", "element", "->", "get_name", "(", ")", "]", "=", "true", ";", "$", "paths", "[", "$", "element", "->", "get_path", "(", ")", "]", "=", "$", "element", ";", "}", "// Now, for each element not having one processing object, if", "// not child of grouped element, assign $this (the step itself) as processing element", "// Note method must exist or we'll get one @restore_path_element_exception", "foreach", "(", "$", "paths", "as", "$", "key", "=>", "$", "pelement", ")", "{", "if", "(", "$", "pelement", "->", "get_processing_object", "(", ")", "===", "null", "&&", "!", "$", "this", "->", "grouped_parent_exists", "(", "$", "pelement", ",", "$", "paths", ")", ")", "{", "$", "paths", "[", "$", "key", "]", "->", "set_processing_object", "(", "$", "this", ")", ";", "}", "// Populate $elementsoldid and $elementsoldid based on available pathelements", "$", "this", "->", "elementsoldid", "[", "$", "pelement", "->", "get_name", "(", ")", "]", "=", "null", ";", "$", "this", "->", "elementsnewid", "[", "$", "pelement", "->", "get_name", "(", ")", "]", "=", "null", ";", "}", "// Done, add them to pathelements (dupes by key - path - are discarded)", "$", "this", "->", "pathelements", "=", "array_merge", "(", "$", "this", "->", "pathelements", ",", "$", "paths", ")", ";", "}" ]
Prepare the pathelements for processing, looking for duplicates, applying processing objects and other adjustments
[ "Prepare", "the", "pathelements", "for", "processing", "looking", "for", "duplicates", "applying", "processing", "objects", "and", "other", "adjustments" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L478-L510
220,289
moodle/moodle
backup/util/plan/restore_structure_step.class.php
restore_structure_step.grouped_parent_exists
protected function grouped_parent_exists($pelement, $elements) { foreach ($elements as $element) { if ($pelement->get_path() == $element->get_path()) { continue; // Don't compare against itself } // If element is grouped and parent of pelement, return true if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) { return true; } } return false; // no grouped parent found }
php
protected function grouped_parent_exists($pelement, $elements) { foreach ($elements as $element) { if ($pelement->get_path() == $element->get_path()) { continue; // Don't compare against itself } // If element is grouped and parent of pelement, return true if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) { return true; } } return false; // no grouped parent found }
[ "protected", "function", "grouped_parent_exists", "(", "$", "pelement", ",", "$", "elements", ")", "{", "foreach", "(", "$", "elements", "as", "$", "element", ")", "{", "if", "(", "$", "pelement", "->", "get_path", "(", ")", "==", "$", "element", "->", "get_path", "(", ")", ")", "{", "continue", ";", "// Don't compare against itself", "}", "// If element is grouped and parent of pelement, return true", "if", "(", "$", "element", "->", "is_grouped", "(", ")", "and", "strpos", "(", "$", "pelement", "->", "get_path", "(", ")", ".", "'/'", ",", "$", "element", "->", "get_path", "(", ")", ")", "===", "0", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "// no grouped parent found", "}" ]
Given one pathelement, return true if grouped parent was found
[ "Given", "one", "pathelement", "return", "true", "if", "grouped", "parent", "was", "found" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/plan/restore_structure_step.class.php#L515-L526
220,290
moodle/moodle
lib/ltiprovider/src/ToolProvider/ToolProvider.php
ToolProvider.doToolProxyService
public function doToolProxyService() { // Create tool proxy $toolProxyService = $this->findService('application/vnd.ims.lti.v2.toolproxy+json', array('POST')); $secret = DataConnector::getRandomString(12); $toolProxy = new MediaType\ToolProxy($this, $toolProxyService, $secret); $http = $this->consumer->doServiceRequest($toolProxyService, 'POST', 'application/vnd.ims.lti.v2.toolproxy+json', json_encode($toolProxy)); $ok = $http->ok && ($http->status == 201) && isset($http->responseJson->tool_proxy_guid) && (strlen($http->responseJson->tool_proxy_guid) > 0); if ($ok) { $this->consumer->setKey($http->responseJson->tool_proxy_guid); $this->consumer->secret = $toolProxy->security_contract->shared_secret; $this->consumer->toolProxy = json_encode($toolProxy); $this->consumer->save(); } return $ok; }
php
public function doToolProxyService() { // Create tool proxy $toolProxyService = $this->findService('application/vnd.ims.lti.v2.toolproxy+json', array('POST')); $secret = DataConnector::getRandomString(12); $toolProxy = new MediaType\ToolProxy($this, $toolProxyService, $secret); $http = $this->consumer->doServiceRequest($toolProxyService, 'POST', 'application/vnd.ims.lti.v2.toolproxy+json', json_encode($toolProxy)); $ok = $http->ok && ($http->status == 201) && isset($http->responseJson->tool_proxy_guid) && (strlen($http->responseJson->tool_proxy_guid) > 0); if ($ok) { $this->consumer->setKey($http->responseJson->tool_proxy_guid); $this->consumer->secret = $toolProxy->security_contract->shared_secret; $this->consumer->toolProxy = json_encode($toolProxy); $this->consumer->save(); } return $ok; }
[ "public", "function", "doToolProxyService", "(", ")", "{", "// Create tool proxy", "$", "toolProxyService", "=", "$", "this", "->", "findService", "(", "'application/vnd.ims.lti.v2.toolproxy+json'", ",", "array", "(", "'POST'", ")", ")", ";", "$", "secret", "=", "DataConnector", "::", "getRandomString", "(", "12", ")", ";", "$", "toolProxy", "=", "new", "MediaType", "\\", "ToolProxy", "(", "$", "this", ",", "$", "toolProxyService", ",", "$", "secret", ")", ";", "$", "http", "=", "$", "this", "->", "consumer", "->", "doServiceRequest", "(", "$", "toolProxyService", ",", "'POST'", ",", "'application/vnd.ims.lti.v2.toolproxy+json'", ",", "json_encode", "(", "$", "toolProxy", ")", ")", ";", "$", "ok", "=", "$", "http", "->", "ok", "&&", "(", "$", "http", "->", "status", "==", "201", ")", "&&", "isset", "(", "$", "http", "->", "responseJson", "->", "tool_proxy_guid", ")", "&&", "(", "strlen", "(", "$", "http", "->", "responseJson", "->", "tool_proxy_guid", ")", ">", "0", ")", ";", "if", "(", "$", "ok", ")", "{", "$", "this", "->", "consumer", "->", "setKey", "(", "$", "http", "->", "responseJson", "->", "tool_proxy_guid", ")", ";", "$", "this", "->", "consumer", "->", "secret", "=", "$", "toolProxy", "->", "security_contract", "->", "shared_secret", ";", "$", "this", "->", "consumer", "->", "toolProxy", "=", "json_encode", "(", "$", "toolProxy", ")", ";", "$", "this", "->", "consumer", "->", "save", "(", ")", ";", "}", "return", "$", "ok", ";", "}" ]
Send the tool proxy to the Tool Consumer @return boolean True if the tool proxy was accepted
[ "Send", "the", "tool", "proxy", "to", "the", "Tool", "Consumer" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/ltiprovider/src/ToolProvider/ToolProvider.php#L423-L441
220,291
moodle/moodle
lib/ltiprovider/src/ToolProvider/ToolProvider.php
ToolProvider.checkValue
private function checkValue($value, $values, $reason) { $ok = in_array($value, $values); if (!$ok && !empty($reason)) { $this->reason = sprintf($reason, $value); } return $ok; }
php
private function checkValue($value, $values, $reason) { $ok = in_array($value, $values); if (!$ok && !empty($reason)) { $this->reason = sprintf($reason, $value); } return $ok; }
[ "private", "function", "checkValue", "(", "$", "value", ",", "$", "values", ",", "$", "reason", ")", "{", "$", "ok", "=", "in_array", "(", "$", "value", ",", "$", "values", ")", ";", "if", "(", "!", "$", "ok", "&&", "!", "empty", "(", "$", "reason", ")", ")", "{", "$", "this", "->", "reason", "=", "sprintf", "(", "$", "reason", ",", "$", "value", ")", ";", "}", "return", "$", "ok", ";", "}" ]
Validate a parameter value from an array of permitted values. @return boolean True if value is valid
[ "Validate", "a", "parameter", "value", "from", "an", "array", "of", "permitted", "values", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/ltiprovider/src/ToolProvider/ToolProvider.php#L1261-L1271
220,292
moodle/moodle
blocks/section_links/block_section_links.php
block_section_links.get_content
public function get_content() { // The config should be loaded by now. // If its empty then we will use the global config for the section links block. if (isset($this->config)){ $config = $this->config; } else{ $config = get_config('block_section_links'); } if ($this->content !== null) { return $this->content; } $this->content = new stdClass; $this->content->footer = ''; $this->content->text = ''; if (empty($this->instance)) { return $this->content; } $course = $this->page->course; $courseformat = course_get_format($course); $numsections = $courseformat->get_last_section_number(); $context = context_course::instance($course->id); // Course format options 'numsections' is required to display the block. if (empty($numsections)) { return $this->content; } // Prepare the increment value. if (!empty($config->numsections1) and ($numsections > $config->numsections1)) { $inc = $config->incby1; } else if ($numsections > 22) { $inc = 2; } else { $inc = 1; } if (!empty($config->numsections2) and ($numsections > $config->numsections2)) { $inc = $config->incby2; } else { if ($numsections > 40) { $inc = 5; } } // Prepare an array of sections to create links for. $sections = array(); $canviewhidden = has_capability('moodle/course:update', $context); $coursesections = $courseformat->get_sections(); $coursesectionscount = count($coursesections); $sectiontojumpto = false; for ($i = $inc; $i <= $coursesectionscount; $i += $inc) { if ($i > $numsections || !isset($coursesections[$i])) { continue; } $section = $coursesections[$i]; if ($section->section && ($section->visible || $canviewhidden)) { $sections[$i] = (object)array( 'section' => $section->section, 'visible' => $section->visible, 'highlight' => false ); if ($courseformat->is_section_current($section)) { $sections[$i]->highlight = true; $sectiontojumpto = $section->section; } } } if (!empty($sections)) { // Render the sections. $renderer = $this->page->get_renderer('block_section_links'); $this->content->text = $renderer->render_section_links($this->page->course, $sections, $sectiontojumpto); } return $this->content; }
php
public function get_content() { // The config should be loaded by now. // If its empty then we will use the global config for the section links block. if (isset($this->config)){ $config = $this->config; } else{ $config = get_config('block_section_links'); } if ($this->content !== null) { return $this->content; } $this->content = new stdClass; $this->content->footer = ''; $this->content->text = ''; if (empty($this->instance)) { return $this->content; } $course = $this->page->course; $courseformat = course_get_format($course); $numsections = $courseformat->get_last_section_number(); $context = context_course::instance($course->id); // Course format options 'numsections' is required to display the block. if (empty($numsections)) { return $this->content; } // Prepare the increment value. if (!empty($config->numsections1) and ($numsections > $config->numsections1)) { $inc = $config->incby1; } else if ($numsections > 22) { $inc = 2; } else { $inc = 1; } if (!empty($config->numsections2) and ($numsections > $config->numsections2)) { $inc = $config->incby2; } else { if ($numsections > 40) { $inc = 5; } } // Prepare an array of sections to create links for. $sections = array(); $canviewhidden = has_capability('moodle/course:update', $context); $coursesections = $courseformat->get_sections(); $coursesectionscount = count($coursesections); $sectiontojumpto = false; for ($i = $inc; $i <= $coursesectionscount; $i += $inc) { if ($i > $numsections || !isset($coursesections[$i])) { continue; } $section = $coursesections[$i]; if ($section->section && ($section->visible || $canviewhidden)) { $sections[$i] = (object)array( 'section' => $section->section, 'visible' => $section->visible, 'highlight' => false ); if ($courseformat->is_section_current($section)) { $sections[$i]->highlight = true; $sectiontojumpto = $section->section; } } } if (!empty($sections)) { // Render the sections. $renderer = $this->page->get_renderer('block_section_links'); $this->content->text = $renderer->render_section_links($this->page->course, $sections, $sectiontojumpto); } return $this->content; }
[ "public", "function", "get_content", "(", ")", "{", "// The config should be loaded by now.", "// If its empty then we will use the global config for the section links block.", "if", "(", "isset", "(", "$", "this", "->", "config", ")", ")", "{", "$", "config", "=", "$", "this", "->", "config", ";", "}", "else", "{", "$", "config", "=", "get_config", "(", "'block_section_links'", ")", ";", "}", "if", "(", "$", "this", "->", "content", "!==", "null", ")", "{", "return", "$", "this", "->", "content", ";", "}", "$", "this", "->", "content", "=", "new", "stdClass", ";", "$", "this", "->", "content", "->", "footer", "=", "''", ";", "$", "this", "->", "content", "->", "text", "=", "''", ";", "if", "(", "empty", "(", "$", "this", "->", "instance", ")", ")", "{", "return", "$", "this", "->", "content", ";", "}", "$", "course", "=", "$", "this", "->", "page", "->", "course", ";", "$", "courseformat", "=", "course_get_format", "(", "$", "course", ")", ";", "$", "numsections", "=", "$", "courseformat", "->", "get_last_section_number", "(", ")", ";", "$", "context", "=", "context_course", "::", "instance", "(", "$", "course", "->", "id", ")", ";", "// Course format options 'numsections' is required to display the block.", "if", "(", "empty", "(", "$", "numsections", ")", ")", "{", "return", "$", "this", "->", "content", ";", "}", "// Prepare the increment value.", "if", "(", "!", "empty", "(", "$", "config", "->", "numsections1", ")", "and", "(", "$", "numsections", ">", "$", "config", "->", "numsections1", ")", ")", "{", "$", "inc", "=", "$", "config", "->", "incby1", ";", "}", "else", "if", "(", "$", "numsections", ">", "22", ")", "{", "$", "inc", "=", "2", ";", "}", "else", "{", "$", "inc", "=", "1", ";", "}", "if", "(", "!", "empty", "(", "$", "config", "->", "numsections2", ")", "and", "(", "$", "numsections", ">", "$", "config", "->", "numsections2", ")", ")", "{", "$", "inc", "=", "$", "config", "->", "incby2", ";", "}", "else", "{", "if", "(", "$", "numsections", ">", "40", ")", "{", "$", "inc", "=", "5", ";", "}", "}", "// Prepare an array of sections to create links for.", "$", "sections", "=", "array", "(", ")", ";", "$", "canviewhidden", "=", "has_capability", "(", "'moodle/course:update'", ",", "$", "context", ")", ";", "$", "coursesections", "=", "$", "courseformat", "->", "get_sections", "(", ")", ";", "$", "coursesectionscount", "=", "count", "(", "$", "coursesections", ")", ";", "$", "sectiontojumpto", "=", "false", ";", "for", "(", "$", "i", "=", "$", "inc", ";", "$", "i", "<=", "$", "coursesectionscount", ";", "$", "i", "+=", "$", "inc", ")", "{", "if", "(", "$", "i", ">", "$", "numsections", "||", "!", "isset", "(", "$", "coursesections", "[", "$", "i", "]", ")", ")", "{", "continue", ";", "}", "$", "section", "=", "$", "coursesections", "[", "$", "i", "]", ";", "if", "(", "$", "section", "->", "section", "&&", "(", "$", "section", "->", "visible", "||", "$", "canviewhidden", ")", ")", "{", "$", "sections", "[", "$", "i", "]", "=", "(", "object", ")", "array", "(", "'section'", "=>", "$", "section", "->", "section", ",", "'visible'", "=>", "$", "section", "->", "visible", ",", "'highlight'", "=>", "false", ")", ";", "if", "(", "$", "courseformat", "->", "is_section_current", "(", "$", "section", ")", ")", "{", "$", "sections", "[", "$", "i", "]", "->", "highlight", "=", "true", ";", "$", "sectiontojumpto", "=", "$", "section", "->", "section", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "sections", ")", ")", "{", "// Render the sections.", "$", "renderer", "=", "$", "this", "->", "page", "->", "get_renderer", "(", "'block_section_links'", ")", ";", "$", "this", "->", "content", "->", "text", "=", "$", "renderer", "->", "render_section_links", "(", "$", "this", "->", "page", "->", "course", ",", "$", "sections", ",", "$", "sectiontojumpto", ")", ";", "}", "return", "$", "this", "->", "content", ";", "}" ]
Generates the content of the block and returns it. If the content has already been generated then the previously generated content is returned. @return stdClass
[ "Generates", "the", "content", "of", "the", "block", "and", "returns", "it", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/blocks/section_links/block_section_links.php#L60-L139
220,293
moodle/moodle
lib/classes/event/user_info_field_deleted.php
user_info_field_deleted.create_from_field
public static function create_from_field($field) { $event = self::create(array( 'objectid' => $field->id, 'context' => \context_system::instance(), 'other' => array( 'shortname' => $field->shortname, 'name' => $field->name, 'datatype' => $field->datatype, ) )); $event->add_record_snapshot('user_info_field', $field); return $event; }
php
public static function create_from_field($field) { $event = self::create(array( 'objectid' => $field->id, 'context' => \context_system::instance(), 'other' => array( 'shortname' => $field->shortname, 'name' => $field->name, 'datatype' => $field->datatype, ) )); $event->add_record_snapshot('user_info_field', $field); return $event; }
[ "public", "static", "function", "create_from_field", "(", "$", "field", ")", "{", "$", "event", "=", "self", "::", "create", "(", "array", "(", "'objectid'", "=>", "$", "field", "->", "id", ",", "'context'", "=>", "\\", "context_system", "::", "instance", "(", ")", ",", "'other'", "=>", "array", "(", "'shortname'", "=>", "$", "field", "->", "shortname", ",", "'name'", "=>", "$", "field", "->", "name", ",", "'datatype'", "=>", "$", "field", "->", "datatype", ",", ")", ")", ")", ";", "$", "event", "->", "add_record_snapshot", "(", "'user_info_field'", ",", "$", "field", ")", ";", "return", "$", "event", ";", "}" ]
Creates an event from a profile field. @since Moodle 3.4 @param \stdClass $field A snapshot of the deleted field. @return \core\event\base
[ "Creates", "an", "event", "from", "a", "profile", "field", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/classes/event/user_info_field_deleted.php#L62-L76
220,294
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.setMacrosCode
public function setMacrosCode($MacrosCode = null) { $this->macrosCode=$MacrosCode; $this->setHasMacros(!is_null($MacrosCode)); }
php
public function setMacrosCode($MacrosCode = null) { $this->macrosCode=$MacrosCode; $this->setHasMacros(!is_null($MacrosCode)); }
[ "public", "function", "setMacrosCode", "(", "$", "MacrosCode", "=", "null", ")", "{", "$", "this", "->", "macrosCode", "=", "$", "MacrosCode", ";", "$", "this", "->", "setHasMacros", "(", "!", "is_null", "(", "$", "MacrosCode", ")", ")", ";", "}" ]
Set the macros code @param string $MacrosCode string|null
[ "Set", "the", "macros", "code" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L166-L170
220,295
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.getIndex
public function getIndex(PHPExcel_Worksheet $pSheet) { foreach ($this->workSheetCollection as $key => $value) { if ($value->getHashCode() == $pSheet->getHashCode()) { return $key; } } throw new PHPExcel_Exception("Sheet does not exist."); }
php
public function getIndex(PHPExcel_Worksheet $pSheet) { foreach ($this->workSheetCollection as $key => $value) { if ($value->getHashCode() == $pSheet->getHashCode()) { return $key; } } throw new PHPExcel_Exception("Sheet does not exist."); }
[ "public", "function", "getIndex", "(", "PHPExcel_Worksheet", "$", "pSheet", ")", "{", "foreach", "(", "$", "this", "->", "workSheetCollection", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "->", "getHashCode", "(", ")", "==", "$", "pSheet", "->", "getHashCode", "(", ")", ")", "{", "return", "$", "key", ";", "}", "}", "throw", "new", "PHPExcel_Exception", "(", "\"Sheet does not exist.\"", ")", ";", "}" ]
Get index for sheet @param PHPExcel_Worksheet $pSheet @return Sheet index @throws PHPExcel_Exception
[ "Get", "index", "for", "sheet" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L627-L636
220,296
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.setIndexByName
public function setIndexByName($sheetName, $newIndex) { $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); $pSheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, $newIndex, 0, $pSheet ); return $newIndex; }
php
public function setIndexByName($sheetName, $newIndex) { $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); $pSheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, $newIndex, 0, $pSheet ); return $newIndex; }
[ "public", "function", "setIndexByName", "(", "$", "sheetName", ",", "$", "newIndex", ")", "{", "$", "oldIndex", "=", "$", "this", "->", "getIndex", "(", "$", "this", "->", "getSheetByName", "(", "$", "sheetName", ")", ")", ";", "$", "pSheet", "=", "array_splice", "(", "$", "this", "->", "workSheetCollection", ",", "$", "oldIndex", ",", "1", ")", ";", "array_splice", "(", "$", "this", "->", "workSheetCollection", ",", "$", "newIndex", ",", "0", ",", "$", "pSheet", ")", ";", "return", "$", "newIndex", ";", "}" ]
Set index for sheet by sheet name. @param string $sheetName Sheet name to modify index for @param int $newIndex New index for the sheet @return New sheet index @throws PHPExcel_Exception
[ "Set", "index", "for", "sheet", "by", "sheet", "name", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L646-L661
220,297
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.setActiveSheetIndexByName
public function setActiveSheetIndexByName($pValue = '') { if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue); }
php
public function setActiveSheetIndexByName($pValue = '') { if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue); }
[ "public", "function", "setActiveSheetIndexByName", "(", "$", "pValue", "=", "''", ")", "{", "if", "(", "(", "$", "worksheet", "=", "$", "this", "->", "getSheetByName", "(", "$", "pValue", ")", ")", "instanceof", "PHPExcel_Worksheet", ")", "{", "$", "this", "->", "setActiveSheetIndex", "(", "$", "this", "->", "getIndex", "(", "$", "worksheet", ")", ")", ";", "return", "$", "worksheet", ";", "}", "throw", "new", "PHPExcel_Exception", "(", "'Workbook does not contain sheet:'", ".", "$", "pValue", ")", ";", "}" ]
Set active sheet index by name @param string $pValue Sheet title @return PHPExcel_Worksheet @throws PHPExcel_Exception
[ "Set", "active", "sheet", "index", "by", "name" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L711-L719
220,298
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.getSheetNames
public function getSheetNames() { $returnValue = array(); $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); } return $returnValue; }
php
public function getSheetNames() { $returnValue = array(); $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); } return $returnValue; }
[ "public", "function", "getSheetNames", "(", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "$", "worksheetCount", "=", "$", "this", "->", "getSheetCount", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "worksheetCount", ";", "++", "$", "i", ")", "{", "$", "returnValue", "[", "]", "=", "$", "this", "->", "getSheet", "(", "$", "i", ")", "->", "getTitle", "(", ")", ";", "}", "return", "$", "returnValue", ";", "}" ]
Get sheet names @return string[]
[ "Get", "sheet", "names" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L726-L735
220,299
moodle/moodle
lib/phpexcel/PHPExcel.php
PHPExcel.addExternalSheet
public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) { if ($this->sheetNameExists($pSheet->getTitle())) { throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); } // count how many cellXfs there are in this workbook currently, we will need this below $countCellXfs = count($this->cellXfCollection); // copy all the shared cellXfs from the external workbook and append them to the current foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook $pSheet->rebindParent($this); // update the cellXfs foreach ($pSheet->getCellCollection(false) as $cellID) { $cell = $pSheet->getCell($cellID); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } return $this->addSheet($pSheet, $iSheetIndex); }
php
public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) { if ($this->sheetNameExists($pSheet->getTitle())) { throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); } // count how many cellXfs there are in this workbook currently, we will need this below $countCellXfs = count($this->cellXfCollection); // copy all the shared cellXfs from the external workbook and append them to the current foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook $pSheet->rebindParent($this); // update the cellXfs foreach ($pSheet->getCellCollection(false) as $cellID) { $cell = $pSheet->getCell($cellID); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } return $this->addSheet($pSheet, $iSheetIndex); }
[ "public", "function", "addExternalSheet", "(", "PHPExcel_Worksheet", "$", "pSheet", ",", "$", "iSheetIndex", "=", "null", ")", "{", "if", "(", "$", "this", "->", "sheetNameExists", "(", "$", "pSheet", "->", "getTitle", "(", ")", ")", ")", "{", "throw", "new", "PHPExcel_Exception", "(", "\"Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.\"", ")", ";", "}", "// count how many cellXfs there are in this workbook currently, we will need this below", "$", "countCellXfs", "=", "count", "(", "$", "this", "->", "cellXfCollection", ")", ";", "// copy all the shared cellXfs from the external workbook and append them to the current", "foreach", "(", "$", "pSheet", "->", "getParent", "(", ")", "->", "getCellXfCollection", "(", ")", "as", "$", "cellXf", ")", "{", "$", "this", "->", "addCellXf", "(", "clone", "$", "cellXf", ")", ";", "}", "// move sheet to this workbook", "$", "pSheet", "->", "rebindParent", "(", "$", "this", ")", ";", "// update the cellXfs", "foreach", "(", "$", "pSheet", "->", "getCellCollection", "(", "false", ")", "as", "$", "cellID", ")", "{", "$", "cell", "=", "$", "pSheet", "->", "getCell", "(", "$", "cellID", ")", ";", "$", "cell", "->", "setXfIndex", "(", "$", "cell", "->", "getXfIndex", "(", ")", "+", "$", "countCellXfs", ")", ";", "}", "return", "$", "this", "->", "addSheet", "(", "$", "pSheet", ",", "$", "iSheetIndex", ")", ";", "}" ]
Add external sheet @param PHPExcel_Worksheet $pSheet External sheet to add @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) @throws PHPExcel_Exception @return PHPExcel_Worksheet
[ "Add", "external", "sheet" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpexcel/PHPExcel.php#L745-L769