Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

Code for handling and processing questions This is code that is module independent, i.e., can be used by any module that uses questions, like quiz, lesson, .. This script also loads the questiontype classes Code for handling the editing of questions is in {@link question/editlib.php}

Copyright: 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2397 lines (91 kb)
Included or required:0 times
Referenced: 1 time
Includes or requires: 0 files

Defines 2 classes

Defines 22 functions


Class: context_to_string_translator  - X-Ref

Converts contextlevels to strings and back to help with reading/writing contexts
to/from import/export files.

__construct($contexts)   X-Ref


context_to_string($contextid)   X-Ref
No description

string_to_context($contextname)   X-Ref
No description

generate_context_to_string_array($contexts)   X-Ref
No description

question_has_capability_on($questionorid, $cap, $notused = -1)   X-Ref
Check capability on category

param: int|stdClass|question_definition $questionorid object or id.
param: string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
param: int $notused no longer used.
return: bool this user has the capability $cap for this question $question?

question_require_capability_on($question, $cap)   X-Ref
Require capability on question.


question_edit_url($context)   X-Ref

param: object $context a context
return: string A URL for editing questions in this context.

question_extend_settings_navigation(navigation_node $navigationnode, $context)   X-Ref
Adds question bank setting links to the given navigation node if caps are met.

param: navigation_node $navigationnode The navigation node to add the question branch to
param: object $context
return: navigation_node Returns the question branch that was added

question_get_question_capabilities()   X-Ref

return: array all the capabilities that relate to accessing particular questions.

question_get_all_capabilities()   X-Ref

return: array all the question bank capabilities.

Class: question_edit_contexts  - X-Ref

Tracks all the contexts related to the one where we are currently editing
questions, and provides helper methods to check permissions.

__construct(context $thiscontext)   X-Ref
Constructor

param: context the current context.

all()   X-Ref

return: context[] all parent contexts

lowest()   X-Ref

return: context lowest context which must be either the module or course context

having_cap($cap)   X-Ref

param: string $cap capability
return: context[] parent contexts having capability, zero based index

having_one_cap($caps)   X-Ref

param: array $caps capabilities
return: context[] parent contexts having at least one of $caps, zero based index

having_one_edit_tab_cap($tabname)   X-Ref

param: string $tabname edit tab name
return: context[] parent contexts having at least one of $caps, zero based index

having_add_and_use()   X-Ref

return: context[] those contexts where a user can add a question and then use it.

have_cap($cap)   X-Ref
Has at least one parent context got the cap $cap?

param: string $cap capability
return: boolean

have_one_cap($caps)   X-Ref
Has at least one parent context got one of the caps $caps?

param: array $caps capability
return: boolean

have_one_edit_tab_cap($tabname)   X-Ref
Has at least one parent context got one of the caps for actions on $tabname

param: string $tabname edit tab name
return: boolean

require_cap($cap)   X-Ref
Throw error if at least one parent context hasn't got the cap $cap

param: string $cap capability

require_one_cap($caps)   X-Ref
Throw error if at least one parent context hasn't got one of the caps $caps

param: array $caps capabilities

require_one_edit_tab_cap($tabname)   X-Ref
Throw error if at least one parent context hasn't got one of the caps $caps

param: string $tabname edit tab name

question_rewrite_question_urls($text, $file, $contextid, $component,$filearea, array $ids, $itemid, array $options=null)   X-Ref
Helps call file_rewrite_pluginfile_urls with the right parameters.

param: string $text text being processed
param: string $file the php script used to serve files
param: int $contextid context ID
param: string $component component
param: string $filearea filearea
param: array $ids other IDs will be used to check file permission
param: int $itemid item ID
param: array $options options
return: string

question_rewrite_question_preview_urls($text, $questionid,$filecontextid, $filecomponent, $filearea, $itemid,$previewcontextid, $previewcomponent, $options = null)   X-Ref
Rewrite the PLUGINFILE urls in part of the content of a question, for use when
viewing the question outside an attempt (for example, in the question bank
listing or in the quiz statistics report).

param: string $text the question text.
param: int $questionid the question id.
param: int $filecontextid the context id of the question being displayed.
param: string $filecomponent the component that owns the file area.
param: string $filearea the file area name.
param: int|null $itemid the file's itemid
param: int $previewcontextid the context id where the preview is being displayed.
param: string $previewcomponent component responsible for displaying the preview.
param: array $options text and file options ('forcehttps'=>false)
return: string $questiontext with URLs rewritten.

question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()   X-Ref
Called by pluginfile.php to serve files related to the 'question' core
component and for files belonging to qtypes.

For files that relate to questions in a question_attempt, then we delegate to
a function in the component that owns the attempt (for example in the quiz,
or in core question preview) to get necessary inforation.

