Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/mod/quiz/ -> lib.php (source)

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

Library of functions for the quiz module. This contains functions that are called also from outside the quiz module Functions that are only called by the quiz module itself are in {@link locallib.php}

Copyright: 1999 onwards Martin Dougiamas {@link http://moodle.com}
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2522 lines (93 kb)
Included or required:0 times
Referenced: 3 times
Includes or requires: 1 file
 mod/quiz/deprecatedlib.php

Defines 59 functions

  quiz_add_instance()
  quiz_update_instance()
  quiz_delete_instance()
  quiz_delete_override()
  quiz_delete_all_overrides()
  quiz_update_effective_access()
  quiz_delete_all_attempts()
  quiz_delete_user_attempts()
  quiz_get_best_grade()
  quiz_has_grades()
  quiz_allows_multiple_tries()
  quiz_user_outline()
  quiz_user_complete()
  quiz_get_user_attempts()
  quiz_get_user_grades()
  quiz_format_grade()
  quiz_get_grade_format()
  quiz_format_question_grade()
  quiz_update_grades()
  quiz_grade_item_update()
  quiz_grade_item_delete()
  quiz_refresh_events()
  quiz_get_recent_mod_activity()
  quiz_print_recent_mod_activity()
  quiz_process_options()
  quiz_review_option_form_to_db()
  mod_quiz_inplace_editable()
  quiz_after_add_or_update()
  quiz_update_events()
  quiz_get_group_override_priorities()
  quiz_get_view_actions()
  quiz_get_post_actions()
  quiz_questions_in_use()
  quiz_reset_course_form_definition()
  quiz_reset_course_form_defaults()
  quiz_reset_gradebook()
  quiz_reset_userdata()
  quiz_num_attempt_summary()
  quiz_attempt_summary_link_to_reports()
  quiz_supports()
  quiz_get_extra_capabilities()
  quiz_extend_settings_navigation()
  quiz_pluginfile()
  quiz_question_pluginfile()
  quiz_page_type_list()
  quiz_get_navigation_options()
  quiz_check_updates_since()
  mod_quiz_get_fontawesome_icon_map()
  mod_quiz_core_calendar_provide_event_action()
  quiz_get_coursemodule_info()
  mod_quiz_cm_info_dynamic()
  mod_quiz_get_completion_active_rule_descriptions()
  mod_quiz_core_calendar_get_valid_event_timestart_range()
  mod_quiz_core_calendar_event_timestart_updated()
  mod_quiz_output_fragment_quiz_question_bank()
  mod_quiz_output_fragment_add_random_question_form()
  mod_quiz_core_calendar_get_event_action_string()
  quiz_delete_references()
  mod_quiz_calculate_question_stats()

Functions that are not part of a class:

quiz_add_instance($quiz)   X-Ref
Given an object containing all the necessary data,
(defined by the form in mod_form.php) this function
will create a new instance and return the id number
of the new instance.

param: stdClass $quiz the data that came from the form.
return: mixed the id of the new instance on success,

quiz_update_instance($quiz, $mform)   X-Ref
Given an object containing all the necessary data,
(defined by the form in mod_form.php) this function
will update an existing instance with new data.

param: stdClass $quiz the data that came from the form.
param: stdClass $mform no longer used.
return: mixed true on success, false or a string error message on failure.

quiz_delete_instance($id)   X-Ref
Given an ID of an instance of this module,
this function will permanently delete the instance
and any data that depends on it.

param: int $id the id of the quiz to delete.
return: bool success or failure.

quiz_delete_override($quiz, $overrideid, $log = true)   X-Ref
Deletes a quiz override from the database and clears any corresponding calendar events

param: stdClass $quiz The quiz object.
param: int $overrideid The id of the override being deleted
param: bool $log Whether to trigger logs.
return: bool true on success

quiz_delete_all_overrides($quiz, $log = true)   X-Ref
Deletes all quiz overrides from the database and clears any corresponding calendar events

param: stdClass $quiz The quiz object.
param: bool $log Whether to trigger logs.

quiz_update_effective_access($quiz, $userid)   X-Ref
Updates a quiz object with override information for a user.

Algorithm:  For each quiz setting, if there is a matching user-specific override,
then use that otherwise, if there are group-specific overrides, return the most
lenient combination of them.  If neither applies, leave the quiz setting unchanged.

Special case: if there is more than one password that applies to the user, then
quiz->extrapasswords will contain an array of strings giving the remaining
passwords.

param: stdClass $quiz The quiz object.
param: int $userid The userid.
return: stdClass $quiz The updated quiz object.

quiz_delete_all_attempts($quiz)   X-Ref
Delete all the attempts belonging to a quiz.

param: stdClass $quiz The quiz object.

quiz_delete_user_attempts($quiz, $user)   X-Ref
Delete all the attempts belonging to a user in a particular quiz.

param: \mod_quiz\quiz_settings $quiz The quiz object.
param: stdClass $user The user object.

quiz_get_best_grade($quiz, $userid)   X-Ref
Get the best current grade for a particular user in a quiz.

param: stdClass $quiz the quiz settings.
param: int $userid the id of the user.
return: float the user's current grade for this quiz, or null if this user does

quiz_has_grades($quiz)   X-Ref
Is this a graded quiz? If this method returns true, you can assume that
$quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
divide by them).

