Moodle PHP Documentation 4.5
Moodle 4.5dev (Build: 20240606) (d3ae1391abe)
restore_controller_dbops Class Reference

Non instantiable helper class providing DB support to the @restore_controller. More...

Inheritance diagram for restore_controller_dbops:
restore_dbops

Static Public Member Functions

static apply_config_defaults (restore_controller $controller)
 Sets the default values for the settings in a restore operation.
 
static calculate_course_names ($courseid, $fullname, $shortname)
 Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes.
 
static create_included_users ($basepath, $restoreid, $userid, core\progress\base $progress, int $courseid=0)
 Given one restoreid, create in DB all the users present in backup_ids having newitemid = 0, as far as precheck_included_users() have left them there ready to be created.
 
static moodle_database create_new_course ($fullname, $shortname, $categoryid)
 Creates a skeleton record within the database using the passed parameters and returns the new course id.
 
static create_restore_temp_tables ($restoreid)
 
static delete_course_content ($courseid, array $options=null)
 Deletes all of the content associated with the given course (courseid)
 
static drop_restore_temp_tables ($backupid)
 
static get_backup_ids_record ($restoreid, $itemname, $itemid)
 
static get_included_tasks ($restoreid)
 Return one array containing all the tasks that have been included in the restore process.
 
static load_categories_and_questions_to_tempids ($restoreid, $questionsfile)
 Load the needed questions.xml file to backup_ids table for future reference.
 
static load_controller ($restoreid)
 
static load_inforef_to_tempids ($restoreid, $inforeffile, core\progress\base $progress=null)
 Load one inforef.xml file to backup_ids table for future reference.
 
static load_roles_to_tempids ($restoreid, $rolesfile)
 Load the needed role.xml file to backup_ids table for future reference.
 
static load_users_to_tempids ($restoreid, $usersfile, core\progress\base $progress=null)
 Load the needed users.xml file to backup_ids table for future reference.
 
static precheck_categories_and_questions ($restoreid, $courseid, $userid, $samesite)
 Check all the included categories and questions, deciding the action to perform for each one (mapping / creation) and returning one array of problems in case something is wrong.
 
static precheck_included_roles ($restoreid, $courseid, $userid, $samesite, $rolemappings)
 Precheck the loaded roles, return empty array if everything is ok, and array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks) with any problem found.
 
static precheck_included_users ($restoreid, $courseid, $userid, $samesite, core\progress\base $progress)
 Check all the included users, deciding the action to perform for each one (mapping / creation) and returning one array of problems in case something is wrong (lack of permissions, conficts)
 
static prechek_precheck_qbanks_by_level ($restoreid, $courseid, $userid, $samesite, $contextlevel)
 This function will process all the question banks present in restore at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding the target contexts where each bank will be restored and returning warnings/errors as needed.
 
static process_categories_and_questions ($restoreid, $courseid, $userid, $samesite)
 Process the needed question categories and questions to check all them, deciding about the action to perform (create/map) and target.
 
static process_included_roles ($restoreid, $courseid, $userid, $samesite, $rolemappings)
 Process the loaded roles, looking for their best mapping or skipping Any error will cause exception.
 
static process_included_users ($restoreid, $courseid, $userid, $samesite, core\progress\base $progress=null)
 Process the needed users in order to decide which action to perform with them (create/map)
 
static reset_backup_ids_cached ()
 Reset the ids caches completely.
 
static restore_find_best_target_context ($categories, $courseid, $contextlevel)
 Calculates the best context found to restore one collection of qcats, al them belonging to the same context (question bank), returning the target context found (object) or false.
 
static restore_get_question_banks ($restoreid, $contextlevel=null)
 Return one array of contextid => contextlevel pairs of question banks to be checked for one given restore operation ordered from CONTEXT_SYSTEM downto CONTEXT_MODULE If contextlevel is specified, then only banks corresponding to that level are returned.
 
static restore_get_question_categories ($restoreid, $contextid, $contextlevel)
 Return one array of question_category records for a given restore operation and one restore context (question bank)
 