(Note that, at the moment, all question file areas relate to questions in
attempts, so the If at the start of the last paragraph is always true.)

Does not return, either calls send_file_not_found(); or serves the file.

param: stdClass $course course settings object
param: stdClass $context context object
param: string $component the name of the component we are serving files for.
param: string $filearea the name of the file area.
param: array $args the remaining bits of the file path.
param: bool $forcedownload whether the user must be forced to download the file.
param: array $options additional options affecting the file serving

core_question_question_preview_pluginfile($previewcontext, $questionid,$filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()   X-Ref
Serve questiontext files in the question text when they are displayed in this report.

param: context $previewcontext the context in which the preview is happening.
param: int $questionid the question id.
param: context $filecontext the file (question) context.
param: string $filecomponent the component the file belongs to.
param: string $filearea the file area.
param: array $args remaining file args.
param: bool $forcedownload.
param: array $options additional options affecting the file serving.

question_make_export_url($contextid, $categoryid, $format, $withcategories,$withcontexts, $filename)   X-Ref
Create url for question export

param: int $contextid, current context
param: int $categoryid, categoryid
param: string $format
param: string $withcategories
param: string $ithcontexts
param: moodle_url export file url

question_get_export_single_question_url($question)   X-Ref
Get the URL to export a single question (exportone.php).

param: stdClass|question_definition $question the question definition as obtained from
return: moodle_url the requested URL.

question_page_type_list($pagetype, $parentcontext, $currentcontext)   X-Ref
Return a list of page types

param: string $pagetype current page type
param: stdClass $parentcontext Block's parent context
param: stdClass $currentcontext Current context of block

question_module_uses_questions($modname)   X-Ref
Does an activity module use the question bank?

param: string $modname The name of the module (without mod_ prefix).
return: bool true if the module uses questions.

core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid)   X-Ref
If $oldidnumber ends in some digits then return the next available idnumber of the same form.

So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.

param: string|null $oldidnumber a question idnumber, or can be null.
param: int $categoryid a question category id.
return: string|null suggested new idnumber for a question in that category, or null if one cannot be found.

Functions that are not part of a class:

question_reorder_qtypes($sortedqtypes, $tomove, $direction)   X-Ref
Move one question type in a list of question types. If you try to move one element
off of the end, nothing will change.

param: array $sortedqtypes An array $qtype => anything.
param: string $tomove one of the keys from $sortedqtypes
param: integer $direction +1 or -1
return: array an array $index => $qtype, with $index from 0 to n in order, and

question_save_qtype_order($neworder, $config = null)   X-Ref
Save a new question type order to the config_plugins table.

param: $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
param: $config get_config('question'), if you happen to have it around, to save one DB query.

questions_in_use($questionids)   X-Ref

param: array $questionids of question ids.
return: boolean whether any of these questions are being used by any part of Moodle.

question_context_has_any_questions($context)   X-Ref
Determine whether there arey any questions belonging to this context, that is whether any of its
question categories contain any questions. This will return true even if all the questions are
hidden.

param: mixed $context either a context object, or a context id.
return: boolean whether any of the question categories beloning to this context have

match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error')   X-Ref
Check whether a given grade is one of a list of allowed options. If not,
depending on $matchgrades, either return the nearest match, or return false
to signal an error.

param: array $gradeoptionsfull list of valid options
param: int $grade grade to be tested
param: string $matchgrades 'error' or 'nearest'
return: mixed either 'fixed' value or false if error.

question_remove_stale_questions_from_category($categoryid)   X-Ref
Remove stale questions from a category.

While questions should not be left behind when they are not used any more,
it does happen, maybe via restore, or old logic, or uncovered scenarios. When
this happens, the users are unable to delete the question category unless
they move those stale questions to another one category, but to them the
category is empty as it does not contain anything. The purpose of this function
is to detect the questions that may have gone stale and remove them.

You will typically use this prior to checking if the category contains questions.

The stale questions (unused and hidden to the user) handled are:
- hidden questions
- random questions

param: int $categoryid The category ID.

question_category_delete_safe($category)   X-Ref
Category is about to be deleted,
1/ All questions are deleted for this question category.
2/ Any questions that can't be deleted are moved to a new category
NOTE: this function is called from lib/db/upgrade.php

param: object|core_course_category $category course category object

question_category_in_use($categoryid, $recursive = false)   X-Ref
Tests whether any question in a category is used by any part of Moodle.

param: integer $categoryid a question category id.
param: boolean $recursive whether to check child categories too.
return: boolean whether any question in this category is in use.

question_delete_question($questionid)   X-Ref
Deletes question and all associated data from the database

It will not delete a question if it is used somewhere.

param: object $question  The question being deleted

question_delete_context($contextid)   X-Ref
All question categories and their questions are deleted for this context id.

param: int $contextid The contextid to delete question categories from
return: array only returns an empty array for backwards compatibility.

