/** * Execute. */ public function execute() { mtrace('Sync cohort roles...'); $result = api::sync_all_cohort_roles(); mtrace('Added ' . count($result['rolesadded'])); mtrace('Removed ' . count($result['rolesremoved'])); }
/** * set or unset an access to some peer * @param int $userid * @param bool $access true or false * @param string $wwwroot optional host root to give acces to. the access filed name is computed from the wwwroot url */ function user_mnet_hosts_set_access($userid, $access, $wwwroot = null) { global $CFG, $DB; if (!$wwwroot) { $wwwroot = $CFG->wwwroot; } $accesskey = user_mnet_hosts_make_accesskey($wwwroot, true); if (!($field = $DB->get_record('user_info_field', array('shortname' => $accesskey)))) { // Try to setup install if results not having done before. if ($wwwroot == $CFG->wwwroot) { require_once $CFG->dirroot . '/blocks/user_mnet_hosts/db/install.php'; xmldb_block_user_mnet_hosts_install(); mtrace("Second chance {$accesskey} "); $field = $DB->get_record('user_info_field', array('shortname' => $accesskey)); } else { return false; } } if ($data = $DB->get_record('user_info_data', array('userid' => $userid, 'fieldid' => $field->id))) { $data->data = $access; $DB->update_record('user_info_data', $data); } else { $data = new StdClass(); $data->userid = $userid; $data->fieldid = $field->id; $data->data = $access; $DB->insert_record('user_info_data', $data); } }
public function execute() { include_once $CFG->dirroot . '/local/enrolmentreminder/lib.php'; mtrace('running enrolment reminders scheduled task'); local_enrolmentreminder_cron(); set_config('lastcron', time(), 'local_enrolmentreminder'); }
/** * Function to be run periodically according to the moodle cron * This function searches for things that need to be done, such * as sending out mail, toggling flags etc ... * * Runs any automatically scheduled reports weekly or monthly. * * @return boolean */ public function execute() { global $CFG, $DB; require_once dirname(__FILE__) . '/../../locallib.php'; $timenow = time(); list($startofthisweek, $startoflastweek) = report_customsql_get_week_starts($timenow); list($startofthismonth) = report_customsql_get_month_starts($timenow); mtrace("... Looking for old temp CSV files to delete."); $numdeleted = report_customsql_delete_old_temp_files($startoflastweek); if ($numdeleted) { mtrace("... {$numdeleted} old temporary files deleted."); } // Get daily scheduled reports. $dailyreportstorun = report_customsql_get_ready_to_run_daily_reports($timenow); // Get weekly and monthly scheduled reports. $scheduledreportstorun = $DB->get_records_select('report_customsql_queries', "(runable = 'weekly' AND lastrun < :startofthisweek) OR\n (runable = 'monthly' AND lastrun < :startofthismonth)", array('startofthisweek' => $startofthisweek, 'startofthismonth' => $startofthismonth), 'lastrun'); // All reports ready to run. $reportstorun = array_merge($dailyreportstorun, $scheduledreportstorun); foreach ($reportstorun as $report) { mtrace("... Running report " . strip_tags($report->displayname)); try { report_customsql_generate_csv($report, $timenow); } catch (\Exception $e) { mtrace("... REPORT FAILED " . $e->getMessage()); } } }
function filter($text, array $options = array()) { global $CFG; if (!is_string($text) or empty($text)) { // non string data can not be filtered anyway return $text; } if (stripos($text, '</a>') === false) { // performance shortcut - all regexes bellow end with the </a> tag, // if not present nothing can match return $text; } $newtext = $text; // we need to return the original value if regex fails! /** * TODO * The following doesn't work correctly; we get an array with only letters: * * [0]=>"<a href="http://link.mediacore.tv/media/video">link</a>", * [1]=>"n", * [2]=>"N"; * * This effects the actual filter function below. * */ $search = '/<a\\s[^>]+http:\\/\\/([0-9A-Za-z])+\\.mediacore\\.tv\\/([0-9A-Za-z])[^>]+>([0-9A-Za-z])+[^>]+>/'; $newtext = preg_replace_callback($search, 'filter_mediacorefilter_callback', $newtext); if (empty($newtext) or $newtext === $text) { // error or not filtered mtrace('link empty'); unset($newtext); return $text; } return $newtext; }
/** * Cron that runs any automatically scheduled reports weekly or monthly. */ function report_customsql_cron() { global $CFG; $timenow = time(); if (!empty($CFG->reportcustomsqlmaxruntime)) { $timestop = $timenow + $CFG->reportcustomsqlmaxruntime; } else { $timestop = $timenow + 180; // Three minutes. } list($startofthisweek, $startoflastweek) = report_customsql_get_week_starts($timenow); list($startofthismonth) = report_customsql_get_month_starts($timenow); mtrace("... Looking for old temp CSV files to delete."); $numdeleted = report_customsql_delete_old_temp_files($startoflastweek); if ($numdeleted) { mtrace("... {$numdeleted} files deleted."); } $reportstorun = get_records_select('report_customsql_queries', "(runable = 'weekly' AND lastrun < {$startofthisweek}) OR\n (runable = 'monthly' AND lastrun < {$startofthismonth})", 'lastrun'); if (empty($reportstorun)) { return; } while (!empty($reportstorun) && time() < $timestop) { $report = array_shift($reportstorun); mtrace("... Running report " . strip_tags($report->displayname)); try { report_customsql_generate_csv($report, $timenow); } catch (Exception $e) { mtrace("... REPORT FAILED " . $e->getMessage()); } } }
/** * MS Word extractor * @param object $resource * @uses CFG, USER */ function get_text_for_indexing_doc(&$resource) { global $CFG, $USER; // SECURITY : do not allow non admin execute anything on system !! if (!isadmin($USER->id)) { return; } $moodleroot = @$CFG->block_search_usemoodleroot ? "{$CFG->dirroot}/" : ''; // just call pdftotext over stdout and capture the output if (!empty($CFG->block_search_word_to_text_cmd)) { if (!file_exists("{$moodleroot}{$CFG->block_search_word_to_text_cmd}")) { mtrace('Error with MSWord to text converter command : exectuable not found.'); } else { $file = escapeshellarg($CFG->dataroot . '/' . $resource->course . '/' . $resource->reference); $command = trim($CFG->block_search_word_to_text_cmd); $text_converter_cmd = "{$moodleroot}{$command} {$file}"; if ($CFG->block_search_word_to_text_env) { putenv($CFG->block_search_word_to_text_env); } mtrace("Executing : {$text_converter_cmd}"); $result = shell_exec($text_converter_cmd); if ($result) { return mb_convert_encoding($result, 'UTF8', 'auto'); } else { mtrace('Error with MSWord to text converter command : execution failed. '); return ''; } } } else { mtrace('Error with MSWord to text converter command : command not set up. Execute once search block configuration.'); return ''; } }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG; $timenow = time(); // Run stats as at the end because they are known to take very long time on large sites. if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // Check we're not before our runtime. $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if ($timenow > $timetocheck) { // Process configured number of days as max (defaulting to 31). $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } \core_php_time_limit::raise(); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } }
/** * Automatically update the registration on all hubs */ public function cron() { global $CFG; if (extension_loaded('xmlrpc')) { //check if the last registration cron update was less than a week ago $lastcron = get_config('registration', 'crontime'); if ($lastcron === false or $lastcron < strtotime("-7 day")) { //set to a week, see MDL-23704 $function = 'hub_update_site_info'; require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php"; //update all hub where the site is registered on $hubs = $this->get_registered_on_hubs(); foreach ($hubs as $hub) { //update the registration $siteinfo = $this->get_site_info($hub->huburl); $params = array('siteinfo' => $siteinfo); $serverurl = $hub->huburl . "/local/hub/webservice/webservices.php"; $xmlrpcclient = new webservice_xmlrpc_client($serverurl, $hub->token); try { $result = $xmlrpcclient->call($function, $params); mtrace(get_string('siteupdatedcron', 'hub', $hub->hubname)); } catch (Exception $e) { $errorparam = new stdClass(); $errorparam->errormessage = $e->getMessage(); $errorparam->hubname = $hub->hubname; mtrace(get_string('errorcron', 'hub', $errorparam)); } } set_config('crontime', time(), 'registration'); } } else { mtrace(get_string('errorcronnoxmlrpc', 'hub')); } }
/** * @param object $resource * @uses CFG, USER */ function get_text_for_indexing_pdf(&$resource) { global $CFG, $USER; // SECURITY : do not allow non admin execute anything on system !! if (!isadmin($USER->id)) { return; } // adds moodle root switch if none was defined if (!isset($CFG->block_search_usemoodleroot)) { set_config('block_search_usemoodleroot', 1); } $moodleroot = $CFG->block_search_usemoodleroot ? "{$CFG->dirroot}/" : ''; // just call pdftotext over stdout and capture the output if (!empty($CFG->block_search_pdf_to_text_cmd)) { preg_match("/^\\S+/", $CFG->block_search_pdf_to_text_cmd, $matches); if (!file_exists("{$moodleroot}{$matches[0]}")) { mtrace('Error with pdf to text converter command : executable not found at ' . $moodleroot . $matches[0]); } else { $file = escapeshellarg($CFG->dataroot . '/' . $resource->course . '/' . $resource->reference); $command = trim($CFG->block_search_pdf_to_text_cmd); $text_converter_cmd = "{$moodleroot}{$command} {$file} -"; $result = shell_exec($text_converter_cmd); if ($result) { return $result; } else { mtrace('Error with pdf to text converter command : execution failed for ' . $text_converter_cmd . '. Check for execution permission on pdf converter executable.'); return ''; } } } else { mtrace('Error with pdf to text converter command : command not set up. Execute once search block configuration.'); return ''; } }
public function authenticate($userId, $challenge, $response) { Manager::logMessage("[LOGIN] Authenticating {$userId} MD5"); $login = NULL; try { $user = Manager::getModelMAD('user'); $user->getByLogin($userId); mtrace("Authenticate userID = {$userId}"); if ($user->validatePasswordMD5($challenge, $response)) { $profile = $user->getProfileAtual(); $user->getByProfile($profile); $login = new MLogin($user); if (Manager::getOptions("dbsession")) { $session = Manager::getModelMAD('session'); $session->lastAccess($login); $session->registerIn($login); } $this->setLogin($login); $this->setLoginLogUserId($user->getId()); $this->setLoginLog($login->getLogin()); Manager::logMessage("[LOGIN] Authenticated {$userId} MD5"); return true; } else { Manager::logMessage("[LOGIN] {$userId} NOT Authenticated MD5"); } } catch (Exception $e) { Manager::logMessage("[LOGIN] {$userId} NOT Authenticated MD5 - " . $e->getMessage()); } return false; }
/** * Performs the task * * @throws moodle_exception on an error (the job will be retried) */ public function execute() { global $DB; $subcourses = $DB->get_records("subcourse", null, "", "id, course, refcourse"); if (empty($subcourses)) { return; } $updatedids = array(); foreach ($subcourses as $subcourse) { if (empty($subcourse->refcourse)) { mtrace("Subcourse {$subcourse->id}: no referenced course configured ... skipped"); continue; } mtrace("Subcourse {$subcourse->id}: fetching grades from course {$subcourse->refcourse} to course {$subcourse->course} ... ", ""); $result = subcourse_grades_update($subcourse->course, $subcourse->id, $subcourse->refcourse); if ($result == GRADE_UPDATE_OK) { $updatedids[] = $subcourse->id; mtrace("ok"); } else { mtrace("failed with error code " . $result); } } if (!empty($updatedids)) { subcourse_update_timefetched($updatedids); } }
/** * Automatically update the registration on all hubs */ public function cron() { global $CFG; if (extension_loaded('xmlrpc')) { $function = 'hub_update_site_info'; require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php"; // Update all hubs where the site is registered. $hubs = $this->get_registered_on_hubs(); if (empty($hubs)) { mtrace(get_string('registrationwarning', 'admin')); } foreach ($hubs as $hub) { // Update the registration. $siteinfo = $this->get_site_info($hub->huburl); $params = array('siteinfo' => $siteinfo); $serverurl = $hub->huburl . "/local/hub/webservice/webservices.php"; $xmlrpcclient = new webservice_xmlrpc_client($serverurl, $hub->token); try { $result = $xmlrpcclient->call($function, $params); $this->update_registeredhub($hub); // To update timemodified. mtrace(get_string('siteupdatedcron', 'hub', $hub->hubname)); } catch (Exception $e) { $errorparam = new stdClass(); $errorparam->errormessage = $e->getMessage(); $errorparam->hubname = $hub->hubname; mtrace(get_string('errorcron', 'hub', $errorparam)); } } } else { mtrace(get_string('errorcronnoxmlrpc', 'hub')); } }
/** * This function does the cron process within the time range according to settings. */ function tool_qeupgradehelper_process($settings) { global $CFG; require_once dirname(__FILE__) . '/locallib.php'; if (!tool_qeupgradehelper_is_upgraded()) { mtrace('qeupgradehelper: site not yet upgraded. Doing nothing.'); return; } require_once dirname(__FILE__) . '/afterupgradelib.php'; $hour = (int) date('H'); if ($hour < $settings->starthour || $hour >= $settings->stophour) { mtrace('qeupgradehelper: not between starthour and stophour, so doing nothing (hour = ' . $hour . ').'); return; } $stoptime = time() + $settings->procesingtime; mtrace('qeupgradehelper: processing ...'); while (time() < $stoptime) { $quiz = tool_qeupgradehelper_get_quiz_for_upgrade(); if (!$quiz) { mtrace('qeupgradehelper: No more quizzes to process. You should probably disable the qeupgradehelper cron settings now.'); break; // No more to do; } $quizid = $quiz->id; $quizsummary = tool_qeupgradehelper_get_quiz($quizid); if ($quizsummary) { mtrace(' starting upgrade of attempts at quiz ' . $quizid); $upgrader = new tool_qeupgradehelper_attempt_upgrader($quizsummary->id, $quizsummary->numtoconvert); $upgrader->convert_all_quiz_attempts(); mtrace(' upgrade of quiz ' . $quizid . ' complete.'); } } mtrace('qeupgradehelper: Done.'); return; }
public static function handlerRequest($data = NULL) { try { // se é uma chamada Ajax, inicializa MAjax if (Manager::isAjaxCall()) { Manager::$ajax = new \Maestro\UI\MAjax(Manager::getOptions('charset')); } MApp::contextualize(); self::setData($data ?: $_REQUEST); mtrace('DTO Data:'); mtrace(self::getData()); self::init(); do { self::$result = MApp::handler(); } while (self::$forward != ''); self::terminate(); } catch (\Maestro\Services\Exception\ENotFoundException $e) { self::$result = new Results\MNotFound($e); } catch (\Maestro\Services\Exception\ESecurityException $e) { self::$result = new Results\MInternalError($e); } catch (\Maestro\Services\Exception\ETimeOutException $e) { self::$result = new Results\MInternalError($e); } catch (\Maestro\Services\Exception\ERuntimeException $e) { self::$result = new Results\MRunTimeError($e); } catch (\Maestro\Services\Exception\EMException $e) { self::$result = new Results\MInternalError($e); } catch (\Exception $e) { self::$result = new Results\MInternalError($e); } }
/** * OpenOffice Odt extractor * @param object $resource * @uses $CFG */ function get_text_for_indexing_odt(&$resource, $directfile = '') { global $CFG; // SECURITY : do not allow non admin execute anything on system !! if (!has_capability('moodle/site:doanything', get_context_instance(CONTEXT_SYSTEM))) { return; } $moodleroot = @$CFG->block_search_usemoodleroot ? "{$CFG->dirroot}/" : ''; // just call pdftotext over stdout and capture the output if (!empty($CFG->block_search_odt_to_text_cmd)) { if (!file_exists("{$moodleroot}{$CFG->block_search_odt_to_text_cmd}")) { mtrace('Error with OpenOffice ODT to text converter command : exectuable not found.'); } else { if ($directfile == '') { $file = escapeshellarg("{$CFG->dataroot}/{$resource->course}/{$resource->reference}"); } else { $file = escapeshellarg("{$CFG->dataroot}/{$directfile}"); } $command = trim($CFG->block_search_odt_to_text_cmd); $text_converter_cmd = "{$moodleroot}{$command} --encoding=UTF-8 {$file}"; mtrace("Executing : {$text_converter_cmd}"); $result = shell_exec($text_converter_cmd); if ($result) { return $result; } else { mtrace('Error with OpenOffice ODT to text converter command : execution failed. '); return ''; } } } else { mtrace('Error with OpenOffice ODT to text converter command : command not set up. Execute once search block configuration.'); return ''; } }
function glossary_rss_feeds() { global $CFG; $status = true; //Check CFG->enablerssfeeds if (empty($CFG->enablerssfeeds)) { debugging("DISABLED (admin variables)"); //Check CFG->glossary_enablerssfeeds } else { if (empty($CFG->glossary_enablerssfeeds)) { debugging("DISABLED (module configuration)"); //It's working so we start... } else { //Iterate over all glossaries if ($glossaries = get_records("glossary")) { foreach ($glossaries as $glossary) { if (!empty($glossary->rsstype) && !empty($glossary->rssarticles) && $status) { $filename = rss_file_name('glossary', $glossary); // RSS file //First let's make sure there is work to do by checking existing files if (file_exists($filename)) { if ($lastmodified = filemtime($filename)) { if (!glossary_rss_newstuff($glossary, $lastmodified)) { continue; } } } //Ignore hidden forums if (!instance_is_visible('glossary', $glossary)) { if (file_exists($filename)) { @unlink($filename); } continue; } mtrace("Updating RSS feed for " . format_string($glossary->name, true) . ", ID: {$glossary->id}"); //Get the XML contents $result = glossary_rss_feed($glossary); //Save the XML contents to file if (!empty($result)) { $status = rss_save_file("glossary", $glossary, $result); } //Some debug... if (debugging()) { if (empty($result)) { echo "ID: {$glossary->id}-> (empty) "; } else { if (!empty($status)) { echo "ID: {$glossary->id}-> OK "; } else { echo "ID: {$glossary->id}-> FAIL "; } } } } } } } } return $status; }
/** * this function schedules the user synchronisation updates * * Implementation specific : Generic */ function local_ent_installer_cron() { global $CFG; if (!get_config('local_ent_installer', 'cron_enable')) { return; } $now = time(); $needscron = false; $chour = 0 + get_config('local_ent_installer', 'cron_hour'); $cmin = 0 + get_config('local_ent_installer', 'cron_min'); $cfreq = get_config('local_ent_installer', 'cron_enable'); $now = time(); $nowdt = getdate($now); $expectedtime = get_config('local_ent_installer', 'last_sync_date') + $cfreq - HOURSEC; $crondebug = optional_param('crondebug', false, PARAM_BOOL); if ($now < $expectedtime && !$crondebug) { return; } if (!empty($CFG->ent_installer_running)) { return; } if ($nowdt['hours'] * 60 + $nowdt['minutes'] >= $chour * 60 + $cmin || $crondebug) { set_config('ent_installer_running', 1); set_config('last_sync_date', $now, 'local_ent_installer'); // Get ldap params from real ldap plugin. $ldapauth = get_auth_plugin('ldap'); $options = array('host' => $CFG->wwwroot); // Run the customised synchro. local_ent_installer_sync_users($ldapauth, $options); set_config('ent_installer_running', null); } else { mtrace('waiting for valid time '); } }
/** * Update course visibility if the start date has become due. * * @return void */ public function execute() { global $CFG, $DB; $start = time(); // Get list of courses to update. mtrace("\n Searching for courses to make visible ..."); // Use the configured timezone. date_default_timezone_set($CFG->timezone); // Course start dates are always set to midnight but we will check the whole day in case the value has been // manually updated. $beginofday = strtotime('midnight', time()); $endofday = strtotime('tomorrow', $beginofday) - 1; // If startdate is today and visibility = 0 then set visibility = 1. $select = "visible = 0 AND startdate BETWEEN {$beginofday} AND {$endofday}"; if ($courses = $DB->get_records_select('course', $select)) { foreach ($courses as $course) { if (!$DB->set_field('course', 'visible', 1, array('id' => $course->id))) { mtrace(" {$course->id}: {$course->shortname} could not be updated for some reason."); } else { mtrace(" {$course->id}: {$course->shortname} is now visible"); } } } else { mtrace(" Nothing to do, except ponder the boundless wonders of the Universe, perhaps. ;-)\n"); } $end = time(); mtrace(($end - $start) / 60 . ' mins'); }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG; $tmpdir = $CFG->tempdir; // Default to last weeks time. $time = strtotime('-1 week'); $dir = new \RecursiveDirectoryIterator($tmpdir); // Show all child nodes prior to their parent. $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST); for ($iter->rewind(); $iter->valid(); $iter->next()) { $node = $iter->getRealPath(); if (!is_readable($node)) { continue; } // Check if file or directory is older than the given time. if ($iter->getMTime() < $time) { if ($iter->isDir() && !$iter->isDot()) { // Don't attempt to delete the directory if it isn't empty. if (!glob($node . DIRECTORY_SEPARATOR . '*')) { if (@rmdir($node) === false) { mtrace("Failed removing directory '{$node}'."); } } } if ($iter->isFile()) { if (@unlink($node) === false) { mtrace("Failed removing file '{$node}'."); } } } } }
/** * Global Search Engine for Moodle * add-on 1.8+ : Valery Fremaux [valery.fremaux@club-internet.fr] * 2007/08/02 * * this is a format handler for getting text out of a proprietary binary format * so it can be indexed by Lucene search engine */ function get_text_for_indexing_pdf(&$resource) { global $CFG, $USER; // SECURITY : do not allow non admin execute anything on system !! if (!isadmin($USER->id)) { return; } // just call pdftotext over stdout and capture the output if (!empty($CFG->block_search_pdf_to_text_cmd)) { preg_match("/^\\S+/", $CFG->block_search_pdf_to_text_cmd, $matches); if (!file_exists("{$CFG->dirroot}/{$matches[0]}")) { mtrace('Error with pdf to text converter command : exectuable not found.'); } else { $file = $CFG->dataroot . '/' . $resource->course . '/' . $resource->reference; $text_converter_cmd = "{$CFG->dirroot}/{$CFG->block_search_pdf_to_text_cmd} {$file} -"; $result = shell_exec($text_converter_cmd); if ($result) { return $result; } else { mtrace('Error with pdf to text converter command : execution failed.'); return ''; } } } else { mtrace('Error with pdf to text converter command : command not set up. Execute once search block configuration.'); return ''; } }
/** * Quiz statistics report cron code. Deletes cached data more than a certain age. */ function quiz_statistics_cron() { global $DB; mtrace("\n Cleaning up old quiz statistics cache records...", ''); $expiretime = time() - 5 * HOURSECS; $DB->delete_records_select('quiz_statistics', 'timemodified < ?', array($expiretime)); return true; }
public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/local/bibliography/locallib.php'; mtrace("Starting download of primo URLs"); list($totalurls, $numcourseocodes) = local_bibliography_download_urls(); mtrace("A total of {$totalurls} were downloaded for {$numcourseocodes} course codes."); }
function xlog($message) { global $reportfile; // Output to screen mtrace($message); // Write to report file fwrite($reportfile, $message . "\n"); }
public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/local/uai/locallib.php'; mtrace("Starting quiz notifications"); list($totalmessages, $numnotifications) = local_uai_send_notifications(); mtrace("A total of {$totalmessages} were sent for {$numnotifications} courses."); }
function before_delete() { $hook = CoursePrefsHook::findByUnique($this->cpsName()); if ($hook && $hook->delete()) { $a->name = $hook->getName(); $a->type = $hook->getType(); mtrace(get_string('hook_delete', 'block_courseprefs', $a)); } }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { // Context maintenance stuff. \context_helper::cleanup_instances(); mtrace(' Cleaned up context instances'); \context_helper::build_all_paths(false); // If you suspect that the context paths are somehow corrupt // replace the line below with: context_helper::build_all_paths(true). }
/** * Task execution which syncs users with LDAP * * @see \core\task\task_base::execute() * @global \moodle_database $DB */ public function execute() { global $DB; $enrolments = $DB->get_records('enrol', ['enrol' => 'mandatory', 'status' => 0]); foreach ($enrolments as $enrolment) { $userids = $this->process_enrolment($enrolment); mtrace(vsprintf('Enroled %d users in course %s', [count($userids), $enrolment->courseid])); } }
function local_mail_update_process($settings) { global $DB; $hour = (int) date('H'); if ($hour < $settings->cronstart || $hour >= $settings->cronstop) { mtrace('mailupdater: not between starthour and stophour, so doing nothing (hour = ' . $hour . ').'); return false; } // Setup the stop time. if ($settings->cronduration) { $stoptime = time() + $settings->cronduration; } else { $stoptime = false; } $countrecords = $DB->count_records('local_mail_messages'); $limitfrom = 0; $limitnum = 1000; $countrecords; $inserts = 0; $fs = get_file_storage(); $count = 0; $starttime = time(); while ((!$stoptime || time() < $stoptime) && $count < $countrecords) { $recordset = $DB->get_recordset('local_mail_messages', array(), '', '*', $limitfrom, $limitnum); try { $transaction = $DB->start_delegated_transaction(); foreach ($recordset as $record) { if (!$DB->get_records('local_mail_index', array('messageid' => $record->id, 'type' => 'attachment'))) { $indexrecord = new stdClass(); $userid = $DB->get_field('local_mail_message_users', 'userid', array('messageid' => $record->id, 'role' => 'from')); $indexrecord->userid = $userid; $indexrecord->type = 'attachment'; $indexrecord->time = $record->time; $indexrecord->messageid = $record->id; $unread = $DB->get_field('local_mail_message_users', 'unread', array('messageid' => $record->id, 'role' => 'from')); $indexrecord->unread = $unread; $context = context_course::instance($record->courseid); if ($fs->is_area_empty($context->id, 'local_mail', 'message', $record->id, 'filename', false)) { $indexrecord->item = 0; } else { $indexrecord->item = 1; } $DB->insert_record('local_mail_index', $indexrecord); $inserts++; } } $recordset->close(); $transaction->allow_commit(); } catch (Exception $e) { $transaction->rollback($e); } $count += 1000; $limitfrom += $limitnum; } return true; }
function mdk_set_config($name, $value, $plugin = null) { set_config($name, $value, $plugin); $value = is_bool($value) ? (int) $value : $value; if ($plugin) { // Make a fancy name. $name = "{$plugin}/{$name}"; } mtrace("Setting {$name} to {$value}"); }