id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
216,000
moodle/moodle
backup/util/ui/backup_ui.class.php
backup_ui.execute
public function execute() { if ($this->progress >= self::PROGRESS_EXECUTED) { throw new backup_ui_exception('backupuialreadyexecuted'); } if ($this->stage->get_stage() < self::STAGE_FINAL) { throw new backup_ui_exception('backupuifinalisedbeforeexecute'); } $this->progress = self::PROGRESS_EXECUTED; $this->controller->finish_ui(); $this->controller->execute_plan(); $this->stage = new backup_ui_stage_complete($this, $this->stage->get_params(), $this->controller->get_results()); return true; }
php
public function execute() { if ($this->progress >= self::PROGRESS_EXECUTED) { throw new backup_ui_exception('backupuialreadyexecuted'); } if ($this->stage->get_stage() < self::STAGE_FINAL) { throw new backup_ui_exception('backupuifinalisedbeforeexecute'); } $this->progress = self::PROGRESS_EXECUTED; $this->controller->finish_ui(); $this->controller->execute_plan(); $this->stage = new backup_ui_stage_complete($this, $this->stage->get_params(), $this->controller->get_results()); return true; }
[ "public", "function", "execute", "(", ")", "{", "if", "(", "$", "this", "->", "progress", ">=", "self", "::", "PROGRESS_EXECUTED", ")", "{", "throw", "new", "backup_ui_exception", "(", "'backupuialreadyexecuted'", ")", ";", "}", "if", "(", "$", "this", "->", "stage", "->", "get_stage", "(", ")", "<", "self", "::", "STAGE_FINAL", ")", "{", "throw", "new", "backup_ui_exception", "(", "'backupuifinalisedbeforeexecute'", ")", ";", "}", "$", "this", "->", "progress", "=", "self", "::", "PROGRESS_EXECUTED", ";", "$", "this", "->", "controller", "->", "finish_ui", "(", ")", ";", "$", "this", "->", "controller", "->", "execute_plan", "(", ")", ";", "$", "this", "->", "stage", "=", "new", "backup_ui_stage_complete", "(", "$", "this", ",", "$", "this", "->", "stage", "->", "get_params", "(", ")", ",", "$", "this", "->", "controller", "->", "get_results", "(", ")", ")", ";", "return", "true", ";", "}" ]
Executes the backup plan @throws backup_ui_exception when the steps are wrong. @return bool
[ "Executes", "the", "backup", "plan" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/ui/backup_ui.class.php#L127-L139
216,001
moodle/moodle
backup/util/ui/backup_ui.class.php
backup_ui.load_controller
final public static function load_controller($backupid = false) { // Get the backup id optional param. if ($backupid) { try { // Try to load the controller with it. // If it fails at this point it is likely because this is the first load. $controller = backup_controller::load_controller($backupid); return $controller; } catch (Exception $e) { return false; } } return $backupid; }
php
final public static function load_controller($backupid = false) { // Get the backup id optional param. if ($backupid) { try { // Try to load the controller with it. // If it fails at this point it is likely because this is the first load. $controller = backup_controller::load_controller($backupid); return $controller; } catch (Exception $e) { return false; } } return $backupid; }
[ "final", "public", "static", "function", "load_controller", "(", "$", "backupid", "=", "false", ")", "{", "// Get the backup id optional param.", "if", "(", "$", "backupid", ")", "{", "try", "{", "// Try to load the controller with it.", "// If it fails at this point it is likely because this is the first load.", "$", "controller", "=", "backup_controller", "::", "load_controller", "(", "$", "backupid", ")", ";", "return", "$", "controller", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}", "return", "$", "backupid", ";", "}" ]
Loads the backup controller if we are tracking one @param string $backupid @return backup_controller|false
[ "Loads", "the", "backup", "controller", "if", "we", "are", "tracking", "one" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/ui/backup_ui.class.php#L146-L159
216,002
moodle/moodle
backup/util/ui/backup_ui.class.php
backup_ui.get_progress_bar
public function get_progress_bar() { global $PAGE; $stage = self::STAGE_COMPLETE; $currentstage = $this->stage->get_stage(); $items = array(); while ($stage > 0) { $classes = array('backup_stage'); if (floor($stage / 2) == $currentstage) { $classes[] = 'backup_stage_next'; } else if ($stage == $currentstage) { $classes[] = 'backup_stage_current'; } else if ($stage < $currentstage) { $classes[] = 'backup_stage_complete'; } $item = array('text' => strlen(decbin($stage)).'. '.get_string('currentstage'.$stage, 'backup'), 'class' => join(' ', $classes)); if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE && (!self::$skipcurrentstage || ($stage * 2) != $currentstage)) { $params = $this->stage->get_params(); if (empty($params)) { $params = array(); } $params = array_merge($params, array('backup' => $this->get_backupid(), 'stage' => $stage)); $item['link'] = new moodle_url($PAGE->url, $params); } array_unshift($items, $item); $stage = floor($stage / 2); } return $items; }
php
public function get_progress_bar() { global $PAGE; $stage = self::STAGE_COMPLETE; $currentstage = $this->stage->get_stage(); $items = array(); while ($stage > 0) { $classes = array('backup_stage'); if (floor($stage / 2) == $currentstage) { $classes[] = 'backup_stage_next'; } else if ($stage == $currentstage) { $classes[] = 'backup_stage_current'; } else if ($stage < $currentstage) { $classes[] = 'backup_stage_complete'; } $item = array('text' => strlen(decbin($stage)).'. '.get_string('currentstage'.$stage, 'backup'), 'class' => join(' ', $classes)); if ($stage < $currentstage && $currentstage < self::STAGE_COMPLETE && (!self::$skipcurrentstage || ($stage * 2) != $currentstage)) { $params = $this->stage->get_params(); if (empty($params)) { $params = array(); } $params = array_merge($params, array('backup' => $this->get_backupid(), 'stage' => $stage)); $item['link'] = new moodle_url($PAGE->url, $params); } array_unshift($items, $item); $stage = floor($stage / 2); } return $items; }
[ "public", "function", "get_progress_bar", "(", ")", "{", "global", "$", "PAGE", ";", "$", "stage", "=", "self", "::", "STAGE_COMPLETE", ";", "$", "currentstage", "=", "$", "this", "->", "stage", "->", "get_stage", "(", ")", ";", "$", "items", "=", "array", "(", ")", ";", "while", "(", "$", "stage", ">", "0", ")", "{", "$", "classes", "=", "array", "(", "'backup_stage'", ")", ";", "if", "(", "floor", "(", "$", "stage", "/", "2", ")", "==", "$", "currentstage", ")", "{", "$", "classes", "[", "]", "=", "'backup_stage_next'", ";", "}", "else", "if", "(", "$", "stage", "==", "$", "currentstage", ")", "{", "$", "classes", "[", "]", "=", "'backup_stage_current'", ";", "}", "else", "if", "(", "$", "stage", "<", "$", "currentstage", ")", "{", "$", "classes", "[", "]", "=", "'backup_stage_complete'", ";", "}", "$", "item", "=", "array", "(", "'text'", "=>", "strlen", "(", "decbin", "(", "$", "stage", ")", ")", ".", "'. '", ".", "get_string", "(", "'currentstage'", ".", "$", "stage", ",", "'backup'", ")", ",", "'class'", "=>", "join", "(", "' '", ",", "$", "classes", ")", ")", ";", "if", "(", "$", "stage", "<", "$", "currentstage", "&&", "$", "currentstage", "<", "self", "::", "STAGE_COMPLETE", "&&", "(", "!", "self", "::", "$", "skipcurrentstage", "||", "(", "$", "stage", "*", "2", ")", "!=", "$", "currentstage", ")", ")", "{", "$", "params", "=", "$", "this", "->", "stage", "->", "get_params", "(", ")", ";", "if", "(", "empty", "(", "$", "params", ")", ")", "{", "$", "params", "=", "array", "(", ")", ";", "}", "$", "params", "=", "array_merge", "(", "$", "params", ",", "array", "(", "'backup'", "=>", "$", "this", "->", "get_backupid", "(", ")", ",", "'stage'", "=>", "$", "stage", ")", ")", ";", "$", "item", "[", "'link'", "]", "=", "new", "moodle_url", "(", "$", "PAGE", "->", "url", ",", "$", "params", ")", ";", "}", "array_unshift", "(", "$", "items", ",", "$", "item", ")", ";", "$", "stage", "=", "floor", "(", "$", "stage", "/", "2", ")", ";", "}", "return", "$", "items", ";", "}" ]
Gets an array of progress bar items that can be displayed through the backup renderer. @return array Array of items for the progress bar
[ "Gets", "an", "array", "of", "progress", "bar", "items", "that", "can", "be", "displayed", "through", "the", "backup", "renderer", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/backup/util/ui/backup_ui.class.php#L165-L193
216,003
moodle/moodle
lib/htmlpurifier/HTMLPurifier/Lexer/DirectLex.php
HTMLPurifier_Lexer_DirectLex.substrCount
protected function substrCount($haystack, $needle, $offset, $length) { static $oldVersion; if ($oldVersion === null) { $oldVersion = version_compare(PHP_VERSION, '5.1', '<'); } if ($oldVersion) { $haystack = substr($haystack, $offset, $length); return substr_count($haystack, $needle); } else { return substr_count($haystack, $needle, $offset, $length); } }
php
protected function substrCount($haystack, $needle, $offset, $length) { static $oldVersion; if ($oldVersion === null) { $oldVersion = version_compare(PHP_VERSION, '5.1', '<'); } if ($oldVersion) { $haystack = substr($haystack, $offset, $length); return substr_count($haystack, $needle); } else { return substr_count($haystack, $needle, $offset, $length); } }
[ "protected", "function", "substrCount", "(", "$", "haystack", ",", "$", "needle", ",", "$", "offset", ",", "$", "length", ")", "{", "static", "$", "oldVersion", ";", "if", "(", "$", "oldVersion", "===", "null", ")", "{", "$", "oldVersion", "=", "version_compare", "(", "PHP_VERSION", ",", "'5.1'", ",", "'<'", ")", ";", "}", "if", "(", "$", "oldVersion", ")", "{", "$", "haystack", "=", "substr", "(", "$", "haystack", ",", "$", "offset", ",", "$", "length", ")", ";", "return", "substr_count", "(", "$", "haystack", ",", "$", "needle", ")", ";", "}", "else", "{", "return", "substr_count", "(", "$", "haystack", ",", "$", "needle", ",", "$", "offset", ",", "$", "length", ")", ";", "}", "}" ]
PHP 5.0.x compatible substr_count that implements offset and length @param string $haystack @param string $needle @param int $offset @param int $length @return int
[ "PHP", "5", ".", "0", ".", "x", "compatible", "substr_count", "that", "implements", "offset", "and", "length" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/htmlpurifier/HTMLPurifier/Lexer/DirectLex.php#L354-L366
216,004
moodle/moodle
mod/quiz/cronlib.php
mod_quiz_overdue_attempt_updater.update_overdue_attempts
public function update_overdue_attempts($timenow, $processto) { global $DB; $attemptstoprocess = $this->get_list_of_overdue_attempts($processto); $course = null; $quiz = null; $cm = null; $count = 0; $quizcount = 0; foreach ($attemptstoprocess as $attempt) { try { // If we have moved on to a different quiz, fetch the new data. if (!$quiz || $attempt->quiz != $quiz->id) { $quiz = $DB->get_record('quiz', array('id' => $attempt->quiz), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('quiz', $attempt->quiz); $quizcount += 1; } // If we have moved on to a different course, fetch the new data. if (!$course || $course->id != $quiz->course) { $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST); } // Make a specialised version of the quiz settings, with the relevant overrides. $quizforuser = clone($quiz); $quizforuser->timeclose = $attempt->usertimeclose; $quizforuser->timelimit = $attempt->usertimelimit; // Trigger any transitions that are required. $attemptobj = new quiz_attempt($attempt, $quizforuser, $cm, $course); $attemptobj->handle_if_time_expired($timenow, false); $count += 1; } catch (moodle_exception $e) { // If an error occurs while processing one attempt, don't let that kill cron. mtrace("Error while processing attempt {$attempt->id} at {$attempt->quiz} quiz:"); mtrace($e->getMessage()); mtrace($e->getTraceAsString()); // Close down any currently open transactions, otherwise one error // will stop following DB changes from being committed. $DB->force_transaction_rollback(); } } $attemptstoprocess->close(); return array($count, $quizcount); }
php
public function update_overdue_attempts($timenow, $processto) { global $DB; $attemptstoprocess = $this->get_list_of_overdue_attempts($processto); $course = null; $quiz = null; $cm = null; $count = 0; $quizcount = 0; foreach ($attemptstoprocess as $attempt) { try { // If we have moved on to a different quiz, fetch the new data. if (!$quiz || $attempt->quiz != $quiz->id) { $quiz = $DB->get_record('quiz', array('id' => $attempt->quiz), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('quiz', $attempt->quiz); $quizcount += 1; } // If we have moved on to a different course, fetch the new data. if (!$course || $course->id != $quiz->course) { $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST); } // Make a specialised version of the quiz settings, with the relevant overrides. $quizforuser = clone($quiz); $quizforuser->timeclose = $attempt->usertimeclose; $quizforuser->timelimit = $attempt->usertimelimit; // Trigger any transitions that are required. $attemptobj = new quiz_attempt($attempt, $quizforuser, $cm, $course); $attemptobj->handle_if_time_expired($timenow, false); $count += 1; } catch (moodle_exception $e) { // If an error occurs while processing one attempt, don't let that kill cron. mtrace("Error while processing attempt {$attempt->id} at {$attempt->quiz} quiz:"); mtrace($e->getMessage()); mtrace($e->getTraceAsString()); // Close down any currently open transactions, otherwise one error // will stop following DB changes from being committed. $DB->force_transaction_rollback(); } } $attemptstoprocess->close(); return array($count, $quizcount); }
[ "public", "function", "update_overdue_attempts", "(", "$", "timenow", ",", "$", "processto", ")", "{", "global", "$", "DB", ";", "$", "attemptstoprocess", "=", "$", "this", "->", "get_list_of_overdue_attempts", "(", "$", "processto", ")", ";", "$", "course", "=", "null", ";", "$", "quiz", "=", "null", ";", "$", "cm", "=", "null", ";", "$", "count", "=", "0", ";", "$", "quizcount", "=", "0", ";", "foreach", "(", "$", "attemptstoprocess", "as", "$", "attempt", ")", "{", "try", "{", "// If we have moved on to a different quiz, fetch the new data.", "if", "(", "!", "$", "quiz", "||", "$", "attempt", "->", "quiz", "!=", "$", "quiz", "->", "id", ")", "{", "$", "quiz", "=", "$", "DB", "->", "get_record", "(", "'quiz'", ",", "array", "(", "'id'", "=>", "$", "attempt", "->", "quiz", ")", ",", "'*'", ",", "MUST_EXIST", ")", ";", "$", "cm", "=", "get_coursemodule_from_instance", "(", "'quiz'", ",", "$", "attempt", "->", "quiz", ")", ";", "$", "quizcount", "+=", "1", ";", "}", "// If we have moved on to a different course, fetch the new data.", "if", "(", "!", "$", "course", "||", "$", "course", "->", "id", "!=", "$", "quiz", "->", "course", ")", "{", "$", "course", "=", "$", "DB", "->", "get_record", "(", "'course'", ",", "array", "(", "'id'", "=>", "$", "quiz", "->", "course", ")", ",", "'*'", ",", "MUST_EXIST", ")", ";", "}", "// Make a specialised version of the quiz settings, with the relevant overrides.", "$", "quizforuser", "=", "clone", "(", "$", "quiz", ")", ";", "$", "quizforuser", "->", "timeclose", "=", "$", "attempt", "->", "usertimeclose", ";", "$", "quizforuser", "->", "timelimit", "=", "$", "attempt", "->", "usertimelimit", ";", "// Trigger any transitions that are required.", "$", "attemptobj", "=", "new", "quiz_attempt", "(", "$", "attempt", ",", "$", "quizforuser", ",", "$", "cm", ",", "$", "course", ")", ";", "$", "attemptobj", "->", "handle_if_time_expired", "(", "$", "timenow", ",", "false", ")", ";", "$", "count", "+=", "1", ";", "}", "catch", "(", "moodle_exception", "$", "e", ")", "{", "// If an error occurs while processing one attempt, don't let that kill cron.", "mtrace", "(", "\"Error while processing attempt {$attempt->id} at {$attempt->quiz} quiz:\"", ")", ";", "mtrace", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "mtrace", "(", "$", "e", "->", "getTraceAsString", "(", ")", ")", ";", "// Close down any currently open transactions, otherwise one error", "// will stop following DB changes from being committed.", "$", "DB", "->", "force_transaction_rollback", "(", ")", ";", "}", "}", "$", "attemptstoprocess", "->", "close", "(", ")", ";", "return", "array", "(", "$", "count", ",", "$", "quizcount", ")", ";", "}" ]
Do the processing required. @param int $timenow the time to consider as 'now' during the processing. @param int $processto only process attempt with timecheckstate longer ago than this. @return array with two elements, the number of attempt considered, and how many different quizzes that was.
[ "Do", "the", "processing", "required", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/mod/quiz/cronlib.php#L46-L95
216,005
moodle/moodle
question/type/essay/renderer.php
qtype_essay_renderer.files_read_only
public function files_read_only(question_attempt $qa, question_display_options $options) { $files = $qa->get_last_qt_files('attachments', $options->context->id); $output = array(); foreach ($files as $file) { $output[] = html_writer::tag('p', html_writer::link($qa->get_response_file_url($file), $this->output->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . ' ' . s($file->get_filename()))); } return implode($output); }
php
public function files_read_only(question_attempt $qa, question_display_options $options) { $files = $qa->get_last_qt_files('attachments', $options->context->id); $output = array(); foreach ($files as $file) { $output[] = html_writer::tag('p', html_writer::link($qa->get_response_file_url($file), $this->output->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . ' ' . s($file->get_filename()))); } return implode($output); }
[ "public", "function", "files_read_only", "(", "question_attempt", "$", "qa", ",", "question_display_options", "$", "options", ")", "{", "$", "files", "=", "$", "qa", "->", "get_last_qt_files", "(", "'attachments'", ",", "$", "options", "->", "context", "->", "id", ")", ";", "$", "output", "=", "array", "(", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "output", "[", "]", "=", "html_writer", "::", "tag", "(", "'p'", ",", "html_writer", "::", "link", "(", "$", "qa", "->", "get_response_file_url", "(", "$", "file", ")", ",", "$", "this", "->", "output", "->", "pix_icon", "(", "file_file_icon", "(", "$", "file", ")", ",", "get_mimetype_description", "(", "$", "file", ")", ",", "'moodle'", ",", "array", "(", "'class'", "=>", "'icon'", ")", ")", ".", "' '", ".", "s", "(", "$", "file", "->", "get_filename", "(", ")", ")", ")", ")", ";", "}", "return", "implode", "(", "$", "output", ")", ";", "}" ]
Displays any attached files when the question is in read-only mode. @param question_attempt $qa the question attempt to display. @param question_display_options $options controls what should and should not be displayed. Used to get the context.
[ "Displays", "any", "attached", "files", "when", "the", "question", "is", "in", "read", "-", "only", "mode", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/essay/renderer.php#L88-L98
216,006
moodle/moodle
question/type/essay/renderer.php
qtype_essay_renderer.files_input
public function files_input(question_attempt $qa, $numallowed, question_display_options $options) { global $CFG; require_once($CFG->dirroot . '/lib/form/filemanager.php'); $pickeroptions = new stdClass(); $pickeroptions->mainfile = null; $pickeroptions->maxfiles = $numallowed; $pickeroptions->itemid = $qa->prepare_response_files_draft_itemid( 'attachments', $options->context->id); $pickeroptions->context = $options->context; $pickeroptions->return_types = FILE_INTERNAL | FILE_CONTROLLED_LINK; $pickeroptions->itemid = $qa->prepare_response_files_draft_itemid( 'attachments', $options->context->id); $pickeroptions->accepted_types = $qa->get_question()->filetypeslist; $fm = new form_filemanager($pickeroptions); $filesrenderer = $this->page->get_renderer('core', 'files'); $text = ''; if (!empty($qa->get_question()->filetypeslist)) { $text = html_writer::tag('p', get_string('acceptedfiletypes', 'qtype_essay')); $filetypesutil = new \core_form\filetypes_util(); $filetypes = $qa->get_question()->filetypeslist; $filetypedescriptions = $filetypesutil->describe_file_types($filetypes); $text .= $this->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions); } return $filesrenderer->render($fm). html_writer::empty_tag( 'input', array('type' => 'hidden', 'name' => $qa->get_qt_field_name('attachments'), 'value' => $pickeroptions->itemid)) . $text; }
php
public function files_input(question_attempt $qa, $numallowed, question_display_options $options) { global $CFG; require_once($CFG->dirroot . '/lib/form/filemanager.php'); $pickeroptions = new stdClass(); $pickeroptions->mainfile = null; $pickeroptions->maxfiles = $numallowed; $pickeroptions->itemid = $qa->prepare_response_files_draft_itemid( 'attachments', $options->context->id); $pickeroptions->context = $options->context; $pickeroptions->return_types = FILE_INTERNAL | FILE_CONTROLLED_LINK; $pickeroptions->itemid = $qa->prepare_response_files_draft_itemid( 'attachments', $options->context->id); $pickeroptions->accepted_types = $qa->get_question()->filetypeslist; $fm = new form_filemanager($pickeroptions); $filesrenderer = $this->page->get_renderer('core', 'files'); $text = ''; if (!empty($qa->get_question()->filetypeslist)) { $text = html_writer::tag('p', get_string('acceptedfiletypes', 'qtype_essay')); $filetypesutil = new \core_form\filetypes_util(); $filetypes = $qa->get_question()->filetypeslist; $filetypedescriptions = $filetypesutil->describe_file_types($filetypes); $text .= $this->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions); } return $filesrenderer->render($fm). html_writer::empty_tag( 'input', array('type' => 'hidden', 'name' => $qa->get_qt_field_name('attachments'), 'value' => $pickeroptions->itemid)) . $text; }
[ "public", "function", "files_input", "(", "question_attempt", "$", "qa", ",", "$", "numallowed", ",", "question_display_options", "$", "options", ")", "{", "global", "$", "CFG", ";", "require_once", "(", "$", "CFG", "->", "dirroot", ".", "'/lib/form/filemanager.php'", ")", ";", "$", "pickeroptions", "=", "new", "stdClass", "(", ")", ";", "$", "pickeroptions", "->", "mainfile", "=", "null", ";", "$", "pickeroptions", "->", "maxfiles", "=", "$", "numallowed", ";", "$", "pickeroptions", "->", "itemid", "=", "$", "qa", "->", "prepare_response_files_draft_itemid", "(", "'attachments'", ",", "$", "options", "->", "context", "->", "id", ")", ";", "$", "pickeroptions", "->", "context", "=", "$", "options", "->", "context", ";", "$", "pickeroptions", "->", "return_types", "=", "FILE_INTERNAL", "|", "FILE_CONTROLLED_LINK", ";", "$", "pickeroptions", "->", "itemid", "=", "$", "qa", "->", "prepare_response_files_draft_itemid", "(", "'attachments'", ",", "$", "options", "->", "context", "->", "id", ")", ";", "$", "pickeroptions", "->", "accepted_types", "=", "$", "qa", "->", "get_question", "(", ")", "->", "filetypeslist", ";", "$", "fm", "=", "new", "form_filemanager", "(", "$", "pickeroptions", ")", ";", "$", "filesrenderer", "=", "$", "this", "->", "page", "->", "get_renderer", "(", "'core'", ",", "'files'", ")", ";", "$", "text", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "qa", "->", "get_question", "(", ")", "->", "filetypeslist", ")", ")", "{", "$", "text", "=", "html_writer", "::", "tag", "(", "'p'", ",", "get_string", "(", "'acceptedfiletypes'", ",", "'qtype_essay'", ")", ")", ";", "$", "filetypesutil", "=", "new", "\\", "core_form", "\\", "filetypes_util", "(", ")", ";", "$", "filetypes", "=", "$", "qa", "->", "get_question", "(", ")", "->", "filetypeslist", ";", "$", "filetypedescriptions", "=", "$", "filetypesutil", "->", "describe_file_types", "(", "$", "filetypes", ")", ";", "$", "text", ".=", "$", "this", "->", "render_from_template", "(", "'core_form/filetypes-descriptions'", ",", "$", "filetypedescriptions", ")", ";", "}", "return", "$", "filesrenderer", "->", "render", "(", "$", "fm", ")", ".", "html_writer", "::", "empty_tag", "(", "'input'", ",", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "$", "qa", "->", "get_qt_field_name", "(", "'attachments'", ")", ",", "'value'", "=>", "$", "pickeroptions", "->", "itemid", ")", ")", ".", "$", "text", ";", "}" ]
Displays the input control for when the student should upload a single file. @param question_attempt $qa the question attempt to display. @param int $numallowed the maximum number of attachments allowed. -1 = unlimited. @param question_display_options $options controls what should and should not be displayed. Used to get the context.
[ "Displays", "the", "input", "control", "for", "when", "the", "student", "should", "upload", "a", "single", "file", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/essay/renderer.php#L107-L138
216,007
moodle/moodle
question/type/essay/renderer.php
qtype_essay_format_editorfilepicker_renderer.specific_filepicker_options
protected function specific_filepicker_options($acceptedtypes, $draftitemid, $context) { debugging('qtype_essay_format_editorfilepicker_renderer::specific_filepicker_options() is deprecated, ' . 'use question_utils::specific_filepicker_options() instead.', DEBUG_DEVELOPER); $filepickeroptions = new stdClass(); $filepickeroptions->accepted_types = $acceptedtypes; $filepickeroptions->return_types = FILE_INTERNAL | FILE_EXTERNAL; $filepickeroptions->context = $context; $filepickeroptions->env = 'filepicker'; $options = initialise_filepicker($filepickeroptions); $options->context = $context; $options->client_id = uniqid(); $options->env = 'editor'; $options->itemid = $draftitemid; return $options; }
php
protected function specific_filepicker_options($acceptedtypes, $draftitemid, $context) { debugging('qtype_essay_format_editorfilepicker_renderer::specific_filepicker_options() is deprecated, ' . 'use question_utils::specific_filepicker_options() instead.', DEBUG_DEVELOPER); $filepickeroptions = new stdClass(); $filepickeroptions->accepted_types = $acceptedtypes; $filepickeroptions->return_types = FILE_INTERNAL | FILE_EXTERNAL; $filepickeroptions->context = $context; $filepickeroptions->env = 'filepicker'; $options = initialise_filepicker($filepickeroptions); $options->context = $context; $options->client_id = uniqid(); $options->env = 'editor'; $options->itemid = $draftitemid; return $options; }
[ "protected", "function", "specific_filepicker_options", "(", "$", "acceptedtypes", ",", "$", "draftitemid", ",", "$", "context", ")", "{", "debugging", "(", "'qtype_essay_format_editorfilepicker_renderer::specific_filepicker_options() is deprecated, '", ".", "'use question_utils::specific_filepicker_options() instead.'", ",", "DEBUG_DEVELOPER", ")", ";", "$", "filepickeroptions", "=", "new", "stdClass", "(", ")", ";", "$", "filepickeroptions", "->", "accepted_types", "=", "$", "acceptedtypes", ";", "$", "filepickeroptions", "->", "return_types", "=", "FILE_INTERNAL", "|", "FILE_EXTERNAL", ";", "$", "filepickeroptions", "->", "context", "=", "$", "context", ";", "$", "filepickeroptions", "->", "env", "=", "'filepicker'", ";", "$", "options", "=", "initialise_filepicker", "(", "$", "filepickeroptions", ")", ";", "$", "options", "->", "context", "=", "$", "context", ";", "$", "options", "->", "client_id", "=", "uniqid", "(", ")", ";", "$", "options", "->", "env", "=", "'editor'", ";", "$", "options", "->", "itemid", "=", "$", "draftitemid", ";", "return", "$", "options", ";", "}" ]
Get the options required to configure the filepicker for one of the editor toolbar buttons. @deprecated since 3.5 @param mixed $acceptedtypes array of types of '*'. @param int $draftitemid the draft area item id. @param object $context the context. @return object the required options.
[ "Get", "the", "options", "required", "to", "configure", "the", "filepicker", "for", "one", "of", "the", "editor", "toolbar", "buttons", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/essay/renderer.php#L389-L406
216,008
moodle/moodle
media/classes/player.php
core_media_player.get_name
protected function get_name($name, $urls) { // If there is a specified name, use that. if ($name) { return $name; } // Get filename of first URL. $url = reset($urls); $name = core_media_manager::instance()->get_filename($url); // If there is more than one url, strip the extension as we could be // referring to a different one or several at once. if (count($urls) > 1) { $name = preg_replace('~\.[^.]*$~', '', $name); } return $name; }
php
protected function get_name($name, $urls) { // If there is a specified name, use that. if ($name) { return $name; } // Get filename of first URL. $url = reset($urls); $name = core_media_manager::instance()->get_filename($url); // If there is more than one url, strip the extension as we could be // referring to a different one or several at once. if (count($urls) > 1) { $name = preg_replace('~\.[^.]*$~', '', $name); } return $name; }
[ "protected", "function", "get_name", "(", "$", "name", ",", "$", "urls", ")", "{", "// If there is a specified name, use that.", "if", "(", "$", "name", ")", "{", "return", "$", "name", ";", "}", "// Get filename of first URL.", "$", "url", "=", "reset", "(", "$", "urls", ")", ";", "$", "name", "=", "core_media_manager", "::", "instance", "(", ")", "->", "get_filename", "(", "$", "url", ")", ";", "// If there is more than one url, strip the extension as we could be", "// referring to a different one or several at once.", "if", "(", "count", "(", "$", "urls", ")", ">", "1", ")", "{", "$", "name", "=", "preg_replace", "(", "'~\\.[^.]*$~'", ",", "''", ",", "$", "name", ")", ";", "}", "return", "$", "name", ";", "}" ]
Obtains suitable name for media. Uses specified name if there is one, otherwise makes one up. @param string $name User-specified name ('' if none) @param array $urls Array of moodle_url used to make up name @return string Name
[ "Obtains", "suitable", "name", "for", "media", ".", "Uses", "specified", "name", "if", "there", "is", "one", "otherwise", "makes", "one", "up", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/media/classes/player.php#L189-L206
216,009
moodle/moodle
lib/simplepie/library/SimplePie/Enclosure.php
SimplePie_Enclosure.get_caption
public function get_caption($key = 0) { $captions = $this->get_captions(); if (isset($captions[$key])) { return $captions[$key]; } else { return null; } }
php
public function get_caption($key = 0) { $captions = $this->get_captions(); if (isset($captions[$key])) { return $captions[$key]; } else { return null; } }
[ "public", "function", "get_caption", "(", "$", "key", "=", "0", ")", "{", "$", "captions", "=", "$", "this", "->", "get_captions", "(", ")", ";", "if", "(", "isset", "(", "$", "captions", "[", "$", "key", "]", ")", ")", "{", "return", "$", "captions", "[", "$", "key", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get a single caption @param int $key @return SimplePie_Caption|null
[ "Get", "a", "single", "caption" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Enclosure.php#L297-L308
216,010
moodle/moodle
lib/simplepie/library/SimplePie/Enclosure.php
SimplePie_Enclosure.get_credit
public function get_credit($key = 0) { $credits = $this->get_credits(); if (isset($credits[$key])) { return $credits[$key]; } else { return null; } }
php
public function get_credit($key = 0) { $credits = $this->get_credits(); if (isset($credits[$key])) { return $credits[$key]; } else { return null; } }
[ "public", "function", "get_credit", "(", "$", "key", "=", "0", ")", "{", "$", "credits", "=", "$", "this", "->", "get_credits", "(", ")", ";", "if", "(", "isset", "(", "$", "credits", "[", "$", "key", "]", ")", ")", "{", "return", "$", "credits", "[", "$", "key", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get a single credit @param int $key @return SimplePie_Credit|null
[ "Get", "a", "single", "credit" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Enclosure.php#L403-L414
216,011
moodle/moodle
lib/simplepie/library/SimplePie/Enclosure.php
SimplePie_Enclosure.get_duration
public function get_duration($convert = false) { if ($this->duration !== null) { if ($convert) { $time = SimplePie_Misc::time_hms($this->duration); return $time; } else { return $this->duration; } } else { return null; } }
php
public function get_duration($convert = false) { if ($this->duration !== null) { if ($convert) { $time = SimplePie_Misc::time_hms($this->duration); return $time; } else { return $this->duration; } } else { return null; } }
[ "public", "function", "get_duration", "(", "$", "convert", "=", "false", ")", "{", "if", "(", "$", "this", "->", "duration", "!==", "null", ")", "{", "if", "(", "$", "convert", ")", "{", "$", "time", "=", "SimplePie_Misc", "::", "time_hms", "(", "$", "this", "->", "duration", ")", ";", "return", "$", "time", ";", "}", "else", "{", "return", "$", "this", "->", "duration", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the duration of the enclosure @param bool $convert Convert seconds into hh:mm:ss @return string|int|null 'hh:mm:ss' string if `$convert` was specified, otherwise integer (or null if none found)
[ "Get", "the", "duration", "of", "the", "enclosure" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Enclosure.php#L456-L474
216,012
moodle/moodle
lib/simplepie/library/SimplePie/Enclosure.php
SimplePie_Enclosure.get_extension
public function get_extension() { if ($this->link !== null) { $url = SimplePie_Misc::parse_url($this->link); if ($url['path'] !== '') { return pathinfo($url['path'], PATHINFO_EXTENSION); } } return null; }
php
public function get_extension() { if ($this->link !== null) { $url = SimplePie_Misc::parse_url($this->link); if ($url['path'] !== '') { return pathinfo($url['path'], PATHINFO_EXTENSION); } } return null; }
[ "public", "function", "get_extension", "(", ")", "{", "if", "(", "$", "this", "->", "link", "!==", "null", ")", "{", "$", "url", "=", "SimplePie_Misc", "::", "parse_url", "(", "$", "this", "->", "link", ")", ";", "if", "(", "$", "url", "[", "'path'", "]", "!==", "''", ")", "{", "return", "pathinfo", "(", "$", "url", "[", "'path'", "]", ",", "PATHINFO_EXTENSION", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get the file extension @return string|null
[ "Get", "the", "file", "extension" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/simplepie/library/SimplePie/Enclosure.php#L498-L509
216,013
moodle/moodle
webservice/lib.php
webservice.update_token_lastaccess
public static function update_token_lastaccess($token, int $time = 0) { global $DB; if (!$time) { $time = time(); } // Only update the field if it is a different time from previous request, // so as not to waste database effort. if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) { $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id)); } }
php
public static function update_token_lastaccess($token, int $time = 0) { global $DB; if (!$time) { $time = time(); } // Only update the field if it is a different time from previous request, // so as not to waste database effort. if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) { $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id)); } }
[ "public", "static", "function", "update_token_lastaccess", "(", "$", "token", ",", "int", "$", "time", "=", "0", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "$", "time", ")", "{", "$", "time", "=", "time", "(", ")", ";", "}", "// Only update the field if it is a different time from previous request,", "// so as not to waste database effort.", "if", "(", "$", "time", ">=", "$", "token", "->", "lastaccess", "+", "self", "::", "TOKEN_LASTACCESS_UPDATE_SECS", ")", "{", "$", "DB", "->", "set_field", "(", "'external_tokens'", ",", "'lastaccess'", ",", "$", "time", ",", "array", "(", "'id'", "=>", "$", "token", "->", "id", ")", ")", ";", "}", "}" ]
Updates the last access time for a token. @param \stdClass $token Token object (must include id, lastaccess fields) @param int $time Time of access (0 = use current time) @throws dml_exception If database error
[ "Updates", "the", "last", "access", "time", "for", "a", "token", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L232-L244
216,014
moodle/moodle
webservice/lib.php
webservice.generate_user_ws_tokens
public function generate_user_ws_tokens($userid) { global $CFG, $DB; // generate a token for non admin if web service are enable and the user has the capability to create a token if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) { // for every service than the user is authorised on, create a token (if it doesn't already exist) // get all services which are set to all user (no restricted to specific users) $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0)); $serviceidlist = array(); foreach ($norestrictedservices as $service) { $serviceidlist[] = $service->id; } // get all services which are set to the current user (the current user is specified in the restricted user list) $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid)); foreach ($servicesusers as $serviceuser) { if (!in_array($serviceuser->externalserviceid,$serviceidlist)) { $serviceidlist[] = $serviceuser->externalserviceid; } } // get all services which already have a token set for the current user $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT)); $tokenizedservice = array(); foreach ($usertokens as $token) { $tokenizedservice[] = $token->externalserviceid; } // create a token for the service which have no token already foreach ($serviceidlist as $serviceid) { if (!in_array($serviceid, $tokenizedservice)) { // create the token for this service $newtoken = new stdClass(); $newtoken->token = md5(uniqid(rand(),1)); // check that the user has capability on this service $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT; $newtoken->userid = $userid; $newtoken->externalserviceid = $serviceid; // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE $newtoken->contextid = context_system::instance()->id; $newtoken->creatorid = $userid; $newtoken->timecreated = time(); $newtoken->privatetoken = null; $DB->insert_record('external_tokens', $newtoken); } } } }
php
public function generate_user_ws_tokens($userid) { global $CFG, $DB; // generate a token for non admin if web service are enable and the user has the capability to create a token if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) { // for every service than the user is authorised on, create a token (if it doesn't already exist) // get all services which are set to all user (no restricted to specific users) $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0)); $serviceidlist = array(); foreach ($norestrictedservices as $service) { $serviceidlist[] = $service->id; } // get all services which are set to the current user (the current user is specified in the restricted user list) $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid)); foreach ($servicesusers as $serviceuser) { if (!in_array($serviceuser->externalserviceid,$serviceidlist)) { $serviceidlist[] = $serviceuser->externalserviceid; } } // get all services which already have a token set for the current user $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT)); $tokenizedservice = array(); foreach ($usertokens as $token) { $tokenizedservice[] = $token->externalserviceid; } // create a token for the service which have no token already foreach ($serviceidlist as $serviceid) { if (!in_array($serviceid, $tokenizedservice)) { // create the token for this service $newtoken = new stdClass(); $newtoken->token = md5(uniqid(rand(),1)); // check that the user has capability on this service $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT; $newtoken->userid = $userid; $newtoken->externalserviceid = $serviceid; // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE $newtoken->contextid = context_system::instance()->id; $newtoken->creatorid = $userid; $newtoken->timecreated = time(); $newtoken->privatetoken = null; $DB->insert_record('external_tokens', $newtoken); } } } }
[ "public", "function", "generate_user_ws_tokens", "(", "$", "userid", ")", "{", "global", "$", "CFG", ",", "$", "DB", ";", "// generate a token for non admin if web service are enable and the user has the capability to create a token", "if", "(", "!", "is_siteadmin", "(", ")", "&&", "has_capability", "(", "'moodle/webservice:createtoken'", ",", "context_system", "::", "instance", "(", ")", ",", "$", "userid", ")", "&&", "!", "empty", "(", "$", "CFG", "->", "enablewebservices", ")", ")", "{", "// for every service than the user is authorised on, create a token (if it doesn't already exist)", "// get all services which are set to all user (no restricted to specific users)", "$", "norestrictedservices", "=", "$", "DB", "->", "get_records", "(", "'external_services'", ",", "array", "(", "'restrictedusers'", "=>", "0", ")", ")", ";", "$", "serviceidlist", "=", "array", "(", ")", ";", "foreach", "(", "$", "norestrictedservices", "as", "$", "service", ")", "{", "$", "serviceidlist", "[", "]", "=", "$", "service", "->", "id", ";", "}", "// get all services which are set to the current user (the current user is specified in the restricted user list)", "$", "servicesusers", "=", "$", "DB", "->", "get_records", "(", "'external_services_users'", ",", "array", "(", "'userid'", "=>", "$", "userid", ")", ")", ";", "foreach", "(", "$", "servicesusers", "as", "$", "serviceuser", ")", "{", "if", "(", "!", "in_array", "(", "$", "serviceuser", "->", "externalserviceid", ",", "$", "serviceidlist", ")", ")", "{", "$", "serviceidlist", "[", "]", "=", "$", "serviceuser", "->", "externalserviceid", ";", "}", "}", "// get all services which already have a token set for the current user", "$", "usertokens", "=", "$", "DB", "->", "get_records", "(", "'external_tokens'", ",", "array", "(", "'userid'", "=>", "$", "userid", ",", "'tokentype'", "=>", "EXTERNAL_TOKEN_PERMANENT", ")", ")", ";", "$", "tokenizedservice", "=", "array", "(", ")", ";", "foreach", "(", "$", "usertokens", "as", "$", "token", ")", "{", "$", "tokenizedservice", "[", "]", "=", "$", "token", "->", "externalserviceid", ";", "}", "// create a token for the service which have no token already", "foreach", "(", "$", "serviceidlist", "as", "$", "serviceid", ")", "{", "if", "(", "!", "in_array", "(", "$", "serviceid", ",", "$", "tokenizedservice", ")", ")", "{", "// create the token for this service", "$", "newtoken", "=", "new", "stdClass", "(", ")", ";", "$", "newtoken", "->", "token", "=", "md5", "(", "uniqid", "(", "rand", "(", ")", ",", "1", ")", ")", ";", "// check that the user has capability on this service", "$", "newtoken", "->", "tokentype", "=", "EXTERNAL_TOKEN_PERMANENT", ";", "$", "newtoken", "->", "userid", "=", "$", "userid", ";", "$", "newtoken", "->", "externalserviceid", "=", "$", "serviceid", ";", "// TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE", "$", "newtoken", "->", "contextid", "=", "context_system", "::", "instance", "(", ")", "->", "id", ";", "$", "newtoken", "->", "creatorid", "=", "$", "userid", ";", "$", "newtoken", "->", "timecreated", "=", "time", "(", ")", ";", "$", "newtoken", "->", "privatetoken", "=", "null", ";", "$", "DB", "->", "insert_record", "(", "'external_tokens'", ",", "$", "newtoken", ")", ";", "}", "}", "}", "}" ]
Generate all tokens of a specific user @param int $userid user id
[ "Generate", "all", "tokens", "of", "a", "specific", "user" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L330-L381
216,015
moodle/moodle
webservice/lib.php
webservice.get_token_by_id_with_details
public function get_token_by_id_with_details($tokenid) { global $DB; $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid FROM {external_tokens} t, {user} u, {external_services} s WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id"; $token = $DB->get_record_sql($sql, array($tokenid, EXTERNAL_TOKEN_PERMANENT), MUST_EXIST); return $token; }
php
public function get_token_by_id_with_details($tokenid) { global $DB; $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid FROM {external_tokens} t, {user} u, {external_services} s WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id"; $token = $DB->get_record_sql($sql, array($tokenid, EXTERNAL_TOKEN_PERMANENT), MUST_EXIST); return $token; }
[ "public", "function", "get_token_by_id_with_details", "(", "$", "tokenid", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "\"SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid\n FROM {external_tokens} t, {user} u, {external_services} s\n WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id\"", ";", "$", "token", "=", "$", "DB", "->", "get_record_sql", "(", "$", "sql", ",", "array", "(", "$", "tokenid", ",", "EXTERNAL_TOKEN_PERMANENT", ")", ",", "MUST_EXIST", ")", ";", "return", "$", "token", ";", "}" ]
Return a token of an arbitrary user by tokenid, including details of the associated user and the service name. If no tokens exist an exception is thrown The returned value is a stdClass: ->id token id ->token ->firstname user firstname ->lastname ->name service name @param int $tokenid token id @return stdClass
[ "Return", "a", "token", "of", "an", "arbitrary", "user", "by", "tokenid", "including", "details", "of", "the", "associated", "user", "and", "the", "service", "name", ".", "If", "no", "tokens", "exist", "an", "exception", "is", "thrown" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L448-L455
216,016
moodle/moodle
webservice/lib.php
webservice.delete_service
public function delete_service($serviceid) { global $DB; $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid)); $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid)); $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid)); $DB->delete_records('external_services', array('id' => $serviceid)); }
php
public function delete_service($serviceid) { global $DB; $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid)); $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid)); $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid)); $DB->delete_records('external_services', array('id' => $serviceid)); }
[ "public", "function", "delete_service", "(", "$", "serviceid", ")", "{", "global", "$", "DB", ";", "$", "DB", "->", "delete_records", "(", "'external_services_users'", ",", "array", "(", "'externalserviceid'", "=>", "$", "serviceid", ")", ")", ";", "$", "DB", "->", "delete_records", "(", "'external_services_functions'", ",", "array", "(", "'externalserviceid'", "=>", "$", "serviceid", ")", ")", ";", "$", "DB", "->", "delete_records", "(", "'external_tokens'", ",", "array", "(", "'externalserviceid'", "=>", "$", "serviceid", ")", ")", ";", "$", "DB", "->", "delete_records", "(", "'external_services'", ",", "array", "(", "'id'", "=>", "$", "serviceid", ")", ")", ";", "}" ]
Delete a service Also delete function references and authorised user references. @param int $serviceid service id
[ "Delete", "a", "service", "Also", "delete", "function", "references", "and", "authorised", "user", "references", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L494-L500
216,017
moodle/moodle
webservice/lib.php
webservice.get_not_associated_external_functions
public function get_not_associated_external_functions($serviceid) { global $DB; $select = "name NOT IN (SELECT s.functionname FROM {external_services_functions} s WHERE s.externalserviceid = :sid )"; $functions = $DB->get_records_select('external_functions', $select, array('sid' => $serviceid), 'name'); return $functions; }
php
public function get_not_associated_external_functions($serviceid) { global $DB; $select = "name NOT IN (SELECT s.functionname FROM {external_services_functions} s WHERE s.externalserviceid = :sid )"; $functions = $DB->get_records_select('external_functions', $select, array('sid' => $serviceid), 'name'); return $functions; }
[ "public", "function", "get_not_associated_external_functions", "(", "$", "serviceid", ")", "{", "global", "$", "DB", ";", "$", "select", "=", "\"name NOT IN (SELECT s.functionname\n FROM {external_services_functions} s\n WHERE s.externalserviceid = :sid\n )\"", ";", "$", "functions", "=", "$", "DB", "->", "get_records_select", "(", "'external_functions'", ",", "$", "select", ",", "array", "(", "'sid'", "=>", "$", "serviceid", ")", ",", "'name'", ")", ";", "return", "$", "functions", ";", "}" ]
Get functions not included in a service @param int $serviceid service id @return array functions
[ "Get", "functions", "not", "included", "in", "a", "service" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L568-L579
216,018
moodle/moodle
webservice/lib.php
webservice.get_external_service_by_id
public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) { global $DB; $service = $DB->get_record('external_services', array('id' => $serviceid), '*', $strictness); return $service; }
php
public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) { global $DB; $service = $DB->get_record('external_services', array('id' => $serviceid), '*', $strictness); return $service; }
[ "public", "function", "get_external_service_by_id", "(", "$", "serviceid", ",", "$", "strictness", "=", "IGNORE_MISSING", ")", "{", "global", "$", "DB", ";", "$", "service", "=", "$", "DB", "->", "get_record", "(", "'external_services'", ",", "array", "(", "'id'", "=>", "$", "serviceid", ")", ",", "'*'", ",", "$", "strictness", ")", ";", "return", "$", "service", ";", "}" ]
Get an external service for a given service id @param int $serviceid service id @param int $strictness IGNORE_MISSING, MUST_EXIST... @return stdClass external service
[ "Get", "an", "external", "service", "for", "a", "given", "service", "id" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L690-L695
216,019
moodle/moodle
webservice/lib.php
webservice.get_external_service_by_shortname
public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) { global $DB; $service = $DB->get_record('external_services', array('shortname' => $shortname), '*', $strictness); return $service; }
php
public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) { global $DB; $service = $DB->get_record('external_services', array('shortname' => $shortname), '*', $strictness); return $service; }
[ "public", "function", "get_external_service_by_shortname", "(", "$", "shortname", ",", "$", "strictness", "=", "IGNORE_MISSING", ")", "{", "global", "$", "DB", ";", "$", "service", "=", "$", "DB", "->", "get_record", "(", "'external_services'", ",", "array", "(", "'shortname'", "=>", "$", "shortname", ")", ",", "'*'", ",", "$", "strictness", ")", ";", "return", "$", "service", ";", "}" ]
Get an external service for a given shortname @param string $shortname service shortname @param int $strictness IGNORE_MISSING, MUST_EXIST... @return stdClass external service
[ "Get", "an", "external", "service", "for", "a", "given", "shortname" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L704-L709
216,020
moodle/moodle
webservice/lib.php
webservice.add_external_function_to_service
public function add_external_function_to_service($functionname, $serviceid) { global $DB; $addedfunction = new stdClass(); $addedfunction->externalserviceid = $serviceid; $addedfunction->functionname = $functionname; $DB->insert_record('external_services_functions', $addedfunction); }
php
public function add_external_function_to_service($functionname, $serviceid) { global $DB; $addedfunction = new stdClass(); $addedfunction->externalserviceid = $serviceid; $addedfunction->functionname = $functionname; $DB->insert_record('external_services_functions', $addedfunction); }
[ "public", "function", "add_external_function_to_service", "(", "$", "functionname", ",", "$", "serviceid", ")", "{", "global", "$", "DB", ";", "$", "addedfunction", "=", "new", "stdClass", "(", ")", ";", "$", "addedfunction", "->", "externalserviceid", "=", "$", "serviceid", ";", "$", "addedfunction", "->", "functionname", "=", "$", "functionname", ";", "$", "DB", "->", "insert_record", "(", "'external_services_functions'", ",", "$", "addedfunction", ")", ";", "}" ]
Add a function to a service @param string $functionname function name @param int $serviceid service id
[ "Add", "a", "function", "to", "a", "service" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L731-L737
216,021
moodle/moodle
webservice/lib.php
webservice.add_external_service
public function add_external_service($service) { global $DB; $service->timecreated = time(); $serviceid = $DB->insert_record('external_services', $service); return $serviceid; }
php
public function add_external_service($service) { global $DB; $service->timecreated = time(); $serviceid = $DB->insert_record('external_services', $service); return $serviceid; }
[ "public", "function", "add_external_service", "(", "$", "service", ")", "{", "global", "$", "DB", ";", "$", "service", "->", "timecreated", "=", "time", "(", ")", ";", "$", "serviceid", "=", "$", "DB", "->", "insert_record", "(", "'external_services'", ",", "$", "service", ")", ";", "return", "$", "serviceid", ";", "}" ]
Add a service It generates the timecreated field automatically. @param stdClass $service @return serviceid integer
[ "Add", "a", "service", "It", "generates", "the", "timecreated", "field", "automatically", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L746-L751
216,022
moodle/moodle
webservice/lib.php
webservice.get_active_tokens
public static function get_active_tokens($userid) { global $DB; $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN {external_services} s ON t.externalserviceid = s.id WHERE t.userid = :userid AND (t.validuntil IS NULL OR t.validuntil > :now)'; $params = array('userid' => $userid, 'now' => time()); return $DB->get_records_sql($sql, $params); }
php
public static function get_active_tokens($userid) { global $DB; $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN {external_services} s ON t.externalserviceid = s.id WHERE t.userid = :userid AND (t.validuntil IS NULL OR t.validuntil > :now)'; $params = array('userid' => $userid, 'now' => time()); return $DB->get_records_sql($sql, $params); }
[ "public", "static", "function", "get_active_tokens", "(", "$", "userid", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN\n {external_services} s ON t.externalserviceid = s.id WHERE\n t.userid = :userid AND (t.validuntil IS NULL OR t.validuntil > :now)'", ";", "$", "params", "=", "array", "(", "'userid'", "=>", "$", "userid", ",", "'now'", "=>", "time", "(", ")", ")", ";", "return", "$", "DB", "->", "get_records_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "}" ]
Return a list with all the valid user tokens for the given user, it only excludes expired tokens. @param string $userid user id to retrieve tokens from @return array array of token entries @since Moodle 3.2
[ "Return", "a", "list", "with", "all", "the", "valid", "user", "tokens", "for", "the", "given", "user", "it", "only", "excludes", "expired", "tokens", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L800-L808
216,023
moodle/moodle
webservice/lib.php
webservice_server.authenticate_by_token
protected function authenticate_by_token($tokentype){ global $DB; $loginfaileddefaultparams = array( 'other' => array( 'method' => $this->authmethod, 'reason' => null ) ); if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) { // Log failed login attempts. $params = $loginfaileddefaultparams; $params['other']['reason'] = 'invalid_token'; $event = \core\event\webservice_login_failed::create($params); $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0)); $event->trigger(); throw new moodle_exception('invalidtoken', 'webservice'); } if ($token->validuntil and $token->validuntil < time()) { $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype)); throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token'); } if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type if (!\core\session\manager::session_exists($token->sid)){ $DB->delete_records('external_tokens', array('sid'=>$token->sid)); throw new webservice_access_exception('Invalid session based token - session not found or expired'); } } if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) { $params = $loginfaileddefaultparams; $params['other']['reason'] = 'ip_restricted'; $params['other']['tokenid'] = $token->id; $event = \core\event\webservice_login_failed::create($params); $event->add_record_snapshot('external_tokens', $token); $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0)); $event->trigger(); throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr() . ' is not supported - check this allowed user'); } $this->restricted_context = context::instance_by_id($token->contextid); $this->restricted_serviceid = $token->externalserviceid; $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST); // log token access webservice::update_token_lastaccess($token); return $user; }
php
protected function authenticate_by_token($tokentype){ global $DB; $loginfaileddefaultparams = array( 'other' => array( 'method' => $this->authmethod, 'reason' => null ) ); if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) { // Log failed login attempts. $params = $loginfaileddefaultparams; $params['other']['reason'] = 'invalid_token'; $event = \core\event\webservice_login_failed::create($params); $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0)); $event->trigger(); throw new moodle_exception('invalidtoken', 'webservice'); } if ($token->validuntil and $token->validuntil < time()) { $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype)); throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token'); } if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type if (!\core\session\manager::session_exists($token->sid)){ $DB->delete_records('external_tokens', array('sid'=>$token->sid)); throw new webservice_access_exception('Invalid session based token - session not found or expired'); } } if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) { $params = $loginfaileddefaultparams; $params['other']['reason'] = 'ip_restricted'; $params['other']['tokenid'] = $token->id; $event = \core\event\webservice_login_failed::create($params); $event->add_record_snapshot('external_tokens', $token); $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' , get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0)); $event->trigger(); throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr() . ' is not supported - check this allowed user'); } $this->restricted_context = context::instance_by_id($token->contextid); $this->restricted_serviceid = $token->externalserviceid; $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST); // log token access webservice::update_token_lastaccess($token); return $user; }
[ "protected", "function", "authenticate_by_token", "(", "$", "tokentype", ")", "{", "global", "$", "DB", ";", "$", "loginfaileddefaultparams", "=", "array", "(", "'other'", "=>", "array", "(", "'method'", "=>", "$", "this", "->", "authmethod", ",", "'reason'", "=>", "null", ")", ")", ";", "if", "(", "!", "$", "token", "=", "$", "DB", "->", "get_record", "(", "'external_tokens'", ",", "array", "(", "'token'", "=>", "$", "this", "->", "token", ",", "'tokentype'", "=>", "$", "tokentype", ")", ")", ")", "{", "// Log failed login attempts.", "$", "params", "=", "$", "loginfaileddefaultparams", ";", "$", "params", "[", "'other'", "]", "[", "'reason'", "]", "=", "'invalid_token'", ";", "$", "event", "=", "\\", "core", "\\", "event", "\\", "webservice_login_failed", "::", "create", "(", "$", "params", ")", ";", "$", "event", "->", "set_legacy_logdata", "(", "array", "(", "SITEID", ",", "'webservice'", ",", "get_string", "(", "'tokenauthlog'", ",", "'webservice'", ")", ",", "''", ",", "get_string", "(", "'failedtolog'", ",", "'webservice'", ")", ".", "\": \"", ".", "$", "this", "->", "token", ".", "\" - \"", ".", "getremoteaddr", "(", ")", ",", "0", ")", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "throw", "new", "moodle_exception", "(", "'invalidtoken'", ",", "'webservice'", ")", ";", "}", "if", "(", "$", "token", "->", "validuntil", "and", "$", "token", "->", "validuntil", "<", "time", "(", ")", ")", "{", "$", "DB", "->", "delete_records", "(", "'external_tokens'", ",", "array", "(", "'token'", "=>", "$", "this", "->", "token", ",", "'tokentype'", "=>", "$", "tokentype", ")", ")", ";", "throw", "new", "webservice_access_exception", "(", "'Invalid token - token expired - check validuntil time for the token'", ")", ";", "}", "if", "(", "$", "token", "->", "sid", ")", "{", "//assumes that if sid is set then there must be a valid associated session no matter the token type", "if", "(", "!", "\\", "core", "\\", "session", "\\", "manager", "::", "session_exists", "(", "$", "token", "->", "sid", ")", ")", "{", "$", "DB", "->", "delete_records", "(", "'external_tokens'", ",", "array", "(", "'sid'", "=>", "$", "token", "->", "sid", ")", ")", ";", "throw", "new", "webservice_access_exception", "(", "'Invalid session based token - session not found or expired'", ")", ";", "}", "}", "if", "(", "$", "token", "->", "iprestriction", "and", "!", "address_in_subnet", "(", "getremoteaddr", "(", ")", ",", "$", "token", "->", "iprestriction", ")", ")", "{", "$", "params", "=", "$", "loginfaileddefaultparams", ";", "$", "params", "[", "'other'", "]", "[", "'reason'", "]", "=", "'ip_restricted'", ";", "$", "params", "[", "'other'", "]", "[", "'tokenid'", "]", "=", "$", "token", "->", "id", ";", "$", "event", "=", "\\", "core", "\\", "event", "\\", "webservice_login_failed", "::", "create", "(", "$", "params", ")", ";", "$", "event", "->", "add_record_snapshot", "(", "'external_tokens'", ",", "$", "token", ")", ";", "$", "event", "->", "set_legacy_logdata", "(", "array", "(", "SITEID", ",", "'webservice'", ",", "get_string", "(", "'tokenauthlog'", ",", "'webservice'", ")", ",", "''", ",", "get_string", "(", "'failedtolog'", ",", "'webservice'", ")", ".", "\": \"", ".", "getremoteaddr", "(", ")", ",", "0", ")", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "throw", "new", "webservice_access_exception", "(", "'Invalid service - IP:'", ".", "getremoteaddr", "(", ")", ".", "' is not supported - check this allowed user'", ")", ";", "}", "$", "this", "->", "restricted_context", "=", "context", "::", "instance_by_id", "(", "$", "token", "->", "contextid", ")", ";", "$", "this", "->", "restricted_serviceid", "=", "$", "token", "->", "externalserviceid", ";", "$", "user", "=", "$", "DB", "->", "get_record", "(", "'user'", ",", "array", "(", "'id'", "=>", "$", "token", "->", "userid", ")", ",", "'*'", ",", "MUST_EXIST", ")", ";", "// log token access", "webservice", "::", "update_token_lastaccess", "(", "$", "token", ")", ";", "return", "$", "user", ";", "}" ]
User authentication by token @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT) @return stdClass the authenticated user @throws webservice_access_exception
[ "User", "authentication", "by", "token" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1089-L1145
216,024
moodle/moodle
webservice/lib.php
webservice_base_server.run
public function run() { global $CFG, $SESSION; // we will probably need a lot of memory in some functions raise_memory_limit(MEMORY_EXTRA); // set some longer timeout, this script is not sending any output, // this means we need to manually extend the timeout operations // that need longer time to finish external_api::set_timeout(); // set up exception handler first, we want to sent them back in correct format that // the other system understands // we do not need to call the original default handler because this ws handler does everything set_exception_handler(array($this, 'exception_handler')); // init all properties from the request data $this->parse_request(); // authenticate user, this has to be done after the request parsing // this also sets up $USER and $SESSION $this->authenticate_user(); // find all needed function info and make sure user may actually execute the function $this->load_function_info(); // Log the web service request. $params = array( 'other' => array( 'function' => $this->functionname ) ); $event = \core\event\webservice_function_called::create($params); $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid)); $event->trigger(); // Do additional setup stuff. $settings = external_settings::get_instance(); $sessionlang = $settings->get_lang(); if (!empty($sessionlang)) { $SESSION->lang = $sessionlang; } setup_lang_from_browser(); if (empty($CFG->lang)) { if (empty($SESSION->lang)) { $CFG->lang = 'en'; } else { $CFG->lang = $SESSION->lang; } } // finally, execute the function - any errors are catched by the default exception handler $this->execute(); // send the results back in correct format $this->send_response(); // session cleanup $this->session_cleanup(); die; }
php
public function run() { global $CFG, $SESSION; // we will probably need a lot of memory in some functions raise_memory_limit(MEMORY_EXTRA); // set some longer timeout, this script is not sending any output, // this means we need to manually extend the timeout operations // that need longer time to finish external_api::set_timeout(); // set up exception handler first, we want to sent them back in correct format that // the other system understands // we do not need to call the original default handler because this ws handler does everything set_exception_handler(array($this, 'exception_handler')); // init all properties from the request data $this->parse_request(); // authenticate user, this has to be done after the request parsing // this also sets up $USER and $SESSION $this->authenticate_user(); // find all needed function info and make sure user may actually execute the function $this->load_function_info(); // Log the web service request. $params = array( 'other' => array( 'function' => $this->functionname ) ); $event = \core\event\webservice_function_called::create($params); $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid)); $event->trigger(); // Do additional setup stuff. $settings = external_settings::get_instance(); $sessionlang = $settings->get_lang(); if (!empty($sessionlang)) { $SESSION->lang = $sessionlang; } setup_lang_from_browser(); if (empty($CFG->lang)) { if (empty($SESSION->lang)) { $CFG->lang = 'en'; } else { $CFG->lang = $SESSION->lang; } } // finally, execute the function - any errors are catched by the default exception handler $this->execute(); // send the results back in correct format $this->send_response(); // session cleanup $this->session_cleanup(); die; }
[ "public", "function", "run", "(", ")", "{", "global", "$", "CFG", ",", "$", "SESSION", ";", "// we will probably need a lot of memory in some functions", "raise_memory_limit", "(", "MEMORY_EXTRA", ")", ";", "// set some longer timeout, this script is not sending any output,", "// this means we need to manually extend the timeout operations", "// that need longer time to finish", "external_api", "::", "set_timeout", "(", ")", ";", "// set up exception handler first, we want to sent them back in correct format that", "// the other system understands", "// we do not need to call the original default handler because this ws handler does everything", "set_exception_handler", "(", "array", "(", "$", "this", ",", "'exception_handler'", ")", ")", ";", "// init all properties from the request data", "$", "this", "->", "parse_request", "(", ")", ";", "// authenticate user, this has to be done after the request parsing", "// this also sets up $USER and $SESSION", "$", "this", "->", "authenticate_user", "(", ")", ";", "// find all needed function info and make sure user may actually execute the function", "$", "this", "->", "load_function_info", "(", ")", ";", "// Log the web service request.", "$", "params", "=", "array", "(", "'other'", "=>", "array", "(", "'function'", "=>", "$", "this", "->", "functionname", ")", ")", ";", "$", "event", "=", "\\", "core", "\\", "event", "\\", "webservice_function_called", "::", "create", "(", "$", "params", ")", ";", "$", "event", "->", "set_legacy_logdata", "(", "array", "(", "SITEID", ",", "'webservice'", ",", "$", "this", "->", "functionname", ",", "''", ",", "getremoteaddr", "(", ")", ",", "0", ",", "$", "this", "->", "userid", ")", ")", ";", "$", "event", "->", "trigger", "(", ")", ";", "// Do additional setup stuff.", "$", "settings", "=", "external_settings", "::", "get_instance", "(", ")", ";", "$", "sessionlang", "=", "$", "settings", "->", "get_lang", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "sessionlang", ")", ")", "{", "$", "SESSION", "->", "lang", "=", "$", "sessionlang", ";", "}", "setup_lang_from_browser", "(", ")", ";", "if", "(", "empty", "(", "$", "CFG", "->", "lang", ")", ")", "{", "if", "(", "empty", "(", "$", "SESSION", "->", "lang", ")", ")", "{", "$", "CFG", "->", "lang", "=", "'en'", ";", "}", "else", "{", "$", "CFG", "->", "lang", "=", "$", "SESSION", "->", "lang", ";", "}", "}", "// finally, execute the function - any errors are catched by the default exception handler", "$", "this", "->", "execute", "(", ")", ";", "// send the results back in correct format", "$", "this", "->", "send_response", "(", ")", ";", "// session cleanup", "$", "this", "->", "session_cleanup", "(", ")", ";", "die", ";", "}" ]
Process request from client. @uses die
[ "Process", "request", "from", "client", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1236-L1299
216,025
moodle/moodle
webservice/lib.php
webservice_base_server.exception_handler
public function exception_handler($ex) { // detect active db transactions, rollback and log as error abort_all_db_transactions(); // some hacks might need a cleanup hook $this->session_cleanup($ex); // now let the plugin send the exception to client $this->send_error($ex); // not much else we can do now, add some logging later exit(1); }
php
public function exception_handler($ex) { // detect active db transactions, rollback and log as error abort_all_db_transactions(); // some hacks might need a cleanup hook $this->session_cleanup($ex); // now let the plugin send the exception to client $this->send_error($ex); // not much else we can do now, add some logging later exit(1); }
[ "public", "function", "exception_handler", "(", "$", "ex", ")", "{", "// detect active db transactions, rollback and log as error", "abort_all_db_transactions", "(", ")", ";", "// some hacks might need a cleanup hook", "$", "this", "->", "session_cleanup", "(", "$", "ex", ")", ";", "// now let the plugin send the exception to client", "$", "this", "->", "send_error", "(", "$", "ex", ")", ";", "// not much else we can do now, add some logging later", "exit", "(", "1", ")", ";", "}" ]
Specialised exception handler, we can not use the standard one because it can not just print html to output. @param exception $ex $uses exit
[ "Specialised", "exception", "handler", "we", "can", "not", "use", "the", "standard", "one", "because", "it", "can", "not", "just", "print", "html", "to", "output", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1308-L1320
216,026
moodle/moodle
webservice/lib.php
webservice_base_server.load_function_info
protected function load_function_info() { global $DB, $USER, $CFG; if (empty($this->functionname)) { throw new invalid_parameter_exception('Missing function name'); } // function must exist $function = external_api::external_function_info($this->functionname); if ($this->restricted_serviceid) { $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid); $wscond1 = 'AND s.id = :sid1'; $wscond2 = 'AND s.id = :sid2'; } else { $params = array(); $wscond1 = ''; $wscond2 = ''; } // now let's verify access control // now make sure the function is listed in at least one service user is allowed to use // allow access only if: // 1/ entry in the external_services_users table if required // 2/ validuntil not reached // 3/ has capability if specified in service desc // 4/ iprestriction $sql = "SELECT s.*, NULL AS iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1) WHERE s.enabled = 1 $wscond1 UNION SELECT s.*, su.iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time())); $rs = $DB->get_recordset_sql($sql, $params); // now make sure user may access at least one service $remoteaddr = getremoteaddr(); $allowed = false; foreach ($rs as $service) { if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) { continue; // cap required, sorry } if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) { continue; // wrong request source ip, sorry } $allowed = true; break; // one service is enough, no need to continue } $rs->close(); if (!$allowed) { throw new webservice_access_exception( 'Access to the function '.$this->functionname.'() is not allowed. There could be multiple reasons for this: 1. The service linked to the user token does not contain the function. 2. The service is user-restricted and the user is not listed. 3. The service is IP-restricted and the user IP is not listed. 4. The service is time-restricted and the time has expired. 5. The token is time-restricted and the time has expired. 6. The service requires a specific capability which the user does not have. 7. The function is called with username/password (no user token is sent) and none of the services has the function to allow the user. These settings can be found in Administration > Site administration > Plugins > Web services > External services and Manage tokens.'); } // we have all we need now $this->function = $function; }
php
protected function load_function_info() { global $DB, $USER, $CFG; if (empty($this->functionname)) { throw new invalid_parameter_exception('Missing function name'); } // function must exist $function = external_api::external_function_info($this->functionname); if ($this->restricted_serviceid) { $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid); $wscond1 = 'AND s.id = :sid1'; $wscond2 = 'AND s.id = :sid2'; } else { $params = array(); $wscond1 = ''; $wscond2 = ''; } // now let's verify access control // now make sure the function is listed in at least one service user is allowed to use // allow access only if: // 1/ entry in the external_services_users table if required // 2/ validuntil not reached // 3/ has capability if specified in service desc // 4/ iprestriction $sql = "SELECT s.*, NULL AS iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1) WHERE s.enabled = 1 $wscond1 UNION SELECT s.*, su.iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time())); $rs = $DB->get_recordset_sql($sql, $params); // now make sure user may access at least one service $remoteaddr = getremoteaddr(); $allowed = false; foreach ($rs as $service) { if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) { continue; // cap required, sorry } if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) { continue; // wrong request source ip, sorry } $allowed = true; break; // one service is enough, no need to continue } $rs->close(); if (!$allowed) { throw new webservice_access_exception( 'Access to the function '.$this->functionname.'() is not allowed. There could be multiple reasons for this: 1. The service linked to the user token does not contain the function. 2. The service is user-restricted and the user is not listed. 3. The service is IP-restricted and the user IP is not listed. 4. The service is time-restricted and the time has expired. 5. The token is time-restricted and the time has expired. 6. The service requires a specific capability which the user does not have. 7. The function is called with username/password (no user token is sent) and none of the services has the function to allow the user. These settings can be found in Administration > Site administration > Plugins > Web services > External services and Manage tokens.'); } // we have all we need now $this->function = $function; }
[ "protected", "function", "load_function_info", "(", ")", "{", "global", "$", "DB", ",", "$", "USER", ",", "$", "CFG", ";", "if", "(", "empty", "(", "$", "this", "->", "functionname", ")", ")", "{", "throw", "new", "invalid_parameter_exception", "(", "'Missing function name'", ")", ";", "}", "// function must exist", "$", "function", "=", "external_api", "::", "external_function_info", "(", "$", "this", "->", "functionname", ")", ";", "if", "(", "$", "this", "->", "restricted_serviceid", ")", "{", "$", "params", "=", "array", "(", "'sid1'", "=>", "$", "this", "->", "restricted_serviceid", ",", "'sid2'", "=>", "$", "this", "->", "restricted_serviceid", ")", ";", "$", "wscond1", "=", "'AND s.id = :sid1'", ";", "$", "wscond2", "=", "'AND s.id = :sid2'", ";", "}", "else", "{", "$", "params", "=", "array", "(", ")", ";", "$", "wscond1", "=", "''", ";", "$", "wscond2", "=", "''", ";", "}", "// now let's verify access control", "// now make sure the function is listed in at least one service user is allowed to use", "// allow access only if:", "// 1/ entry in the external_services_users table if required", "// 2/ validuntil not reached", "// 3/ has capability if specified in service desc", "// 4/ iprestriction", "$", "sql", "=", "\"SELECT s.*, NULL AS iprestriction\n FROM {external_services} s\n JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)\n WHERE s.enabled = 1 $wscond1\n\n UNION\n\n SELECT s.*, su.iprestriction\n FROM {external_services} s\n JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)\n JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2\"", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "array", "(", "'userid'", "=>", "$", "USER", "->", "id", ",", "'name1'", "=>", "$", "function", "->", "name", ",", "'name2'", "=>", "$", "function", "->", "name", ",", "'now'", "=>", "time", "(", ")", ")", ")", ";", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "// now make sure user may access at least one service", "$", "remoteaddr", "=", "getremoteaddr", "(", ")", ";", "$", "allowed", "=", "false", ";", "foreach", "(", "$", "rs", "as", "$", "service", ")", "{", "if", "(", "$", "service", "->", "requiredcapability", "and", "!", "has_capability", "(", "$", "service", "->", "requiredcapability", ",", "$", "this", "->", "restricted_context", ")", ")", "{", "continue", ";", "// cap required, sorry", "}", "if", "(", "$", "service", "->", "iprestriction", "and", "!", "address_in_subnet", "(", "$", "remoteaddr", ",", "$", "service", "->", "iprestriction", ")", ")", "{", "continue", ";", "// wrong request source ip, sorry", "}", "$", "allowed", "=", "true", ";", "break", ";", "// one service is enough, no need to continue", "}", "$", "rs", "->", "close", "(", ")", ";", "if", "(", "!", "$", "allowed", ")", "{", "throw", "new", "webservice_access_exception", "(", "'Access to the function '", ".", "$", "this", "->", "functionname", ".", "'() is not allowed.\n There could be multiple reasons for this:\n 1. The service linked to the user token does not contain the function.\n 2. The service is user-restricted and the user is not listed.\n 3. The service is IP-restricted and the user IP is not listed.\n 4. The service is time-restricted and the time has expired.\n 5. The token is time-restricted and the time has expired.\n 6. The service requires a specific capability which the user does not have.\n 7. The function is called with username/password (no user token is sent)\n and none of the services has the function to allow the user.\n These settings can be found in Administration > Site administration\n > Plugins > Web services > External services and Manage tokens.'", ")", ";", "}", "// we have all we need now", "$", "this", "->", "function", "=", "$", "function", ";", "}" ]
Fetches the function description from database, verifies user is allowed to use this function and loads all paremeters and return descriptions.
[ "Fetches", "the", "function", "description", "from", "database", "verifies", "user", "is", "allowed", "to", "use", "this", "function", "and", "loads", "all", "paremeters", "and", "return", "descriptions", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1340-L1416
216,027
moodle/moodle
webservice/lib.php
webservice_base_server.execute
protected function execute() { // validate params, this also sorts the params properly, we need the correct order in the next part $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters); $params = array_values($params); // Allow any Moodle plugin a chance to override this call. This is a convenient spot to // make arbitrary behaviour customisations, for example to affect the mobile app behaviour. // The overriding plugin could call the 'real' function first and then modify the results, // or it could do a completely separate thing. $callbacks = get_plugins_with_function('override_webservice_execution'); foreach ($callbacks as $plugintype => $plugins) { foreach ($plugins as $plugin => $callback) { $result = $callback($this->function, $params); if ($result !== false) { // If the callback returns anything other than false, we assume it replaces the // real function. $this->returns = $result; return; } } } // execute - yay! $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), $params); }
php
protected function execute() { // validate params, this also sorts the params properly, we need the correct order in the next part $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters); $params = array_values($params); // Allow any Moodle plugin a chance to override this call. This is a convenient spot to // make arbitrary behaviour customisations, for example to affect the mobile app behaviour. // The overriding plugin could call the 'real' function first and then modify the results, // or it could do a completely separate thing. $callbacks = get_plugins_with_function('override_webservice_execution'); foreach ($callbacks as $plugintype => $plugins) { foreach ($plugins as $plugin => $callback) { $result = $callback($this->function, $params); if ($result !== false) { // If the callback returns anything other than false, we assume it replaces the // real function. $this->returns = $result; return; } } } // execute - yay! $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), $params); }
[ "protected", "function", "execute", "(", ")", "{", "// validate params, this also sorts the params properly, we need the correct order in the next part", "$", "params", "=", "call_user_func", "(", "array", "(", "$", "this", "->", "function", "->", "classname", ",", "'validate_parameters'", ")", ",", "$", "this", "->", "function", "->", "parameters_desc", ",", "$", "this", "->", "parameters", ")", ";", "$", "params", "=", "array_values", "(", "$", "params", ")", ";", "// Allow any Moodle plugin a chance to override this call. This is a convenient spot to", "// make arbitrary behaviour customisations, for example to affect the mobile app behaviour.", "// The overriding plugin could call the 'real' function first and then modify the results,", "// or it could do a completely separate thing.", "$", "callbacks", "=", "get_plugins_with_function", "(", "'override_webservice_execution'", ")", ";", "foreach", "(", "$", "callbacks", "as", "$", "plugintype", "=>", "$", "plugins", ")", "{", "foreach", "(", "$", "plugins", "as", "$", "plugin", "=>", "$", "callback", ")", "{", "$", "result", "=", "$", "callback", "(", "$", "this", "->", "function", ",", "$", "params", ")", ";", "if", "(", "$", "result", "!==", "false", ")", "{", "// If the callback returns anything other than false, we assume it replaces the", "// real function.", "$", "this", "->", "returns", "=", "$", "result", ";", "return", ";", "}", "}", "}", "// execute - yay!", "$", "this", "->", "returns", "=", "call_user_func_array", "(", "array", "(", "$", "this", "->", "function", "->", "classname", ",", "$", "this", "->", "function", "->", "methodname", ")", ",", "$", "params", ")", ";", "}" ]
Execute previously loaded function using parameters parsed from the request data.
[ "Execute", "previously", "loaded", "function", "using", "parameters", "parsed", "from", "the", "request", "data", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1421-L1445
216,028
moodle/moodle
webservice/lib.php
webservice_base_server.init_service_class
protected function init_service_class() { global $USER, $DB; // Initialise service methods and struct classes. $this->servicemethods = array(); $this->servicestructs = array(); $params = array(); $wscond1 = ''; $wscond2 = ''; if ($this->restricted_serviceid) { $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid); $wscond1 = 'AND s.id = :sid1'; $wscond2 = 'AND s.id = :sid2'; } $sql = "SELECT s.*, NULL AS iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0) WHERE s.enabled = 1 $wscond1 UNION SELECT s.*, su.iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid' => $USER->id, 'now' => time())); $serviceids = array(); $remoteaddr = getremoteaddr(); // Query list of external services for the user. $rs = $DB->get_recordset_sql($sql, $params); // Check which service ID to include. foreach ($rs as $service) { if (isset($serviceids[$service->id])) { continue; // Service already added. } if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) { continue; // Cap required, sorry. } if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) { continue; // Wrong request source ip, sorry. } $serviceids[$service->id] = $service->id; } $rs->close(); // Generate the virtual class name. $classname = 'webservices_virtual_class_000000'; while (class_exists($classname)) { $classname++; } $this->serviceclass = $classname; // Get the list of all available external functions. $wsmanager = new webservice(); $functions = $wsmanager->get_external_functions($serviceids); // Generate code for the virtual methods for this web service. $methods = ''; foreach ($functions as $function) { $methods .= $this->get_virtual_method_code($function); } $code = <<<EOD /** * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}. */ class $classname { $methods } EOD; // Load the virtual class definition into memory. eval($code); }
php
protected function init_service_class() { global $USER, $DB; // Initialise service methods and struct classes. $this->servicemethods = array(); $this->servicestructs = array(); $params = array(); $wscond1 = ''; $wscond2 = ''; if ($this->restricted_serviceid) { $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid); $wscond1 = 'AND s.id = :sid1'; $wscond2 = 'AND s.id = :sid2'; } $sql = "SELECT s.*, NULL AS iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0) WHERE s.enabled = 1 $wscond1 UNION SELECT s.*, su.iprestriction FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid' => $USER->id, 'now' => time())); $serviceids = array(); $remoteaddr = getremoteaddr(); // Query list of external services for the user. $rs = $DB->get_recordset_sql($sql, $params); // Check which service ID to include. foreach ($rs as $service) { if (isset($serviceids[$service->id])) { continue; // Service already added. } if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) { continue; // Cap required, sorry. } if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) { continue; // Wrong request source ip, sorry. } $serviceids[$service->id] = $service->id; } $rs->close(); // Generate the virtual class name. $classname = 'webservices_virtual_class_000000'; while (class_exists($classname)) { $classname++; } $this->serviceclass = $classname; // Get the list of all available external functions. $wsmanager = new webservice(); $functions = $wsmanager->get_external_functions($serviceids); // Generate code for the virtual methods for this web service. $methods = ''; foreach ($functions as $function) { $methods .= $this->get_virtual_method_code($function); } $code = <<<EOD /** * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}. */ class $classname { $methods } EOD; // Load the virtual class definition into memory. eval($code); }
[ "protected", "function", "init_service_class", "(", ")", "{", "global", "$", "USER", ",", "$", "DB", ";", "// Initialise service methods and struct classes.", "$", "this", "->", "servicemethods", "=", "array", "(", ")", ";", "$", "this", "->", "servicestructs", "=", "array", "(", ")", ";", "$", "params", "=", "array", "(", ")", ";", "$", "wscond1", "=", "''", ";", "$", "wscond2", "=", "''", ";", "if", "(", "$", "this", "->", "restricted_serviceid", ")", "{", "$", "params", "=", "array", "(", "'sid1'", "=>", "$", "this", "->", "restricted_serviceid", ",", "'sid2'", "=>", "$", "this", "->", "restricted_serviceid", ")", ";", "$", "wscond1", "=", "'AND s.id = :sid1'", ";", "$", "wscond2", "=", "'AND s.id = :sid2'", ";", "}", "$", "sql", "=", "\"SELECT s.*, NULL AS iprestriction\n FROM {external_services} s\n JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)\n WHERE s.enabled = 1 $wscond1\n\n UNION\n\n SELECT s.*, su.iprestriction\n FROM {external_services} s\n JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)\n JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2\"", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "array", "(", "'userid'", "=>", "$", "USER", "->", "id", ",", "'now'", "=>", "time", "(", ")", ")", ")", ";", "$", "serviceids", "=", "array", "(", ")", ";", "$", "remoteaddr", "=", "getremoteaddr", "(", ")", ";", "// Query list of external services for the user.", "$", "rs", "=", "$", "DB", "->", "get_recordset_sql", "(", "$", "sql", ",", "$", "params", ")", ";", "// Check which service ID to include.", "foreach", "(", "$", "rs", "as", "$", "service", ")", "{", "if", "(", "isset", "(", "$", "serviceids", "[", "$", "service", "->", "id", "]", ")", ")", "{", "continue", ";", "// Service already added.", "}", "if", "(", "$", "service", "->", "requiredcapability", "and", "!", "has_capability", "(", "$", "service", "->", "requiredcapability", ",", "$", "this", "->", "restricted_context", ")", ")", "{", "continue", ";", "// Cap required, sorry.", "}", "if", "(", "$", "service", "->", "iprestriction", "and", "!", "address_in_subnet", "(", "$", "remoteaddr", ",", "$", "service", "->", "iprestriction", ")", ")", "{", "continue", ";", "// Wrong request source ip, sorry.", "}", "$", "serviceids", "[", "$", "service", "->", "id", "]", "=", "$", "service", "->", "id", ";", "}", "$", "rs", "->", "close", "(", ")", ";", "// Generate the virtual class name.", "$", "classname", "=", "'webservices_virtual_class_000000'", ";", "while", "(", "class_exists", "(", "$", "classname", ")", ")", "{", "$", "classname", "++", ";", "}", "$", "this", "->", "serviceclass", "=", "$", "classname", ";", "// Get the list of all available external functions.", "$", "wsmanager", "=", "new", "webservice", "(", ")", ";", "$", "functions", "=", "$", "wsmanager", "->", "get_external_functions", "(", "$", "serviceids", ")", ";", "// Generate code for the virtual methods for this web service.", "$", "methods", "=", "''", ";", "foreach", "(", "$", "functions", "as", "$", "function", ")", "{", "$", "methods", ".=", "$", "this", "->", "get_virtual_method_code", "(", "$", "function", ")", ";", "}", "$", "code", "=", " <<<EOD\n/**\n * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.\n */\nclass $classname {\n$methods\n}\nEOD", ";", "// Load the virtual class definition into memory.", "eval", "(", "$", "code", ")", ";", "}" ]
Load the virtual class needed for the web service. Initialises the virtual class that contains the web service functions that the user is allowed to use. The web service function will be available if the user: - is validly registered in the external_services_users table. - has the required capability. - meets the IP restriction requirement. This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
[ "Load", "the", "virtual", "class", "needed", "for", "the", "web", "service", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1457-L1535
216,029
moodle/moodle
webservice/lib.php
webservice_base_server.generate_simple_struct_class
protected function generate_simple_struct_class(external_single_structure $structdesc) { global $USER; $propeties = array(); $fields = array(); foreach ($structdesc->keys as $name => $fieldsdesc) { $type = $this->get_phpdoc_type($fieldsdesc); $propertytype = array('type' => $type); if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) { $propertytype['nillable'] = true; } $propeties[$name] = $propertytype; $fields[] = ' /** @var ' . $type . ' $' . $name . '*/'; $fields[] = ' public $' . $name .';'; } $fieldsstr = implode("\n", $fields); // We do this after the call to get_phpdoc_type() to avoid duplicate class creation. $classname = 'webservices_struct_class_000000'; while (class_exists($classname)) { $classname++; } $code = <<<EOD /** * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}. */ class $classname { $fieldsstr } EOD; // Load into memory. eval($code); // Prepare struct info. $structinfo = new stdClass(); $structinfo->classname = $classname; $structinfo->properties = $propeties; // Add the struct info the the list of service struct classes. $this->servicestructs[] = $structinfo; return $classname; }
php
protected function generate_simple_struct_class(external_single_structure $structdesc) { global $USER; $propeties = array(); $fields = array(); foreach ($structdesc->keys as $name => $fieldsdesc) { $type = $this->get_phpdoc_type($fieldsdesc); $propertytype = array('type' => $type); if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) { $propertytype['nillable'] = true; } $propeties[$name] = $propertytype; $fields[] = ' /** @var ' . $type . ' $' . $name . '*/'; $fields[] = ' public $' . $name .';'; } $fieldsstr = implode("\n", $fields); // We do this after the call to get_phpdoc_type() to avoid duplicate class creation. $classname = 'webservices_struct_class_000000'; while (class_exists($classname)) { $classname++; } $code = <<<EOD /** * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}. */ class $classname { $fieldsstr } EOD; // Load into memory. eval($code); // Prepare struct info. $structinfo = new stdClass(); $structinfo->classname = $classname; $structinfo->properties = $propeties; // Add the struct info the the list of service struct classes. $this->servicestructs[] = $structinfo; return $classname; }
[ "protected", "function", "generate_simple_struct_class", "(", "external_single_structure", "$", "structdesc", ")", "{", "global", "$", "USER", ";", "$", "propeties", "=", "array", "(", ")", ";", "$", "fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "structdesc", "->", "keys", "as", "$", "name", "=>", "$", "fieldsdesc", ")", "{", "$", "type", "=", "$", "this", "->", "get_phpdoc_type", "(", "$", "fieldsdesc", ")", ";", "$", "propertytype", "=", "array", "(", "'type'", "=>", "$", "type", ")", ";", "if", "(", "empty", "(", "$", "fieldsdesc", "->", "allownull", ")", "||", "$", "fieldsdesc", "->", "allownull", "==", "NULL_ALLOWED", ")", "{", "$", "propertytype", "[", "'nillable'", "]", "=", "true", ";", "}", "$", "propeties", "[", "$", "name", "]", "=", "$", "propertytype", ";", "$", "fields", "[", "]", "=", "' /** @var '", ".", "$", "type", ".", "' $'", ".", "$", "name", ".", "'*/'", ";", "$", "fields", "[", "]", "=", "' public $'", ".", "$", "name", ".", "';'", ";", "}", "$", "fieldsstr", "=", "implode", "(", "\"\\n\"", ",", "$", "fields", ")", ";", "// We do this after the call to get_phpdoc_type() to avoid duplicate class creation.", "$", "classname", "=", "'webservices_struct_class_000000'", ";", "while", "(", "class_exists", "(", "$", "classname", ")", ")", "{", "$", "classname", "++", ";", "}", "$", "code", "=", " <<<EOD\n/**\n * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.\n */\nclass $classname {\n$fieldsstr\n}\nEOD", ";", "// Load into memory.", "eval", "(", "$", "code", ")", ";", "// Prepare struct info.", "$", "structinfo", "=", "new", "stdClass", "(", ")", ";", "$", "structinfo", "->", "classname", "=", "$", "classname", ";", "$", "structinfo", "->", "properties", "=", "$", "propeties", ";", "// Add the struct info the the list of service struct classes.", "$", "this", "->", "servicestructs", "[", "]", "=", "$", "structinfo", ";", "return", "$", "classname", ";", "}" ]
Generates a struct class. @param external_single_structure $structdesc The basis of the struct class to be generated. @return string The class name of the generated struct class.
[ "Generates", "a", "struct", "class", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1543-L1584
216,030
moodle/moodle
webservice/lib.php
webservice_base_server.get_phpdoc_type
protected function get_phpdoc_type($keydesc) { $type = null; if ($keydesc instanceof external_value) { switch ($keydesc->type) { case PARAM_BOOL: // 0 or 1 only for now. case PARAM_INT: $type = 'int'; break; case PARAM_FLOAT; $type = 'double'; break; default: $type = 'string'; } } else if ($keydesc instanceof external_single_structure) { $type = $this->generate_simple_struct_class($keydesc); } else if ($keydesc instanceof external_multiple_structure) { $type = 'array'; } return $type; }
php
protected function get_phpdoc_type($keydesc) { $type = null; if ($keydesc instanceof external_value) { switch ($keydesc->type) { case PARAM_BOOL: // 0 or 1 only for now. case PARAM_INT: $type = 'int'; break; case PARAM_FLOAT; $type = 'double'; break; default: $type = 'string'; } } else if ($keydesc instanceof external_single_structure) { $type = $this->generate_simple_struct_class($keydesc); } else if ($keydesc instanceof external_multiple_structure) { $type = 'array'; } return $type; }
[ "protected", "function", "get_phpdoc_type", "(", "$", "keydesc", ")", "{", "$", "type", "=", "null", ";", "if", "(", "$", "keydesc", "instanceof", "external_value", ")", "{", "switch", "(", "$", "keydesc", "->", "type", ")", "{", "case", "PARAM_BOOL", ":", "// 0 or 1 only for now.", "case", "PARAM_INT", ":", "$", "type", "=", "'int'", ";", "break", ";", "case", "PARAM_FLOAT", ";", "$", "type", "=", "'double'", ";", "break", ";", "default", ":", "$", "type", "=", "'string'", ";", "}", "}", "else", "if", "(", "$", "keydesc", "instanceof", "external_single_structure", ")", "{", "$", "type", "=", "$", "this", "->", "generate_simple_struct_class", "(", "$", "keydesc", ")", ";", "}", "else", "if", "(", "$", "keydesc", "instanceof", "external_multiple_structure", ")", "{", "$", "type", "=", "'array'", ";", "}", "return", "$", "type", ";", "}" ]
Get the phpdoc type for an external_description object. external_value => int, double or string external_single_structure => object|struct, on-fly generated stdClass name. external_multiple_structure => array @param mixed $keydesc The type description. @return string The PHP doc type of the external_description object.
[ "Get", "the", "phpdoc", "type", "for", "an", "external_description", "object", ".", "external_value", "=", ">", "int", "double", "or", "string", "external_single_structure", "=", ">", "object|struct", "on", "-", "fly", "generated", "stdClass", "name", ".", "external_multiple_structure", "=", ">", "array" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1699-L1720
216,031
moodle/moodle
webservice/lib.php
webservice_base_server.service_class_method_body
protected function service_class_method_body($function, $params) { // Cast the param from object to array (validate_parameters except array only). $castingcode = ''; $paramsstr = ''; if (!empty($params)) { foreach ($params as $paramtocast) { // Clean the parameter from any white space. $paramtocast = trim($paramtocast); $castingcode .= " $paramtocast = json_decode(json_encode($paramtocast), true);\n"; } $paramsstr = implode(', ', $params); } $descriptionmethod = $function->methodname . '_returns()'; $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod; $methodbody = <<<EOD $castingcode if ($callforreturnvaluedesc == null) { $function->classname::$function->methodname($paramsstr); return null; } return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr)); EOD; return $methodbody; }
php
protected function service_class_method_body($function, $params) { // Cast the param from object to array (validate_parameters except array only). $castingcode = ''; $paramsstr = ''; if (!empty($params)) { foreach ($params as $paramtocast) { // Clean the parameter from any white space. $paramtocast = trim($paramtocast); $castingcode .= " $paramtocast = json_decode(json_encode($paramtocast), true);\n"; } $paramsstr = implode(', ', $params); } $descriptionmethod = $function->methodname . '_returns()'; $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod; $methodbody = <<<EOD $castingcode if ($callforreturnvaluedesc == null) { $function->classname::$function->methodname($paramsstr); return null; } return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr)); EOD; return $methodbody; }
[ "protected", "function", "service_class_method_body", "(", "$", "function", ",", "$", "params", ")", "{", "// Cast the param from object to array (validate_parameters except array only).", "$", "castingcode", "=", "''", ";", "$", "paramsstr", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "params", ")", ")", "{", "foreach", "(", "$", "params", "as", "$", "paramtocast", ")", "{", "// Clean the parameter from any white space.", "$", "paramtocast", "=", "trim", "(", "$", "paramtocast", ")", ";", "$", "castingcode", ".=", "\" $paramtocast = json_decode(json_encode($paramtocast), true);\\n\"", ";", "}", "$", "paramsstr", "=", "implode", "(", "', '", ",", "$", "params", ")", ";", "}", "$", "descriptionmethod", "=", "$", "function", "->", "methodname", ".", "'_returns()'", ";", "$", "callforreturnvaluedesc", "=", "$", "function", "->", "classname", ".", "'::'", ".", "$", "descriptionmethod", ";", "$", "methodbody", "=", " <<<EOD\n$castingcode\n if ($callforreturnvaluedesc == null) {\n $function->classname::$function->methodname($paramsstr);\n return null;\n }\n return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));\nEOD", ";", "return", "$", "methodbody", ";", "}" ]
Generates the method body of the virtual external function. @param stdClass $function a record from external_function. @param array $params web service function parameters. @return string body of the method for $function ie. everything within the {} of the method declaration.
[ "Generates", "the", "method", "body", "of", "the", "virtual", "external", "function", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/lib.php#L1729-L1754
216,032
moodle/moodle
question/engine/renderer.php
core_question_renderer.question_preview_link
public function question_preview_link($questionid, context $context, $showlabel) { if ($showlabel) { $alt = ''; $label = get_string('preview'); $attributes = array(); } else { $alt = get_string('preview'); $label = ''; $attributes = array('title' => $alt); } $image = $this->pix_icon('t/preview', $alt, '', array('class' => 'iconsmall')); $link = question_preview_url($questionid, null, null, null, null, $context); $action = new popup_action('click', $link, 'questionpreview', question_preview_popup_params()); return $this->action_link($link, $image . $label, $action, $attributes); }
php
public function question_preview_link($questionid, context $context, $showlabel) { if ($showlabel) { $alt = ''; $label = get_string('preview'); $attributes = array(); } else { $alt = get_string('preview'); $label = ''; $attributes = array('title' => $alt); } $image = $this->pix_icon('t/preview', $alt, '', array('class' => 'iconsmall')); $link = question_preview_url($questionid, null, null, null, null, $context); $action = new popup_action('click', $link, 'questionpreview', question_preview_popup_params()); return $this->action_link($link, $image . $label, $action, $attributes); }
[ "public", "function", "question_preview_link", "(", "$", "questionid", ",", "context", "$", "context", ",", "$", "showlabel", ")", "{", "if", "(", "$", "showlabel", ")", "{", "$", "alt", "=", "''", ";", "$", "label", "=", "get_string", "(", "'preview'", ")", ";", "$", "attributes", "=", "array", "(", ")", ";", "}", "else", "{", "$", "alt", "=", "get_string", "(", "'preview'", ")", ";", "$", "label", "=", "''", ";", "$", "attributes", "=", "array", "(", "'title'", "=>", "$", "alt", ")", ";", "}", "$", "image", "=", "$", "this", "->", "pix_icon", "(", "'t/preview'", ",", "$", "alt", ",", "''", ",", "array", "(", "'class'", "=>", "'iconsmall'", ")", ")", ";", "$", "link", "=", "question_preview_url", "(", "$", "questionid", ",", "null", ",", "null", ",", "null", ",", "null", ",", "$", "context", ")", ";", "$", "action", "=", "new", "popup_action", "(", "'click'", ",", "$", "link", ",", "'questionpreview'", ",", "question_preview_popup_params", "(", ")", ")", ";", "return", "$", "this", "->", "action_link", "(", "$", "link", ",", "$", "image", ".", "$", "label", ",", "$", "action", ",", "$", "attributes", ")", ";", "}" ]
Render an icon, optionally with the word 'Preview' beside it, to preview a given question. @param int $questionid the id of the question to be previewed. @param context $context the context in which the preview is happening. Must be a course or category context. @param bool $showlabel if true, show the word 'Preview' after the icon. If false, just show the icon.
[ "Render", "an", "icon", "optionally", "with", "the", "word", "Preview", "beside", "it", "to", "preview", "a", "given", "question", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L52-L69
216,033
moodle/moodle
question/engine/renderer.php
core_question_renderer.info
protected function info(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options, $number) { $output = ''; $output .= $this->number($number); $output .= $this->status($qa, $behaviouroutput, $options); $output .= $this->mark_summary($qa, $behaviouroutput, $options); $output .= $this->question_flag($qa, $options->flags); $output .= $this->edit_question_link($qa, $options); return $output; }
php
protected function info(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options, $number) { $output = ''; $output .= $this->number($number); $output .= $this->status($qa, $behaviouroutput, $options); $output .= $this->mark_summary($qa, $behaviouroutput, $options); $output .= $this->question_flag($qa, $options->flags); $output .= $this->edit_question_link($qa, $options); return $output; }
[ "protected", "function", "info", "(", "question_attempt", "$", "qa", ",", "qbehaviour_renderer", "$", "behaviouroutput", ",", "qtype_renderer", "$", "qtoutput", ",", "question_display_options", "$", "options", ",", "$", "number", ")", "{", "$", "output", "=", "''", ";", "$", "output", ".=", "$", "this", "->", "number", "(", "$", "number", ")", ";", "$", "output", ".=", "$", "this", "->", "status", "(", "$", "qa", ",", "$", "behaviouroutput", ",", "$", "options", ")", ";", "$", "output", ".=", "$", "this", "->", "mark_summary", "(", "$", "qa", ",", "$", "behaviouroutput", ",", "$", "options", ")", ";", "$", "output", ".=", "$", "this", "->", "question_flag", "(", "$", "qa", ",", "$", "options", "->", "flags", ")", ";", "$", "output", ".=", "$", "this", "->", "edit_question_link", "(", "$", "qa", ",", "$", "options", ")", ";", "return", "$", "output", ";", "}" ]
Generate the information bit of the question display that contains the metadata like the question number, current state, and mark. @param question_attempt $qa the question attempt to display. @param qbehaviour_renderer $behaviouroutput the renderer to output the behaviour specific parts. @param qtype_renderer $qtoutput the renderer to output the question type specific parts. @param question_display_options $options controls what should and should not be displayed. @param string|null $number The question number to display. 'i' is a special value that gets displayed as Information. Null means no number is displayed. @return HTML fragment.
[ "Generate", "the", "information", "bit", "of", "the", "question", "display", "that", "contains", "the", "metadata", "like", "the", "question", "number", "current", "state", "and", "mark", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L141-L150
216,034
moodle/moodle
question/engine/renderer.php
core_question_renderer.number
protected function number($number) { if (trim($number) === '') { return ''; } $numbertext = ''; if (trim($number) === 'i') { $numbertext = get_string('information', 'question'); } else { $numbertext = get_string('questionx', 'question', html_writer::tag('span', $number, array('class' => 'qno'))); } return html_writer::tag('h3', $numbertext, array('class' => 'no')); }
php
protected function number($number) { if (trim($number) === '') { return ''; } $numbertext = ''; if (trim($number) === 'i') { $numbertext = get_string('information', 'question'); } else { $numbertext = get_string('questionx', 'question', html_writer::tag('span', $number, array('class' => 'qno'))); } return html_writer::tag('h3', $numbertext, array('class' => 'no')); }
[ "protected", "function", "number", "(", "$", "number", ")", "{", "if", "(", "trim", "(", "$", "number", ")", "===", "''", ")", "{", "return", "''", ";", "}", "$", "numbertext", "=", "''", ";", "if", "(", "trim", "(", "$", "number", ")", "===", "'i'", ")", "{", "$", "numbertext", "=", "get_string", "(", "'information'", ",", "'question'", ")", ";", "}", "else", "{", "$", "numbertext", "=", "get_string", "(", "'questionx'", ",", "'question'", ",", "html_writer", "::", "tag", "(", "'span'", ",", "$", "number", ",", "array", "(", "'class'", "=>", "'qno'", ")", ")", ")", ";", "}", "return", "html_writer", "::", "tag", "(", "'h3'", ",", "$", "numbertext", ",", "array", "(", "'class'", "=>", "'no'", ")", ")", ";", "}" ]
Generate the display of the question number. @param string|null $number The question number to display. 'i' is a special value that gets displayed as Information. Null means no number is displayed. @return HTML fragment.
[ "Generate", "the", "display", "of", "the", "question", "number", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L158-L170
216,035
moodle/moodle
question/engine/renderer.php
core_question_renderer.add_part_heading
protected function add_part_heading($heading, $content) { if ($content) { $content = html_writer::tag('h4', $heading, array('class' => 'accesshide')) . $content; } return $content; }
php
protected function add_part_heading($heading, $content) { if ($content) { $content = html_writer::tag('h4', $heading, array('class' => 'accesshide')) . $content; } return $content; }
[ "protected", "function", "add_part_heading", "(", "$", "heading", ",", "$", "content", ")", "{", "if", "(", "$", "content", ")", "{", "$", "content", "=", "html_writer", "::", "tag", "(", "'h4'", ",", "$", "heading", ",", "array", "(", "'class'", "=>", "'accesshide'", ")", ")", ".", "$", "content", ";", "}", "return", "$", "content", ";", "}" ]
Add an invisible heading like 'question text', 'feebdack' at the top of a section's contents, but only if the section has some content. @param string $heading the heading to add. @param string $content the content of the section. @return string HTML fragment with the heading added.
[ "Add", "an", "invisible", "heading", "like", "question", "text", "feebdack", "at", "the", "top", "of", "a", "section", "s", "contents", "but", "only", "if", "the", "section", "has", "some", "content", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L179-L184
216,036
moodle/moodle
question/engine/renderer.php
core_question_renderer.status
protected function status(question_attempt $qa, qbehaviour_renderer $behaviouroutput, question_display_options $options) { return html_writer::tag('div', $qa->get_state_string($options->correctness), array('class' => 'state')); }
php
protected function status(question_attempt $qa, qbehaviour_renderer $behaviouroutput, question_display_options $options) { return html_writer::tag('div', $qa->get_state_string($options->correctness), array('class' => 'state')); }
[ "protected", "function", "status", "(", "question_attempt", "$", "qa", ",", "qbehaviour_renderer", "$", "behaviouroutput", ",", "question_display_options", "$", "options", ")", "{", "return", "html_writer", "::", "tag", "(", "'div'", ",", "$", "qa", "->", "get_state_string", "(", "$", "options", "->", "correctness", ")", ",", "array", "(", "'class'", "=>", "'state'", ")", ")", ";", "}" ]
Generate the display of the status line that gives the current state of the question. @param question_attempt $qa the question attempt to display. @param qbehaviour_renderer $behaviouroutput the renderer to output the behaviour specific parts. @param question_display_options $options controls what should and should not be displayed. @return HTML fragment.
[ "Generate", "the", "display", "of", "the", "status", "line", "that", "gives", "the", "current", "state", "of", "the", "question", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L195-L199
216,037
moodle/moodle
question/engine/renderer.php
core_question_renderer.get_flag_html
protected function get_flag_html($flagged, $id = '') { if ($flagged) { $icon = 'i/flagged'; $alt = get_string('flagged', 'question'); } else { $icon = 'i/unflagged'; $alt = get_string('notflagged', 'question'); } $attributes = array( 'src' => $this->image_url($icon), 'alt' => $alt, ); if ($id) { $attributes['id'] = $id; } $img = html_writer::empty_tag('img', $attributes); if ($flagged) { $img .= ' ' . get_string('flagged', 'question'); } return $img; }
php
protected function get_flag_html($flagged, $id = '') { if ($flagged) { $icon = 'i/flagged'; $alt = get_string('flagged', 'question'); } else { $icon = 'i/unflagged'; $alt = get_string('notflagged', 'question'); } $attributes = array( 'src' => $this->image_url($icon), 'alt' => $alt, ); if ($id) { $attributes['id'] = $id; } $img = html_writer::empty_tag('img', $attributes); if ($flagged) { $img .= ' ' . get_string('flagged', 'question'); } return $img; }
[ "protected", "function", "get_flag_html", "(", "$", "flagged", ",", "$", "id", "=", "''", ")", "{", "if", "(", "$", "flagged", ")", "{", "$", "icon", "=", "'i/flagged'", ";", "$", "alt", "=", "get_string", "(", "'flagged'", ",", "'question'", ")", ";", "}", "else", "{", "$", "icon", "=", "'i/unflagged'", ";", "$", "alt", "=", "get_string", "(", "'notflagged'", ",", "'question'", ")", ";", "}", "$", "attributes", "=", "array", "(", "'src'", "=>", "$", "this", "->", "image_url", "(", "$", "icon", ")", ",", "'alt'", "=>", "$", "alt", ",", ")", ";", "if", "(", "$", "id", ")", "{", "$", "attributes", "[", "'id'", "]", "=", "$", "id", ";", "}", "$", "img", "=", "html_writer", "::", "empty_tag", "(", "'img'", ",", "$", "attributes", ")", ";", "if", "(", "$", "flagged", ")", "{", "$", "img", ".=", "' '", ".", "get_string", "(", "'flagged'", ",", "'question'", ")", ";", "}", "return", "$", "img", ";", "}" ]
Work out the actual img tag needed for the flag @param bool $flagged whether the question is currently flagged. @param string $id an id to be added as an attribute to the img (optional). @return string the img tag.
[ "Work", "out", "the", "actual", "img", "tag", "needed", "for", "the", "flag" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L322-L342
216,038
moodle/moodle
question/engine/renderer.php
core_question_renderer.formulation
protected function formulation(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { $output = ''; $output .= html_writer::empty_tag('input', array( 'type' => 'hidden', 'name' => $qa->get_control_field_name('sequencecheck'), 'value' => $qa->get_sequence_check_count())); $output .= $qtoutput->formulation_and_controls($qa, $options); if ($options->clearwrong) { $output .= $qtoutput->clear_wrong($qa); } $output .= html_writer::nonempty_tag('div', $behaviouroutput->controls($qa, $options), array('class' => 'im-controls')); return $output; }
php
protected function formulation(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { $output = ''; $output .= html_writer::empty_tag('input', array( 'type' => 'hidden', 'name' => $qa->get_control_field_name('sequencecheck'), 'value' => $qa->get_sequence_check_count())); $output .= $qtoutput->formulation_and_controls($qa, $options); if ($options->clearwrong) { $output .= $qtoutput->clear_wrong($qa); } $output .= html_writer::nonempty_tag('div', $behaviouroutput->controls($qa, $options), array('class' => 'im-controls')); return $output; }
[ "protected", "function", "formulation", "(", "question_attempt", "$", "qa", ",", "qbehaviour_renderer", "$", "behaviouroutput", ",", "qtype_renderer", "$", "qtoutput", ",", "question_display_options", "$", "options", ")", "{", "$", "output", "=", "''", ";", "$", "output", ".=", "html_writer", "::", "empty_tag", "(", "'input'", ",", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "$", "qa", "->", "get_control_field_name", "(", "'sequencecheck'", ")", ",", "'value'", "=>", "$", "qa", "->", "get_sequence_check_count", "(", ")", ")", ")", ";", "$", "output", ".=", "$", "qtoutput", "->", "formulation_and_controls", "(", "$", "qa", ",", "$", "options", ")", ";", "if", "(", "$", "options", "->", "clearwrong", ")", "{", "$", "output", ".=", "$", "qtoutput", "->", "clear_wrong", "(", "$", "qa", ")", ";", "}", "$", "output", ".=", "html_writer", "::", "nonempty_tag", "(", "'div'", ",", "$", "behaviouroutput", "->", "controls", "(", "$", "qa", ",", "$", "options", ")", ",", "array", "(", "'class'", "=>", "'im-controls'", ")", ")", ";", "return", "$", "output", ";", "}" ]
Generate the display of the formulation part of the question. This is the area that contains the quetsion text, and the controls for students to input their answers. Some question types also embed feedback, for example ticks and crosses, in this area. @param question_attempt $qa the question attempt to display. @param qbehaviour_renderer $behaviouroutput the renderer to output the behaviour specific parts. @param qtype_renderer $qtoutput the renderer to output the question type specific parts. @param question_display_options $options controls what should and should not be displayed. @return HTML fragment.
[ "Generate", "the", "display", "of", "the", "formulation", "part", "of", "the", "question", ".", "This", "is", "the", "area", "that", "contains", "the", "quetsion", "text", "and", "the", "controls", "for", "students", "to", "input", "their", "answers", ".", "Some", "question", "types", "also", "embed", "feedback", "for", "example", "ticks", "and", "crosses", "in", "this", "area", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L379-L393
216,039
moodle/moodle
question/engine/renderer.php
core_question_renderer.outcome
protected function outcome(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { $output = ''; $output .= html_writer::nonempty_tag('div', $qtoutput->feedback($qa, $options), array('class' => 'feedback')); $output .= html_writer::nonempty_tag('div', $behaviouroutput->feedback($qa, $options), array('class' => 'im-feedback')); $output .= html_writer::nonempty_tag('div', $options->extrainfocontent, array('class' => 'extra-feedback')); return $output; }
php
protected function outcome(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { $output = ''; $output .= html_writer::nonempty_tag('div', $qtoutput->feedback($qa, $options), array('class' => 'feedback')); $output .= html_writer::nonempty_tag('div', $behaviouroutput->feedback($qa, $options), array('class' => 'im-feedback')); $output .= html_writer::nonempty_tag('div', $options->extrainfocontent, array('class' => 'extra-feedback')); return $output; }
[ "protected", "function", "outcome", "(", "question_attempt", "$", "qa", ",", "qbehaviour_renderer", "$", "behaviouroutput", ",", "qtype_renderer", "$", "qtoutput", ",", "question_display_options", "$", "options", ")", "{", "$", "output", "=", "''", ";", "$", "output", ".=", "html_writer", "::", "nonempty_tag", "(", "'div'", ",", "$", "qtoutput", "->", "feedback", "(", "$", "qa", ",", "$", "options", ")", ",", "array", "(", "'class'", "=>", "'feedback'", ")", ")", ";", "$", "output", ".=", "html_writer", "::", "nonempty_tag", "(", "'div'", ",", "$", "behaviouroutput", "->", "feedback", "(", "$", "qa", ",", "$", "options", ")", ",", "array", "(", "'class'", "=>", "'im-feedback'", ")", ")", ";", "$", "output", ".=", "html_writer", "::", "nonempty_tag", "(", "'div'", ",", "$", "options", "->", "extrainfocontent", ",", "array", "(", "'class'", "=>", "'extra-feedback'", ")", ")", ";", "return", "$", "output", ";", "}" ]
Generate the display of the outcome part of the question. This is the area that contains the various forms of feedback. @param question_attempt $qa the question attempt to display. @param qbehaviour_renderer $behaviouroutput the renderer to output the behaviour specific parts. @param qtype_renderer $qtoutput the renderer to output the question type specific parts. @param question_display_options $options controls what should and should not be displayed. @return HTML fragment.
[ "Generate", "the", "display", "of", "the", "outcome", "part", "of", "the", "question", ".", "This", "is", "the", "area", "that", "contains", "the", "various", "forms", "of", "feedback", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L407-L417
216,040
moodle/moodle
question/engine/renderer.php
core_question_renderer.response_history
protected function response_history(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { if (!$options->history) { return ''; } $table = new html_table(); $table->head = array ( get_string('step', 'question'), get_string('time'), get_string('action', 'question'), get_string('state', 'question'), ); if ($options->marks >= question_display_options::MARK_AND_MAX) { $table->head[] = get_string('marks', 'question'); } foreach ($qa->get_full_step_iterator() as $i => $step) { $stepno = $i + 1; $rowclass = ''; if ($stepno == $qa->get_num_steps()) { $rowclass = 'current'; } else if (!empty($options->questionreviewlink)) { $url = new moodle_url($options->questionreviewlink, array('slot' => $qa->get_slot(), 'step' => $i)); $stepno = $this->output->action_link($url, $stepno, new popup_action('click', $url, 'reviewquestion', array('width' => 450, 'height' => 650)), array('title' => get_string('reviewresponse', 'question'))); } $restrictedqa = new question_attempt_with_restricted_history($qa, $i, null); $user = new stdClass(); $user->id = $step->get_user_id(); $row = array( $stepno, userdate($step->get_timecreated(), get_string('strftimedatetimeshort')), s($qa->summarise_action($step)), $restrictedqa->get_state_string($options->correctness), ); if ($options->marks >= question_display_options::MARK_AND_MAX) { $row[] = $qa->format_fraction_as_mark($step->get_fraction(), $options->markdp); } $table->rowclasses[] = $rowclass; $table->data[] = $row; } return html_writer::tag('h4', get_string('responsehistory', 'question'), array('class' => 'responsehistoryheader')) . $options->extrahistorycontent . html_writer::tag('div', html_writer::table($table, true), array('class' => 'responsehistoryheader')); }
php
protected function response_history(question_attempt $qa, qbehaviour_renderer $behaviouroutput, qtype_renderer $qtoutput, question_display_options $options) { if (!$options->history) { return ''; } $table = new html_table(); $table->head = array ( get_string('step', 'question'), get_string('time'), get_string('action', 'question'), get_string('state', 'question'), ); if ($options->marks >= question_display_options::MARK_AND_MAX) { $table->head[] = get_string('marks', 'question'); } foreach ($qa->get_full_step_iterator() as $i => $step) { $stepno = $i + 1; $rowclass = ''; if ($stepno == $qa->get_num_steps()) { $rowclass = 'current'; } else if (!empty($options->questionreviewlink)) { $url = new moodle_url($options->questionreviewlink, array('slot' => $qa->get_slot(), 'step' => $i)); $stepno = $this->output->action_link($url, $stepno, new popup_action('click', $url, 'reviewquestion', array('width' => 450, 'height' => 650)), array('title' => get_string('reviewresponse', 'question'))); } $restrictedqa = new question_attempt_with_restricted_history($qa, $i, null); $user = new stdClass(); $user->id = $step->get_user_id(); $row = array( $stepno, userdate($step->get_timecreated(), get_string('strftimedatetimeshort')), s($qa->summarise_action($step)), $restrictedqa->get_state_string($options->correctness), ); if ($options->marks >= question_display_options::MARK_AND_MAX) { $row[] = $qa->format_fraction_as_mark($step->get_fraction(), $options->markdp); } $table->rowclasses[] = $rowclass; $table->data[] = $row; } return html_writer::tag('h4', get_string('responsehistory', 'question'), array('class' => 'responsehistoryheader')) . $options->extrahistorycontent . html_writer::tag('div', html_writer::table($table, true), array('class' => 'responsehistoryheader')); }
[ "protected", "function", "response_history", "(", "question_attempt", "$", "qa", ",", "qbehaviour_renderer", "$", "behaviouroutput", ",", "qtype_renderer", "$", "qtoutput", ",", "question_display_options", "$", "options", ")", "{", "if", "(", "!", "$", "options", "->", "history", ")", "{", "return", "''", ";", "}", "$", "table", "=", "new", "html_table", "(", ")", ";", "$", "table", "->", "head", "=", "array", "(", "get_string", "(", "'step'", ",", "'question'", ")", ",", "get_string", "(", "'time'", ")", ",", "get_string", "(", "'action'", ",", "'question'", ")", ",", "get_string", "(", "'state'", ",", "'question'", ")", ",", ")", ";", "if", "(", "$", "options", "->", "marks", ">=", "question_display_options", "::", "MARK_AND_MAX", ")", "{", "$", "table", "->", "head", "[", "]", "=", "get_string", "(", "'marks'", ",", "'question'", ")", ";", "}", "foreach", "(", "$", "qa", "->", "get_full_step_iterator", "(", ")", "as", "$", "i", "=>", "$", "step", ")", "{", "$", "stepno", "=", "$", "i", "+", "1", ";", "$", "rowclass", "=", "''", ";", "if", "(", "$", "stepno", "==", "$", "qa", "->", "get_num_steps", "(", ")", ")", "{", "$", "rowclass", "=", "'current'", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "options", "->", "questionreviewlink", ")", ")", "{", "$", "url", "=", "new", "moodle_url", "(", "$", "options", "->", "questionreviewlink", ",", "array", "(", "'slot'", "=>", "$", "qa", "->", "get_slot", "(", ")", ",", "'step'", "=>", "$", "i", ")", ")", ";", "$", "stepno", "=", "$", "this", "->", "output", "->", "action_link", "(", "$", "url", ",", "$", "stepno", ",", "new", "popup_action", "(", "'click'", ",", "$", "url", ",", "'reviewquestion'", ",", "array", "(", "'width'", "=>", "450", ",", "'height'", "=>", "650", ")", ")", ",", "array", "(", "'title'", "=>", "get_string", "(", "'reviewresponse'", ",", "'question'", ")", ")", ")", ";", "}", "$", "restrictedqa", "=", "new", "question_attempt_with_restricted_history", "(", "$", "qa", ",", "$", "i", ",", "null", ")", ";", "$", "user", "=", "new", "stdClass", "(", ")", ";", "$", "user", "->", "id", "=", "$", "step", "->", "get_user_id", "(", ")", ";", "$", "row", "=", "array", "(", "$", "stepno", ",", "userdate", "(", "$", "step", "->", "get_timecreated", "(", ")", ",", "get_string", "(", "'strftimedatetimeshort'", ")", ")", ",", "s", "(", "$", "qa", "->", "summarise_action", "(", "$", "step", ")", ")", ",", "$", "restrictedqa", "->", "get_state_string", "(", "$", "options", "->", "correctness", ")", ",", ")", ";", "if", "(", "$", "options", "->", "marks", ">=", "question_display_options", "::", "MARK_AND_MAX", ")", "{", "$", "row", "[", "]", "=", "$", "qa", "->", "format_fraction_as_mark", "(", "$", "step", "->", "get_fraction", "(", ")", ",", "$", "options", "->", "markdp", ")", ";", "}", "$", "table", "->", "rowclasses", "[", "]", "=", "$", "rowclass", ";", "$", "table", "->", "data", "[", "]", "=", "$", "row", ";", "}", "return", "html_writer", "::", "tag", "(", "'h4'", ",", "get_string", "(", "'responsehistory'", ",", "'question'", ")", ",", "array", "(", "'class'", "=>", "'responsehistoryheader'", ")", ")", ".", "$", "options", "->", "extrahistorycontent", ".", "html_writer", "::", "tag", "(", "'div'", ",", "html_writer", "::", "table", "(", "$", "table", ",", "true", ")", ",", "array", "(", "'class'", "=>", "'responsehistoryheader'", ")", ")", ";", "}" ]
Generate the display of the response history part of the question. This is the table showing all the steps the question has been through. @param question_attempt $qa the question attempt to display. @param qbehaviour_renderer $behaviouroutput the renderer to output the behaviour specific parts. @param qtype_renderer $qtoutput the renderer to output the question type specific parts. @param question_display_options $options controls what should and should not be displayed. @return HTML fragment.
[ "Generate", "the", "display", "of", "the", "response", "history", "part", "of", "the", "question", ".", "This", "is", "the", "table", "showing", "all", "the", "steps", "the", "question", "has", "been", "through", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/engine/renderer.php#L437-L494
216,041
moodle/moodle
webservice/soap/classes/wsdl.php
wsdl.add_complex_type
public function add_complex_type($classname, $properties) { $typeschema = $this->nodetypes->children(); // Append the complex type. $complextype = $typeschema->addChild('x:xsd:complexType'); $complextype->addAttribute('name', $classname); $child = $complextype->addChild('x:xsd:all'); foreach ($properties as $name => $options) { $param = $child->addChild('x:xsd:element'); $param->addAttribute('name', $name); $param->addAttribute('type', $this->get_soap_type($options['type'])); if (!empty($options['nillable'])) { $param->addAttribute('nillable', 'true'); } } }
php
public function add_complex_type($classname, $properties) { $typeschema = $this->nodetypes->children(); // Append the complex type. $complextype = $typeschema->addChild('x:xsd:complexType'); $complextype->addAttribute('name', $classname); $child = $complextype->addChild('x:xsd:all'); foreach ($properties as $name => $options) { $param = $child->addChild('x:xsd:element'); $param->addAttribute('name', $name); $param->addAttribute('type', $this->get_soap_type($options['type'])); if (!empty($options['nillable'])) { $param->addAttribute('nillable', 'true'); } } }
[ "public", "function", "add_complex_type", "(", "$", "classname", ",", "$", "properties", ")", "{", "$", "typeschema", "=", "$", "this", "->", "nodetypes", "->", "children", "(", ")", ";", "// Append the complex type.", "$", "complextype", "=", "$", "typeschema", "->", "addChild", "(", "'x:xsd:complexType'", ")", ";", "$", "complextype", "->", "addAttribute", "(", "'name'", ",", "$", "classname", ")", ";", "$", "child", "=", "$", "complextype", "->", "addChild", "(", "'x:xsd:all'", ")", ";", "foreach", "(", "$", "properties", "as", "$", "name", "=>", "$", "options", ")", "{", "$", "param", "=", "$", "child", "->", "addChild", "(", "'x:xsd:element'", ")", ";", "$", "param", "->", "addAttribute", "(", "'name'", ",", "$", "name", ")", ";", "$", "param", "->", "addAttribute", "(", "'type'", ",", "$", "this", "->", "get_soap_type", "(", "$", "options", "[", "'type'", "]", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "options", "[", "'nillable'", "]", ")", ")", "{", "$", "param", "->", "addAttribute", "(", "'nillable'", ",", "'true'", ")", ";", "}", "}", "}" ]
Adds a complex type to the WSDL. @param string $classname The complex type's class name. @param array $properties An associative array containing the properties of the complex type class.
[ "Adds", "a", "complex", "type", "to", "the", "WSDL", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/soap/classes/wsdl.php#L145-L159
216,042
moodle/moodle
webservice/soap/classes/wsdl.php
wsdl.register
public function register($functionname, $inputparams = array(), $outputparams = array(), $documentation = '') { // Process portType operation nodes. $porttypeoperation = $this->nodeporttype->addChild('operation'); $porttypeoperation->addAttribute('name', $functionname); // Documentation node. $porttypeoperation->addChild('documentation', $documentation); // Process binding operation nodes. $bindingoperation = $this->nodebinding->addChild('operation'); $bindingoperation->addAttribute('name', $functionname); $soapoperation = $bindingoperation->addChild('x:soap:operation'); $soapoperation->addAttribute('soapAction', $this->namespace . '#' . $functionname); // Input nodes. $this->process_params($functionname, $porttypeoperation, $bindingoperation, $inputparams); // Output nodes. $this->process_params($functionname, $porttypeoperation, $bindingoperation, $outputparams, true); }
php
public function register($functionname, $inputparams = array(), $outputparams = array(), $documentation = '') { // Process portType operation nodes. $porttypeoperation = $this->nodeporttype->addChild('operation'); $porttypeoperation->addAttribute('name', $functionname); // Documentation node. $porttypeoperation->addChild('documentation', $documentation); // Process binding operation nodes. $bindingoperation = $this->nodebinding->addChild('operation'); $bindingoperation->addAttribute('name', $functionname); $soapoperation = $bindingoperation->addChild('x:soap:operation'); $soapoperation->addAttribute('soapAction', $this->namespace . '#' . $functionname); // Input nodes. $this->process_params($functionname, $porttypeoperation, $bindingoperation, $inputparams); // Output nodes. $this->process_params($functionname, $porttypeoperation, $bindingoperation, $outputparams, true); }
[ "public", "function", "register", "(", "$", "functionname", ",", "$", "inputparams", "=", "array", "(", ")", ",", "$", "outputparams", "=", "array", "(", ")", ",", "$", "documentation", "=", "''", ")", "{", "// Process portType operation nodes.", "$", "porttypeoperation", "=", "$", "this", "->", "nodeporttype", "->", "addChild", "(", "'operation'", ")", ";", "$", "porttypeoperation", "->", "addAttribute", "(", "'name'", ",", "$", "functionname", ")", ";", "// Documentation node.", "$", "porttypeoperation", "->", "addChild", "(", "'documentation'", ",", "$", "documentation", ")", ";", "// Process binding operation nodes.", "$", "bindingoperation", "=", "$", "this", "->", "nodebinding", "->", "addChild", "(", "'operation'", ")", ";", "$", "bindingoperation", "->", "addAttribute", "(", "'name'", ",", "$", "functionname", ")", ";", "$", "soapoperation", "=", "$", "bindingoperation", "->", "addChild", "(", "'x:soap:operation'", ")", ";", "$", "soapoperation", "->", "addAttribute", "(", "'soapAction'", ",", "$", "this", "->", "namespace", ".", "'#'", ".", "$", "functionname", ")", ";", "// Input nodes.", "$", "this", "->", "process_params", "(", "$", "functionname", ",", "$", "porttypeoperation", ",", "$", "bindingoperation", ",", "$", "inputparams", ")", ";", "// Output nodes.", "$", "this", "->", "process_params", "(", "$", "functionname", ",", "$", "porttypeoperation", ",", "$", "bindingoperation", ",", "$", "outputparams", ",", "true", ")", ";", "}" ]
Registers the external service method to the WSDL. @param string $functionname The name of the web service function to be registered. @param array $inputparams Contains the function's input parameters with their associated types. @param array $outputparams Contains the function's output parameters with their associated types. @param string $documentation The function's description.
[ "Registers", "the", "external", "service", "method", "to", "the", "WSDL", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/webservice/soap/classes/wsdl.php#L169-L187
216,043
moodle/moodle
search/classes/output/renderer.php
renderer.render_results
public function render_results($results, $page, $totalcount, $url, $cat = null) { $content = ''; if (\core_search\manager::is_search_area_categories_enabled() && !empty($cat)) { $toprow = []; foreach (\core_search\manager::get_search_area_categories() as $category) { $taburl = clone $url; $taburl->param('cat', $category->get_name()); $taburl->param('page', 0); $taburl->remove_params(['page', 'areaids']); $toprow[$category->get_name()] = new \tabobject($category->get_name(), $taburl, $category->get_visiblename()); } if (\core_search\manager::should_hide_all_results_category()) { unset($toprow[\core_search\manager::SEARCH_AREA_CATEGORY_ALL]); } $content .= $this->tabtree($toprow, $cat->get_name()); } // Paging bar. $perpage = \core_search\manager::DISPLAY_RESULTS_PER_PAGE; $content .= $this->output->paging_bar($totalcount, $page, $perpage, $url); // Results. $resultshtml = array(); foreach ($results as $hit) { $resultshtml[] = $this->render_result($hit); } $content .= \html_writer::tag('div', implode('<hr/>', $resultshtml), array('class' => 'search-results')); // Paging bar. $content .= $this->output->paging_bar($totalcount, $page, $perpage, $url); return $content; }
php
public function render_results($results, $page, $totalcount, $url, $cat = null) { $content = ''; if (\core_search\manager::is_search_area_categories_enabled() && !empty($cat)) { $toprow = []; foreach (\core_search\manager::get_search_area_categories() as $category) { $taburl = clone $url; $taburl->param('cat', $category->get_name()); $taburl->param('page', 0); $taburl->remove_params(['page', 'areaids']); $toprow[$category->get_name()] = new \tabobject($category->get_name(), $taburl, $category->get_visiblename()); } if (\core_search\manager::should_hide_all_results_category()) { unset($toprow[\core_search\manager::SEARCH_AREA_CATEGORY_ALL]); } $content .= $this->tabtree($toprow, $cat->get_name()); } // Paging bar. $perpage = \core_search\manager::DISPLAY_RESULTS_PER_PAGE; $content .= $this->output->paging_bar($totalcount, $page, $perpage, $url); // Results. $resultshtml = array(); foreach ($results as $hit) { $resultshtml[] = $this->render_result($hit); } $content .= \html_writer::tag('div', implode('<hr/>', $resultshtml), array('class' => 'search-results')); // Paging bar. $content .= $this->output->paging_bar($totalcount, $page, $perpage, $url); return $content; }
[ "public", "function", "render_results", "(", "$", "results", ",", "$", "page", ",", "$", "totalcount", ",", "$", "url", ",", "$", "cat", "=", "null", ")", "{", "$", "content", "=", "''", ";", "if", "(", "\\", "core_search", "\\", "manager", "::", "is_search_area_categories_enabled", "(", ")", "&&", "!", "empty", "(", "$", "cat", ")", ")", "{", "$", "toprow", "=", "[", "]", ";", "foreach", "(", "\\", "core_search", "\\", "manager", "::", "get_search_area_categories", "(", ")", "as", "$", "category", ")", "{", "$", "taburl", "=", "clone", "$", "url", ";", "$", "taburl", "->", "param", "(", "'cat'", ",", "$", "category", "->", "get_name", "(", ")", ")", ";", "$", "taburl", "->", "param", "(", "'page'", ",", "0", ")", ";", "$", "taburl", "->", "remove_params", "(", "[", "'page'", ",", "'areaids'", "]", ")", ";", "$", "toprow", "[", "$", "category", "->", "get_name", "(", ")", "]", "=", "new", "\\", "tabobject", "(", "$", "category", "->", "get_name", "(", ")", ",", "$", "taburl", ",", "$", "category", "->", "get_visiblename", "(", ")", ")", ";", "}", "if", "(", "\\", "core_search", "\\", "manager", "::", "should_hide_all_results_category", "(", ")", ")", "{", "unset", "(", "$", "toprow", "[", "\\", "core_search", "\\", "manager", "::", "SEARCH_AREA_CATEGORY_ALL", "]", ")", ";", "}", "$", "content", ".=", "$", "this", "->", "tabtree", "(", "$", "toprow", ",", "$", "cat", "->", "get_name", "(", ")", ")", ";", "}", "// Paging bar.", "$", "perpage", "=", "\\", "core_search", "\\", "manager", "::", "DISPLAY_RESULTS_PER_PAGE", ";", "$", "content", ".=", "$", "this", "->", "output", "->", "paging_bar", "(", "$", "totalcount", ",", "$", "page", ",", "$", "perpage", ",", "$", "url", ")", ";", "// Results.", "$", "resultshtml", "=", "array", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "hit", ")", "{", "$", "resultshtml", "[", "]", "=", "$", "this", "->", "render_result", "(", "$", "hit", ")", ";", "}", "$", "content", ".=", "\\", "html_writer", "::", "tag", "(", "'div'", ",", "implode", "(", "'<hr/>'", ",", "$", "resultshtml", ")", ",", "array", "(", "'class'", "=>", "'search-results'", ")", ")", ";", "// Paging bar.", "$", "content", ".=", "$", "this", "->", "output", "->", "paging_bar", "(", "$", "totalcount", ",", "$", "page", ",", "$", "perpage", ",", "$", "url", ")", ";", "return", "$", "content", ";", "}" ]
Renders search results. @param \core_search\document[] $results @param int $page Zero based page number. @param int $totalcount Total number of results available. @param \moodle_url $url @param \core_search\area_category|null $cat Selected search are category or null if category functionality is disabled. @return string HTML
[ "Renders", "search", "results", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/classes/output/renderer.php#L59-L94
216,044
moodle/moodle
search/classes/output/renderer.php
renderer.render_result
public function render_result(\core_search\document $doc) { $docdata = $doc->export_for_template($this); // Limit text fields size. $docdata['title'] = shorten_text($docdata['title'], static::SEARCH_RESULT_STRING_SIZE, true); $docdata['content'] = $docdata['content'] ? shorten_text($docdata['content'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; $docdata['description1'] = $docdata['description1'] ? shorten_text($docdata['description1'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; $docdata['description2'] = $docdata['description2'] ? shorten_text($docdata['description2'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; return $this->output->render_from_template('core_search/result', $docdata); }
php
public function render_result(\core_search\document $doc) { $docdata = $doc->export_for_template($this); // Limit text fields size. $docdata['title'] = shorten_text($docdata['title'], static::SEARCH_RESULT_STRING_SIZE, true); $docdata['content'] = $docdata['content'] ? shorten_text($docdata['content'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; $docdata['description1'] = $docdata['description1'] ? shorten_text($docdata['description1'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; $docdata['description2'] = $docdata['description2'] ? shorten_text($docdata['description2'], static::SEARCH_RESULT_TEXT_SIZE, true) : ''; return $this->output->render_from_template('core_search/result', $docdata); }
[ "public", "function", "render_result", "(", "\\", "core_search", "\\", "document", "$", "doc", ")", "{", "$", "docdata", "=", "$", "doc", "->", "export_for_template", "(", "$", "this", ")", ";", "// Limit text fields size.", "$", "docdata", "[", "'title'", "]", "=", "shorten_text", "(", "$", "docdata", "[", "'title'", "]", ",", "static", "::", "SEARCH_RESULT_STRING_SIZE", ",", "true", ")", ";", "$", "docdata", "[", "'content'", "]", "=", "$", "docdata", "[", "'content'", "]", "?", "shorten_text", "(", "$", "docdata", "[", "'content'", "]", ",", "static", "::", "SEARCH_RESULT_TEXT_SIZE", ",", "true", ")", ":", "''", ";", "$", "docdata", "[", "'description1'", "]", "=", "$", "docdata", "[", "'description1'", "]", "?", "shorten_text", "(", "$", "docdata", "[", "'description1'", "]", ",", "static", "::", "SEARCH_RESULT_TEXT_SIZE", ",", "true", ")", ":", "''", ";", "$", "docdata", "[", "'description2'", "]", "=", "$", "docdata", "[", "'description2'", "]", "?", "shorten_text", "(", "$", "docdata", "[", "'description2'", "]", ",", "static", "::", "SEARCH_RESULT_TEXT_SIZE", ",", "true", ")", ":", "''", ";", "return", "$", "this", "->", "output", "->", "render_from_template", "(", "'core_search/result'", ",", "$", "docdata", ")", ";", "}" ]
Displaying search results. @param \core_search\document Containing a single search response to be displayed.a @return string HTML
[ "Displaying", "search", "results", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/classes/output/renderer.php#L102-L112
216,045
moodle/moodle
search/classes/output/renderer.php
renderer.render_search_disabled
public function render_search_disabled() { $content = $this->output->box_start(); $content .= $this->output->notification(get_string('globalsearchdisabled', 'search'), 'notifymessage'); $content .= $this->output->box_end(); return $content; }
php
public function render_search_disabled() { $content = $this->output->box_start(); $content .= $this->output->notification(get_string('globalsearchdisabled', 'search'), 'notifymessage'); $content .= $this->output->box_end(); return $content; }
[ "public", "function", "render_search_disabled", "(", ")", "{", "$", "content", "=", "$", "this", "->", "output", "->", "box_start", "(", ")", ";", "$", "content", ".=", "$", "this", "->", "output", "->", "notification", "(", "get_string", "(", "'globalsearchdisabled'", ",", "'search'", ")", ",", "'notifymessage'", ")", ";", "$", "content", ".=", "$", "this", "->", "output", "->", "box_end", "(", ")", ";", "return", "$", "content", ";", "}" ]
Returns a box with a search disabled lang string. @return string HTML
[ "Returns", "a", "box", "with", "a", "search", "disabled", "lang", "string", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/classes/output/renderer.php#L119-L124
216,046
moodle/moodle
competency/classes/competency.php
competency.after_update
protected function after_update($result) { global $DB; if (!$result) { $this->beforeupdate = null; return; } // The parent ID has changed, we need to fix all the paths of the children. if ($this->beforeupdate->get('parentid') != $this->get('parentid')) { $beforepath = $this->beforeupdate->get('path') . $this->get('id') . '/'; $like = $DB->sql_like('path', '?'); $likesearch = $DB->sql_like_escape($beforepath) . '%'; $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET path = REPLACE(path, ?, ?) WHERE " . $like; $DB->execute($sql, array( $beforepath, $this->get('path') . $this->get('id') . '/', $likesearch )); // Resolving sortorder holes left after changing parent. $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET sortorder = sortorder -1 " . " WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?"; $DB->execute($sql, array($this->get('competencyframeworkid'), $this->beforeupdate->get('parentid'), $this->beforeupdate->get('sortorder') )); } $this->beforeupdate = null; }
php
protected function after_update($result) { global $DB; if (!$result) { $this->beforeupdate = null; return; } // The parent ID has changed, we need to fix all the paths of the children. if ($this->beforeupdate->get('parentid') != $this->get('parentid')) { $beforepath = $this->beforeupdate->get('path') . $this->get('id') . '/'; $like = $DB->sql_like('path', '?'); $likesearch = $DB->sql_like_escape($beforepath) . '%'; $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET path = REPLACE(path, ?, ?) WHERE " . $like; $DB->execute($sql, array( $beforepath, $this->get('path') . $this->get('id') . '/', $likesearch )); // Resolving sortorder holes left after changing parent. $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET sortorder = sortorder -1 " . " WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?"; $DB->execute($sql, array($this->get('competencyframeworkid'), $this->beforeupdate->get('parentid'), $this->beforeupdate->get('sortorder') )); } $this->beforeupdate = null; }
[ "protected", "function", "after_update", "(", "$", "result", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "$", "result", ")", "{", "$", "this", "->", "beforeupdate", "=", "null", ";", "return", ";", "}", "// The parent ID has changed, we need to fix all the paths of the children.", "if", "(", "$", "this", "->", "beforeupdate", "->", "get", "(", "'parentid'", ")", "!=", "$", "this", "->", "get", "(", "'parentid'", ")", ")", "{", "$", "beforepath", "=", "$", "this", "->", "beforeupdate", "->", "get", "(", "'path'", ")", ".", "$", "this", "->", "get", "(", "'id'", ")", ".", "'/'", ";", "$", "like", "=", "$", "DB", "->", "sql_like", "(", "'path'", ",", "'?'", ")", ";", "$", "likesearch", "=", "$", "DB", "->", "sql_like_escape", "(", "$", "beforepath", ")", ".", "'%'", ";", "$", "table", "=", "'{'", ".", "self", "::", "TABLE", ".", "'}'", ";", "$", "sql", "=", "\"UPDATE $table SET path = REPLACE(path, ?, ?) WHERE \"", ".", "$", "like", ";", "$", "DB", "->", "execute", "(", "$", "sql", ",", "array", "(", "$", "beforepath", ",", "$", "this", "->", "get", "(", "'path'", ")", ".", "$", "this", "->", "get", "(", "'id'", ")", ".", "'/'", ",", "$", "likesearch", ")", ")", ";", "// Resolving sortorder holes left after changing parent.", "$", "table", "=", "'{'", ".", "self", "::", "TABLE", ".", "'}'", ";", "$", "sql", "=", "\"UPDATE $table SET sortorder = sortorder -1 \"", ".", "\" WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?\"", ";", "$", "DB", "->", "execute", "(", "$", "sql", ",", "array", "(", "$", "this", "->", "get", "(", "'competencyframeworkid'", ")", ",", "$", "this", "->", "beforeupdate", "->", "get", "(", "'parentid'", ")", ",", "$", "this", "->", "beforeupdate", "->", "get", "(", "'sortorder'", ")", ")", ")", ";", "}", "$", "this", "->", "beforeupdate", "=", "null", ";", "}" ]
Hook to execute after an update. @param bool $result Whether or not the update was successful. @return void
[ "Hook", "to", "execute", "after", "an", "update", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L160-L194
216,047
moodle/moodle
competency/classes/competency.php
competency.after_delete
protected function after_delete($result) { global $DB; if (!$result) { return; } // Resolving sortorder holes left after delete. $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET sortorder = sortorder -1 WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?"; $DB->execute($sql, array($this->get('competencyframeworkid'), $this->get('parentid'), $this->get('sortorder'))); }
php
protected function after_delete($result) { global $DB; if (!$result) { return; } // Resolving sortorder holes left after delete. $table = '{' . self::TABLE . '}'; $sql = "UPDATE $table SET sortorder = sortorder -1 WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?"; $DB->execute($sql, array($this->get('competencyframeworkid'), $this->get('parentid'), $this->get('sortorder'))); }
[ "protected", "function", "after_delete", "(", "$", "result", ")", "{", "global", "$", "DB", ";", "if", "(", "!", "$", "result", ")", "{", "return", ";", "}", "// Resolving sortorder holes left after delete.", "$", "table", "=", "'{'", ".", "self", "::", "TABLE", ".", "'}'", ";", "$", "sql", "=", "\"UPDATE $table SET sortorder = sortorder -1 WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?\"", ";", "$", "DB", "->", "execute", "(", "$", "sql", ",", "array", "(", "$", "this", "->", "get", "(", "'competencyframeworkid'", ")", ",", "$", "this", "->", "get", "(", "'parentid'", ")", ",", "$", "this", "->", "get", "(", "'sortorder'", ")", ")", ")", ";", "}" ]
Hook to execute after a delete. @param bool $result Whether or not the delete was successful. @return void
[ "Hook", "to", "execute", "after", "a", "delete", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L203-L213
216,048
moodle/moodle
competency/classes/competency.php
competency.get_default_grade
public function get_default_grade() { $scaleid = $this->get('scaleid'); $scaleconfig = $this->get('scaleconfiguration'); if ($scaleid === null) { $scaleconfig = $this->get_framework()->get('scaleconfiguration'); } return competency_framework::get_default_grade_from_scale_configuration($scaleconfig); }
php
public function get_default_grade() { $scaleid = $this->get('scaleid'); $scaleconfig = $this->get('scaleconfiguration'); if ($scaleid === null) { $scaleconfig = $this->get_framework()->get('scaleconfiguration'); } return competency_framework::get_default_grade_from_scale_configuration($scaleconfig); }
[ "public", "function", "get_default_grade", "(", ")", "{", "$", "scaleid", "=", "$", "this", "->", "get", "(", "'scaleid'", ")", ";", "$", "scaleconfig", "=", "$", "this", "->", "get", "(", "'scaleconfiguration'", ")", ";", "if", "(", "$", "scaleid", "===", "null", ")", "{", "$", "scaleconfig", "=", "$", "this", "->", "get_framework", "(", ")", "->", "get", "(", "'scaleconfiguration'", ")", ";", "}", "return", "competency_framework", "::", "get_default_grade_from_scale_configuration", "(", "$", "scaleconfig", ")", ";", "}" ]
Extracts the default grade from the scale configuration. Returns an array where the first element is the grade, and the second is a boolean representing whether or not this grade is considered 'proficient'. @return array(int grade, bool proficient)
[ "Extracts", "the", "default", "grade", "from", "the", "scale", "configuration", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L223-L230
216,049
moodle/moodle
competency/classes/competency.php
competency.get_proficiency_of_grade
public function get_proficiency_of_grade($grade) { $scaleid = $this->get('scaleid'); $scaleconfig = $this->get('scaleconfiguration'); if ($scaleid === null) { $scaleconfig = $this->get_framework()->get('scaleconfiguration'); } return competency_framework::get_proficiency_of_grade_from_scale_configuration($scaleconfig, $grade); }
php
public function get_proficiency_of_grade($grade) { $scaleid = $this->get('scaleid'); $scaleconfig = $this->get('scaleconfiguration'); if ($scaleid === null) { $scaleconfig = $this->get_framework()->get('scaleconfiguration'); } return competency_framework::get_proficiency_of_grade_from_scale_configuration($scaleconfig, $grade); }
[ "public", "function", "get_proficiency_of_grade", "(", "$", "grade", ")", "{", "$", "scaleid", "=", "$", "this", "->", "get", "(", "'scaleid'", ")", ";", "$", "scaleconfig", "=", "$", "this", "->", "get", "(", "'scaleconfiguration'", ")", ";", "if", "(", "$", "scaleid", "===", "null", ")", "{", "$", "scaleconfig", "=", "$", "this", "->", "get_framework", "(", ")", "->", "get", "(", "'scaleconfiguration'", ")", ";", "}", "return", "competency_framework", "::", "get_proficiency_of_grade_from_scale_configuration", "(", "$", "scaleconfig", ",", "$", "grade", ")", ";", "}" ]
Extracts the proficiency of a grade from the scale configuration. @param int $grade The grade (scale item ID). @return array(int grade, bool proficient)
[ "Extracts", "the", "proficiency", "of", "a", "grade", "from", "the", "scale", "configuration", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L271-L278
216,050
moodle/moodle
competency/classes/competency.php
competency.get_rule_object
public function get_rule_object() { $rule = $this->get('ruletype'); if (!$rule || !is_subclass_of($rule, 'core_competency\\competency_rule')) { // Double check that the rule is extending the right class to avoid bad surprises. return null; } return new $rule($this); }
php
public function get_rule_object() { $rule = $this->get('ruletype'); if (!$rule || !is_subclass_of($rule, 'core_competency\\competency_rule')) { // Double check that the rule is extending the right class to avoid bad surprises. return null; } return new $rule($this); }
[ "public", "function", "get_rule_object", "(", ")", "{", "$", "rule", "=", "$", "this", "->", "get", "(", "'ruletype'", ")", ";", "if", "(", "!", "$", "rule", "||", "!", "is_subclass_of", "(", "$", "rule", ",", "'core_competency\\\\competency_rule'", ")", ")", "{", "// Double check that the rule is extending the right class to avoid bad surprises.", "return", "null", ";", "}", "return", "new", "$", "rule", "(", "$", "this", ")", ";", "}" ]
Get the rule object. @return null|competency_rule
[ "Get", "the", "rule", "object", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L294-L303
216,051
moodle/moodle
competency/classes/competency.php
competency.get_scale
public function get_scale() { $scaleid = $this->get('scaleid'); if ($scaleid === null) { return $this->get_framework()->get_scale(); } $scale = \grade_scale::fetch(array('id' => $scaleid)); $scale->load_items(); return $scale; }
php
public function get_scale() { $scaleid = $this->get('scaleid'); if ($scaleid === null) { return $this->get_framework()->get_scale(); } $scale = \grade_scale::fetch(array('id' => $scaleid)); $scale->load_items(); return $scale; }
[ "public", "function", "get_scale", "(", ")", "{", "$", "scaleid", "=", "$", "this", "->", "get", "(", "'scaleid'", ")", ";", "if", "(", "$", "scaleid", "===", "null", ")", "{", "return", "$", "this", "->", "get_framework", "(", ")", "->", "get_scale", "(", ")", ";", "}", "$", "scale", "=", "\\", "grade_scale", "::", "fetch", "(", "array", "(", "'id'", "=>", "$", "scaleid", ")", ")", ";", "$", "scale", "->", "load_items", "(", ")", ";", "return", "$", "scale", ";", "}" ]
Return the scale. @return \grade_scale
[ "Return", "the", "scale", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L310-L318
216,052
moodle/moodle
competency/classes/competency.php
competency.is_parent_of
public function is_parent_of(array $ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED); $params['parentid'] = $this->get('id'); return $DB->count_records_select(self::TABLE, "id $insql AND parentid = :parentid", $params) == count($ids); }
php
public function is_parent_of(array $ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED); $params['parentid'] = $this->get('id'); return $DB->count_records_select(self::TABLE, "id $insql AND parentid = :parentid", $params) == count($ids); }
[ "public", "function", "is_parent_of", "(", "array", "$", "ids", ")", "{", "global", "$", "DB", ";", "list", "(", "$", "insql", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "ids", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "params", "[", "'parentid'", "]", "=", "$", "this", "->", "get", "(", "'id'", ")", ";", "return", "$", "DB", "->", "count_records_select", "(", "self", "::", "TABLE", ",", "\"id $insql AND parentid = :parentid\"", ",", "$", "params", ")", "==", "count", "(", "$", "ids", ")", ";", "}" ]
Check if the competency is the parent of passed competencies. @param array $ids IDs of supposedly direct children. @return boolean
[ "Check", "if", "the", "competency", "is", "the", "parent", "of", "passed", "competencies", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L338-L345
216,053
moodle/moodle
competency/classes/competency.php
competency.reset_rule
public function reset_rule() { $this->raw_set('ruleoutcome', static::OUTCOME_NONE); $this->raw_set('ruletype', null); $this->raw_set('ruleconfig', null); }
php
public function reset_rule() { $this->raw_set('ruleoutcome', static::OUTCOME_NONE); $this->raw_set('ruletype', null); $this->raw_set('ruleconfig', null); }
[ "public", "function", "reset_rule", "(", ")", "{", "$", "this", "->", "raw_set", "(", "'ruleoutcome'", ",", "static", "::", "OUTCOME_NONE", ")", ";", "$", "this", "->", "raw_set", "(", "'ruletype'", ",", "null", ")", ";", "$", "this", "->", "raw_set", "(", "'ruleconfig'", ",", "null", ")", ";", "}" ]
Reset the rule. @return void
[ "Reset", "the", "rule", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L352-L356
216,054
moodle/moodle
competency/classes/competency.php
competency.set_new_path
protected function set_new_path(competency $parent = null) { $path = '/0/'; if ($this->get('parentid')) { $parent = $parent !== null ? $parent : $this->get_parent(); $path = $parent->get('path') . $this->get('parentid') . '/'; } $this->raw_set('path', $path); }
php
protected function set_new_path(competency $parent = null) { $path = '/0/'; if ($this->get('parentid')) { $parent = $parent !== null ? $parent : $this->get_parent(); $path = $parent->get('path') . $this->get('parentid') . '/'; } $this->raw_set('path', $path); }
[ "protected", "function", "set_new_path", "(", "competency", "$", "parent", "=", "null", ")", "{", "$", "path", "=", "'/0/'", ";", "if", "(", "$", "this", "->", "get", "(", "'parentid'", ")", ")", "{", "$", "parent", "=", "$", "parent", "!==", "null", "?", "$", "parent", ":", "$", "this", "->", "get_parent", "(", ")", ";", "$", "path", "=", "$", "parent", "->", "get", "(", "'path'", ")", ".", "$", "this", "->", "get", "(", "'parentid'", ")", ".", "'/'", ";", "}", "$", "this", "->", "raw_set", "(", "'path'", ",", "$", "path", ")", ";", "}" ]
Helper method to set the path. @param competency $parent The parent competency object. @return void
[ "Helper", "method", "to", "set", "the", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L364-L371
216,055
moodle/moodle
competency/classes/competency.php
competency.set_new_sortorder
protected function set_new_sortorder() { $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid')); $this->raw_set('sortorder', $this->count_records($search)); }
php
protected function set_new_sortorder() { $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid')); $this->raw_set('sortorder', $this->count_records($search)); }
[ "protected", "function", "set_new_sortorder", "(", ")", "{", "$", "search", "=", "array", "(", "'parentid'", "=>", "$", "this", "->", "get", "(", "'parentid'", ")", ",", "'competencyframeworkid'", "=>", "$", "this", "->", "get", "(", "'competencyframeworkid'", ")", ")", ";", "$", "this", "->", "raw_set", "(", "'sortorder'", ",", "$", "this", "->", "count_records", "(", "$", "search", ")", ")", ";", "}" ]
Helper method to set the sortorder. @return void
[ "Helper", "method", "to", "set", "the", "sortorder", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L378-L381
216,056
moodle/moodle
competency/classes/competency.php
competency.search
public static function search($searchtext, $competencyframeworkid) { global $DB; $like1 = $DB->sql_like('shortname', ':like1', false); $like2 = $DB->sql_like('idnumber', ':like2', false); $like3 = $DB->sql_like('description', ':like3', false); $params = array( 'like1' => '%' . $DB->sql_like_escape($searchtext) . '%', 'like2' => '%' . $DB->sql_like_escape($searchtext) . '%', 'like3' => '%' . $DB->sql_like_escape($searchtext) . '%', 'frameworkid' => $competencyframeworkid ); $sql = 'competencyframeworkid = :frameworkid AND ((' . $like1 . ') OR (' . $like2 . ') OR (' . $like3 . '))'; $records = $DB->get_records_select(self::TABLE, $sql, $params, 'path, sortorder ASC', '*'); // Now get all the parents. $parents = array(); foreach ($records as $record) { $split = explode('/', trim($record->path, '/')); foreach ($split as $parent) { $parents[intval($parent)] = true; } } $parents = array_keys($parents); // Skip ones we already fetched. foreach ($parents as $idx => $parent) { if ($parent == 0 || isset($records[$parent])) { unset($parents[$idx]); } } if (count($parents)) { list($parentsql, $parentparams) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED); $parentrecords = $DB->get_records_select(self::TABLE, 'id ' . $parentsql, $parentparams, 'path, sortorder ASC', '*'); foreach ($parentrecords as $id => $record) { $records[$id] = $record; } } $instances = array(); // Convert to instances of this class. foreach ($records as $record) { $newrecord = new static(0, $record); $instances[$newrecord->get('id')] = $newrecord; } return $instances; }
php
public static function search($searchtext, $competencyframeworkid) { global $DB; $like1 = $DB->sql_like('shortname', ':like1', false); $like2 = $DB->sql_like('idnumber', ':like2', false); $like3 = $DB->sql_like('description', ':like3', false); $params = array( 'like1' => '%' . $DB->sql_like_escape($searchtext) . '%', 'like2' => '%' . $DB->sql_like_escape($searchtext) . '%', 'like3' => '%' . $DB->sql_like_escape($searchtext) . '%', 'frameworkid' => $competencyframeworkid ); $sql = 'competencyframeworkid = :frameworkid AND ((' . $like1 . ') OR (' . $like2 . ') OR (' . $like3 . '))'; $records = $DB->get_records_select(self::TABLE, $sql, $params, 'path, sortorder ASC', '*'); // Now get all the parents. $parents = array(); foreach ($records as $record) { $split = explode('/', trim($record->path, '/')); foreach ($split as $parent) { $parents[intval($parent)] = true; } } $parents = array_keys($parents); // Skip ones we already fetched. foreach ($parents as $idx => $parent) { if ($parent == 0 || isset($records[$parent])) { unset($parents[$idx]); } } if (count($parents)) { list($parentsql, $parentparams) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED); $parentrecords = $DB->get_records_select(self::TABLE, 'id ' . $parentsql, $parentparams, 'path, sortorder ASC', '*'); foreach ($parentrecords as $id => $record) { $records[$id] = $record; } } $instances = array(); // Convert to instances of this class. foreach ($records as $record) { $newrecord = new static(0, $record); $instances[$newrecord->get('id')] = $newrecord; } return $instances; }
[ "public", "static", "function", "search", "(", "$", "searchtext", ",", "$", "competencyframeworkid", ")", "{", "global", "$", "DB", ";", "$", "like1", "=", "$", "DB", "->", "sql_like", "(", "'shortname'", ",", "':like1'", ",", "false", ")", ";", "$", "like2", "=", "$", "DB", "->", "sql_like", "(", "'idnumber'", ",", "':like2'", ",", "false", ")", ";", "$", "like3", "=", "$", "DB", "->", "sql_like", "(", "'description'", ",", "':like3'", ",", "false", ")", ";", "$", "params", "=", "array", "(", "'like1'", "=>", "'%'", ".", "$", "DB", "->", "sql_like_escape", "(", "$", "searchtext", ")", ".", "'%'", ",", "'like2'", "=>", "'%'", ".", "$", "DB", "->", "sql_like_escape", "(", "$", "searchtext", ")", ".", "'%'", ",", "'like3'", "=>", "'%'", ".", "$", "DB", "->", "sql_like_escape", "(", "$", "searchtext", ")", ".", "'%'", ",", "'frameworkid'", "=>", "$", "competencyframeworkid", ")", ";", "$", "sql", "=", "'competencyframeworkid = :frameworkid AND (('", ".", "$", "like1", ".", "') OR ('", ".", "$", "like2", ".", "') OR ('", ".", "$", "like3", ".", "'))'", ";", "$", "records", "=", "$", "DB", "->", "get_records_select", "(", "self", "::", "TABLE", ",", "$", "sql", ",", "$", "params", ",", "'path, sortorder ASC'", ",", "'*'", ")", ";", "// Now get all the parents.", "$", "parents", "=", "array", "(", ")", ";", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "split", "=", "explode", "(", "'/'", ",", "trim", "(", "$", "record", "->", "path", ",", "'/'", ")", ")", ";", "foreach", "(", "$", "split", "as", "$", "parent", ")", "{", "$", "parents", "[", "intval", "(", "$", "parent", ")", "]", "=", "true", ";", "}", "}", "$", "parents", "=", "array_keys", "(", "$", "parents", ")", ";", "// Skip ones we already fetched.", "foreach", "(", "$", "parents", "as", "$", "idx", "=>", "$", "parent", ")", "{", "if", "(", "$", "parent", "==", "0", "||", "isset", "(", "$", "records", "[", "$", "parent", "]", ")", ")", "{", "unset", "(", "$", "parents", "[", "$", "idx", "]", ")", ";", "}", "}", "if", "(", "count", "(", "$", "parents", ")", ")", "{", "list", "(", "$", "parentsql", ",", "$", "parentparams", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "parents", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "parentrecords", "=", "$", "DB", "->", "get_records_select", "(", "self", "::", "TABLE", ",", "'id '", ".", "$", "parentsql", ",", "$", "parentparams", ",", "'path, sortorder ASC'", ",", "'*'", ")", ";", "foreach", "(", "$", "parentrecords", "as", "$", "id", "=>", "$", "record", ")", "{", "$", "records", "[", "$", "id", "]", "=", "$", "record", ";", "}", "}", "$", "instances", "=", "array", "(", ")", ";", "// Convert to instances of this class.", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "newrecord", "=", "new", "static", "(", "0", ",", "$", "record", ")", ";", "$", "instances", "[", "$", "newrecord", "->", "get", "(", "'id'", ")", "]", "=", "$", "newrecord", ";", "}", "return", "$", "instances", ";", "}" ]
This does a specialised search that finds all nodes in the tree with matching text on any text like field, and returns this node and all its parents in a displayable sort order. @param string $searchtext The text to search for. @param int $competencyframeworkid The competency framework to limit the search. @return persistent[]
[ "This", "does", "a", "specialised", "search", "that", "finds", "all", "nodes", "in", "the", "tree", "with", "matching", "text", "on", "any", "text", "like", "field", "and", "returns", "this", "node", "and", "all", "its", "parents", "in", "a", "displayable", "sort", "order", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L391-L443
216,057
moodle/moodle
competency/classes/competency.php
competency.validate_competencyframeworkid
protected function validate_competencyframeworkid($value) { // During update. if ($this->get('id')) { // Ensure that we are not trying to move the competency across frameworks. if ($this->beforeupdate->get('competencyframeworkid') != $value) { return new lang_string('invaliddata', 'error'); } } else { // During create. // Check that the framework exists. if (!competency_framework::record_exists($value)) { return new lang_string('invaliddata', 'error'); } } return true; }
php
protected function validate_competencyframeworkid($value) { // During update. if ($this->get('id')) { // Ensure that we are not trying to move the competency across frameworks. if ($this->beforeupdate->get('competencyframeworkid') != $value) { return new lang_string('invaliddata', 'error'); } } else { // During create. // Check that the framework exists. if (!competency_framework::record_exists($value)) { return new lang_string('invaliddata', 'error'); } } return true; }
[ "protected", "function", "validate_competencyframeworkid", "(", "$", "value", ")", "{", "// During update.", "if", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", "{", "// Ensure that we are not trying to move the competency across frameworks.", "if", "(", "$", "this", "->", "beforeupdate", "->", "get", "(", "'competencyframeworkid'", ")", "!=", "$", "value", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "}", "else", "{", "// During create.", "// Check that the framework exists.", "if", "(", "!", "competency_framework", "::", "record_exists", "(", "$", "value", ")", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "}", "return", "true", ";", "}" ]
Validate the competency framework ID. @param int $value The framework ID. @return true|lang_string
[ "Validate", "the", "competency", "framework", "ID", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L451-L471
216,058
moodle/moodle
competency/classes/competency.php
competency.validate_idnumber
protected function validate_idnumber($value) { global $DB; $sql = 'idnumber = :idnumber AND competencyframeworkid = :competencyframeworkid AND id <> :id'; $params = array( 'id' => $this->get('id'), 'idnumber' => $value, 'competencyframeworkid' => $this->get('competencyframeworkid') ); if ($DB->record_exists_select(self::TABLE, $sql, $params)) { return new lang_string('idnumbertaken', 'error'); } return true; }
php
protected function validate_idnumber($value) { global $DB; $sql = 'idnumber = :idnumber AND competencyframeworkid = :competencyframeworkid AND id <> :id'; $params = array( 'id' => $this->get('id'), 'idnumber' => $value, 'competencyframeworkid' => $this->get('competencyframeworkid') ); if ($DB->record_exists_select(self::TABLE, $sql, $params)) { return new lang_string('idnumbertaken', 'error'); } return true; }
[ "protected", "function", "validate_idnumber", "(", "$", "value", ")", "{", "global", "$", "DB", ";", "$", "sql", "=", "'idnumber = :idnumber AND competencyframeworkid = :competencyframeworkid AND id <> :id'", ";", "$", "params", "=", "array", "(", "'id'", "=>", "$", "this", "->", "get", "(", "'id'", ")", ",", "'idnumber'", "=>", "$", "value", ",", "'competencyframeworkid'", "=>", "$", "this", "->", "get", "(", "'competencyframeworkid'", ")", ")", ";", "if", "(", "$", "DB", "->", "record_exists_select", "(", "self", "::", "TABLE", ",", "$", "sql", ",", "$", "params", ")", ")", "{", "return", "new", "lang_string", "(", "'idnumbertaken'", ",", "'error'", ")", ";", "}", "return", "true", ";", "}" ]
Validate the ID number. @param string $value The ID number. @return true|lang_string
[ "Validate", "the", "ID", "number", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L479-L491
216,059
moodle/moodle
competency/classes/competency.php
competency.validate_path
protected function validate_path($value) { // The last item should be the parent ID. $id = $this->get('parentid'); if (substr($value, -(strlen($id) + 2)) != '/' . $id . '/') { return new lang_string('invaliddata', 'error'); } else if (!preg_match('@/([0-9]+/)+@', $value)) { // The format of the path is not correct. return new lang_string('invaliddata', 'error'); } return true; }
php
protected function validate_path($value) { // The last item should be the parent ID. $id = $this->get('parentid'); if (substr($value, -(strlen($id) + 2)) != '/' . $id . '/') { return new lang_string('invaliddata', 'error'); } else if (!preg_match('@/([0-9]+/)+@', $value)) { // The format of the path is not correct. return new lang_string('invaliddata', 'error'); } return true; }
[ "protected", "function", "validate_path", "(", "$", "value", ")", "{", "// The last item should be the parent ID.", "$", "id", "=", "$", "this", "->", "get", "(", "'parentid'", ")", ";", "if", "(", "substr", "(", "$", "value", ",", "-", "(", "strlen", "(", "$", "id", ")", "+", "2", ")", ")", "!=", "'/'", ".", "$", "id", ".", "'/'", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "else", "if", "(", "!", "preg_match", "(", "'@/([0-9]+/)+@'", ",", "$", "value", ")", ")", "{", "// The format of the path is not correct.", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "return", "true", ";", "}" ]
Validate the path. @param string $value The path. @return true|lang_string
[ "Validate", "the", "path", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L499-L512
216,060
moodle/moodle
competency/classes/competency.php
competency.validate_parentid
protected function validate_parentid($value) { // Check that the parent exists. But only if we don't have it already, and we actually have a parent. if (!empty($value) && !$this->newparent && !self::record_exists($value)) { return new lang_string('invaliddata', 'error'); } // During update. if ($this->get('id')) { // If there is a new parent. if ($this->beforeupdate->get('parentid') != $value && $this->newparent) { // Check that the new parent belongs to the same framework. if ($this->newparent->get('competencyframeworkid') != $this->get('competencyframeworkid')) { return new lang_string('invaliddata', 'error'); } } } return true; }
php
protected function validate_parentid($value) { // Check that the parent exists. But only if we don't have it already, and we actually have a parent. if (!empty($value) && !$this->newparent && !self::record_exists($value)) { return new lang_string('invaliddata', 'error'); } // During update. if ($this->get('id')) { // If there is a new parent. if ($this->beforeupdate->get('parentid') != $value && $this->newparent) { // Check that the new parent belongs to the same framework. if ($this->newparent->get('competencyframeworkid') != $this->get('competencyframeworkid')) { return new lang_string('invaliddata', 'error'); } } } return true; }
[ "protected", "function", "validate_parentid", "(", "$", "value", ")", "{", "// Check that the parent exists. But only if we don't have it already, and we actually have a parent.", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "!", "$", "this", "->", "newparent", "&&", "!", "self", "::", "record_exists", "(", "$", "value", ")", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "// During update.", "if", "(", "$", "this", "->", "get", "(", "'id'", ")", ")", "{", "// If there is a new parent.", "if", "(", "$", "this", "->", "beforeupdate", "->", "get", "(", "'parentid'", ")", "!=", "$", "value", "&&", "$", "this", "->", "newparent", ")", "{", "// Check that the new parent belongs to the same framework.", "if", "(", "$", "this", "->", "newparent", "->", "get", "(", "'competencyframeworkid'", ")", "!=", "$", "this", "->", "get", "(", "'competencyframeworkid'", ")", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
Validate the parent ID. @param string $value The ID. @return true|lang_string
[ "Validate", "the", "parent", "ID", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L520-L541
216,061
moodle/moodle
competency/classes/competency.php
competency.validate_ruletype
protected function validate_ruletype($value) { if ($value === null) { return true; } if (!class_exists($value) || !is_subclass_of($value, 'core_competency\\competency_rule')) { return new lang_string('invaliddata', 'error'); } return true; }
php
protected function validate_ruletype($value) { if ($value === null) { return true; } if (!class_exists($value) || !is_subclass_of($value, 'core_competency\\competency_rule')) { return new lang_string('invaliddata', 'error'); } return true; }
[ "protected", "function", "validate_ruletype", "(", "$", "value", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "true", ";", "}", "if", "(", "!", "class_exists", "(", "$", "value", ")", "||", "!", "is_subclass_of", "(", "$", "value", ",", "'core_competency\\\\competency_rule'", ")", ")", "{", "return", "new", "lang_string", "(", "'invaliddata'", ",", "'error'", ")", ";", "}", "return", "true", ";", "}" ]
Validate the rule. @param string $value The ID. @return true|lang_string
[ "Validate", "the", "rule", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L549-L559
216,062
moodle/moodle
competency/classes/competency.php
competency.share_same_framework
public static function share_same_framework(array $ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids); $sql = "SELECT COUNT('x') FROM (SELECT DISTINCT(competencyframeworkid) FROM {" . self::TABLE . "} WHERE id {$insql}) f"; return $DB->count_records_sql($sql, $params) == 1; }
php
public static function share_same_framework(array $ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids); $sql = "SELECT COUNT('x') FROM (SELECT DISTINCT(competencyframeworkid) FROM {" . self::TABLE . "} WHERE id {$insql}) f"; return $DB->count_records_sql($sql, $params) == 1; }
[ "public", "static", "function", "share_same_framework", "(", "array", "$", "ids", ")", "{", "global", "$", "DB", ";", "list", "(", "$", "insql", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "ids", ")", ";", "$", "sql", "=", "\"SELECT COUNT('x') FROM (SELECT DISTINCT(competencyframeworkid) FROM {\"", ".", "self", "::", "TABLE", ".", "\"} WHERE id {$insql}) f\"", ";", "return", "$", "DB", "->", "count_records_sql", "(", "$", "sql", ",", "$", "params", ")", "==", "1", ";", "}" ]
Return whether or not the competency IDs share the same framework. @param array $ids Competency IDs @return bool
[ "Return", "whether", "or", "not", "the", "competency", "IDs", "share", "the", "same", "framework", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L676-L681
216,063
moodle/moodle
competency/classes/competency.php
competency.get_framework_depth
public static function get_framework_depth($frameworkid) { global $DB; $totallength = $DB->sql_length('path'); $trimmedlength = $DB->sql_length("REPLACE(path, '/', '')"); $sql = "SELECT ($totallength - $trimmedlength - 1) AS depth FROM {" . self::TABLE . "} WHERE competencyframeworkid = :id ORDER BY depth DESC"; $record = $DB->get_record_sql($sql, array('id' => $frameworkid), IGNORE_MULTIPLE); if (!$record) { $depth = 0; } else { $depth = $record->depth; } return $depth; }
php
public static function get_framework_depth($frameworkid) { global $DB; $totallength = $DB->sql_length('path'); $trimmedlength = $DB->sql_length("REPLACE(path, '/', '')"); $sql = "SELECT ($totallength - $trimmedlength - 1) AS depth FROM {" . self::TABLE . "} WHERE competencyframeworkid = :id ORDER BY depth DESC"; $record = $DB->get_record_sql($sql, array('id' => $frameworkid), IGNORE_MULTIPLE); if (!$record) { $depth = 0; } else { $depth = $record->depth; } return $depth; }
[ "public", "static", "function", "get_framework_depth", "(", "$", "frameworkid", ")", "{", "global", "$", "DB", ";", "$", "totallength", "=", "$", "DB", "->", "sql_length", "(", "'path'", ")", ";", "$", "trimmedlength", "=", "$", "DB", "->", "sql_length", "(", "\"REPLACE(path, '/', '')\"", ")", ";", "$", "sql", "=", "\"SELECT ($totallength - $trimmedlength - 1) AS depth\n FROM {\"", ".", "self", "::", "TABLE", ".", "\"}\n WHERE competencyframeworkid = :id\n ORDER BY depth DESC\"", ";", "$", "record", "=", "$", "DB", "->", "get_record_sql", "(", "$", "sql", ",", "array", "(", "'id'", "=>", "$", "frameworkid", ")", ",", "IGNORE_MULTIPLE", ")", ";", "if", "(", "!", "$", "record", ")", "{", "$", "depth", "=", "0", ";", "}", "else", "{", "$", "depth", "=", "$", "record", "->", "depth", ";", "}", "return", "$", "depth", ";", "}" ]
Return the current depth of a competency framework. @param int $frameworkid The framework ID. @return int
[ "Return", "the", "current", "depth", "of", "a", "competency", "framework", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L703-L718
216,064
moodle/moodle
competency/classes/competency.php
competency.build_tree
protected static function build_tree($all, $parentid) { $tree = array(); foreach ($all as $one) { if ($one->get('parentid') == $parentid) { $node = new stdClass(); $node->competency = $one; $node->children = self::build_tree($all, $one->get('id')); $tree[] = $node; } } return $tree; }
php
protected static function build_tree($all, $parentid) { $tree = array(); foreach ($all as $one) { if ($one->get('parentid') == $parentid) { $node = new stdClass(); $node->competency = $one; $node->children = self::build_tree($all, $one->get('id')); $tree[] = $node; } } return $tree; }
[ "protected", "static", "function", "build_tree", "(", "$", "all", ",", "$", "parentid", ")", "{", "$", "tree", "=", "array", "(", ")", ";", "foreach", "(", "$", "all", "as", "$", "one", ")", "{", "if", "(", "$", "one", "->", "get", "(", "'parentid'", ")", "==", "$", "parentid", ")", "{", "$", "node", "=", "new", "stdClass", "(", ")", ";", "$", "node", "->", "competency", "=", "$", "one", ";", "$", "node", "->", "children", "=", "self", "::", "build_tree", "(", "$", "all", ",", "$", "one", "->", "get", "(", "'id'", ")", ")", ";", "$", "tree", "[", "]", "=", "$", "node", ";", "}", "}", "return", "$", "tree", ";", "}" ]
Recursively build up the tree of nodes. @param array $all - List of all competency classes. @param int $parentid - The current parent ID. Pass 0 to build the tree from the top. @return node[] $tree tree of nodes
[ "Recursively", "build", "up", "the", "tree", "of", "nodes", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L747-L758
216,065
moodle/moodle
competency/classes/competency.php
competency.can_all_be_deleted
public static function can_all_be_deleted($ids) { global $CFG; if (empty($ids)) { return true; } // Check if competency is used in template. if (template_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in plan. if (plan_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in course. if (course_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in user_competency. if (user_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in user_competency_plan. if (user_competency_plan::has_records_for_competencies($ids)) { return false; } require_once($CFG->libdir . '/badgeslib.php'); // Check if competency is used in a badge. if (badge_award_criteria_competency_has_records_for_competencies($ids)) { return false; } return true; }
php
public static function can_all_be_deleted($ids) { global $CFG; if (empty($ids)) { return true; } // Check if competency is used in template. if (template_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in plan. if (plan_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in course. if (course_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in user_competency. if (user_competency::has_records_for_competencies($ids)) { return false; } // Check if competency is used in user_competency_plan. if (user_competency_plan::has_records_for_competencies($ids)) { return false; } require_once($CFG->libdir . '/badgeslib.php'); // Check if competency is used in a badge. if (badge_award_criteria_competency_has_records_for_competencies($ids)) { return false; } return true; }
[ "public", "static", "function", "can_all_be_deleted", "(", "$", "ids", ")", "{", "global", "$", "CFG", ";", "if", "(", "empty", "(", "$", "ids", ")", ")", "{", "return", "true", ";", "}", "// Check if competency is used in template.", "if", "(", "template_competency", "::", "has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "// Check if competency is used in plan.", "if", "(", "plan_competency", "::", "has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "// Check if competency is used in course.", "if", "(", "course_competency", "::", "has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "// Check if competency is used in user_competency.", "if", "(", "user_competency", "::", "has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "// Check if competency is used in user_competency_plan.", "if", "(", "user_competency_plan", "::", "has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "require_once", "(", "$", "CFG", "->", "libdir", ".", "'/badgeslib.php'", ")", ";", "// Check if competency is used in a badge.", "if", "(", "badge_award_criteria_competency_has_records_for_competencies", "(", "$", "ids", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if we can delete competencies safely. This moethod does not check any capablities. Check if competency is used in a plan and user competency. Check if competency is used in a template. Check if competency is linked to a course. @param array $ids Array of competencies ids. @return bool True if we can delete the competencies.
[ "Check", "if", "we", "can", "delete", "competencies", "safely", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L771-L805
216,066
moodle/moodle
competency/classes/competency.php
competency.delete_multiple
public static function delete_multiple($ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED); return $DB->delete_records_select(self::TABLE, "id $insql", $params); }
php
public static function delete_multiple($ids) { global $DB; list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED); return $DB->delete_records_select(self::TABLE, "id $insql", $params); }
[ "public", "static", "function", "delete_multiple", "(", "$", "ids", ")", "{", "global", "$", "DB", ";", "list", "(", "$", "insql", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "ids", ",", "SQL_PARAMS_NAMED", ")", ";", "return", "$", "DB", "->", "delete_records_select", "(", "self", "::", "TABLE", ",", "\"id $insql\"", ",", "$", "params", ")", ";", "}" ]
Delete the competencies. This method is reserved to core usage. This method does not trigger the after_delete event. This method does not delete related objects such as related competencies and evidences. @param array $ids The competencies ids. @return bool True if the competencies were deleted successfully.
[ "Delete", "the", "competencies", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L817-L821
216,067
moodle/moodle
competency/classes/competency.php
competency.get_descendants_ids
public static function get_descendants_ids($competency) { global $DB; $path = $DB->sql_like_escape($competency->get('path') . $competency->get('id') . '/') . '%'; $like = $DB->sql_like('path', ':likepath'); return $DB->get_fieldset_select(self::TABLE, 'id', $like, array('likepath' => $path)); }
php
public static function get_descendants_ids($competency) { global $DB; $path = $DB->sql_like_escape($competency->get('path') . $competency->get('id') . '/') . '%'; $like = $DB->sql_like('path', ':likepath'); return $DB->get_fieldset_select(self::TABLE, 'id', $like, array('likepath' => $path)); }
[ "public", "static", "function", "get_descendants_ids", "(", "$", "competency", ")", "{", "global", "$", "DB", ";", "$", "path", "=", "$", "DB", "->", "sql_like_escape", "(", "$", "competency", "->", "get", "(", "'path'", ")", ".", "$", "competency", "->", "get", "(", "'id'", ")", ".", "'/'", ")", ".", "'%'", ";", "$", "like", "=", "$", "DB", "->", "sql_like", "(", "'path'", ",", "':likepath'", ")", ";", "return", "$", "DB", "->", "get_fieldset_select", "(", "self", "::", "TABLE", ",", "'id'", ",", "$", "like", ",", "array", "(", "'likepath'", "=>", "$", "path", ")", ")", ";", "}" ]
Get descendant ids. @param competency $competency The competency. @return array Array of competencies ids.
[ "Get", "descendant", "ids", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L829-L835
216,068
moodle/moodle
competency/classes/competency.php
competency.get_ancestors
public function get_ancestors() { global $DB; $ancestors = array(); $ancestorsids = explode('/', trim($this->get('path'), '/')); // Drop the root item from the array /0/. array_shift($ancestorsids); if (!empty($ancestorsids)) { list($insql, $params) = $DB->get_in_or_equal($ancestorsids, SQL_PARAMS_NAMED); $ancestors = self::get_records_select("id $insql", $params); } return $ancestors; }
php
public function get_ancestors() { global $DB; $ancestors = array(); $ancestorsids = explode('/', trim($this->get('path'), '/')); // Drop the root item from the array /0/. array_shift($ancestorsids); if (!empty($ancestorsids)) { list($insql, $params) = $DB->get_in_or_equal($ancestorsids, SQL_PARAMS_NAMED); $ancestors = self::get_records_select("id $insql", $params); } return $ancestors; }
[ "public", "function", "get_ancestors", "(", ")", "{", "global", "$", "DB", ";", "$", "ancestors", "=", "array", "(", ")", ";", "$", "ancestorsids", "=", "explode", "(", "'/'", ",", "trim", "(", "$", "this", "->", "get", "(", "'path'", ")", ",", "'/'", ")", ")", ";", "// Drop the root item from the array /0/.", "array_shift", "(", "$", "ancestorsids", ")", ";", "if", "(", "!", "empty", "(", "$", "ancestorsids", ")", ")", "{", "list", "(", "$", "insql", ",", "$", "params", ")", "=", "$", "DB", "->", "get_in_or_equal", "(", "$", "ancestorsids", ",", "SQL_PARAMS_NAMED", ")", ";", "$", "ancestors", "=", "self", "::", "get_records_select", "(", "\"id $insql\"", ",", "$", "params", ")", ";", "}", "return", "$", "ancestors", ";", "}" ]
Get competency ancestors. @return competency[] Return array of ancestors.
[ "Get", "competency", "ancestors", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/competency/classes/competency.php#L869-L880
216,069
moodle/moodle
lib/scssphp/SourceMap/Base64VLQEncoder.php
Base64VLQEncoder.zeroFill
public function zeroFill($a, $b) { return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1)); }
php
public function zeroFill($a, $b) { return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1)); }
[ "public", "function", "zeroFill", "(", "$", "a", ",", "$", "b", ")", "{", "return", "(", "$", "a", ">=", "0", ")", "?", "(", "$", "a", ">>", "$", "b", ")", ":", "(", "$", "a", ">>", "$", "b", ")", "&", "(", "PHP_INT_MAX", ">>", "(", "$", "b", "-", "1", ")", ")", ";", "}" ]
Right shift with zero fill. @param integer $a number to shift @param integer $b number of bits to shift @return integer
[ "Right", "shift", "with", "zero", "fill", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/scssphp/SourceMap/Base64VLQEncoder.php#L177-L180
216,070
moodle/moodle
lib/scssphp/SourceMap/Base64VLQEncoder.php
Base64VLQEncoder.base64Encode
public function base64Encode($number) { if ($number < 0 || $number > 63) { throw new \Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number)); } return $this->intToCharMap[$number]; }
php
public function base64Encode($number) { if ($number < 0 || $number > 63) { throw new \Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number)); } return $this->intToCharMap[$number]; }
[ "public", "function", "base64Encode", "(", "$", "number", ")", "{", "if", "(", "$", "number", "<", "0", "||", "$", "number", ">", "63", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Invalid number \"%s\" given. Must be between 0 and 63.'", ",", "$", "number", ")", ")", ";", "}", "return", "$", "this", "->", "intToCharMap", "[", "$", "number", "]", ";", "}" ]
Encode single 6-bit digit as base64. @param integer $number @return string @throws \Exception If the number is invalid
[ "Encode", "single", "6", "-", "bit", "digit", "as", "base64", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/scssphp/SourceMap/Base64VLQEncoder.php#L191-L198
216,071
moodle/moodle
question/type/ddmarker/question.php
qtype_ddmarker_question.arrays_same_at_key_integer
public function arrays_same_at_key_integer( array $array1, array $array2, $key) { if (array_key_exists($key, $array1)) { $value1 = $array1[$key]; } else { $value1 = ''; } if (array_key_exists($key, $array2)) { $value2 = $array2[$key]; } else { $value2 = ''; } $coords1 = explode(';', $value1); $coords2 = explode(';', $value2); if (count($coords1) !== count($coords2)) { return false; } else if (count($coords1) === 0) { return true; } else { $valuesinbotharrays = $this->array_intersect_fixed($coords1, $coords2); return (count($valuesinbotharrays) == count($coords1)); } }
php
public function arrays_same_at_key_integer( array $array1, array $array2, $key) { if (array_key_exists($key, $array1)) { $value1 = $array1[$key]; } else { $value1 = ''; } if (array_key_exists($key, $array2)) { $value2 = $array2[$key]; } else { $value2 = ''; } $coords1 = explode(';', $value1); $coords2 = explode(';', $value2); if (count($coords1) !== count($coords2)) { return false; } else if (count($coords1) === 0) { return true; } else { $valuesinbotharrays = $this->array_intersect_fixed($coords1, $coords2); return (count($valuesinbotharrays) == count($coords1)); } }
[ "public", "function", "arrays_same_at_key_integer", "(", "array", "$", "array1", ",", "array", "$", "array2", ",", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "array1", ")", ")", "{", "$", "value1", "=", "$", "array1", "[", "$", "key", "]", ";", "}", "else", "{", "$", "value1", "=", "''", ";", "}", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "array2", ")", ")", "{", "$", "value2", "=", "$", "array2", "[", "$", "key", "]", ";", "}", "else", "{", "$", "value2", "=", "''", ";", "}", "$", "coords1", "=", "explode", "(", "';'", ",", "$", "value1", ")", ";", "$", "coords2", "=", "explode", "(", "';'", ",", "$", "value2", ")", ";", "if", "(", "count", "(", "$", "coords1", ")", "!==", "count", "(", "$", "coords2", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "count", "(", "$", "coords1", ")", "===", "0", ")", "{", "return", "true", ";", "}", "else", "{", "$", "valuesinbotharrays", "=", "$", "this", "->", "array_intersect_fixed", "(", "$", "coords1", ",", "$", "coords2", ")", ";", "return", "(", "count", "(", "$", "valuesinbotharrays", ")", "==", "count", "(", "$", "coords1", ")", ")", ";", "}", "}" ]
Tests to see whether two arrays have the same set of coords at a particular key. Coords can be in any order. @param array $array1 the first array. @param array $array2 the second array. @param string $key an array key. @return bool whether the two arrays have the same set of coords (or lack of them) for a given key.
[ "Tests", "to", "see", "whether", "two", "arrays", "have", "the", "same", "set", "of", "coords", "at", "a", "particular", "key", ".", "Coords", "can", "be", "in", "any", "order", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/ddmarker/question.php#L105-L127
216,072
moodle/moodle
question/type/ddmarker/question.php
qtype_ddmarker_question.choose_hits
protected function choose_hits(array $response) { $allhits = $this->get_all_hits($response); $chosenhits = array(); foreach ($allhits as $placeno => $hits) { foreach ($hits as $itemno => $hit) { $choice = $this->get_right_choice_for($placeno); $choiceitem = "$choice $itemno"; if (!in_array($choiceitem, $chosenhits)) { $chosenhits[$placeno] = $choiceitem; break; } } } return $chosenhits; }
php
protected function choose_hits(array $response) { $allhits = $this->get_all_hits($response); $chosenhits = array(); foreach ($allhits as $placeno => $hits) { foreach ($hits as $itemno => $hit) { $choice = $this->get_right_choice_for($placeno); $choiceitem = "$choice $itemno"; if (!in_array($choiceitem, $chosenhits)) { $chosenhits[$placeno] = $choiceitem; break; } } } return $chosenhits; }
[ "protected", "function", "choose_hits", "(", "array", "$", "response", ")", "{", "$", "allhits", "=", "$", "this", "->", "get_all_hits", "(", "$", "response", ")", ";", "$", "chosenhits", "=", "array", "(", ")", ";", "foreach", "(", "$", "allhits", "as", "$", "placeno", "=>", "$", "hits", ")", "{", "foreach", "(", "$", "hits", "as", "$", "itemno", "=>", "$", "hit", ")", "{", "$", "choice", "=", "$", "this", "->", "get_right_choice_for", "(", "$", "placeno", ")", ";", "$", "choiceitem", "=", "\"$choice $itemno\"", ";", "if", "(", "!", "in_array", "(", "$", "choiceitem", ",", "$", "chosenhits", ")", ")", "{", "$", "chosenhits", "[", "$", "placeno", "]", "=", "$", "choiceitem", ";", "break", ";", "}", "}", "}", "return", "$", "chosenhits", ";", "}" ]
Choose hits to maximize grade where drop targets may have more than one hit and drop targets can overlap. @param array $response @return array chosen hits
[ "Choose", "hits", "to", "maximize", "grade", "where", "drop", "targets", "may", "have", "more", "than", "one", "hit", "and", "drop", "targets", "can", "overlap", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/ddmarker/question.php#L169-L183
216,073
moodle/moodle
question/type/ddmarker/question.php
qtype_ddmarker_question.get_all_hits
protected function get_all_hits(array $response) { $hits = array(); foreach ($this->places as $placeno => $place) { $rightchoice = $this->get_right_choice_for($placeno); $rightchoicekey = $this->choice($rightchoice); if (!array_key_exists($rightchoicekey, $response)) { continue; } $choicecoords = $response[$rightchoicekey]; $coords = explode(';', $choicecoords); foreach ($coords as $itemno => $coord) { if (trim($coord) === '') { continue; } $pointxy = explode(',', $coord); $pointxy[0] = round($pointxy[0]); $pointxy[1] = round($pointxy[1]); if ($place->drop_hit($pointxy)) { if (!isset($hits[$placeno])) { $hits[$placeno] = array(); } $hits[$placeno][$itemno] = $coord; } } } // Reverse sort in order of number of hits per place (if two or more // hits per place then we want to make sure hits do not hit elsewhere). $sortcomparison = function ($a1, $a2){ return (count($a1) - count($a2)); }; uasort($hits, $sortcomparison); return $hits; }
php
protected function get_all_hits(array $response) { $hits = array(); foreach ($this->places as $placeno => $place) { $rightchoice = $this->get_right_choice_for($placeno); $rightchoicekey = $this->choice($rightchoice); if (!array_key_exists($rightchoicekey, $response)) { continue; } $choicecoords = $response[$rightchoicekey]; $coords = explode(';', $choicecoords); foreach ($coords as $itemno => $coord) { if (trim($coord) === '') { continue; } $pointxy = explode(',', $coord); $pointxy[0] = round($pointxy[0]); $pointxy[1] = round($pointxy[1]); if ($place->drop_hit($pointxy)) { if (!isset($hits[$placeno])) { $hits[$placeno] = array(); } $hits[$placeno][$itemno] = $coord; } } } // Reverse sort in order of number of hits per place (if two or more // hits per place then we want to make sure hits do not hit elsewhere). $sortcomparison = function ($a1, $a2){ return (count($a1) - count($a2)); }; uasort($hits, $sortcomparison); return $hits; }
[ "protected", "function", "get_all_hits", "(", "array", "$", "response", ")", "{", "$", "hits", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "places", "as", "$", "placeno", "=>", "$", "place", ")", "{", "$", "rightchoice", "=", "$", "this", "->", "get_right_choice_for", "(", "$", "placeno", ")", ";", "$", "rightchoicekey", "=", "$", "this", "->", "choice", "(", "$", "rightchoice", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "rightchoicekey", ",", "$", "response", ")", ")", "{", "continue", ";", "}", "$", "choicecoords", "=", "$", "response", "[", "$", "rightchoicekey", "]", ";", "$", "coords", "=", "explode", "(", "';'", ",", "$", "choicecoords", ")", ";", "foreach", "(", "$", "coords", "as", "$", "itemno", "=>", "$", "coord", ")", "{", "if", "(", "trim", "(", "$", "coord", ")", "===", "''", ")", "{", "continue", ";", "}", "$", "pointxy", "=", "explode", "(", "','", ",", "$", "coord", ")", ";", "$", "pointxy", "[", "0", "]", "=", "round", "(", "$", "pointxy", "[", "0", "]", ")", ";", "$", "pointxy", "[", "1", "]", "=", "round", "(", "$", "pointxy", "[", "1", "]", ")", ";", "if", "(", "$", "place", "->", "drop_hit", "(", "$", "pointxy", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "hits", "[", "$", "placeno", "]", ")", ")", "{", "$", "hits", "[", "$", "placeno", "]", "=", "array", "(", ")", ";", "}", "$", "hits", "[", "$", "placeno", "]", "[", "$", "itemno", "]", "=", "$", "coord", ";", "}", "}", "}", "// Reverse sort in order of number of hits per place (if two or more", "// hits per place then we want to make sure hits do not hit elsewhere).", "$", "sortcomparison", "=", "function", "(", "$", "a1", ",", "$", "a2", ")", "{", "return", "(", "count", "(", "$", "a1", ")", "-", "count", "(", "$", "a2", ")", ")", ";", "}", ";", "uasort", "(", "$", "hits", ",", "$", "sortcomparison", ")", ";", "return", "$", "hits", ";", "}" ]
Get's an array of all hits on drop targets. Needs further processing to find which hits to select in the general case that drop targets may have more than one hit and drop targets can overlap. @param array $response @return array all hits
[ "Get", "s", "an", "array", "of", "all", "hits", "on", "drop", "targets", ".", "Needs", "further", "processing", "to", "find", "which", "hits", "to", "select", "in", "the", "general", "case", "that", "drop", "targets", "may", "have", "more", "than", "one", "hit", "and", "drop", "targets", "can", "overlap", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/question/type/ddmarker/question.php#L202-L234
216,074
moodle/moodle
lib/phpmailer/moodle_phpmailer.php
moodle_phpmailer.encodeHeader
public function encodeHeader($str, $position = 'text') { $encoded = core_text::encode_mimeheader($str, $this->CharSet); if ($encoded !== false) { if ($position === 'phrase') { // Escape special symbols in each line in the encoded string, join back together and enclose in quotes. $chunks = preg_split("/\\n/", $encoded); $chunks = array_map(function($chunk) { return addcslashes($chunk, "\0..\37\177\\\""); }, $chunks); return '"' . join(parent::getLE(), $chunks) . '"'; } return str_replace("\n", parent::getLE(), $encoded); } return parent::encodeHeader($str, $position); }
php
public function encodeHeader($str, $position = 'text') { $encoded = core_text::encode_mimeheader($str, $this->CharSet); if ($encoded !== false) { if ($position === 'phrase') { // Escape special symbols in each line in the encoded string, join back together and enclose in quotes. $chunks = preg_split("/\\n/", $encoded); $chunks = array_map(function($chunk) { return addcslashes($chunk, "\0..\37\177\\\""); }, $chunks); return '"' . join(parent::getLE(), $chunks) . '"'; } return str_replace("\n", parent::getLE(), $encoded); } return parent::encodeHeader($str, $position); }
[ "public", "function", "encodeHeader", "(", "$", "str", ",", "$", "position", "=", "'text'", ")", "{", "$", "encoded", "=", "core_text", "::", "encode_mimeheader", "(", "$", "str", ",", "$", "this", "->", "CharSet", ")", ";", "if", "(", "$", "encoded", "!==", "false", ")", "{", "if", "(", "$", "position", "===", "'phrase'", ")", "{", "// Escape special symbols in each line in the encoded string, join back together and enclose in quotes.", "$", "chunks", "=", "preg_split", "(", "\"/\\\\n/\"", ",", "$", "encoded", ")", ";", "$", "chunks", "=", "array_map", "(", "function", "(", "$", "chunk", ")", "{", "return", "addcslashes", "(", "$", "chunk", ",", "\"\\0..\\37\\177\\\\\\\"\"", ")", ";", "}", ",", "$", "chunks", ")", ";", "return", "'\"'", ".", "join", "(", "parent", "::", "getLE", "(", ")", ",", "$", "chunks", ")", ".", "'\"'", ";", "}", "return", "str_replace", "(", "\"\\n\"", ",", "parent", "::", "getLE", "(", ")", ",", "$", "encoded", ")", ";", "}", "return", "parent", "::", "encodeHeader", "(", "$", "str", ",", "$", "position", ")", ";", "}" ]
Use internal moodles own core_text to encode mimeheaders. Fall back to phpmailers inbuilt functions if not
[ "Use", "internal", "moodles", "own", "core_text", "to", "encode", "mimeheaders", ".", "Fall", "back", "to", "phpmailers", "inbuilt", "functions", "if", "not" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpmailer/moodle_phpmailer.php#L88-L103
216,075
moodle/moodle
lib/phpmailer/moodle_phpmailer.php
moodle_phpmailer.postSend
public function postSend() { // Now ask phpunit if it wants to catch this message. if (PHPUNIT_TEST) { if (!phpunit_util::is_redirecting_phpmailer()) { debugging('Unit tests must not send real emails! Use $this->redirectEmails()'); return true; } $mail = new stdClass(); $mail->header = $this->MIMEHeader; $mail->body = $this->MIMEBody; $mail->subject = $this->Subject; $mail->from = $this->From; $mail->to = $this->to[0][0]; phpunit_util::phpmailer_sent($mail); return true; } else { return parent::postSend(); } }
php
public function postSend() { // Now ask phpunit if it wants to catch this message. if (PHPUNIT_TEST) { if (!phpunit_util::is_redirecting_phpmailer()) { debugging('Unit tests must not send real emails! Use $this->redirectEmails()'); return true; } $mail = new stdClass(); $mail->header = $this->MIMEHeader; $mail->body = $this->MIMEBody; $mail->subject = $this->Subject; $mail->from = $this->From; $mail->to = $this->to[0][0]; phpunit_util::phpmailer_sent($mail); return true; } else { return parent::postSend(); } }
[ "public", "function", "postSend", "(", ")", "{", "// Now ask phpunit if it wants to catch this message.", "if", "(", "PHPUNIT_TEST", ")", "{", "if", "(", "!", "phpunit_util", "::", "is_redirecting_phpmailer", "(", ")", ")", "{", "debugging", "(", "'Unit tests must not send real emails! Use $this->redirectEmails()'", ")", ";", "return", "true", ";", "}", "$", "mail", "=", "new", "stdClass", "(", ")", ";", "$", "mail", "->", "header", "=", "$", "this", "->", "MIMEHeader", ";", "$", "mail", "->", "body", "=", "$", "this", "->", "MIMEBody", ";", "$", "mail", "->", "subject", "=", "$", "this", "->", "Subject", ";", "$", "mail", "->", "from", "=", "$", "this", "->", "From", ";", "$", "mail", "->", "to", "=", "$", "this", "->", "to", "[", "0", "]", "[", "0", "]", ";", "phpunit_util", "::", "phpmailer_sent", "(", "$", "mail", ")", ";", "return", "true", ";", "}", "else", "{", "return", "parent", "::", "postSend", "(", ")", ";", "}", "}" ]
Sends this mail. This function has been overridden to facilitate unit testing. @return bool
[ "Sends", "this", "mail", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/phpmailer/moodle_phpmailer.php#L126-L144
216,076
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.get_sql_where
public function get_sql_where() { list($where, $params) = parent::get_sql_where(); $where = preg_replace('/firstname/', 'u.firstname', $where); $where = preg_replace('/lastname/', 'u.lastname', $where); return [$where, $params]; }
php
public function get_sql_where() { list($where, $params) = parent::get_sql_where(); $where = preg_replace('/firstname/', 'u.firstname', $where); $where = preg_replace('/lastname/', 'u.lastname', $where); return [$where, $params]; }
[ "public", "function", "get_sql_where", "(", ")", "{", "list", "(", "$", "where", ",", "$", "params", ")", "=", "parent", "::", "get_sql_where", "(", ")", ";", "$", "where", "=", "preg_replace", "(", "'/firstname/'", ",", "'u.firstname'", ",", "$", "where", ")", ";", "$", "where", "=", "preg_replace", "(", "'/lastname/'", ",", "'u.lastname'", ",", "$", "where", ")", ";", "return", "[", "$", "where", ",", "$", "params", "]", ";", "}" ]
Get sql to add to where statement. @return string
[ "Get", "sql", "to", "add", "to", "where", "statement", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L246-L251
216,077
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.build_sql_for_roles_filter
protected function build_sql_for_roles_filter() { foreach ($this->acceptancesfilter->get_role_filters() as $roleid) { $this->sql->where .= ' AND ' . $this->sql_has_role([$roleid => $roleid]); } }
php
protected function build_sql_for_roles_filter() { foreach ($this->acceptancesfilter->get_role_filters() as $roleid) { $this->sql->where .= ' AND ' . $this->sql_has_role([$roleid => $roleid]); } }
[ "protected", "function", "build_sql_for_roles_filter", "(", ")", "{", "foreach", "(", "$", "this", "->", "acceptancesfilter", "->", "get_role_filters", "(", ")", "as", "$", "roleid", ")", "{", "$", "this", "->", "sql", "->", "where", ".=", "' AND '", ".", "$", "this", "->", "sql_has_role", "(", "[", "$", "roleid", "=>", "$", "roleid", "]", ")", ";", "}", "}" ]
If there is a filter by user roles add it to the SQL query.
[ "If", "there", "is", "a", "filter", "by", "user", "roles", "add", "it", "to", "the", "SQL", "query", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L409-L413
216,078
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.col_fullname
public function col_fullname($row) { global $OUTPUT; $userpic = $this->is_downloading() ? '' : $OUTPUT->user_picture($row->user); return $userpic . $this->username($row->user, true); }
php
public function col_fullname($row) { global $OUTPUT; $userpic = $this->is_downloading() ? '' : $OUTPUT->user_picture($row->user); return $userpic . $this->username($row->user, true); }
[ "public", "function", "col_fullname", "(", "$", "row", ")", "{", "global", "$", "OUTPUT", ";", "$", "userpic", "=", "$", "this", "->", "is_downloading", "(", ")", "?", "''", ":", "$", "OUTPUT", "->", "user_picture", "(", "$", "row", "->", "user", ")", ";", "return", "$", "userpic", ".", "$", "this", "->", "username", "(", "$", "row", "->", "user", ",", "true", ")", ";", "}" ]
Get the column fullname value. @param stdClass $row @return string
[ "Get", "the", "column", "fullname", "value", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L491-L495
216,079
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.username
protected function username($user, $profilelink = true) { $canviewfullnames = has_capability('moodle/site:viewfullnames', \context_system::instance()) || has_capability('moodle/site:viewfullnames', \context_user::instance($user->id)); $name = fullname($user, $canviewfullnames); if (!$this->is_downloading() && $profilelink) { $profileurl = new \moodle_url('/user/profile.php', array('id' => $user->id)); return \html_writer::link($profileurl, $name); } return $name; }
php
protected function username($user, $profilelink = true) { $canviewfullnames = has_capability('moodle/site:viewfullnames', \context_system::instance()) || has_capability('moodle/site:viewfullnames', \context_user::instance($user->id)); $name = fullname($user, $canviewfullnames); if (!$this->is_downloading() && $profilelink) { $profileurl = new \moodle_url('/user/profile.php', array('id' => $user->id)); return \html_writer::link($profileurl, $name); } return $name; }
[ "protected", "function", "username", "(", "$", "user", ",", "$", "profilelink", "=", "true", ")", "{", "$", "canviewfullnames", "=", "has_capability", "(", "'moodle/site:viewfullnames'", ",", "\\", "context_system", "::", "instance", "(", ")", ")", "||", "has_capability", "(", "'moodle/site:viewfullnames'", ",", "\\", "context_user", "::", "instance", "(", "$", "user", "->", "id", ")", ")", ";", "$", "name", "=", "fullname", "(", "$", "user", ",", "$", "canviewfullnames", ")", ";", "if", "(", "!", "$", "this", "->", "is_downloading", "(", ")", "&&", "$", "profilelink", ")", "{", "$", "profileurl", "=", "new", "\\", "moodle_url", "(", "'/user/profile.php'", ",", "array", "(", "'id'", "=>", "$", "user", "->", "id", ")", ")", ";", "return", "\\", "html_writer", "::", "link", "(", "$", "profileurl", ",", "$", "name", ")", ";", "}", "return", "$", "name", ";", "}" ]
User name with a link to profile @param stdClass $user @param bool $profilelink show link to profile (when we are downloading never show links) @return string
[ "User", "name", "with", "a", "link", "to", "profile" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L504-L513
216,080
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.status
protected function status($versionid, $row) { $onbehalf = false; $versions = $versionid ? [$versionid => $this->versionids[$versionid]] : $this->versionids; // List of versions. $accepted = []; // List of versionids that user has accepted. $declined = []; foreach ($versions as $v => $name) { if ($row->{'status' . $v} !== null) { if (empty($row->{'status' . $v})) { $declined[] = $v; } else { $accepted[] = $v; } $agreedby = $row->{'usermodified' . $v}; if ($agreedby && $agreedby != $row->id) { $onbehalf = true; } } } $ua = new user_agreement($row->id, $accepted, $declined, $this->get_return_url(), $versions, $onbehalf, $row->canaccept); if ($this->is_downloading()) { return $ua->export_for_download(); } else { return $this->output->render($ua); } }
php
protected function status($versionid, $row) { $onbehalf = false; $versions = $versionid ? [$versionid => $this->versionids[$versionid]] : $this->versionids; // List of versions. $accepted = []; // List of versionids that user has accepted. $declined = []; foreach ($versions as $v => $name) { if ($row->{'status' . $v} !== null) { if (empty($row->{'status' . $v})) { $declined[] = $v; } else { $accepted[] = $v; } $agreedby = $row->{'usermodified' . $v}; if ($agreedby && $agreedby != $row->id) { $onbehalf = true; } } } $ua = new user_agreement($row->id, $accepted, $declined, $this->get_return_url(), $versions, $onbehalf, $row->canaccept); if ($this->is_downloading()) { return $ua->export_for_download(); } else { return $this->output->render($ua); } }
[ "protected", "function", "status", "(", "$", "versionid", ",", "$", "row", ")", "{", "$", "onbehalf", "=", "false", ";", "$", "versions", "=", "$", "versionid", "?", "[", "$", "versionid", "=>", "$", "this", "->", "versionids", "[", "$", "versionid", "]", "]", ":", "$", "this", "->", "versionids", ";", "// List of versions.", "$", "accepted", "=", "[", "]", ";", "// List of versionids that user has accepted.", "$", "declined", "=", "[", "]", ";", "foreach", "(", "$", "versions", "as", "$", "v", "=>", "$", "name", ")", "{", "if", "(", "$", "row", "->", "{", "'status'", ".", "$", "v", "}", "!==", "null", ")", "{", "if", "(", "empty", "(", "$", "row", "->", "{", "'status'", ".", "$", "v", "}", ")", ")", "{", "$", "declined", "[", "]", "=", "$", "v", ";", "}", "else", "{", "$", "accepted", "[", "]", "=", "$", "v", ";", "}", "$", "agreedby", "=", "$", "row", "->", "{", "'usermodified'", ".", "$", "v", "}", ";", "if", "(", "$", "agreedby", "&&", "$", "agreedby", "!=", "$", "row", "->", "id", ")", "{", "$", "onbehalf", "=", "true", ";", "}", "}", "}", "$", "ua", "=", "new", "user_agreement", "(", "$", "row", "->", "id", ",", "$", "accepted", ",", "$", "declined", ",", "$", "this", "->", "get_return_url", "(", ")", ",", "$", "versions", ",", "$", "onbehalf", ",", "$", "row", "->", "canaccept", ")", ";", "if", "(", "$", "this", "->", "is_downloading", "(", ")", ")", "{", "return", "$", "ua", "->", "export_for_download", "(", ")", ";", "}", "else", "{", "return", "$", "this", "->", "output", "->", "render", "(", "$", "ua", ")", ";", "}", "}" ]
Return agreement status @param int $versionid either id of an individual version or empty for overall status @param stdClass $row @return string
[ "Return", "agreement", "status" ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L533-L561
216,081
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.col_timemodified
public function col_timemodified($row) { if ($row->timemodified) { if ($this->is_downloading()) { // Use timestamp format readable for both machines and humans. return date_format_string($row->timemodified, '%Y-%m-%d %H:%M:%S %Z'); } else { // Use localised calendar format. return userdate($row->timemodified, get_string('strftimedatetime')); } } else { return null; } }
php
public function col_timemodified($row) { if ($row->timemodified) { if ($this->is_downloading()) { // Use timestamp format readable for both machines and humans. return date_format_string($row->timemodified, '%Y-%m-%d %H:%M:%S %Z'); } else { // Use localised calendar format. return userdate($row->timemodified, get_string('strftimedatetime')); } } else { return null; } }
[ "public", "function", "col_timemodified", "(", "$", "row", ")", "{", "if", "(", "$", "row", "->", "timemodified", ")", "{", "if", "(", "$", "this", "->", "is_downloading", "(", ")", ")", "{", "// Use timestamp format readable for both machines and humans.", "return", "date_format_string", "(", "$", "row", "->", "timemodified", ",", "'%Y-%m-%d %H:%M:%S %Z'", ")", ";", "}", "else", "{", "// Use localised calendar format.", "return", "userdate", "(", "$", "row", "->", "timemodified", ",", "get_string", "(", "'strftimedatetime'", ")", ")", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the column timemodified value. @param stdClass $row @return string
[ "Get", "the", "column", "timemodified", "value", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L569-L581
216,082
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.col_note
public function col_note($row) { if ($this->is_downloading()) { return $row->note; } else { return format_text($row->note, FORMAT_MOODLE); } }
php
public function col_note($row) { if ($this->is_downloading()) { return $row->note; } else { return format_text($row->note, FORMAT_MOODLE); } }
[ "public", "function", "col_note", "(", "$", "row", ")", "{", "if", "(", "$", "this", "->", "is_downloading", "(", ")", ")", "{", "return", "$", "row", "->", "note", ";", "}", "else", "{", "return", "format_text", "(", "$", "row", "->", "note", ",", "FORMAT_MOODLE", ")", ";", "}", "}" ]
Get the column note value. @param stdClass $row @return string
[ "Get", "the", "column", "note", "value", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L589-L595
216,083
moodle/moodle
admin/tool/policy/classes/acceptances_table.php
acceptances_table.other_cols
public function other_cols($column, $row) { if (preg_match('/^status([\d]+)$/', $column, $matches)) { $versionid = $matches[1]; return $this->status($versionid, $row); } if (preg_match('/^usermodified([\d]+)$/', $column, $matches)) { if ($row->$column && $row->$column != $row->id) { $user = (object)['id' => $row->$column]; username_load_fields_from_object($user, $row, 'mod'); return $this->username($user, true); } return ''; // User agreed by themselves. } return null; }
php
public function other_cols($column, $row) { if (preg_match('/^status([\d]+)$/', $column, $matches)) { $versionid = $matches[1]; return $this->status($versionid, $row); } if (preg_match('/^usermodified([\d]+)$/', $column, $matches)) { if ($row->$column && $row->$column != $row->id) { $user = (object)['id' => $row->$column]; username_load_fields_from_object($user, $row, 'mod'); return $this->username($user, true); } return ''; // User agreed by themselves. } return null; }
[ "public", "function", "other_cols", "(", "$", "column", ",", "$", "row", ")", "{", "if", "(", "preg_match", "(", "'/^status([\\d]+)$/'", ",", "$", "column", ",", "$", "matches", ")", ")", "{", "$", "versionid", "=", "$", "matches", "[", "1", "]", ";", "return", "$", "this", "->", "status", "(", "$", "versionid", ",", "$", "row", ")", ";", "}", "if", "(", "preg_match", "(", "'/^usermodified([\\d]+)$/'", ",", "$", "column", ",", "$", "matches", ")", ")", "{", "if", "(", "$", "row", "->", "$", "column", "&&", "$", "row", "->", "$", "column", "!=", "$", "row", "->", "id", ")", "{", "$", "user", "=", "(", "object", ")", "[", "'id'", "=>", "$", "row", "->", "$", "column", "]", ";", "username_load_fields_from_object", "(", "$", "user", ",", "$", "row", ",", "'mod'", ")", ";", "return", "$", "this", "->", "username", "(", "$", "user", ",", "true", ")", ";", "}", "return", "''", ";", "// User agreed by themselves.", "}", "return", "null", ";", "}" ]
You can override this method in a child class. See the description of build_table which calls this method. @param string $column @param stdClass $row @return string
[ "You", "can", "override", "this", "method", "in", "a", "child", "class", ".", "See", "the", "description", "of", "build_table", "which", "calls", "this", "method", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/admin/tool/policy/classes/acceptances_table.php#L631-L645
216,084
moodle/moodle
filter/local_settings_form.php
filter_local_settings_form.definition
public function definition() { $mform = $this->_form; $this->definition_inner($mform); $mform->addElement('hidden', 'contextid'); $mform->setType('contextid', PARAM_INT); $mform->setDefault('contextid', $this->context->id); $mform->addElement('hidden', 'filter'); $mform->setType('filter', PARAM_SAFEPATH); $mform->setDefault('filter', $this->filter); $this->add_action_buttons(); }
php
public function definition() { $mform = $this->_form; $this->definition_inner($mform); $mform->addElement('hidden', 'contextid'); $mform->setType('contextid', PARAM_INT); $mform->setDefault('contextid', $this->context->id); $mform->addElement('hidden', 'filter'); $mform->setType('filter', PARAM_SAFEPATH); $mform->setDefault('filter', $this->filter); $this->add_action_buttons(); }
[ "public", "function", "definition", "(", ")", "{", "$", "mform", "=", "$", "this", "->", "_form", ";", "$", "this", "->", "definition_inner", "(", "$", "mform", ")", ";", "$", "mform", "->", "addElement", "(", "'hidden'", ",", "'contextid'", ")", ";", "$", "mform", "->", "setType", "(", "'contextid'", ",", "PARAM_INT", ")", ";", "$", "mform", "->", "setDefault", "(", "'contextid'", ",", "$", "this", "->", "context", "->", "id", ")", ";", "$", "mform", "->", "addElement", "(", "'hidden'", ",", "'filter'", ")", ";", "$", "mform", "->", "setType", "(", "'filter'", ",", "PARAM_SAFEPATH", ")", ";", "$", "mform", "->", "setDefault", "(", "'filter'", ",", "$", "this", "->", "filter", ")", ";", "$", "this", "->", "add_action_buttons", "(", ")", ";", "}" ]
Build the form definition. Rather than overriding this method, you should probably override definition_inner instead. This method adds the necessary hidden fields and submit buttons, and calls definition_inner to insert the custom controls in the appropriate place.
[ "Build", "the", "form", "definition", ".", "Rather", "than", "overriding", "this", "method", "you", "should", "probably", "override", "definition_inner", "instead", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/filter/local_settings_form.php#L46-L60
216,085
moodle/moodle
filter/local_settings_form.php
filter_local_settings_form.save_changes
public function save_changes($data) { $data = (array) $data; unset($data['filter']); unset($data['contextid']); foreach ($data as $name => $value) { if ($value !== '') { filter_set_local_config($this->filter, $this->context->id, $name, $value); } else { filter_unset_local_config($this->filter, $this->context->id, $name); } } }
php
public function save_changes($data) { $data = (array) $data; unset($data['filter']); unset($data['contextid']); foreach ($data as $name => $value) { if ($value !== '') { filter_set_local_config($this->filter, $this->context->id, $name, $value); } else { filter_unset_local_config($this->filter, $this->context->id, $name); } } }
[ "public", "function", "save_changes", "(", "$", "data", ")", "{", "$", "data", "=", "(", "array", ")", "$", "data", ";", "unset", "(", "$", "data", "[", "'filter'", "]", ")", ";", "unset", "(", "$", "data", "[", "'contextid'", "]", ")", ";", "foreach", "(", "$", "data", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "!==", "''", ")", "{", "filter_set_local_config", "(", "$", "this", "->", "filter", ",", "$", "this", "->", "context", "->", "id", ",", "$", "name", ",", "$", "value", ")", ";", "}", "else", "{", "filter_unset_local_config", "(", "$", "this", "->", "filter", ",", "$", "this", "->", "context", "->", "id", ",", "$", "name", ")", ";", "}", "}", "}" ]
Override this method to save the settings to the database. The default implementation will probably be sufficient for most simple cases. @param object $data the form data that was submitted.
[ "Override", "this", "method", "to", "save", "the", "settings", "to", "the", "database", ".", "The", "default", "implementation", "will", "probably", "be", "sufficient", "for", "most", "simple", "cases", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/filter/local_settings_form.php#L73-L84
216,086
moodle/moodle
grade/edit/tree/lib.php
grade_edit_tree.format_number
static function format_number($number) { $formatted = rtrim(format_float($number, 4),'0'); if (substr($formatted, -1)==get_string('decsep', 'langconfig')) { //if last char is the decimal point $formatted .= '0'; } return $formatted; }
php
static function format_number($number) { $formatted = rtrim(format_float($number, 4),'0'); if (substr($formatted, -1)==get_string('decsep', 'langconfig')) { //if last char is the decimal point $formatted .= '0'; } return $formatted; }
[ "static", "function", "format_number", "(", "$", "number", ")", "{", "$", "formatted", "=", "rtrim", "(", "format_float", "(", "$", "number", ",", "4", ")", ",", "'0'", ")", ";", "if", "(", "substr", "(", "$", "formatted", ",", "-", "1", ")", "==", "get_string", "(", "'decsep'", ",", "'langconfig'", ")", ")", "{", "//if last char is the decimal point", "$", "formatted", ".=", "'0'", ";", "}", "return", "$", "formatted", ";", "}" ]
Grader report has its own decimal place settings so they are handled elsewhere.
[ "Grader", "report", "has", "its", "own", "decimal", "place", "settings", "so", "they", "are", "handled", "elsewhere", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/grade/edit/tree/lib.php#L427-L433
216,087
moodle/moodle
lib/horde/framework/Horde/Imap/Client/Socket/Connection/Pop3.php
Horde_Imap_Client_Socket_Connection_Pop3.write
public function write($data, $debug = true) { if (fwrite($this->_stream, $data . "\r\n") === false) { throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Server write error."), Horde_Imap_Client_Exception::SERVER_WRITEERROR ); } if ($debug) { $this->_params['debug']->client($data); } }
php
public function write($data, $debug = true) { if (fwrite($this->_stream, $data . "\r\n") === false) { throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Server write error."), Horde_Imap_Client_Exception::SERVER_WRITEERROR ); } if ($debug) { $this->_params['debug']->client($data); } }
[ "public", "function", "write", "(", "$", "data", ",", "$", "debug", "=", "true", ")", "{", "if", "(", "fwrite", "(", "$", "this", "->", "_stream", ",", "$", "data", ".", "\"\\r\\n\"", ")", "===", "false", ")", "{", "throw", "new", "Horde_Imap_Client_Exception", "(", "Horde_Imap_Client_Translation", "::", "r", "(", "\"Server write error.\"", ")", ",", "Horde_Imap_Client_Exception", "::", "SERVER_WRITEERROR", ")", ";", "}", "if", "(", "$", "debug", ")", "{", "$", "this", "->", "_params", "[", "'debug'", "]", "->", "client", "(", "$", "data", ")", ";", "}", "}" ]
Writes data to the POP3 output stream. @param string $data String data. @param boolean $debug Output line to debug? @throws Horde_Imap_Client_Exception
[ "Writes", "data", "to", "the", "POP3", "output", "stream", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Imap/Client/Socket/Connection/Pop3.php#L43-L55
216,088
moodle/moodle
lib/horde/framework/Horde/Imap/Client/Socket/Connection/Pop3.php
Horde_Imap_Client_Socket_Connection_Pop3.read
public function read($size = null) { if (feof($this->_stream)) { $this->close(); $this->_params['debug']->info( 'ERROR: Server closed the connection.' ); throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Server closed the connection unexpectedly."), Horde_Imap_Client_Exception::DISCONNECT ); } if (($read = fgets($this->_stream)) === false) { $this->_params['debug']->info('ERROR: read/timeout error.'); throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Error when communicating with the mail server."), Horde_Imap_Client_Exception::SERVER_READERROR ); } $this->_params['debug']->server(rtrim($read, "\r\n")); return $read; }
php
public function read($size = null) { if (feof($this->_stream)) { $this->close(); $this->_params['debug']->info( 'ERROR: Server closed the connection.' ); throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Server closed the connection unexpectedly."), Horde_Imap_Client_Exception::DISCONNECT ); } if (($read = fgets($this->_stream)) === false) { $this->_params['debug']->info('ERROR: read/timeout error.'); throw new Horde_Imap_Client_Exception( Horde_Imap_Client_Translation::r("Error when communicating with the mail server."), Horde_Imap_Client_Exception::SERVER_READERROR ); } $this->_params['debug']->server(rtrim($read, "\r\n")); return $read; }
[ "public", "function", "read", "(", "$", "size", "=", "null", ")", "{", "if", "(", "feof", "(", "$", "this", "->", "_stream", ")", ")", "{", "$", "this", "->", "close", "(", ")", ";", "$", "this", "->", "_params", "[", "'debug'", "]", "->", "info", "(", "'ERROR: Server closed the connection.'", ")", ";", "throw", "new", "Horde_Imap_Client_Exception", "(", "Horde_Imap_Client_Translation", "::", "r", "(", "\"Server closed the connection unexpectedly.\"", ")", ",", "Horde_Imap_Client_Exception", "::", "DISCONNECT", ")", ";", "}", "if", "(", "(", "$", "read", "=", "fgets", "(", "$", "this", "->", "_stream", ")", ")", "===", "false", ")", "{", "$", "this", "->", "_params", "[", "'debug'", "]", "->", "info", "(", "'ERROR: read/timeout error.'", ")", ";", "throw", "new", "Horde_Imap_Client_Exception", "(", "Horde_Imap_Client_Translation", "::", "r", "(", "\"Error when communicating with the mail server.\"", ")", ",", "Horde_Imap_Client_Exception", "::", "SERVER_READERROR", ")", ";", "}", "$", "this", "->", "_params", "[", "'debug'", "]", "->", "server", "(", "rtrim", "(", "$", "read", ",", "\"\\r\\n\"", ")", ")", ";", "return", "$", "read", ";", "}" ]
Read data from incoming POP3 stream. @param integer $size UNUSED: The number of bytes to read from the socket. @return string Line of data. @throws Horde_Imap_Client_Exception
[ "Read", "data", "from", "incoming", "POP3", "stream", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Imap/Client/Socket/Connection/Pop3.php#L67-L91
216,089
moodle/moodle
lib/horde/framework/Horde/Imap/Client/Cache/Backend/Db.php
Horde_Imap_Client_Cache_Backend_Db._baseSql
protected function _baseSql($mailbox, $join = null) { $sql = sprintf('FROM %s d', self::BASE_TABLE); if (!is_null($join)) { $sql .= sprintf(' INNER JOIN %s t ON d.messageid = t.messageid', $join); } return array( $sql . ' WHERE d.hostspec = ? AND d.port = ? AND d.username = ? AND d.mailbox = ?', array( $this->_params['hostspec'], $this->_params['port'], $this->_params['username'], $mailbox ) ); }
php
protected function _baseSql($mailbox, $join = null) { $sql = sprintf('FROM %s d', self::BASE_TABLE); if (!is_null($join)) { $sql .= sprintf(' INNER JOIN %s t ON d.messageid = t.messageid', $join); } return array( $sql . ' WHERE d.hostspec = ? AND d.port = ? AND d.username = ? AND d.mailbox = ?', array( $this->_params['hostspec'], $this->_params['port'], $this->_params['username'], $mailbox ) ); }
[ "protected", "function", "_baseSql", "(", "$", "mailbox", ",", "$", "join", "=", "null", ")", "{", "$", "sql", "=", "sprintf", "(", "'FROM %s d'", ",", "self", "::", "BASE_TABLE", ")", ";", "if", "(", "!", "is_null", "(", "$", "join", ")", ")", "{", "$", "sql", ".=", "sprintf", "(", "' INNER JOIN %s t ON d.messageid = t.messageid'", ",", "$", "join", ")", ";", "}", "return", "array", "(", "$", "sql", ".", "' WHERE d.hostspec = ? AND d.port = ? AND d.username = ? AND d.mailbox = ?'", ",", "array", "(", "$", "this", "->", "_params", "[", "'hostspec'", "]", ",", "$", "this", "->", "_params", "[", "'port'", "]", ",", "$", "this", "->", "_params", "[", "'username'", "]", ",", "$", "mailbox", ")", ")", ";", "}" ]
Prepare the base SQL query. @param string $mailbox The mailbox. @param string $join The table to join with the base table. @return array SQL query and bound parameters.
[ "Prepare", "the", "base", "SQL", "query", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/lib/horde/framework/Horde/Imap/Client/Cache/Backend/Db.php#L349-L366
216,090
moodle/moodle
search/engine/solr/classes/engine.php
engine.execute_query
public function execute_query($filters, $accessinfo, $limit = 0) { global $USER; if (empty($limit)) { $limit = \core_search\manager::MAX_RESULTS; } // If there is any problem we trigger the exception as soon as possible. $client = $this->get_search_client(); // Create the query object. $query = $this->create_user_query($filters, $accessinfo); // If the query cannot have results, return none. if (!$query) { return []; } // We expect good match rates, so for our first get, we will get a small number of records. // This significantly speeds solr response time for first few pages. $query->setRows(min($limit * 3, static::QUERY_SIZE)); $response = $this->get_query_response($query); // Get count data out of the response, and reset our counters. list($included, $found) = $this->get_response_counts($response); $this->totalenginedocs = $found; $this->processeddocs = 0; $this->skippeddocs = 0; if ($included == 0 || $this->totalenginedocs == 0) { // No results. return array(); } // Get valid documents out of the response. $results = $this->process_response($response, $limit); // We have processed all the docs in the response at this point. $this->processeddocs += $included; // If we haven't reached the limit, and there are more docs left in Solr, lets keep trying. while (count($results) < $limit && ($this->totalenginedocs - $this->processeddocs) > 0) { // Offset the start of the query, and since we are making another call, get more per call. $query->setStart($this->processeddocs); $query->setRows(static::QUERY_SIZE); $response = $this->get_query_response($query); list($included, $found) = $this->get_response_counts($response); if ($included == 0 || $found == 0) { // No new results were found. Found being empty would be weird, so we will just return. return $results; } $this->totalenginedocs = $found; // Get the new response docs, limiting to remaining we need, then add it to the end of the results array. $newdocs = $this->process_response($response, $limit - count($results)); $results = array_merge($results, $newdocs); // Add to our processed docs count. $this->processeddocs += $included; } return $results; }
php
public function execute_query($filters, $accessinfo, $limit = 0) { global $USER; if (empty($limit)) { $limit = \core_search\manager::MAX_RESULTS; } // If there is any problem we trigger the exception as soon as possible. $client = $this->get_search_client(); // Create the query object. $query = $this->create_user_query($filters, $accessinfo); // If the query cannot have results, return none. if (!$query) { return []; } // We expect good match rates, so for our first get, we will get a small number of records. // This significantly speeds solr response time for first few pages. $query->setRows(min($limit * 3, static::QUERY_SIZE)); $response = $this->get_query_response($query); // Get count data out of the response, and reset our counters. list($included, $found) = $this->get_response_counts($response); $this->totalenginedocs = $found; $this->processeddocs = 0; $this->skippeddocs = 0; if ($included == 0 || $this->totalenginedocs == 0) { // No results. return array(); } // Get valid documents out of the response. $results = $this->process_response($response, $limit); // We have processed all the docs in the response at this point. $this->processeddocs += $included; // If we haven't reached the limit, and there are more docs left in Solr, lets keep trying. while (count($results) < $limit && ($this->totalenginedocs - $this->processeddocs) > 0) { // Offset the start of the query, and since we are making another call, get more per call. $query->setStart($this->processeddocs); $query->setRows(static::QUERY_SIZE); $response = $this->get_query_response($query); list($included, $found) = $this->get_response_counts($response); if ($included == 0 || $found == 0) { // No new results were found. Found being empty would be weird, so we will just return. return $results; } $this->totalenginedocs = $found; // Get the new response docs, limiting to remaining we need, then add it to the end of the results array. $newdocs = $this->process_response($response, $limit - count($results)); $results = array_merge($results, $newdocs); // Add to our processed docs count. $this->processeddocs += $included; } return $results; }
[ "public", "function", "execute_query", "(", "$", "filters", ",", "$", "accessinfo", ",", "$", "limit", "=", "0", ")", "{", "global", "$", "USER", ";", "if", "(", "empty", "(", "$", "limit", ")", ")", "{", "$", "limit", "=", "\\", "core_search", "\\", "manager", "::", "MAX_RESULTS", ";", "}", "// If there is any problem we trigger the exception as soon as possible.", "$", "client", "=", "$", "this", "->", "get_search_client", "(", ")", ";", "// Create the query object.", "$", "query", "=", "$", "this", "->", "create_user_query", "(", "$", "filters", ",", "$", "accessinfo", ")", ";", "// If the query cannot have results, return none.", "if", "(", "!", "$", "query", ")", "{", "return", "[", "]", ";", "}", "// We expect good match rates, so for our first get, we will get a small number of records.", "// This significantly speeds solr response time for first few pages.", "$", "query", "->", "setRows", "(", "min", "(", "$", "limit", "*", "3", ",", "static", "::", "QUERY_SIZE", ")", ")", ";", "$", "response", "=", "$", "this", "->", "get_query_response", "(", "$", "query", ")", ";", "// Get count data out of the response, and reset our counters.", "list", "(", "$", "included", ",", "$", "found", ")", "=", "$", "this", "->", "get_response_counts", "(", "$", "response", ")", ";", "$", "this", "->", "totalenginedocs", "=", "$", "found", ";", "$", "this", "->", "processeddocs", "=", "0", ";", "$", "this", "->", "skippeddocs", "=", "0", ";", "if", "(", "$", "included", "==", "0", "||", "$", "this", "->", "totalenginedocs", "==", "0", ")", "{", "// No results.", "return", "array", "(", ")", ";", "}", "// Get valid documents out of the response.", "$", "results", "=", "$", "this", "->", "process_response", "(", "$", "response", ",", "$", "limit", ")", ";", "// We have processed all the docs in the response at this point.", "$", "this", "->", "processeddocs", "+=", "$", "included", ";", "// If we haven't reached the limit, and there are more docs left in Solr, lets keep trying.", "while", "(", "count", "(", "$", "results", ")", "<", "$", "limit", "&&", "(", "$", "this", "->", "totalenginedocs", "-", "$", "this", "->", "processeddocs", ")", ">", "0", ")", "{", "// Offset the start of the query, and since we are making another call, get more per call.", "$", "query", "->", "setStart", "(", "$", "this", "->", "processeddocs", ")", ";", "$", "query", "->", "setRows", "(", "static", "::", "QUERY_SIZE", ")", ";", "$", "response", "=", "$", "this", "->", "get_query_response", "(", "$", "query", ")", ";", "list", "(", "$", "included", ",", "$", "found", ")", "=", "$", "this", "->", "get_response_counts", "(", "$", "response", ")", ";", "if", "(", "$", "included", "==", "0", "||", "$", "found", "==", "0", ")", "{", "// No new results were found. Found being empty would be weird, so we will just return.", "return", "$", "results", ";", "}", "$", "this", "->", "totalenginedocs", "=", "$", "found", ";", "// Get the new response docs, limiting to remaining we need, then add it to the end of the results array.", "$", "newdocs", "=", "$", "this", "->", "process_response", "(", "$", "response", ",", "$", "limit", "-", "count", "(", "$", "results", ")", ")", ";", "$", "results", "=", "array_merge", "(", "$", "results", ",", "$", "newdocs", ")", ";", "// Add to our processed docs count.", "$", "this", "->", "processeddocs", "+=", "$", "included", ";", "}", "return", "$", "results", ";", "}" ]
Prepares a Solr query, applies filters and executes it returning its results. @throws \core_search\engine_exception @param \stdClass $filters Containing query and filters. @param \stdClass $accessinfo Information about areas user can access. @param int $limit The maximum number of results to return. @return \core_search\document[] Results or false if no results
[ "Prepares", "a", "Solr", "query", "applies", "filters", "and", "executes", "it", "returning", "its", "results", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L140-L202
216,091
moodle/moodle
search/engine/solr/classes/engine.php
engine.get_query_response
protected function get_query_response($query) { try { return $this->get_search_client()->query($query)->getResponse(); } catch (\SolrClientException $ex) { debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER); $this->queryerror = $ex->getMessage(); return false; } catch (\SolrServerException $ex) { debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER); $this->queryerror = $ex->getMessage(); return false; } }
php
protected function get_query_response($query) { try { return $this->get_search_client()->query($query)->getResponse(); } catch (\SolrClientException $ex) { debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER); $this->queryerror = $ex->getMessage(); return false; } catch (\SolrServerException $ex) { debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER); $this->queryerror = $ex->getMessage(); return false; } }
[ "protected", "function", "get_query_response", "(", "$", "query", ")", "{", "try", "{", "return", "$", "this", "->", "get_search_client", "(", ")", "->", "query", "(", "$", "query", ")", "->", "getResponse", "(", ")", ";", "}", "catch", "(", "\\", "SolrClientException", "$", "ex", ")", "{", "debugging", "(", "'Error executing the provided query: '", ".", "$", "ex", "->", "getMessage", "(", ")", ",", "DEBUG_DEVELOPER", ")", ";", "$", "this", "->", "queryerror", "=", "$", "ex", "->", "getMessage", "(", ")", ";", "return", "false", ";", "}", "catch", "(", "\\", "SolrServerException", "$", "ex", ")", "{", "debugging", "(", "'Error executing the provided query: '", ".", "$", "ex", "->", "getMessage", "(", ")", ",", "DEBUG_DEVELOPER", ")", ";", "$", "this", "->", "queryerror", "=", "$", "ex", "->", "getMessage", "(", ")", ";", "return", "false", ";", "}", "}" ]
Takes a query and returns the response in SolrObject format. @param SolrQuery $query Solr query object. @return SolrObject|false Response document or false on error.
[ "Takes", "a", "query", "and", "returns", "the", "response", "in", "SolrObject", "format", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L210-L222
216,092
moodle/moodle
search/engine/solr/classes/engine.php
engine.get_response_counts
protected function get_response_counts($response) { $found = 0; $included = 0; if (isset($response->grouped->solr_filegroupingid->ngroups)) { // Get the number of results for file grouped queries. $found = $response->grouped->solr_filegroupingid->ngroups; $included = count($response->grouped->solr_filegroupingid->groups); } else if (isset($response->response->numFound)) { // Get the number of results for standard queries. $found = $response->response->numFound; if ($found > 0 && is_array($response->response->docs)) { $included = count($response->response->docs); } } return array($included, $found); }
php
protected function get_response_counts($response) { $found = 0; $included = 0; if (isset($response->grouped->solr_filegroupingid->ngroups)) { // Get the number of results for file grouped queries. $found = $response->grouped->solr_filegroupingid->ngroups; $included = count($response->grouped->solr_filegroupingid->groups); } else if (isset($response->response->numFound)) { // Get the number of results for standard queries. $found = $response->response->numFound; if ($found > 0 && is_array($response->response->docs)) { $included = count($response->response->docs); } } return array($included, $found); }
[ "protected", "function", "get_response_counts", "(", "$", "response", ")", "{", "$", "found", "=", "0", ";", "$", "included", "=", "0", ";", "if", "(", "isset", "(", "$", "response", "->", "grouped", "->", "solr_filegroupingid", "->", "ngroups", ")", ")", "{", "// Get the number of results for file grouped queries.", "$", "found", "=", "$", "response", "->", "grouped", "->", "solr_filegroupingid", "->", "ngroups", ";", "$", "included", "=", "count", "(", "$", "response", "->", "grouped", "->", "solr_filegroupingid", "->", "groups", ")", ";", "}", "else", "if", "(", "isset", "(", "$", "response", "->", "response", "->", "numFound", ")", ")", "{", "// Get the number of results for standard queries.", "$", "found", "=", "$", "response", "->", "response", "->", "numFound", ";", "if", "(", "$", "found", ">", "0", "&&", "is_array", "(", "$", "response", "->", "response", "->", "docs", ")", ")", "{", "$", "included", "=", "count", "(", "$", "response", "->", "response", "->", "docs", ")", ";", "}", "}", "return", "array", "(", "$", "included", ",", "$", "found", ")", ";", "}" ]
Returns count information for a provided response. Will return 0, 0 for invalid or empty responses. @param SolrDocument $response The response document from Solr. @return array A two part array. First how many response docs are in the response. Second, how many results are vailable in the engine.
[ "Returns", "count", "information", "for", "a", "provided", "response", ".", "Will", "return", "0", "0", "for", "invalid", "or", "empty", "responses", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L241-L258
216,093
moodle/moodle
search/engine/solr/classes/engine.php
engine.set_query
protected function set_query($query, $q) { // Set hightlighting. $query->setHighlight(true); foreach ($this->highlightfields as $field) { $query->addHighlightField($field); } $query->setHighlightFragsize(static::FRAG_SIZE); $query->setHighlightSimplePre(self::HIGHLIGHT_START); $query->setHighlightSimplePost(self::HIGHLIGHT_END); $query->setHighlightMergeContiguous(true); $query->setQuery($q); // A reasonable max. $query->setRows(static::QUERY_SIZE); }
php
protected function set_query($query, $q) { // Set hightlighting. $query->setHighlight(true); foreach ($this->highlightfields as $field) { $query->addHighlightField($field); } $query->setHighlightFragsize(static::FRAG_SIZE); $query->setHighlightSimplePre(self::HIGHLIGHT_START); $query->setHighlightSimplePost(self::HIGHLIGHT_END); $query->setHighlightMergeContiguous(true); $query->setQuery($q); // A reasonable max. $query->setRows(static::QUERY_SIZE); }
[ "protected", "function", "set_query", "(", "$", "query", ",", "$", "q", ")", "{", "// Set hightlighting.", "$", "query", "->", "setHighlight", "(", "true", ")", ";", "foreach", "(", "$", "this", "->", "highlightfields", "as", "$", "field", ")", "{", "$", "query", "->", "addHighlightField", "(", "$", "field", ")", ";", "}", "$", "query", "->", "setHighlightFragsize", "(", "static", "::", "FRAG_SIZE", ")", ";", "$", "query", "->", "setHighlightSimplePre", "(", "self", "::", "HIGHLIGHT_START", ")", ";", "$", "query", "->", "setHighlightSimplePost", "(", "self", "::", "HIGHLIGHT_END", ")", ";", "$", "query", "->", "setHighlightMergeContiguous", "(", "true", ")", ";", "$", "query", "->", "setQuery", "(", "$", "q", ")", ";", "// A reasonable max.", "$", "query", "->", "setRows", "(", "static", "::", "QUERY_SIZE", ")", ";", "}" ]
Prepares a new query by setting the query, start offset and rows to return. @param SolrQuery $query @param object $q Containing query and filters.
[ "Prepares", "a", "new", "query", "by", "setting", "the", "query", "start", "offset", "and", "rows", "to", "return", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L401-L416
216,094
moodle/moodle
search/engine/solr/classes/engine.php
engine.add_fields
public function add_fields($query) { $documentclass = $this->get_document_classname(); $fields = $documentclass::get_default_fields_definition(); $dismax = false; if ($query instanceof \SolrDisMaxQuery) { $dismax = true; } foreach ($fields as $key => $field) { $query->addField($key); if ($dismax && !empty($field['mainquery'])) { // Add fields the main query should be run against. $query->addQueryField($key); } } }
php
public function add_fields($query) { $documentclass = $this->get_document_classname(); $fields = $documentclass::get_default_fields_definition(); $dismax = false; if ($query instanceof \SolrDisMaxQuery) { $dismax = true; } foreach ($fields as $key => $field) { $query->addField($key); if ($dismax && !empty($field['mainquery'])) { // Add fields the main query should be run against. $query->addQueryField($key); } } }
[ "public", "function", "add_fields", "(", "$", "query", ")", "{", "$", "documentclass", "=", "$", "this", "->", "get_document_classname", "(", ")", ";", "$", "fields", "=", "$", "documentclass", "::", "get_default_fields_definition", "(", ")", ";", "$", "dismax", "=", "false", ";", "if", "(", "$", "query", "instanceof", "\\", "SolrDisMaxQuery", ")", "{", "$", "dismax", "=", "true", ";", "}", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "field", ")", "{", "$", "query", "->", "addField", "(", "$", "key", ")", ";", "if", "(", "$", "dismax", "&&", "!", "empty", "(", "$", "field", "[", "'mainquery'", "]", ")", ")", "{", "// Add fields the main query should be run against.", "$", "query", "->", "addQueryField", "(", "$", "key", ")", ";", "}", "}", "}" ]
Sets fields to be returned in the result. @param SolrDisMaxQuery|SolrQuery $query object.
[ "Sets", "fields", "to", "be", "returned", "in", "the", "result", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L423-L439
216,095
moodle/moodle
search/engine/solr/classes/engine.php
engine.add_highlight_content
public function add_highlight_content($response) { if (!isset($response->highlighting)) { // There is no highlighting to add. return; } $highlightedobject = $response->highlighting; foreach ($response->response->docs as $doc) { $x = $doc->id; $highlighteddoc = $highlightedobject->$x; $this->merge_highlight_field_values($doc, $highlighteddoc); } }
php
public function add_highlight_content($response) { if (!isset($response->highlighting)) { // There is no highlighting to add. return; } $highlightedobject = $response->highlighting; foreach ($response->response->docs as $doc) { $x = $doc->id; $highlighteddoc = $highlightedobject->$x; $this->merge_highlight_field_values($doc, $highlighteddoc); } }
[ "public", "function", "add_highlight_content", "(", "$", "response", ")", "{", "if", "(", "!", "isset", "(", "$", "response", "->", "highlighting", ")", ")", "{", "// There is no highlighting to add.", "return", ";", "}", "$", "highlightedobject", "=", "$", "response", "->", "highlighting", ";", "foreach", "(", "$", "response", "->", "response", "->", "docs", "as", "$", "doc", ")", "{", "$", "x", "=", "$", "doc", "->", "id", ";", "$", "highlighteddoc", "=", "$", "highlightedobject", "->", "$", "x", ";", "$", "this", "->", "merge_highlight_field_values", "(", "$", "doc", ",", "$", "highlighteddoc", ")", ";", "}", "}" ]
Finds the key common to both highlighing and docs array returned from response. @param object $response containing results.
[ "Finds", "the", "key", "common", "to", "both", "highlighing", "and", "docs", "array", "returned", "from", "response", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L445-L457
216,096
moodle/moodle
search/engine/solr/classes/engine.php
engine.merge_highlight_field_values
public function merge_highlight_field_values($doc, $highlighteddoc) { foreach ($this->highlightfields as $field) { if (!empty($doc->$field)) { // Check that the returned value is not an array. No way we can make this work with multivalued solr fields. if (is_array($doc->{$field})) { throw new \core_search\engine_exception('multivaluedfield', 'search_solr', '', $field); } if (!empty($highlighteddoc->$field)) { // Replace by the highlighted result. $doc->$field = reset($highlighteddoc->$field); } } } }
php
public function merge_highlight_field_values($doc, $highlighteddoc) { foreach ($this->highlightfields as $field) { if (!empty($doc->$field)) { // Check that the returned value is not an array. No way we can make this work with multivalued solr fields. if (is_array($doc->{$field})) { throw new \core_search\engine_exception('multivaluedfield', 'search_solr', '', $field); } if (!empty($highlighteddoc->$field)) { // Replace by the highlighted result. $doc->$field = reset($highlighteddoc->$field); } } } }
[ "public", "function", "merge_highlight_field_values", "(", "$", "doc", ",", "$", "highlighteddoc", ")", "{", "foreach", "(", "$", "this", "->", "highlightfields", "as", "$", "field", ")", "{", "if", "(", "!", "empty", "(", "$", "doc", "->", "$", "field", ")", ")", "{", "// Check that the returned value is not an array. No way we can make this work with multivalued solr fields.", "if", "(", "is_array", "(", "$", "doc", "->", "{", "$", "field", "}", ")", ")", "{", "throw", "new", "\\", "core_search", "\\", "engine_exception", "(", "'multivaluedfield'", ",", "'search_solr'", ",", "''", ",", "$", "field", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "highlighteddoc", "->", "$", "field", ")", ")", "{", "// Replace by the highlighted result.", "$", "doc", "->", "$", "field", "=", "reset", "(", "$", "highlighteddoc", "->", "$", "field", ")", ";", "}", "}", "}", "}" ]
Adds the highlighting array values to docs array values. @throws \core_search\engine_exception @param object $doc containing the results. @param object $highlighteddoc containing the highlighted results values.
[ "Adds", "the", "highlighting", "array", "values", "to", "docs", "array", "values", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L466-L482
216,097
moodle/moodle
search/engine/solr/classes/engine.php
engine.process_response
protected function process_response($response, $limit = 0, $skipaccesscheck = false) { global $USER; if (empty($response)) { return array(); } if (isset($response->grouped)) { return $this->grouped_files_process_response($response, $limit); } $userid = $USER->id; $noownerid = \core_search\manager::NO_OWNER_ID; $numgranted = 0; if (!$docs = $response->response->docs) { return array(); } $out = array(); if (!empty($response->response->numFound)) { $this->add_highlight_content($response); // Iterate through the results checking its availability and whether they are available for the user or not. foreach ($docs as $key => $docdata) { if ($docdata['owneruserid'] != $noownerid && $docdata['owneruserid'] != $userid) { // If owneruserid is set, no other user should be able to access this record. continue; } if (!$searcharea = $this->get_search_area($docdata->areaid)) { continue; } $docdata = $this->standarize_solr_obj($docdata); if ($skipaccesscheck) { $access = \core_search\manager::ACCESS_GRANTED; } else { $access = $searcharea->check_access($docdata['itemid']); } switch ($access) { case \core_search\manager::ACCESS_DELETED: $this->delete_by_id($docdata['id']); // Remove one from our processed and total counters, since we promptly deleted. $this->processeddocs--; $this->totalenginedocs--; break; case \core_search\manager::ACCESS_DENIED: $this->skippeddocs++; break; case \core_search\manager::ACCESS_GRANTED: $numgranted++; // Add the doc. $out[] = $this->to_document($searcharea, $docdata); break; } // Stop when we hit our limit. if (!empty($limit) && count($out) >= $limit) { break; } } } return $out; }
php
protected function process_response($response, $limit = 0, $skipaccesscheck = false) { global $USER; if (empty($response)) { return array(); } if (isset($response->grouped)) { return $this->grouped_files_process_response($response, $limit); } $userid = $USER->id; $noownerid = \core_search\manager::NO_OWNER_ID; $numgranted = 0; if (!$docs = $response->response->docs) { return array(); } $out = array(); if (!empty($response->response->numFound)) { $this->add_highlight_content($response); // Iterate through the results checking its availability and whether they are available for the user or not. foreach ($docs as $key => $docdata) { if ($docdata['owneruserid'] != $noownerid && $docdata['owneruserid'] != $userid) { // If owneruserid is set, no other user should be able to access this record. continue; } if (!$searcharea = $this->get_search_area($docdata->areaid)) { continue; } $docdata = $this->standarize_solr_obj($docdata); if ($skipaccesscheck) { $access = \core_search\manager::ACCESS_GRANTED; } else { $access = $searcharea->check_access($docdata['itemid']); } switch ($access) { case \core_search\manager::ACCESS_DELETED: $this->delete_by_id($docdata['id']); // Remove one from our processed and total counters, since we promptly deleted. $this->processeddocs--; $this->totalenginedocs--; break; case \core_search\manager::ACCESS_DENIED: $this->skippeddocs++; break; case \core_search\manager::ACCESS_GRANTED: $numgranted++; // Add the doc. $out[] = $this->to_document($searcharea, $docdata); break; } // Stop when we hit our limit. if (!empty($limit) && count($out) >= $limit) { break; } } } return $out; }
[ "protected", "function", "process_response", "(", "$", "response", ",", "$", "limit", "=", "0", ",", "$", "skipaccesscheck", "=", "false", ")", "{", "global", "$", "USER", ";", "if", "(", "empty", "(", "$", "response", ")", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "response", "->", "grouped", ")", ")", "{", "return", "$", "this", "->", "grouped_files_process_response", "(", "$", "response", ",", "$", "limit", ")", ";", "}", "$", "userid", "=", "$", "USER", "->", "id", ";", "$", "noownerid", "=", "\\", "core_search", "\\", "manager", "::", "NO_OWNER_ID", ";", "$", "numgranted", "=", "0", ";", "if", "(", "!", "$", "docs", "=", "$", "response", "->", "response", "->", "docs", ")", "{", "return", "array", "(", ")", ";", "}", "$", "out", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "response", "->", "response", "->", "numFound", ")", ")", "{", "$", "this", "->", "add_highlight_content", "(", "$", "response", ")", ";", "// Iterate through the results checking its availability and whether they are available for the user or not.", "foreach", "(", "$", "docs", "as", "$", "key", "=>", "$", "docdata", ")", "{", "if", "(", "$", "docdata", "[", "'owneruserid'", "]", "!=", "$", "noownerid", "&&", "$", "docdata", "[", "'owneruserid'", "]", "!=", "$", "userid", ")", "{", "// If owneruserid is set, no other user should be able to access this record.", "continue", ";", "}", "if", "(", "!", "$", "searcharea", "=", "$", "this", "->", "get_search_area", "(", "$", "docdata", "->", "areaid", ")", ")", "{", "continue", ";", "}", "$", "docdata", "=", "$", "this", "->", "standarize_solr_obj", "(", "$", "docdata", ")", ";", "if", "(", "$", "skipaccesscheck", ")", "{", "$", "access", "=", "\\", "core_search", "\\", "manager", "::", "ACCESS_GRANTED", ";", "}", "else", "{", "$", "access", "=", "$", "searcharea", "->", "check_access", "(", "$", "docdata", "[", "'itemid'", "]", ")", ";", "}", "switch", "(", "$", "access", ")", "{", "case", "\\", "core_search", "\\", "manager", "::", "ACCESS_DELETED", ":", "$", "this", "->", "delete_by_id", "(", "$", "docdata", "[", "'id'", "]", ")", ";", "// Remove one from our processed and total counters, since we promptly deleted.", "$", "this", "->", "processeddocs", "--", ";", "$", "this", "->", "totalenginedocs", "--", ";", "break", ";", "case", "\\", "core_search", "\\", "manager", "::", "ACCESS_DENIED", ":", "$", "this", "->", "skippeddocs", "++", ";", "break", ";", "case", "\\", "core_search", "\\", "manager", "::", "ACCESS_GRANTED", ":", "$", "numgranted", "++", ";", "// Add the doc.", "$", "out", "[", "]", "=", "$", "this", "->", "to_document", "(", "$", "searcharea", ",", "$", "docdata", ")", ";", "break", ";", "}", "// Stop when we hit our limit.", "if", "(", "!", "empty", "(", "$", "limit", ")", "&&", "count", "(", "$", "out", ")", ">=", "$", "limit", ")", "{", "break", ";", "}", "}", "}", "return", "$", "out", ";", "}" ]
Filters the response on Moodle side. @param SolrObject $response Solr object containing the response return from solr server. @param int $limit The maximum number of results to return. 0 for all. @param bool $skipaccesscheck Don't use check_access() on results. Only to be used when results have known access. @return array $results containing final results to be displayed.
[ "Filters", "the", "response", "on", "Moodle", "side", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L492-L560
216,098
moodle/moodle
search/engine/solr/classes/engine.php
engine.grouped_files_process_response
protected function grouped_files_process_response($response, $limit = 0) { // If we can't find the grouping, or there are no matches in the grouping, return empty. if (!isset($response->grouped->solr_filegroupingid) || empty($response->grouped->solr_filegroupingid->matches)) { return array(); } $numgranted = 0; $orderedids = array(); $completedocs = array(); $incompletedocs = array(); $highlightingobj = $response->highlighting; // Each group represents a "master document". $groups = $response->grouped->solr_filegroupingid->groups; foreach ($groups as $group) { $groupid = $group->groupValue; $groupdocs = $group->doclist->docs; $firstdoc = reset($groupdocs); if (!$searcharea = $this->get_search_area($firstdoc->areaid)) { // Well, this is a problem. continue; } // Check for access. $access = $searcharea->check_access($firstdoc->itemid); switch ($access) { case \core_search\manager::ACCESS_DELETED: // If deleted from Moodle, delete from index and then continue. $this->delete_by_id($firstdoc->id); // Remove one from our processed and total counters, since we promptly deleted. $this->processeddocs--; $this->totalenginedocs--; continue 2; break; case \core_search\manager::ACCESS_DENIED: // This means we should just skip for the current user. $this->skippeddocs++; continue 2; break; } $numgranted++; $maindoc = false; $fileids = array(); // Seperate the main document and any files returned. foreach ($groupdocs as $groupdoc) { if ($groupdoc->id == $groupid) { $maindoc = $groupdoc; } else if (isset($groupdoc->solr_fileid)) { $fileids[] = $groupdoc->solr_fileid; } } // Store the id of this group, in order, for later merging. $orderedids[] = $groupid; if (!$maindoc) { // We don't have the main doc, store what we know for later building. $incompletedocs[$groupid] = $fileids; } else { if (isset($highlightingobj->$groupid)) { // Merge the highlighting for this doc. $this->merge_highlight_field_values($maindoc, $highlightingobj->$groupid); } $docdata = $this->standarize_solr_obj($maindoc); $doc = $this->to_document($searcharea, $docdata); // Now we need to attach the result files to the doc. foreach ($fileids as $fileid) { $doc->add_stored_file($fileid); } $completedocs[$groupid] = $doc; } if (!empty($limit) && $numgranted >= $limit) { // We have hit the max results, we will just ignore the rest. break; } } $incompletedocs = $this->get_missing_docs($incompletedocs); $out = array(); // Now merge the complete and incomplete documents, in results order. foreach ($orderedids as $docid) { if (isset($completedocs[$docid])) { $out[] = $completedocs[$docid]; } else if (isset($incompletedocs[$docid])) { $out[] = $incompletedocs[$docid]; } } return $out; }
php
protected function grouped_files_process_response($response, $limit = 0) { // If we can't find the grouping, or there are no matches in the grouping, return empty. if (!isset($response->grouped->solr_filegroupingid) || empty($response->grouped->solr_filegroupingid->matches)) { return array(); } $numgranted = 0; $orderedids = array(); $completedocs = array(); $incompletedocs = array(); $highlightingobj = $response->highlighting; // Each group represents a "master document". $groups = $response->grouped->solr_filegroupingid->groups; foreach ($groups as $group) { $groupid = $group->groupValue; $groupdocs = $group->doclist->docs; $firstdoc = reset($groupdocs); if (!$searcharea = $this->get_search_area($firstdoc->areaid)) { // Well, this is a problem. continue; } // Check for access. $access = $searcharea->check_access($firstdoc->itemid); switch ($access) { case \core_search\manager::ACCESS_DELETED: // If deleted from Moodle, delete from index and then continue. $this->delete_by_id($firstdoc->id); // Remove one from our processed and total counters, since we promptly deleted. $this->processeddocs--; $this->totalenginedocs--; continue 2; break; case \core_search\manager::ACCESS_DENIED: // This means we should just skip for the current user. $this->skippeddocs++; continue 2; break; } $numgranted++; $maindoc = false; $fileids = array(); // Seperate the main document and any files returned. foreach ($groupdocs as $groupdoc) { if ($groupdoc->id == $groupid) { $maindoc = $groupdoc; } else if (isset($groupdoc->solr_fileid)) { $fileids[] = $groupdoc->solr_fileid; } } // Store the id of this group, in order, for later merging. $orderedids[] = $groupid; if (!$maindoc) { // We don't have the main doc, store what we know for later building. $incompletedocs[$groupid] = $fileids; } else { if (isset($highlightingobj->$groupid)) { // Merge the highlighting for this doc. $this->merge_highlight_field_values($maindoc, $highlightingobj->$groupid); } $docdata = $this->standarize_solr_obj($maindoc); $doc = $this->to_document($searcharea, $docdata); // Now we need to attach the result files to the doc. foreach ($fileids as $fileid) { $doc->add_stored_file($fileid); } $completedocs[$groupid] = $doc; } if (!empty($limit) && $numgranted >= $limit) { // We have hit the max results, we will just ignore the rest. break; } } $incompletedocs = $this->get_missing_docs($incompletedocs); $out = array(); // Now merge the complete and incomplete documents, in results order. foreach ($orderedids as $docid) { if (isset($completedocs[$docid])) { $out[] = $completedocs[$docid]; } else if (isset($incompletedocs[$docid])) { $out[] = $incompletedocs[$docid]; } } return $out; }
[ "protected", "function", "grouped_files_process_response", "(", "$", "response", ",", "$", "limit", "=", "0", ")", "{", "// If we can't find the grouping, or there are no matches in the grouping, return empty.", "if", "(", "!", "isset", "(", "$", "response", "->", "grouped", "->", "solr_filegroupingid", ")", "||", "empty", "(", "$", "response", "->", "grouped", "->", "solr_filegroupingid", "->", "matches", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "numgranted", "=", "0", ";", "$", "orderedids", "=", "array", "(", ")", ";", "$", "completedocs", "=", "array", "(", ")", ";", "$", "incompletedocs", "=", "array", "(", ")", ";", "$", "highlightingobj", "=", "$", "response", "->", "highlighting", ";", "// Each group represents a \"master document\".", "$", "groups", "=", "$", "response", "->", "grouped", "->", "solr_filegroupingid", "->", "groups", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "groupid", "=", "$", "group", "->", "groupValue", ";", "$", "groupdocs", "=", "$", "group", "->", "doclist", "->", "docs", ";", "$", "firstdoc", "=", "reset", "(", "$", "groupdocs", ")", ";", "if", "(", "!", "$", "searcharea", "=", "$", "this", "->", "get_search_area", "(", "$", "firstdoc", "->", "areaid", ")", ")", "{", "// Well, this is a problem.", "continue", ";", "}", "// Check for access.", "$", "access", "=", "$", "searcharea", "->", "check_access", "(", "$", "firstdoc", "->", "itemid", ")", ";", "switch", "(", "$", "access", ")", "{", "case", "\\", "core_search", "\\", "manager", "::", "ACCESS_DELETED", ":", "// If deleted from Moodle, delete from index and then continue.", "$", "this", "->", "delete_by_id", "(", "$", "firstdoc", "->", "id", ")", ";", "// Remove one from our processed and total counters, since we promptly deleted.", "$", "this", "->", "processeddocs", "--", ";", "$", "this", "->", "totalenginedocs", "--", ";", "continue", "2", ";", "break", ";", "case", "\\", "core_search", "\\", "manager", "::", "ACCESS_DENIED", ":", "// This means we should just skip for the current user.", "$", "this", "->", "skippeddocs", "++", ";", "continue", "2", ";", "break", ";", "}", "$", "numgranted", "++", ";", "$", "maindoc", "=", "false", ";", "$", "fileids", "=", "array", "(", ")", ";", "// Seperate the main document and any files returned.", "foreach", "(", "$", "groupdocs", "as", "$", "groupdoc", ")", "{", "if", "(", "$", "groupdoc", "->", "id", "==", "$", "groupid", ")", "{", "$", "maindoc", "=", "$", "groupdoc", ";", "}", "else", "if", "(", "isset", "(", "$", "groupdoc", "->", "solr_fileid", ")", ")", "{", "$", "fileids", "[", "]", "=", "$", "groupdoc", "->", "solr_fileid", ";", "}", "}", "// Store the id of this group, in order, for later merging.", "$", "orderedids", "[", "]", "=", "$", "groupid", ";", "if", "(", "!", "$", "maindoc", ")", "{", "// We don't have the main doc, store what we know for later building.", "$", "incompletedocs", "[", "$", "groupid", "]", "=", "$", "fileids", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "highlightingobj", "->", "$", "groupid", ")", ")", "{", "// Merge the highlighting for this doc.", "$", "this", "->", "merge_highlight_field_values", "(", "$", "maindoc", ",", "$", "highlightingobj", "->", "$", "groupid", ")", ";", "}", "$", "docdata", "=", "$", "this", "->", "standarize_solr_obj", "(", "$", "maindoc", ")", ";", "$", "doc", "=", "$", "this", "->", "to_document", "(", "$", "searcharea", ",", "$", "docdata", ")", ";", "// Now we need to attach the result files to the doc.", "foreach", "(", "$", "fileids", "as", "$", "fileid", ")", "{", "$", "doc", "->", "add_stored_file", "(", "$", "fileid", ")", ";", "}", "$", "completedocs", "[", "$", "groupid", "]", "=", "$", "doc", ";", "}", "if", "(", "!", "empty", "(", "$", "limit", ")", "&&", "$", "numgranted", ">=", "$", "limit", ")", "{", "// We have hit the max results, we will just ignore the rest.", "break", ";", "}", "}", "$", "incompletedocs", "=", "$", "this", "->", "get_missing_docs", "(", "$", "incompletedocs", ")", ";", "$", "out", "=", "array", "(", ")", ";", "// Now merge the complete and incomplete documents, in results order.", "foreach", "(", "$", "orderedids", "as", "$", "docid", ")", "{", "if", "(", "isset", "(", "$", "completedocs", "[", "$", "docid", "]", ")", ")", "{", "$", "out", "[", "]", "=", "$", "completedocs", "[", "$", "docid", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "incompletedocs", "[", "$", "docid", "]", ")", ")", "{", "$", "out", "[", "]", "=", "$", "incompletedocs", "[", "$", "docid", "]", ";", "}", "}", "return", "$", "out", ";", "}" ]
Processes grouped file results into documents, with attached matching files. @param SolrObject $response The response returned from solr server @param int $limit The maximum number of results to return. 0 for all. @return array Final results to be displayed.
[ "Processes", "grouped", "file", "results", "into", "documents", "with", "attached", "matching", "files", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L569-L663
216,099
moodle/moodle
search/engine/solr/classes/engine.php
engine.get_missing_docs
protected function get_missing_docs($missingdocs) { if (empty($missingdocs)) { return array(); } $docids = array_keys($missingdocs); // Build a custom query that will get all the missing documents. $query = new \SolrQuery(); $this->set_query($query, '*'); $this->add_fields($query); $query->setRows(count($docids)); $query->addFilterQuery('{!cache=false}id:(' . implode(' OR ', $docids) . ')'); $response = $this->get_query_response($query); // We know the missing docs have already been checked for access, so don't recheck. $results = $this->process_response($response, 0, true); $out = array(); foreach ($results as $result) { $resultid = $result->get('id'); if (!isset($missingdocs[$resultid])) { // We got a result we didn't expect. Skip it. continue; } // Attach the files. foreach ($missingdocs[$resultid] as $filedoc) { $result->add_stored_file($filedoc); } $out[$resultid] = $result; } return $out; }
php
protected function get_missing_docs($missingdocs) { if (empty($missingdocs)) { return array(); } $docids = array_keys($missingdocs); // Build a custom query that will get all the missing documents. $query = new \SolrQuery(); $this->set_query($query, '*'); $this->add_fields($query); $query->setRows(count($docids)); $query->addFilterQuery('{!cache=false}id:(' . implode(' OR ', $docids) . ')'); $response = $this->get_query_response($query); // We know the missing docs have already been checked for access, so don't recheck. $results = $this->process_response($response, 0, true); $out = array(); foreach ($results as $result) { $resultid = $result->get('id'); if (!isset($missingdocs[$resultid])) { // We got a result we didn't expect. Skip it. continue; } // Attach the files. foreach ($missingdocs[$resultid] as $filedoc) { $result->add_stored_file($filedoc); } $out[$resultid] = $result; } return $out; }
[ "protected", "function", "get_missing_docs", "(", "$", "missingdocs", ")", "{", "if", "(", "empty", "(", "$", "missingdocs", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "docids", "=", "array_keys", "(", "$", "missingdocs", ")", ";", "// Build a custom query that will get all the missing documents.", "$", "query", "=", "new", "\\", "SolrQuery", "(", ")", ";", "$", "this", "->", "set_query", "(", "$", "query", ",", "'*'", ")", ";", "$", "this", "->", "add_fields", "(", "$", "query", ")", ";", "$", "query", "->", "setRows", "(", "count", "(", "$", "docids", ")", ")", ";", "$", "query", "->", "addFilterQuery", "(", "'{!cache=false}id:('", ".", "implode", "(", "' OR '", ",", "$", "docids", ")", ".", "')'", ")", ";", "$", "response", "=", "$", "this", "->", "get_query_response", "(", "$", "query", ")", ";", "// We know the missing docs have already been checked for access, so don't recheck.", "$", "results", "=", "$", "this", "->", "process_response", "(", "$", "response", ",", "0", ",", "true", ")", ";", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "resultid", "=", "$", "result", "->", "get", "(", "'id'", ")", ";", "if", "(", "!", "isset", "(", "$", "missingdocs", "[", "$", "resultid", "]", ")", ")", "{", "// We got a result we didn't expect. Skip it.", "continue", ";", "}", "// Attach the files.", "foreach", "(", "$", "missingdocs", "[", "$", "resultid", "]", "as", "$", "filedoc", ")", "{", "$", "result", "->", "add_stored_file", "(", "$", "filedoc", ")", ";", "}", "$", "out", "[", "$", "resultid", "]", "=", "$", "result", ";", "}", "return", "$", "out", ";", "}" ]
Retreive any missing main documents and attach provided files. The missingdocs array should be an array, indexed by document id, of main documents we need to retrieve. The value associated to the key should be an array of stored_files or stored file ids to attach to the result document. Return array also indexed by document id. @param array() $missingdocs An array, indexed by document id, with arrays of files/ids to attach. @return document[]
[ "Retreive", "any", "missing", "main", "documents", "and", "attach", "provided", "files", "." ]
a411b499b98afc9901c24a9466c7e322946a04aa
https://github.com/moodle/moodle/blob/a411b499b98afc9901c24a9466c7e322946a04aa/search/engine/solr/classes/engine.php#L676-L709