static restore_get_questions ($restoreid, $qcatid)
 Return one array of question records for a given restore operation and one question category.
 
static save_controller ($controller, $checksum, $includeobj=true, $cleanobj=false)
 Send one restore controller to DB.
 
static send_files_to_pool ($basepath, $restoreid, $component, $filearea, $oldcontextid, $dfltuserid, $itemname=null, $olditemid=null, $forcenewcontextid=null, $skipparentitemidctxmatch=false, core\progress\base $progress=null)
 Given one component/filearea/context and optionally one source itemname to match itemids put the corresponding files in the pool.
 
static set_backup_files_record ($restoreid, $filerec)
 
static set_backup_ids_record ($restoreid, $itemname, $itemid, $newitemid=0, $parentitemid=null, $info=null)
 
static set_course_role_names ($restoreid, $courseid)
 For the target course context, put as many custom role names as possible.
 

Static Protected Member Functions

static get_backup_ids_cached ($restoreid, $itemname, $itemid)
 Return cached backup id's.
 
static get_best_assignable_role ($role, $courseid, $userid, $samesite)
 Given one role, as loaded from XML, perform the best possible matching against the assignable roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid) returning the id of the best matching role or 0 if no match is found.
 
static get_missing_file_result ($file)
 Returns suitable entry to include in log when there is a missing file.
 
static precheck_user ($user, $samesite, $siteid=null)
 Given one user object (from backup file), perform all the neccesary checks is order to decide how that user will be handled on restore.
 
static set_backup_ids_cached ($restoreid, $itemname, $itemid, $extrarecord)
 Cache backup ids'.
 
static update_backup_cached_record ($record, $extrarecord, $key, $existingrecord=null)
 Updates existing backup record.
 

Detailed Description

Non instantiable helper class providing DB support to the @restore_controller.

This class contains various static methods available for all the DB operations performed by the restore_controller class

TODO: Finish phpdocs

Member Function Documentation

◆ apply_config_defaults()

static restore_controller_dbops::apply_config_defaults ( restore_controller $controller)
static

Sets the default values for the settings in a restore operation.

Parameters
restore_controller$controller

◆ create_included_users()

static restore_dbops::create_included_users ( $basepath,
$restoreid,
$userid,
core\progress\base $progress,
int $courseid = 0 )
staticinherited

Given one restoreid, create in DB all the users present in backup_ids having newitemid = 0, as far as precheck_included_users() have left them there ready to be created.

Also, annotate their newids once created for later reference.

This function will start and end a new progress section in the progress object.

Parameters
string$basepathBase path of unzipped backup
string$restoreidRestore ID
int$useridDefault userid for files
core\progress\base$progressObject used for progress tracking
int$courseidCourse ID

◆ create_new_course()

static moodle_database restore_dbops::create_new_course ( $fullname,
$shortname,
$categoryid )
staticinherited

Creates a skeleton record within the database using the passed parameters and returns the new course id.

$DB

Parameters
string$fullname
string$shortname
int$categoryid
Return values
intThe new course id

◆ delete_course_content()

static restore_dbops::delete_course_content ( $courseid,
array $options = null )
staticinherited

Deletes all of the content associated with the given course (courseid)

Parameters
int$courseid
array$options
Return values
boolTrue for success

◆ get_backup_ids_cached()

static restore_dbops::get_backup_ids_cached ( $restoreid,
$itemname,
$itemid )
staticprotectedinherited

Return cached backup id's.

Parameters
int$restoreidid of backup
string$itemnamename of the item
int$itemidid of item
Return values
stdClass|falserecord from 'backup_ids_temp' table
Todo
MDL-25290 replace static backupids* with MUC code

◆ get_included_tasks()

static restore_dbops::get_included_tasks ( $restoreid)
staticinherited

Return one array containing all the tasks that have been included in the restore process.

Note that these tasks aren't built (they haven't steps nor ids data available)

◆ get_missing_file_result()

static restore_dbops::get_missing_file_result ( $file)
staticprotectedinherited

Returns suitable entry to include in log when there is a missing file.