question_delete_course($course, $notused = false)   X-Ref
All question categories and their questions are deleted for this course.

param: stdClass $course an object representing the activity
param: bool $notused this argument is not used any more. Kept for backwards compatibility.
return: bool always true.

question_delete_course_category($category, $newcategory, $notused=false)   X-Ref
Category is about to be deleted,
1/ All question categories and their questions are deleted for this course category.
2/ All questions are moved to new category

param: stdClass|core_course_category $category course category object
param: stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
param: bool $notused this argument is no longer used. Kept for backwards compatibility.
return: boolean

question_save_from_deletion($questionids, $newcontextid, $oldplace,$newcategory = null)   X-Ref
Enter description here...

param: array $questionids of question ids
param: object $newcontextid the context to create the saved category in.
param: string $oldplace a textual description of the think being deleted,
param: object $newcategory
return: mixed false on

question_delete_activity($cm, $notused = false)   X-Ref
All question categories and their questions are deleted for this activity.

param: object $cm the course module object representing the activity
param: bool $notused the argument is not used any more. Kept for backwards compatibility.
return: boolean

question_move_question_tags_to_new_context(array $questions, context $newcontext)   X-Ref
This function will handle moving all tag instances to a new context for a
given list of questions.

Questions can be tagged in up to two contexts:
1.) The context the question exists in.
2.) The course context (if the question context is a higher context.
E.g. course category context or system context.

This means a question that exists in a higher context (e.g. course cat or
system context) may have multiple groups of tags in any number of child
course contexts.

Questions in the course category context can be move "down" a context level
into one of their child course contexts or activity contexts which affects the
availability of that question in other courses / activities.

In this case it makes the questions no longer available in the other course or
activity contexts so we need to make sure that the tag instances in those other
contexts are removed.

param: stdClass[] $questions The list of question being moved (must include
param: context $newcontext The Moodle context the questions are being moved to

question_move_questions_to_category($questionids, $newcategoryid)   X-Ref
This function should be considered private to the question bank, it is called from
question/editlib.php question/contextmoveq.php and a few similar places to to the
work of actually moving questions and associated data. However, callers of this
function also have to do other work, which is why you should not call this method
directly from outside the questionbank.

param: array $questionids of question ids.
param: integer $newcategoryid the id of the category to move to.

question_move_category_to_context($categoryid, $oldcontextid, $newcontextid)   X-Ref
This function helps move a question cateogry to a new context by moving all
the files belonging to all the questions to the new context.
Also moves subcategories.

param: integer $categoryid the id of the category being moved.
param: integer $oldcontextid the old context id.
param: integer $newcontextid the new context id.

question_preview_url($questionid, $preferredbehaviour = null,$maxmark = null, $displayoptions = null, $variant = null, $context = null)   X-Ref
Generate the URL for starting a new preview of a given question with the given options.

param: integer $questionid the question to preview.
param: string $preferredbehaviour the behaviour to use for the preview.
param: float $maxmark the maximum to mark the question out of.
param: question_display_options $displayoptions the display options to use.
param: int $variant the variant of the question to preview. If null, one will
param: object $context context to run the preview in (affects things like
return: moodle_url the URL.

question_preview_popup_params()   X-Ref

return: array that can be passed as $params to the {@link popup_action} constructor.

question_preload_questions($questionids = null, $extrafields = '', $join = '',$extraparams = array()   X-Ref
Given a list of ids, load the basic information about a set of questions from
the questions table. The $join and $extrafields arguments can be used together
to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
read the code below to see how the SQL is assembled. Throws exceptions on error.

param: array $questionids array of question ids to load. If null, then all
param: string $extrafields extra SQL code to be added to the query.
param: string $join extra SQL code to be added to the query.
param: array $extraparams values for any placeholders in $join.
param: string $orderby what to order the results by. Optional, default is unspecified order.
return: array partially complete question objects. You need to call get_question_options

question_load_questions($questionids, $extrafields = '', $join = '')   X-Ref
Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
read the code below to see how the SQL is assembled. Throws exceptions on error.

param: array $questionids array of question ids.
param: string $extrafields extra SQL code to be added to the query.
param: string $join extra SQL code to be added to the query.
param: array $extraparams values for any placeholders in $join.
return: array question objects.

_tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null)   X-Ref
Private function to factor common code out of get_question_options().

param: object $question the question to tidy.
param: stdClass $category The question_categories record for the given $question.
param: stdClass[]|null $tagobjects The tags for the given $question.
param: stdClass[]|null $filtercourses The courses to filter the course tags by.

get_question_options(&$questions, $loadtags = false, $filtercourses = null)   X-Ref
Updates the question objects with question type specific
information by calling {@link get_question_options()}

Can be called either with an array of question objects or with a single
question object.

param: mixed $questions Either an array of question objects to be updated
param: bool $loadtags load the question tags from the tags table. Optional, default false.
param: stdClass[] $filtercourses The courses to filter the course tags by.
return: bool Indicates success or failure.

question_sort_tags($tagobjects, $categorycontext, $filtercourses = null)   X-Ref
Sort question tags by course or normal tags.

This function also search tag instances that may have a context id that don't match either a course or
question context and fix the data setting the correct context id.

param: stdClass[] $tagobjects The tags for the given $question.
param: stdClass $categorycontext The question categories context.
param: stdClass[]|null $filtercourses The courses to filter the course tags by.
return: stdClass $sortedtagobjects Sorted tag objects.

print_question_icon($question)   X-Ref
Print the icon for the question type

param: object $question The question object for which the icon is required.
return: string the HTML for the img tag.

question_hash($question)   X-Ref
Creates a stamp that uniquely identifies this version of the question

In future we want this to use a hash of the question data to guarantee that
identical versions have the same version stamp.

param: object $question
return: string A unique version stamp

sort_categories_by_tree(&$categories, $id = 0, $level = 1)   X-Ref
returns the categories with their names ordered following parent-child relationships
finally it tries to return pending categories (those being orphaned, whose parent is
incorrect) to avoid missing any category from original array.


flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1)   X-Ref
Private method, only for the use of add_indented_names().

Recursively adds an indentedname field to each category, starting with the category
with id $id, and dealing with that category and all its children, and
return a new array, with those categories in the right order.

param: array $categories an array of categories which has had childids
param: int $id the category to start the indenting process from.
param: int $depth the indent depth. Used in recursive calls.
return: array a new array of categories, in the right order for the tree.

add_indented_names($categories, $nochildrenof = -1)   X-Ref
Format categories into an indented list reflecting the tree structure.

param: array $categories An array of category objects, for example from the.
return: array The formatted list of categories.

question_category_select_menu($contexts, $top = false, $currentcat = 0,$selected = "", $nochildrenof = -1)   X-Ref
Output a select menu of question categories.

Categories from this course and (optionally) published categories from other courses
are included. Optionally, only categories the current user may edit can be included.

param: integer $courseid the id of the course to get the categories for.
param: integer $published if true, include publised categories from other courses.
param: integer $only_editable if true, exclude categories this user is not allowed to edit.
param: integer $selected optionally, the id of a category to be selected by

question_get_default_category($contextid)   X-Ref

param: integer $contextid a context id.
return: object the default question category for that context, or false if none.

question_get_top_category($contextid, $create = false)   X-Ref
Gets the top category in the given context.
This function can optionally create the top category if it doesn't exist.

param: int $contextid A context id.
param: bool $create Whether create a top category if it doesn't exist.
return: bool|stdClass The top question category for that context, or false if none.

question_get_top_categories_for_contexts($contextids)   X-Ref
Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.

param: array $contextids List of context ids
return: array

question_make_default_categories($contexts)   X-Ref
Gets the default category in the most specific context.
If no categories exist yet then default ones are created in all contexts.

param: array $contexts  The context objects for this context and all parent contexts.
return: object The default category - the category in the course context

get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false)   X-Ref
Get all the category objects, including a count of the number of questions in that category,
for all the categories in the lists $contexts.

param: mixed $contexts either a single contextid, or a comma-separated list of context ids.
param: string $sortorder used as the ORDER BY clause in the select statement.
param: bool $top Whether to return the top categories or not.
return: array of category objects.

question_category_options($contexts, $top = false, $currentcat = 0,$popupform = false, $nochildrenof = -1, $escapecontextnames = true)   X-Ref
Output an array of question categories.

param: array $contexts The list of contexts.
param: bool $top Whether to return the top categories or not.
param: int $currentcat
param: bool $popupform
param: int $nochildrenof
param: boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
return: array

question_add_context_in_key($categories)   X-Ref
No description

question_fix_top_names($categories, $escape = true)   X-Ref
Finds top categories in the given categories hierarchy and replace their name with a proper localised string.

param: array $categories An array of question categories.
param: boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
return: array The same question category list given to the function, with the top category names being translated.

question_categorylist($categoryid)   X-Ref

return: array of question category ids of the category and all subcategories.

question_categorylist_parents(int $categoryid)   X-Ref
Get all parent categories of a given question category in decending order.

param: int $categoryid for which you want to find the parents.
return: array of question category ids of all parents categories.

get_import_export_formats($type)   X-Ref
Get list of available import or export formats

param: string $type 'import' if import list, otherwise export list assumed
return: array sorted list of import/export formats available

question_default_export_filename($course, $category)   X-Ref
Create a reasonable default file name for exporting questions from a particular
category.

param: object $course the course the questions are in.
param: object $category the question category.
return: string the filename.