本文整理汇总了PHP中core_php_time_limit类的典型用法代码示例。如果您正苦于以下问题:PHP core_php_time_limit类的具体用法?PHP core_php_time_limit怎么用?PHP core_php_time_limit使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了core_php_time_limit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
/**
* 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));
}
}
}
示例2: test_basic
/**
* Tests for basic use with simple numeric progress.
*/
public function test_basic()
{
$progress = new core_mock_progress();
// Check values of empty progress things.
$this->assertFalse($progress->is_in_progress_section());
// Start progress counting, check basic values and check that update
// gets called.
$progress->start_progress('hello', 10);
$this->assertTrue($progress->was_update_called());
$this->assertTrue($progress->is_in_progress_section());
$this->assertEquals('hello', $progress->get_current_description());
// Check numeric position and indeterminate count.
$this->assert_min_max(0.0, 0.0, $progress);
$this->assertEquals(0, $progress->get_progress_count());
// Make some progress and check that the time limit gets added.
$progress->step_time();
core_php_time_limit::get_and_clear_unit_test_data();
$progress->progress(2);
$this->assertTrue($progress->was_update_called());
$this->assertEquals(array(\core\progress\base::TIME_LIMIT_WITHOUT_PROGRESS), core_php_time_limit::get_and_clear_unit_test_data());
// Check the new value.
$this->assert_min_max(0.2, 0.2, $progress);
// Do another progress run at same time, it should be ignored.
$progress->progress(3);
$this->assertFalse($progress->was_update_called());
$this->assert_min_max(0.3, 0.3, $progress);
// End the section. This should cause an update.
$progress->end_progress();
$this->assertTrue($progress->was_update_called());
// Because there are no sections left open, it thinks we finished.
$this->assert_min_max(1.0, 1.0, $progress);
// There was 1 progress call.
$this->assertEquals(1, $progress->get_progress_count());
}
示例3: tool_dbtransfer_transfer_database
/**
* Initiate database transfer.
* @param moodle_database $sourcedb
* @param moodle_database $targetdb
* @param progress_trace $feedback
* @return void
*/
function tool_dbtransfer_transfer_database(moodle_database $sourcedb, moodle_database $targetdb, progress_trace $feedback = null)
{
core_php_time_limit::raise();
\core\session\manager::write_close();
// Release session.
$var = new database_mover($sourcedb, $targetdb, true, $feedback);
$var->export_database(null);
tool_dbtransfer_rebuild_target_log_actions($targetdb, $feedback);
}
示例4: prevent_timeout
protected function prevent_timeout()
{
core_php_time_limit::raise(300);
if ($this->doingbackup) {
return;
}
echo '.';
$this->dotcounter += 1;
if ($this->dotcounter % 100 == 0) {
echo '<br />';
}
}
示例5: execute
/**
* Do the job.
* Throw exceptions on errors (the job will be retried).
*/
public function execute()
{
global $CFG;
// 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';
// 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();
}
}
示例6: test_create_instance
public function test_create_instance()
{
global $DB, $USER;
core_php_time_limit::raise();
$this->resetAfterTest();
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course();
// There should not be any module for that course first
$this->assertFalse($DB->record_exists('ratingallocate', array('course' => $course->id)));
$records = $DB->get_records('ratingallocate_choices', array(), 'id');
$this->assertEquals(0, count($records));
// create activity
$mod = $this->getDataGenerator()->create_module('ratingallocate', array('course' => $course));
$records = $DB->get_records('ratingallocate', array('course' => $course->id), 'id');
$this->assertEquals(1, count($records));
$this->assertTrue(array_key_exists($mod->id, $records));
$expected_values_db = array('id' => $mod->id, 'course' => $course->id, 'name' => 'Rating Allocation', 'intro' => 'Test ratingallocate 1', 'introformat' => '0', 'timecreated' => reset($records)->{'timecreated'}, 'timemodified' => '0', 'accesstimestart' => reset($records)->{'accesstimestart'}, 'accesstimestop' => reset($records)->{'accesstimestop'}, 'setting' => '{"strategy_yesno":{"maxcrossout":"1"}}', 'strategy' => 'strategy_yesno', 'publishdate' => reset($records)->{'publishdate'}, 'published' => '0', 'notificationsend' => '0', 'algorithmstarttime' => null, 'algorithmstatus' => '0', 'runalgorithmbycron' => '1');
$this->assertEquals(json_decode(json_encode($expected_values_db, false)), reset($records));
// must have two choices
$records = $DB->get_records('ratingallocate_choices', array('ratingallocateid' => $mod->id), 'title');
$this->assertEquals(2, count($records));
$choice_ids = array_keys($records);
$expected_choices = array($choice_ids[0] => (object) array('title' => 'Choice 1', 'id' => $choice_ids[0], 'ratingallocateid' => $mod->id, 'explanation' => 'Some explanatory text for choice 1', 'maxsize' => '10', 'active' => '1'), $choice_ids[1] => (object) array('title' => 'Choice 2', 'id' => $choice_ids[1], 'ratingallocateid' => $mod->id, 'explanation' => 'Some explanatory text for choice 2', 'maxsize' => '5', 'active' => '0'));
$this->assertEquals($expected_choices, $records);
// Create an other mod_ratingallocate within the course
$params = array('course' => $course->id, 'name' => 'Another mod_ratingallocate');
$mod = $this->getDataGenerator()->create_module('ratingallocate', $params);
$records = $DB->get_records('ratingallocate', array('course' => $course->id), 'id');
// are there 2 modules within the course
$this->assertEquals(2, count($records));
// is the name correct
$this->assertEquals('Another mod_ratingallocate', $records[$mod->id]->name);
$records = $DB->get_records('ratingallocate_choices', array(), 'id');
$this->assertEquals(4, count($records));
// other tables
$records = $DB->get_records('ratingallocate_ratings', array(), 'id');
$this->assertEquals(0, count($records));
$records = $DB->get_records('ratingallocate_allocations', array(), 'id');
$this->assertEquals(0, count($records));
}
示例7: run_automated_backup
/**
* Runs the automated backups if required
*
* @global moodle_database $DB
*/
public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE)
{
global $CFG, $DB;
$status = true;
$emailpending = false;
$now = time();
$config = get_config('backup');
mtrace("Checking automated backup status", '...');
$state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
if ($state === backup_cron_automated_helper::STATE_DISABLED) {
mtrace('INACTIVE');
return $state;
} else {
if ($state === backup_cron_automated_helper::STATE_RUNNING) {
mtrace('RUNNING');
if ($rundirective == self::RUN_IMMEDIATELY) {
mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
} else {
mtrace("automated backup are already running. Execution delayed");
}
return $state;
} else {
mtrace('OK');
}
}
backup_cron_automated_helper::set_state_running();
mtrace("Getting admin info");
$admin = get_admin();
if (!$admin) {
mtrace("Error: No admin account was found");
$state = false;
}
if ($status) {
mtrace("Checking courses");
mtrace("Skipping deleted courses", '...');
mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
}
if ($status) {
mtrace('Running required automated backups...');
cron_trace_time_and_memory();
// This could take a while!
core_php_time_limit::raise();
raise_memory_limit(MEMORY_EXTRA);
$nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
$showtime = "undefined";
if ($nextstarttime > 0) {
$showtime = date('r', $nextstarttime);
}
$rs = $DB->get_recordset('course');
foreach ($rs as $course) {
$backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
if (!$backupcourse) {
$backupcourse = new stdClass();
$backupcourse->courseid = $course->id;
$backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
$DB->insert_record('backup_courses', $backupcourse);
$backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
}
// The last backup is considered as successful when OK or SKIPPED.
$lastbackupwassuccessful = ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED || $backupcourse->laststatus == self::BACKUP_STATUS_OK) && ($backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);
// Assume that we are not skipping anything.
$skipped = false;
$skippedmessage = '';
// Check if we are going to be running the backup now.
$shouldrunnow = $backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now || $rundirective == self::RUN_IMMEDIATELY;
// If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
if ($shouldrunnow && $config->backup_auto_skip_hidden) {
$skipped = $config->backup_auto_skip_hidden && !$course->visible;
$skippedmessage = 'Not visible';
}
// If config backup_auto_skip_modif_days is set to true, skip courses
// that have not been modified since the number of days defined.
if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
$timenotmodifsincedays = $now - $config->backup_auto_skip_modif_days * DAYSECS;
// Check log if there were any modifications to the course content.
$logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
$skipped = $course->timemodified <= $timenotmodifsincedays && !$logexists;
$skippedmessage = 'Not modified in the past ' . $config->backup_auto_skip_modif_days . ' days';
}
// If config backup_auto_skip_modif_prev is set to true, skip courses
// that have not been modified since previous backup.
if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
// Check log if there were any modifications to the course content.
$logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
$skipped = $course->timemodified <= $backupcourse->laststarttime && !$logexists;
$skippedmessage = 'Not modified since previous backup';
}
// Check if the course is not scheduled to run right now.
if (!$shouldrunnow) {
$backupcourse->nextstarttime = $nextstarttime;
$DB->update_record('backup_courses', $backupcourse);
mtrace('Skipping ' . $course->fullname . ' (Not scheduled for backup until ' . $showtime . ')');
} else {
if ($skipped) {
// Must have been skipped for a reason.
//.........这里部分代码省略.........
示例8: db_replace
/**
* Moved from admin/replace.php so that we can use this in cron
*
* @param string $search string to look for
* @param string $replace string to replace
* @return bool success or fail
*/
function db_replace($search, $replace)
{
global $DB, $CFG, $OUTPUT;
// TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
$skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log', 'filter_config', 'sessions', 'events_queue', 'repository_instance_config', 'block_instances', '');
// Turn off time limits, sometimes upgrades can be slow.
core_php_time_limit::raise();
if (!($tables = $DB->get_tables())) {
// No tables yet at all.
return false;
}
foreach ($tables as $table) {
if (in_array($table, $skiptables)) {
// Don't process these
continue;
}
if ($columns = $DB->get_columns($table)) {
$DB->set_debug(true);
foreach ($columns as $column) {
$DB->replace_all_text($table, $column, $search, $replace);
}
$DB->set_debug(false);
}
}
// delete modinfo caches
rebuild_course_cache(0, true);
// TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
$blocks = core_component::get_plugin_list('block');
foreach ($blocks as $blockname => $fullblock) {
if ($blockname === 'NEWBLOCK') {
// Someone has unzipped the template, ignore it
continue;
}
if (!is_readable($fullblock . '/lib.php')) {
continue;
}
$function = 'block_' . $blockname . '_global_db_replace';
include_once $fullblock . '/lib.php';
if (!function_exists($function)) {
continue;
}
echo $OUTPUT->notification("Replacing in {$blockname} blocks...", 'notifysuccess');
$function($search, $replace);
echo $OUTPUT->notification("...finished", 'notifysuccess');
}
purge_all_caches();
return true;
}
示例9: test_simple
public function test_simple()
{
global $DB, $USER;
core_php_time_limit::raise();
$this->resetAfterTest();
$this->setAdminUser();
$course = $this->getDataGenerator()->create_course();
$teacher = mod_ratingallocate_generator::create_user_and_enrol($this, $course, true);
$this->setUser($teacher);
// There should not be any module for that course first
$this->assertFalse($DB->record_exists(this_db\ratingallocate::TABLE, array(this_db\ratingallocate::COURSE => $course->id)));
//set default data for category
$data = mod_ratingallocate_generator::get_default_values();
$data['course'] = $course;
foreach ($data as $name => $value) {
if (subStr($name, strlen($name) - 7, 7) === 'maxsize') {
$data[$name] = 2;
}
if (subStr($name, strlen($name) - 6, 6) === 'active') {
$data[$name] = true;
}
}
// create activity
$mod = $this->getDataGenerator()->create_module(ratingallocate_MOD_NAME, $data);
$this->assertEquals(2, $DB->count_records(this_db\ratingallocate_choices::TABLE), array(this_db\ratingallocate_choices::ID => $mod->id));
$student_1 = mod_ratingallocate_generator::create_user_and_enrol($this, $course);
$student_2 = mod_ratingallocate_generator::create_user_and_enrol($this, $course);
$student_3 = mod_ratingallocate_generator::create_user_and_enrol($this, $course);
$student_4 = mod_ratingallocate_generator::create_user_and_enrol($this, $course);
$ratingallocate = mod_ratingallocate_generator::get_ratingallocate_for_user($this, $mod, $teacher);
$choices = $ratingallocate->get_rateable_choices();
$choice1 = reset($choices);
$choice2 = end($choices);
//Create preferences
$prefers_non = array();
foreach ($choices as $choice) {
$prefers_non[$choice->{this_db\ratingallocate_choices::ID}] = array(this_db\ratingallocate_ratings::CHOICEID => $choice->{this_db\ratingallocate_choices::ID}, this_db\ratingallocate_ratings::RATING => 0);
}
$prefers_first = json_decode(json_encode($prefers_non), true);
$prefers_first[$choice1->{this_db\ratingallocate_choices::ID}][this_db\ratingallocate_ratings::RATING] = true;
$prefers_second = json_decode(json_encode($prefers_non), true);
$prefers_second[$choice2->{this_db\ratingallocate_choices::ID}][this_db\ratingallocate_ratings::RATING] = true;
//assign preferences
mod_ratingallocate_generator::save_rating_for_user($this, $mod, $student_1, $prefers_first);
mod_ratingallocate_generator::save_rating_for_user($this, $mod, $student_2, $prefers_first);
mod_ratingallocate_generator::save_rating_for_user($this, $mod, $student_3, $prefers_second);
mod_ratingallocate_generator::save_rating_for_user($this, $mod, $student_4, $prefers_second);
// allocate choices
$ratingallocate = mod_ratingallocate_generator::get_ratingallocate_for_user($this, $mod, $teacher);
$time_needed = $ratingallocate->distrubute_choices();
$this->assertGreaterThan(0, $time_needed);
$this->assertLessThan(0.1, $time_needed, 'Allocation is very slow');
$allocation_count = $ratingallocate->get_choices_with_allocationcount();
$this->assertCount(2, $allocation_count);
//Test allocations
$num_allocations = $DB->count_records(this_db\ratingallocate_allocations::TABLE);
$this->assertEquals(4, $num_allocations, 'There should be only 4 allocations, since there are only 4 choices.');
$allocations = $DB->get_records(this_db\ratingallocate_allocations::TABLE, array(this_db\ratingallocate_allocations::RATINGALLOCATEID => $mod->{this_db\ratingallocate::ID}), '');
// '' /*sort*/, /*fields*/ this_db\ratingallocate_allocations::USERID . ',' . this_db\ratingallocate_allocations::CHOICEID );
$map_user_id = function ($elem) {
return $elem->{this_db\ratingallocate_allocations::USERID};
};
$alloc1 = self::filter_allocations_by_choice($allocations, $choice1->{this_db\ratingallocate_choices::ID});
$alloc2 = self::filter_allocations_by_choice($allocations, $choice2->{this_db\ratingallocate_choices::ID});
//Assert, that student 1 was allocated to choice 1
$this->assertContains($student_1->id, array_map($map_user_id, $alloc1));
//Assert, that student 2 was allocated to choice 1
$this->assertContains($student_2->id, array_map($map_user_id, $alloc1));
//Assert, that student 3 was allocated to choice 2
$this->assertContains($student_3->id, array_map($map_user_id, $alloc2));
//Assert, that student 4 was allocated to choice 2
$this->assertContains($student_4->id, array_map($map_user_id, $alloc2));
}
示例10: download_submissions
/**
* Download a zip file of all assignment submissions.
*
* @return string - If an error occurs, this will contain the error page.
*/
protected function download_submissions()
{
global $CFG, $DB;
// More efficient to load this here.
require_once $CFG->libdir . '/filelib.php';
// Increase the server timeout to handle the creation and sending of large zip files.
core_php_time_limit::raise();
$this->require_view_grades();
// Load all users with submit.
$students = get_enrolled_users($this->context, "mod/assign:submit", null, 'u.*', null, null, null, $this->show_only_active_users());
// Build a list of files to zip.
$filesforzipping = array();
$fs = get_file_storage();
$groupmode = groups_get_activity_groupmode($this->get_course_module());
// All users.
$groupid = 0;
$groupname = '';
if ($groupmode) {
$groupid = groups_get_activity_group($this->get_course_module(), true);
$groupname = groups_get_group_name($groupid) . '-';
}
// Construct the zip file name.
$filename = clean_filename($this->get_course()->shortname . '-' . $this->get_instance()->name . '-' . $groupname . $this->get_course_module()->id . '.zip');
// Get all the files for each student.
foreach ($students as $student) {
$userid = $student->id;
if (groups_is_member($groupid, $userid) or !$groupmode or !$groupid) {
// Get the plugins to add their own files to the zip.
$submissiongroup = false;
$groupname = '';
if ($this->get_instance()->teamsubmission) {
$submission = $this->get_group_submission($userid, 0, false);
$submissiongroup = $this->get_submission_group($userid);
if ($submissiongroup) {
$groupname = $submissiongroup->name . '-';
} else {
$groupname = get_string('defaultteam', 'assign') . '-';
}
} else {
$submission = $this->get_user_submission($userid, false);
}
if ($this->is_blind_marking()) {
$prefix = str_replace('_', ' ', $groupname . get_string('participant', 'assign'));
$prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
} else {
$prefix = str_replace('_', ' ', $groupname . fullname($student));
$prefix = clean_filename($prefix . '_' . $this->get_uniqueid_for_user($userid) . '_');
}
if ($submission) {
foreach ($this->submissionplugins as $plugin) {
if ($plugin->is_enabled() && $plugin->is_visible()) {
$pluginfiles = $plugin->get_files($submission, $student);
foreach ($pluginfiles as $zipfilename => $file) {
$subtype = $plugin->get_subtype();
$type = $plugin->get_type();
$prefixedfilename = clean_filename($prefix . $subtype . '_' . $type . '_' . $zipfilename);
$filesforzipping[$prefixedfilename] = $file;
}
}
}
}
}
}
$result = '';
if (count($filesforzipping) == 0) {
$header = new assign_header($this->get_instance(), $this->get_context(), '', $this->get_course_module()->id, get_string('downloadall', 'assign'));
$result .= $this->get_renderer()->render($header);
$result .= $this->get_renderer()->notification(get_string('nosubmission', 'assign'));
$url = new moodle_url('/mod/assign/view.php', array('id' => $this->get_course_module()->id, 'action' => 'grading'));
$result .= $this->get_renderer()->continue_button($url);
$result .= $this->view_footer();
} else {
if ($zipfile = $this->pack_files($filesforzipping)) {
\mod_assign\event\all_submissions_downloaded::create_from_assign($this)->trigger();
// Send file and delete after sending.
send_temp_file($zipfile, $filename);
// We will not get here - send_temp_file calls exit.
}
}
return $result;
}
示例11: byteserving_send_file
/**
* Send requested byterange of file.
*
* @param resource $handle A file handle
* @param string $mimetype The mimetype for the output
* @param array $ranges An array of ranges to send
* @param string $filesize The size of the content if only one range is used
*/
function byteserving_send_file($handle, $mimetype, $ranges, $filesize)
{
// better turn off any kind of compression and buffering
ini_set('zlib.output_compression', 'Off');
$chunksize = 1 * (1024 * 1024);
// 1MB chunks - must be less than 2MB!
if ($handle === false) {
die;
}
if (count($ranges) == 1) {
//only one range requested
$length = $ranges[0][2] - $ranges[0][1] + 1;
header('HTTP/1.1 206 Partial content');
header('Content-Length: ' . $length);
header('Content-Range: bytes ' . $ranges[0][1] . '-' . $ranges[0][2] . '/' . $filesize);
header('Content-Type: ' . $mimetype);
while (@ob_get_level()) {
if (!@ob_end_flush()) {
break;
}
}
fseek($handle, $ranges[0][1]);
while (!feof($handle) && $length > 0) {
core_php_time_limit::raise(60 * 60);
//reset time limit to 60 min - should be enough for 1 MB chunk
$buffer = fread($handle, $chunksize < $length ? $chunksize : $length);
echo $buffer;
flush();
$length -= strlen($buffer);
}
fclose($handle);
die;
} else {
// multiple ranges requested - not tested much
$totallength = 0;
foreach ($ranges as $range) {
$totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
}
$totallength += strlen("\r\n--" . BYTESERVING_BOUNDARY . "--\r\n");
header('HTTP/1.1 206 Partial content');
header('Content-Length: ' . $totallength);
header('Content-Type: multipart/byteranges; boundary=' . BYTESERVING_BOUNDARY);
while (@ob_get_level()) {
if (!@ob_end_flush()) {
break;
}
}
foreach ($ranges as $range) {
$length = $range[2] - $range[1] + 1;
echo $range[0];
fseek($handle, $range[1]);
while (!feof($handle) && $length > 0) {
core_php_time_limit::raise(60 * 60);
//reset time limit to 60 min - should be enough for 1 MB chunk
$buffer = fread($handle, $chunksize < $length ? $chunksize : $length);
echo $buffer;
flush();
$length -= strlen($buffer);
}
}
echo "\r\n--" . BYTESERVING_BOUNDARY . "--\r\n";
fclose($handle);
die;
}
}
示例12: sync
/**
* Sync all meta course links.
*
* @param progress_trace $trace
* @param int $courseid one course, empty mean all
* @return int 0 means ok, 1 means error, 2 means plugin disabled
*/
public function sync(progress_trace $trace, $courseid = null)
{
global $DB;
if (!enrol_is_enabled('manual')) {
$trace->finished();
return 2;
}
// Unfortunately this may take a long time, execution can be interrupted safely here.
core_php_time_limit::raise();
raise_memory_limit(MEMORY_HUGE);
$trace->output('Verifying manual enrolment expiration...');
$params = array('now' => time(), 'useractive' => ENROL_USER_ACTIVE, 'courselevel' => CONTEXT_COURSE);
$coursesql = "";
if ($courseid) {
$coursesql = "AND e.courseid = :courseid";
$params['courseid'] = $courseid;
}
// Deal with expired accounts.
$action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
if ($action == ENROL_EXT_REMOVED_UNENROL) {
$instances = array();
$sql = "SELECT ue.*, e.courseid, c.id AS contextid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n WHERE ue.timeend > 0 AND ue.timeend < :now\n {$coursesql}";
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ue) {
if (empty($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
}
$instance = $instances[$ue->enrolid];
// Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true);
$this->unenrol_user($instance, $ue->userid);
$trace->output("unenrolling expired user {$ue->userid} from course {$instance->courseid}", 1);
}
$rs->close();
unset($instances);
} else {
if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
$instances = array();
$sql = "SELECT ue.*, e.courseid, c.id AS contextid\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')\n JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)\n WHERE ue.timeend > 0 AND ue.timeend < :now\n AND ue.status = :useractive\n {$coursesql}";
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ue) {
if (empty($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
}
$instance = $instances[$ue->enrolid];
if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
// Remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
role_unassign_all(array('userid' => $ue->userid, 'contextid' => $ue->contextid, 'component' => '', 'itemid' => 0), true);
$this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
$trace->output("suspending expired user {$ue->userid} in course {$instance->courseid}, roles unassigned", 1);
} else {
$this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
$trace->output("suspending expired user {$ue->userid} in course {$instance->courseid}, roles kept", 1);
}
}
$rs->close();
unset($instances);
} else {
// ENROL_EXT_REMOVED_KEEP means no changes.
}
}
$trace->output('...manual enrolment updates finished.');
$trace->finished();
return 0;
}
示例13: delete_full
/**
* Recursively delete category including all subcategories and courses
*
* Function {@link coursecat::can_delete_full()} MUST be called prior
* to calling this function because there is no capability check
* inside this function
*
* @param boolean $showfeedback display some notices
* @return array return deleted courses
* @throws moodle_exception
*/
public function delete_full($showfeedback = true)
{
global $CFG, $DB;
require_once $CFG->libdir . '/gradelib.php';
require_once $CFG->libdir . '/questionlib.php';
require_once $CFG->dirroot . '/cohort/lib.php';
// Make sure we won't timeout when deleting a lot of courses.
$settimeout = core_php_time_limit::raise();
$deletedcourses = array();
// Get children. Note, we don't want to use cache here because it would be rebuilt too often.
$children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
foreach ($children as $record) {
$coursecat = new coursecat($record);
$deletedcourses += $coursecat->delete_full($showfeedback);
}
if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
foreach ($courses as $course) {
if (!delete_course($course, false)) {
throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
}
$deletedcourses[] = $course;
}
}
// Move or delete cohorts in this context.
cohort_delete_category($this);
// Now delete anything that may depend on course category context.
grade_course_category_delete($this->id, 0, $showfeedback);
if (!question_delete_course_category($this, 0, $showfeedback)) {
throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
}
// Finally delete the category and it's context.
$DB->delete_records('course_categories', array('id' => $this->id));
$coursecatcontext = context_coursecat::instance($this->id);
$coursecatcontext->delete();
cache_helper::purge_by_event('changesincoursecat');
// Trigger a course category deleted event.
/* @var \core\event\course_category_deleted $event */
$event = \core\event\course_category_deleted::create(array('objectid' => $this->id, 'context' => $coursecatcontext, 'other' => array('name' => $this->name)));
$event->set_coursecat($this);
$event->trigger();
// If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
if ($this->id == $CFG->defaultrequestcategory) {
set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
}
return $deletedcourses;
}
示例14: glossary_generate_export_file
/**
*
* @param object $glossary
* @param string $ignored invalid parameter
* @param int|string $hook
* @return string
*/
function glossary_generate_export_file($glossary, $ignored = "", $hook = 0)
{
global $CFG, $DB;
// Large exports are likely to take their time and memory.
core_php_time_limit::raise();
raise_memory_limit(MEMORY_EXTRA);
$cm = get_coursemodule_from_instance('glossary', $glossary->id, $glossary->course);
$context = context_module::instance($cm->id);
$co = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$co .= glossary_start_tag("GLOSSARY", 0, true);
$co .= glossary_start_tag("INFO", 1, true);
$co .= glossary_full_tag("NAME", 2, false, $glossary->name);
$co .= glossary_full_tag("INTRO", 2, false, $glossary->intro);
$co .= glossary_full_tag("INTROFORMAT", 2, false, $glossary->introformat);
$co .= glossary_full_tag("ALLOWDUPLICATEDENTRIES", 2, false, $glossary->allowduplicatedentries);
$co .= glossary_full_tag("DISPLAYFORMAT", 2, false, $glossary->displayformat);
$co .= glossary_full_tag("SHOWSPECIAL", 2, false, $glossary->showspecial);
$co .= glossary_full_tag("SHOWALPHABET", 2, false, $glossary->showalphabet);
$co .= glossary_full_tag("SHOWALL", 2, false, $glossary->showall);
$co .= glossary_full_tag("ALLOWCOMMENTS", 2, false, $glossary->allowcomments);
$co .= glossary_full_tag("USEDYNALINK", 2, false, $glossary->usedynalink);
$co .= glossary_full_tag("DEFAULTAPPROVAL", 2, false, $glossary->defaultapproval);
$co .= glossary_full_tag("GLOBALGLOSSARY", 2, false, $glossary->globalglossary);
$co .= glossary_full_tag("ENTBYPAGE", 2, false, $glossary->entbypage);
$co .= glossary_xml_export_files('INTROFILES', 2, $context->id, 'intro', 0);
if ($entries = $DB->get_records("glossary_entries", array("glossaryid" => $glossary->id))) {
$co .= glossary_start_tag("ENTRIES", 2, true);
foreach ($entries as $entry) {
$permissiongranted = 1;
if ($hook) {
switch ($hook) {
case "ALL":
case "SPECIAL":
break;
default:
$permissiongranted = $entry->concept[strlen($hook) - 1] == $hook;
break;
}
}
if ($hook) {
switch ($hook) {
case GLOSSARY_SHOW_ALL_CATEGORIES:
break;
case GLOSSARY_SHOW_NOT_CATEGORISED:
$permissiongranted = !$DB->record_exists("glossary_entries_categories", array("entryid" => $entry->id));
break;
default:
$permissiongranted = $DB->record_exists("glossary_entries_categories", array("entryid" => $entry->id, "categoryid" => $hook));
break;
}
}
if ($entry->approved and $permissiongranted) {
$co .= glossary_start_tag("ENTRY", 3, true);
$co .= glossary_full_tag("CONCEPT", 4, false, trim($entry->concept));
$co .= glossary_full_tag("DEFINITION", 4, false, $entry->definition);
$co .= glossary_full_tag("FORMAT", 4, false, $entry->definitionformat);
// note: use old name for BC reasons
$co .= glossary_full_tag("USEDYNALINK", 4, false, $entry->usedynalink);
$co .= glossary_full_tag("CASESENSITIVE", 4, false, $entry->casesensitive);
$co .= glossary_full_tag("FULLMATCH", 4, false, $entry->fullmatch);
$co .= glossary_full_tag("TEACHERENTRY", 4, false, $entry->teacherentry);
if ($aliases = $DB->get_records("glossary_alias", array("entryid" => $entry->id))) {
$co .= glossary_start_tag("ALIASES", 4, true);
foreach ($aliases as $alias) {
$co .= glossary_start_tag("ALIAS", 5, true);
$co .= glossary_full_tag("NAME", 6, false, trim($alias->alias));
$co .= glossary_end_tag("ALIAS", 5, true);
}
$co .= glossary_end_tag("ALIASES", 4, true);
}
if ($catentries = $DB->get_records("glossary_entries_categories", array("entryid" => $entry->id))) {
$co .= glossary_start_tag("CATEGORIES", 4, true);
foreach ($catentries as $catentry) {
$category = $DB->get_record("glossary_categories", array("id" => $catentry->categoryid));
$co .= glossary_start_tag("CATEGORY", 5, true);
$co .= glossary_full_tag("NAME", 6, false, $category->name);
$co .= glossary_full_tag("USEDYNALINK", 6, false, $category->usedynalink);
$co .= glossary_end_tag("CATEGORY", 5, true);
}
$co .= glossary_end_tag("CATEGORIES", 4, true);
}
// Export files embedded in entries.
$co .= glossary_xml_export_files('ENTRYFILES', 4, $context->id, 'entry', $entry->id);
// Export attachments.
$co .= glossary_xml_export_files('ATTACHMENTFILES', 4, $context->id, 'attachment', $entry->id);
$co .= glossary_end_tag("ENTRY", 3, true);
}
}
$co .= glossary_end_tag("ENTRIES", 2, true);
}
$co .= glossary_end_tag("INFO", 1, true);
$co .= glossary_end_tag("GLOSSARY", 0, true);
return $co;
//.........这里部分代码省略.........
示例15: stats_cron_monthly
/**
* Execute monthly statistics gathering
* @return boolean success
*/
function stats_cron_monthly()
{
global $CFG, $DB;
require_once $CFG->libdir . '/adminlib.php';
$now = time();
// read last execution date from db
if (!($timestart = get_config(NULL, 'statslastmonthly'))) {
$timestart = stats_get_base_monthly(stats_get_start_from('monthly'));
set_config('statslastmonthly', $timestart);
}
$nextstartmonth = stats_get_next_month_start($timestart);
// are there any months that need to be processed?
if ($now < $nextstartmonth) {
return true;
// everything ok and up-to-date
}
$timeout = empty($CFG->statsmaxruntime) ? 60 * 60 * 24 : $CFG->statsmaxruntime;
if (!set_cron_lock('statsrunning', $now + $timeout)) {
return false;
}
// fisr delete entries that should not be there yet
$DB->delete_records_select('stats_monthly', "timeend > {$timestart}");
$DB->delete_records_select('stats_user_monthly', "timeend > {$timestart}");
$startmonth = stats_get_base_monthly($now);
mtrace("Running monthly statistics gathering, starting at {$timestart}:");
cron_trace_time_and_memory();
$months = 0;
while ($now > $nextstartmonth) {
core_php_time_limit::raise($timeout - 200);
$months++;
if ($months > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$stattimesql = "timeend > {$timestart} AND timeend <= {$nextstartmonth}";
$monthstart = time();
stats_progress('init');
/// process login info first
$sql = "INSERT INTO {stats_user_monthly} (stattype, timeend, courseid, userid, statsreads)\n\n SELECT 'logins', timeend, courseid, userid, SUM(statsreads)\n FROM (\n SELECT {$nextstartmonth} AS timeend, courseid, userid, statsreads\n FROM {stats_user_daily} sd\n WHERE stattype = 'logins' AND {$stattimesql}\n ) inline_view\n GROUP BY timeend, courseid, userid\n HAVING SUM(statsreads) > 0";
$DB->execute($sql);
stats_progress('1');
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)\n\n SELECT 'logins' AS stattype, {$nextstartmonth} AS timeend, " . SITEID . " as courseid, 0,\n COALESCE((SELECT SUM(statsreads)\n FROM {stats_user_monthly} s1\n WHERE s1.stattype = 'logins' AND timeend = {$nextstartmonth}), 0) AS nstat1,\n (SELECT COUNT('x')\n FROM {stats_user_monthly} s2\n WHERE s2.stattype = 'logins' AND timeend = {$nextstartmonth}) AS nstat2" . $DB->sql_null_from_clause();
$DB->execute($sql);
stats_progress('2');
/// now enrolments averages
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)\n\n SELECT 'enrolments', ntimeend, courseid, roleid, " . $DB->sql_ceil('AVG(stat1)') . ", " . $DB->sql_ceil('AVG(stat2)') . "\n FROM (\n SELECT {$nextstartmonth} AS ntimeend, courseid, roleid, stat1, stat2\n FROM {stats_daily} sd\n WHERE stattype = 'enrolments' AND {$stattimesql}\n ) inline_view\n GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('3');
/// activity read/write averages
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)\n\n SELECT 'activity', ntimeend, courseid, roleid, SUM(stat1), SUM(stat2)\n FROM (\n SELECT {$nextstartmonth} AS ntimeend, courseid, roleid, stat1, stat2\n FROM {stats_daily}\n WHERE stattype = 'activity' AND {$stattimesql}\n ) inline_view\n GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('4');
/// user read/write averages
$sql = "INSERT INTO {stats_user_monthly} (stattype, timeend, courseid, userid, statsreads, statswrites)\n\n SELECT 'activity', ntimeend, courseid, userid, SUM(statsreads), SUM(statswrites)\n FROM (\n SELECT {$nextstartmonth} AS ntimeend, courseid, userid, statsreads, statswrites\n FROM {stats_user_daily}\n WHERE stattype = 'activity' AND {$stattimesql}\n ) inline_view\n GROUP BY ntimeend, courseid, userid";
$DB->execute($sql);
stats_progress('5');
set_config('statslastmonthly', $nextstartmonth);
$elapsed = time() - $monthstart;
mtrace(" finished until {$nextstartmonth}: " . userdate($nextstartmonth) . " (in {$elapsed} s)");
$timestart = $nextstartmonth;
$nextstartmonth = stats_get_next_month_start($nextstartmonth);
}
set_cron_lock('statsrunning', null);
mtrace("...completed {$months} months of statistics.");
return true;
}