Parameters
stdClass$fileFile definition
Return values
stdClassLog entry

◆ load_inforef_to_tempids()

static restore_dbops::load_inforef_to_tempids ( $restoreid,
$inforeffile,
core\progress\base $progress = null )
staticinherited

Load one inforef.xml file to backup_ids table for future reference.

Parameters
string$restoreidRestore id
string$inforeffileFile path
core\progress\base$progressProgress tracker

◆ load_users_to_tempids()

static restore_dbops::load_users_to_tempids ( $restoreid,
$usersfile,
core\progress\base $progress = null )
staticinherited

Load the needed users.xml file to backup_ids table for future reference.

Parameters
string$restoreidRestore id
string$usersfileFile path
core\progress\base$progressProgress tracker

◆ precheck_categories_and_questions()

static restore_dbops::precheck_categories_and_questions ( $restoreid,
$courseid,
$userid,
$samesite )
staticinherited

Check all the included categories and questions, deciding the action to perform for each one (mapping / creation) and returning one array of problems in case something is wrong.

There are some basic rules that the method below will always try to enforce:

Rule1: Targets will be, always, calculated for whole question banks (a.k.a. contexid source), so, given 2 question categories belonging to the same bank, their target bank will be always the same. If not, we can be incurring into "fragmentation", leading to random/cloze problems (qtypes having "child" questions).

Rule2: The 'moodle/question:managecategory' and 'moodle/question:add' capabilities will be checked before creating any category/question respectively and, if the cap is not allowed into upper contexts (system, coursecat)) but in lower ones (course), the whole question bank will be created there.

Rule3: Coursecat question banks not existing in the target site will be created as course (lower ctx) question banks, never as "guessed" coursecat question banks base on depth or so.

Rule4: System question banks will be created at system context if user has perms to do so. Else they will created as course (lower ctx) question banks (similary to rule3). In other words, course ctx if always a fallback for system and coursecat question banks.

Also, there are some notes to clarify the scope of this method:

Note1: This method won't create any question category nor question at all. It simply will calculate which actions (create/map) must be performed for each element and where, validating that all those actions are doable by the user executing the restore operation. Any problem found will be returned in the problems array, causing the restore process to stop with error.

Note2: To decide if one question bank (all its question categories and questions) is going to be remapped, then all the categories and questions must exist in the same target bank. If able to do so, missing qcats and qs will be created (rule2). But if, at the end, something is missing, the whole question bank will be recreated at course ctx (rule1), no matter if that duplicates some categories/questions.

Note3: We'll be using the newitemid column in the temp_ids table to store the action to be performed with each question category and question. newitemid = 0 means the qcat/q needs to be created and any other value means the qcat/q is mapped. Also, for qcats, parentitemid will contain the target context where the categories have to be created (but for module contexts where we'll keep the old one until the activity is created)

Note4: All these "actions" will be "executed" later by restore_create_categories_and_questions

◆ precheck_included_roles()

static restore_dbops::precheck_included_roles ( $restoreid,
$courseid,
$userid,
$samesite,
$rolemappings )
staticinherited

Precheck the loaded roles, return empty array if everything is ok, and array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks) with any problem found.

At the same time, store all the mapping into backup_ids_temp and also put the information into $rolemappings (controller->info), so it can be reworked later by post-precheck stages while at the same time accept modified info in the same object coming from UI

◆ precheck_included_users()

static restore_dbops::precheck_included_users ( $restoreid,
$courseid,
$userid,
$samesite,
core\progress\base $progress )
staticinherited

Check all the included users, deciding the action to perform for each one (mapping / creation) and returning one array of problems in case something is wrong (lack of permissions, conficts)

Parameters
string$restoreidRestore id
int$courseidCourse id
int$useridUser id
bool$samesiteTrue if restore is to same site
core\progress\base$progressProgress reporter

◆ precheck_user()

static restore_dbops::precheck_user ( $user,
$samesite,
$siteid = null )
staticprotectedinherited

Given one user object (from backup file), perform all the neccesary checks is order to decide how that user will be handled on restore.