param: stdClass $quiz a row from the quiz table.
return: bool whether this is a graded quiz.

quiz_allows_multiple_tries($quiz)   X-Ref
Does this quiz allow multiple tries?

return: bool

quiz_user_outline($course, $user, $mod, $quiz)   X-Ref
Return a small object with summary information about what a
user has done with a given particular instance of this module
Used for user activity reports.
$return->time = the time they did it
$return->info = a short text description

param: stdClass $course
param: stdClass $user
param: stdClass $mod
param: stdClass $quiz
return: stdClass|null

quiz_user_complete($course, $user, $mod, $quiz)   X-Ref
Print a detailed representation of what a  user has done with
a given particular instance of this module, for user activity reports.

param: stdClass $course
param: stdClass $user
param: stdClass $mod
param: stdClass $quiz
return: bool

quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false)   X-Ref

param: int|array $quizids A quiz ID, or an array of quiz IDs.
param: int $userid the userid.
param: string $status 'all', 'finished' or 'unfinished' to control
param: bool $includepreviews
return: array of all the user's attempts at this quiz. Returns an empty

quiz_get_user_grades($quiz, $userid = 0)   X-Ref
Return grade for given user or all users.

param: int $quizid id of quiz
param: int $userid optional user id, 0 means all users
return: array array of grades, false if none. These are raw grades. They should

quiz_format_grade($quiz, $grade)   X-Ref
Round a grade to the correct number of decimal places, and format it for display.

param: stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
param: float $grade The grade to round.
return: string

quiz_get_grade_format($quiz)   X-Ref
Determine the correct number of decimal places required to format a grade.

param: stdClass $quiz The quiz table row, only $quiz->decimalpoints and
return: integer

quiz_format_question_grade($quiz, $grade)   X-Ref
Round a grade to the correct number of decimal places, and format it for display.

param: stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
param: float $grade The grade to round.
return: string

quiz_update_grades($quiz, $userid = 0, $nullifnone = true)   X-Ref
Update grades in central gradebook

param: stdClass $quiz the quiz settings.
param: int $userid specific user only, 0 means all users.
param: bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted

quiz_grade_item_update($quiz, $grades = null)   X-Ref
Create or update the grade item for given quiz

param: stdClass $quiz object with extra cmidnumber
param: mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
return: int 0 if ok, error code otherwise

quiz_grade_item_delete($quiz)   X-Ref
Delete grade item for given quiz

param: stdClass $quiz object
return: int

quiz_refresh_events($courseid = 0, $instance = null, $cm = null)   X-Ref
This standard function will check all instances of this module
and make sure there are up-to-date events created for each of them.
If courseid = 0, then every quiz event in the site is checked, else
only quiz events belonging to the course specified are checked.
This function is used, in its new format, by restore_refresh_events()

param: int $courseid
param: int|stdClass $instance Quiz module instance or ID.
param: int|stdClass $cm Course module object or ID (not used in this module).
return: bool

quiz_get_recent_mod_activity(&$activities, &$index, $timestart,$courseid, $cmid, $userid = 0, $groupid = 0)   X-Ref
Returns all quiz graded users since a given time for specified quiz


quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames)   X-Ref
No description

quiz_process_options($quiz)   X-Ref
Pre-process the quiz options form data, making any necessary adjustments.
Called by add/update instance in this file.

param: stdClass $quiz The variables set on the form.

quiz_review_option_form_to_db($fromform, $field)   X-Ref
Helper function for {@link quiz_process_options()}.

param: stdClass $fromform the sumbitted form date.
param: string $field one of the review option field names.

mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue)   X-Ref
In place editable callback for slot displaynumber.

param: string $itemtype slotdisplarnumber
param: int $itemid the id of the slot in the quiz_slots table
param: string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table
return: \core\output\inplace_editable|void

quiz_after_add_or_update($quiz)   X-Ref
This function is called at the end of quiz_add_instance
and quiz_update_instance, to do the common processing.

param: stdClass $quiz the quiz object.

quiz_update_events($quiz, $override = null)   X-Ref
This function updates the events associated to the quiz.
If $override is non-zero, then it updates only the events
associated with the specified override.

param: stdClass $quiz the quiz object.
param: stdClass|null $override limit to a specific override

quiz_get_group_override_priorities($quizid)   X-Ref
Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.

param: int $quizid The quiz ID.
return: array|null Array of group override priorities for open and close times. Null if there are no group overrides.

quiz_get_view_actions()   X-Ref
List the actions that correspond to a view of this module.
This is used by the participation report.

Note: This is not used by new logging system. Event with
crud = 'r' and edulevel = LEVEL_PARTICIPATING will
be considered as view action.

return: array

quiz_get_post_actions()   X-Ref
List the actions that correspond to a post of this module.
This is used by the participation report.

Note: This is not used by new logging system. Event with
crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
will be considered as post action.

return: array

quiz_questions_in_use($questionids)   X-Ref
Standard callback used by questions_in_use.

param: array $questionids of question ids.
return: bool whether any of these questions are used by any instance of this module.

quiz_reset_course_form_definition($mform)   X-Ref
Implementation of the function for printing the form elements that control
whether the course reset functionality affects the quiz.

param: MoodleQuickForm $mform the course reset form that is being built.

quiz_reset_course_form_defaults($course)   X-Ref
Course reset form defaults.

return: array the defaults.

quiz_reset_gradebook($courseid, $type='')   X-Ref
Removes all grades from gradebook

param: int $courseid
param: string optional type

quiz_reset_userdata($data)   X-Ref
Actual implementation of the reset course functionality, delete all the
quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
set and true.

Also, move the quiz open and close dates, if the course start date is changing.

param: stdClass $data the data submitted from the reset course.
return: array status array

quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0)   X-Ref
Return a textual summary of the number of attempts that have been made at a particular quiz,
returns '' if no attempts have been made yet, unless $returnzero is passed as true.

param: stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
param: stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
param: bool $returnzero if false (default), when no attempts have been
param: int $currentgroup if there is a concept of current group where this method is being called
return: string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or

quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,$currentgroup = 0)   X-Ref
Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
to the quiz reports.

param: stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
param: stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
param: stdClass $context the quiz context.
param: bool $returnzero if false (default), when no attempts have been made
param: int $currentgroup if there is a concept of current group where this method is being called
return: string HTML fragment for the link.

quiz_supports($feature)   X-Ref

param: string $feature FEATURE_xx constant for requested feature
return: mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.

quiz_get_extra_capabilities()   X-Ref

return: array all other caps used in module

quiz_extend_settings_navigation(settings_navigation $settings, navigation_node $quiznode)   X-Ref
This function extends the settings navigation block for the site.

It is safe to rely on PAGE here as we will only ever be within the module
context when this is called

param: settings_navigation $settings
param: navigation_node $quiznode
return: void

quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= [])   X-Ref
Serves the quiz files.

param: stdClass $course course object
param: stdClass $cm course module object
param: stdClass $context context object
param: string $filearea file area
param: array $args extra arguments
param: bool $forcedownload whether or not force download
param: array $options additional options affecting the file serving
return: bool false if file not found, does not return if found - justsend the file

quiz_question_pluginfile($course, $context, $component,$filearea, $qubaid, $slot, $args, $forcedownload, array $options= [])   X-Ref
Called via pluginfile.php -> question_pluginfile to serve files belonging to
a question in a question_attempt when that attempt is a quiz attempt.

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: int $qubaid the attempt usage id.
param: int $slot the id of a question in this quiz attempt.
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
return: bool false if file not found, does not return if found - justsend the file

quiz_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

quiz_get_navigation_options()   X-Ref

return: the options for quiz navigation.

quiz_check_updates_since(cm_info $cm, $from, $filter = [])   X-Ref
Check if the module has any update that affects the current user since a given time.

param: cm_info $cm course module data
param: int $from the time to check updates from
param: array $filter  if we need to check only specific updates
return: stdClass an object with the different type of areas indicating if they were updated or not

mod_quiz_get_fontawesome_icon_map()   X-Ref
Get icon mapping for font-awesome.


mod_quiz_core_calendar_provide_event_action(calendar_event $event,\core_calendar\action_factory $factory,int $userid = 0)   X-Ref
This function receives a calendar event and returns the action associated with it, or null if there is none.

This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
is not displayed on the block.

param: calendar_event $event
param: \core_calendar\action_factory $factory
param: int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
return: \core_calendar\local\event\entities\action_interface|null

quiz_get_coursemodule_info($coursemodule)   X-Ref
Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
for the course (see resource).

Given a course_module object, this function returns any "extra" information that may be needed
when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.

param: stdClass $coursemodule The coursemodule object (record).
return: cached_cm_info|false An object on information that the courses

mod_quiz_cm_info_dynamic(cm_info $cm)   X-Ref
Sets dynamic information about a course module

This function is called from cm_info when displaying the module

param: cm_info $cm

mod_quiz_get_completion_active_rule_descriptions($cm)   X-Ref
Callback which returns human-readable strings describing the active completion custom rules for the module instance.

param: cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
return: array $descriptions the array of descriptions for the custom rules.

mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz)   X-Ref
Returns the min and max values for the timestart property of a quiz
activity event.

The min and max values will be the timeopen and timeclose properties
of the quiz, respectively, if they are set.

If either value isn't set then null will be returned instead to
indicate that there is no cutoff for that value.

If the vent has no valid timestart range then [false, false] will
be returned. This is the case for overriden events.

A minimum and maximum cutoff return value will look like:
[
[1505704373, 'The date must be after this date'],
[1506741172, 'The date must be before this date']
]

param: \calendar_event $event The calendar event to get the time range for
param: stdClass $quiz The module instance to get the range from
return: array

mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz)   X-Ref
This function will update the quiz module according to the
event that has been modified.

It will set the timeopen or timeclose value of the quiz instance
according to the type of event provided.

param: \calendar_event $event A quiz activity calendar event
param: \stdClass $quiz A quiz activity instance

mod_quiz_output_fragment_quiz_question_bank($args)   X-Ref
Generates the question bank in a fragment output. This allows
the question bank to be displayed in a modal.

The only expected argument provided in the $args array is
'querystring'. The value should be the list of parameters
URL encoded and used to build the question bank page.

The individual list of parameters expected can be found in
question_build_edit_resources.

param: array $args The fragment arguments.
return: string The rendered mform fragment.

mod_quiz_output_fragment_add_random_question_form($args)   X-Ref
Generates the add random question in a fragment output. This allows the
form to be rendered in javascript, for example inside a modal.

The required arguments as keys in the $args array are:
cat {string} The category and category context ids comma separated.
addonpage {int} The page id to add this question to.
returnurl {string} URL to return to after form submission.
cmid {int} The course module id the questions are being added to.

param: array $args The fragment arguments.
return: string The rendered mform fragment.

mod_quiz_core_calendar_get_event_action_string(string $eventtype)   X-Ref
Callback to fetch the activity event type lang string.

param: string $eventtype The event type.
return: lang_string The event type lang string.

quiz_delete_references($quizid)   X-Ref
Delete question reference data.

param: int $quizid The id of quiz.

mod_quiz_calculate_question_stats(context $context)   X-Ref
Implement the calculate_question_stats callback.

This enables quiz statistics to be shown in statistics columns in the database.

param: context $context return the statistics related to this context (which will be a quiz context).
return: all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null.