Note the function requires $user->mnethostid to be already calculated so it's caller responsibility to set it

This function is used both by @restore_precheck_users() and @restore_create_users() to get consistent results in both places

It returns:

  • one user object (from DB), if match has been found and user will be remapped
  • boolean true if the user needs to be created
  • boolean false if some conflict happened and the user cannot be handled

Each test is responsible for returning its results and interrupt execution. At the end, boolean true (user needs to be created) will be returned if no test has interrupted that.

Here it's the logic applied, keep it updated:

If restoring users from same site backup: 1A - Normal check: If match by id and username and mnethost => ok, return target user 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a match by username only => ok, return target user MDL-31484 1C - Handle users deleted in DB and "alive" in backup file: If match by id and mnethost and user is deleted in DB and (match by username LIKE 'backup_email.' or by non empty email = md5(username)) => ok, return target user 1D - Handle users deleted in backup file and "alive" in DB: If match by id and mnethost and user is deleted in backup file and match by email = email_without_time(backup_email) => ok, return target user 1E - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false 1F - None of the above, return true => User needs to be created

if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination): 2A - Normal check: 2A1 - If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user 2A2 - Exceptional handling (MDL-21912): Match "admin" username. Then, if import_general_duplicate_admin_allowed is enabled, attempt to map the admin user to the user 'admin_[oldsiteid]' if it exists. If not, the user 'admin_[oldsiteid]' will be created in precheck_included users 2B - Handle users deleted in DB and "alive" in backup file: 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and (username LIKE 'backup_email.' or non-zero firstaccess) => ok, return target user 2B2 - If match by mnethost and user is deleted in DB and username LIKE 'backup_email.' and non-zero firstaccess) => ok, return target user (to cover situations were md5(username) wasn't implemented on delete we requiere both) 2C - Handle users deleted in backup file and "alive" in DB: If match mnethost and user is deleted in backup file and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false 2E - None of the above, return true => User needs to be created

Note: for DB deleted users email is stored in username field, hence we are looking there for emails. See delete_user() Note: for DB deleted users md5(username) is stored sometimes in the email field, hence we are looking there for usernames if not empty. See delete_user()

◆ prechek_precheck_qbanks_by_level()

static restore_dbops::prechek_precheck_qbanks_by_level ( $restoreid,
$courseid,
$userid,
$samesite,
$contextlevel )
staticinherited

This function will process all the question banks present in restore at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding the target contexts where each bank will be restored and returning warnings/errors as needed.

Some contextlevels (system, coursecat), will delegate process to course level if any problem is found (lack of permissions, non-matching target context...). Other contextlevels (course, module) will cause return error if some problem is found.

At the end, if no errors were found, all the categories in backup_temp_ids will be pointing (parentitemid) to the target context where they must be created later in the restore process.

Note: at the time these prechecks are executed, activities haven't been created yet so, for CONTEXT_MODULE banks, we keep the old contextid in the parentitemid field. Once the activity (and its context) has been created, we'll update that context in the required qcats

Caller precheck_categories_and_questions will, simply, execute this function for all the contextlevels, acting as a simple controller of warnings and errors.

The function returns 2 arrays, one containing errors and another containing warnings. Both empty if no errors/warnings are found.

Parameters
int$restoreidThe restore ID
int$courseidThe ID of the course
int$useridThe id of the user doing the restore
bool$samesiteTrue if restore is to same site
int$contextlevel(CONTEXT_SYSTEM, etc.)
Return values
arrayA separate list of all error and warnings detected

◆ process_categories_and_questions()

static restore_dbops::process_categories_and_questions ( $restoreid,
$courseid,
$userid,
$samesite )
staticinherited

Process the needed question categories and questions to check all them, deciding about the action to perform (create/map) and target.

Just wrap over precheck_categories_and_questions(), returning exception if any problem is found

◆ process_included_roles()

static restore_dbops::process_included_roles ( $restoreid,
$courseid,
$userid,
$samesite,
$rolemappings )
staticinherited

Process the loaded roles, looking for their best mapping or skipping Any error will cause exception.

Note this is one wrapper over precheck_included_roles, that contains all the logic, but returns errors/warnings instead and is executed as part of the restore prechecks

◆ process_included_users()

static restore_dbops::process_included_users ( $restoreid,
$courseid,
$userid,
$samesite,
core\progress\base $progress = null )
staticinherited

Process the needed users in order to decide which action to perform with them (create/map)

Just wrap over precheck_included_users(), returning exception if any problem is found

Parameters
string$restoreidRestore id
int$courseidCourse id
int$useridUser id
bool$samesiteTrue if restore is to same site
core\progress\base$progressOptional progress tracker

◆ reset_backup_ids_cached()

static restore_dbops::reset_backup_ids_cached ( )
staticinherited

Reset the ids caches completely.

Any destructive operation (partial delete, truncate, drop or recreate) performed with the backup_ids table must cause the backup_ids caches to be invalidated by calling this method. See MDL-33630.

Note that right now, the only operation of that type is the recreation (drop & restore) of the table that may happen once the prechecks have ended. All the rest of operations are always routed via set_backup_ids_record(), 1 by 1, keeping the caches on sync.

Todo
MDL-25290 static should be replaced with MUC code.

◆ restore_get_question_categories()

static restore_dbops::restore_get_question_categories ( $restoreid,
$contextid,
$contextlevel )
staticinherited

Return one array of question_category records for a given restore operation and one restore context (question bank)

Parameters
string$restoreidUnique identifier of the restore operation being performed.
int$contextidContext id we want question categories to be returned.
int$contextlevelContext level we want to restrict the returned categories.
Return values
arrayQuestion categories for the given context id and level.

◆ save_controller()

static restore_controller_dbops::save_controller ( $controller,
$checksum,
$includeobj = true,
$cleanobj = false )
static

Send one restore controller to DB.

Parameters
restore_controller$controllercontroller to send to DB
string$checksumhash of the controller to be checked
bool$includeobjto decide if the object itself must be updated (true) or no (false)
bool$cleanobjto decide if the object itself must be cleaned (true) or no (false)
Return values
intid of the controller record in the DB
Exceptions
backup_controller_exception|restore_dbops_exception

◆ send_files_to_pool()

static restore_dbops::send_files_to_pool ( $basepath,
$restoreid,
$component,
$filearea,
$oldcontextid,
$dfltuserid,
$itemname = null,
$olditemid = null,
$forcenewcontextid = null,
$skipparentitemidctxmatch = false,
core\progress\base $progress = null )
staticinherited

Given one component/filearea/context and optionally one source itemname to match itemids put the corresponding files in the pool.

If you specify a progress reporter, it will get called once per file with indeterminate progress.

Parameters
string$basepaththe full path to the root of unzipped backup file
string$restoreidthe restore job's identification
string$component
string$filearea
int$oldcontextid
int$dfltuseriddefault $file->user if the old one can't be mapped
string | null$itemname
int | null$olditemid
int | null$forcenewcontextidexplicit value for the new contextid (skip mapping)
bool$skipparentitemidctxmatch
core\progress\base$progressOptional progress reporter
Return values
arrayof result object

◆ set_backup_ids_cached()

static restore_dbops::set_backup_ids_cached ( $restoreid,
$itemname,
$itemid,
$extrarecord )
staticprotectedinherited

Cache backup ids'.

Parameters
int$restoreidid of backup
string$itemnamename of the item
int$itemidid of item
array$extrarecordextra record which needs to be updated
Return values
void
Todo
MDL-25290 replace static BACKUP_IDS_* with MUC code

◆ update_backup_cached_record()

static restore_dbops::update_backup_cached_record ( $record,
$extrarecord,
$key,
$existingrecord = null )
staticprotectedinherited

Updates existing backup record.

Parameters
array$recordrecord which needs to be updated
array$extrarecordextra record which needs to be updated
string$keyunique key which is used to identify cached record
stdClass$existingrecord(optional) existing record

The documentation for this class was generated from the following file: