当前位置: 首页>>代码示例>>PHP>>正文


PHP cron_setup_user函数代码示例

本文整理汇总了PHP中cron_setup_user函数的典型用法代码示例。如果您正苦于以下问题:PHP cron_setup_user函数的具体用法?PHP cron_setup_user怎么用?PHP cron_setup_user使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了cron_setup_user函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: cron

 static function cron()
 {
     // Setup user object (as admin)
     cron_setup_user();
     // Newline after the forum...
     mtrace("");
     // Send forum emails and digests
     self::email();
     // Delete old playsapces
     self::daily_housekeeping();
 }
开发者ID:nadavkav,项目名称:Moodle2-Hebrew-plugins,代码行数:11,代码来源:mod_forumng_cron.php

示例2: execute

 /**
  * Run the deletion task.
  *
  * @throws \coding_exception if the module could not be removed.
  */
 public function execute()
 {
     global $CFG;
     require_once $CFG->dirroot . '/course/lib.php';
     // Set the proper user.
     if ($this->get_custom_data()->userid !== $this->get_custom_data()->realuserid) {
         $realuser = \core_user::get_user($this->get_custom_data()->realuserid, '*', MUST_EXIST);
         cron_setup_user($realuser);
         \core\session\manager::loginas($this->get_custom_data()->userid, \context_system::instance(), false);
     } else {
         $user = \core_user::get_user($this->get_custom_data()->userid, '*', MUST_EXIST);
         cron_setup_user($user);
     }
     $cms = $this->get_custom_data()->cms;
     foreach ($cms as $cm) {
         try {
             course_delete_module($cm->id);
         } catch (\Exception $e) {
             throw new \coding_exception("The course module {$cm->id} could not be deleted. {$e->getTraceAsString()}");
         }
     }
 }
开发者ID:lucaboesch,项目名称:moodle,代码行数:27,代码来源:course_delete_modules.php

示例3: process_message

 /**
  * Process a message and pass it through the Inbound Message handling systems.
  *
  * @param \Horde_Imap_Client_Data_Fetch $message The message to process
  * @param bool $viewreadmessages Whether to also look at messages which have been marked as read
  * @param bool $skipsenderverification Whether to skip the sender verification stage
  */
 public function process_message(\Horde_Imap_Client_Data_Fetch $message, $viewreadmessages = false, $skipsenderverification = false)
 {
     global $USER;
     // We use the Client IDs several times - store them here.
     $messageid = new \Horde_Imap_Client_Ids($message->getUid());
     mtrace("- Parsing message " . $messageid);
     // First flag this message to prevent another running hitting this message while we look at the headers.
     $this->add_flag_to_message($messageid, self::MESSAGE_FLAGGED);
     if ($this->is_bulk_message($message, $messageid)) {
         mtrace("- The message has a bulk header set. This is likely an auto-generated reply - discarding.");
         return;
     }
     // Record the user that this script is currently being run as.  This is important when re-processing existing
     // messages, as cron_setup_user is called multiple times.
     $originaluser = $USER;
     $envelope = $message->getEnvelope();
     $recipients = $envelope->to->bare_addresses;
     foreach ($recipients as $recipient) {
         if (!\core\message\inbound\address_manager::is_correct_format($recipient)) {
             // Message did not contain a subaddress.
             mtrace("- Recipient '{$recipient}' did not match Inbound Message headers.");
             continue;
         }
         // Message contained a match.
         $senders = $message->getEnvelope()->from->bare_addresses;
         if (count($senders) !== 1) {
             mtrace("- Received multiple senders. Only the first sender will be used.");
         }
         $sender = array_shift($senders);
         mtrace("-- Subject:\t" . $envelope->subject);
         mtrace("-- From:\t" . $sender);
         mtrace("-- Recipient:\t" . $recipient);
         // Grab messagedata including flags.
         $query = new \Horde_Imap_Client_Fetch_Query();
         $query->structure();
         $messagedata = $this->client->fetch($this->get_mailbox(), $query, array('ids' => $messageid))->first();
         if (!$viewreadmessages && $this->message_has_flag($messageid, self::MESSAGE_SEEN)) {
             // Something else has already seen this message. Skip it now.
             mtrace("-- Skipping the message - it has been marked as seen - perhaps by another process.");
             continue;
         }
         // Mark it as read to lock the message.
         $this->add_flag_to_message($messageid, self::MESSAGE_SEEN);
         // Now pass it through the Inbound Message processor.
         $status = $this->addressmanager->process_envelope($recipient, $sender);
         if (($status & ~\core\message\inbound\address_manager::VALIDATION_DISABLED_HANDLER) !== $status) {
             // The handler is disabled.
             mtrace("-- Skipped message - Handler is disabled. Fail code {$status}");
             // In order to handle the user error, we need more information about the message being failed.
             $this->process_message_data($envelope, $messagedata, $messageid);
             $this->inform_user_of_error(get_string('handlerdisabled', 'tool_messageinbound', $this->currentmessagedata));
             return;
         }
         // Check the validation status early. No point processing garbage messages, but we do need to process it
         // for some validation failure types.
         if (!$this->passes_key_validation($status, $messageid)) {
             // None of the above validation failures were found. Skip this message.
             mtrace("-- Skipped message - it does not appear to relate to a Inbound Message pickup. Fail code {$status}");
             // Remove the seen flag from the message as there may be multiple recipients.
             $this->remove_flag_from_message($messageid, self::MESSAGE_SEEN);
             // Skip further processing for this recipient.
             continue;
         }
         // Process the message as the user.
         $user = $this->addressmanager->get_data()->user;
         mtrace("-- Processing the message as user {$user->id} ({$user->username}).");
         cron_setup_user($user);
         // Process and retrieve the message data for this message.
         // This includes fetching the full content, as well as all headers, and attachments.
         if (!$this->process_message_data($envelope, $messagedata, $messageid)) {
             mtrace("--- Message could not be found on the server. Is another process removing messages?");
             return;
         }
         // When processing validation replies, we need to skip the sender verification phase as this has been
         // manually completed.
         if (!$skipsenderverification && $status !== 0) {
             // Check the validation status for failure types which require confirmation.
             // The validation result is tested in a bitwise operation.
             mtrace("-- Message did not meet validation but is possibly recoverable. Fail code {$status}");
             // This is a recoverable error, but requires user input.
             if ($this->handle_verification_failure($messageid, $recipient)) {
                 mtrace("--- Original message retained on mail server and confirmation message sent to user.");
             } else {
                 mtrace("--- Invalid Recipient Handler - unable to save. Informing the user of the failure.");
                 $this->inform_user_of_error(get_string('invalidrecipientfinal', 'tool_messageinbound', $this->currentmessagedata));
             }
             // Returning to normal cron user.
             mtrace("-- Returning to the original user.");
             cron_setup_user($originaluser);
             return;
         }
         // Add the content and attachment data.
         mtrace("-- Validation completed. Fetching rest of message content.");
//.........这里部分代码省略.........
开发者ID:Chocolate-lightning,项目名称:moodle,代码行数:101,代码来源:manager.php

示例4: scheduler_cron

/**
 * Function to be run periodically according to the moodle
 * This function searches for things that need to be done, such
 * as sending out mail, toggling flags etc ...
 * @return boolean always true
 * @uses $CFG
 * @uses $DB
 */
function scheduler_cron()
{
    global $CFG, $DB;
    $date = make_timestamp(date('Y'), date('m'), date('d'), date('H'), date('i'));
    // for every appointment in all schedulers
    $select = 'emaildate > 0 AND emaildate <= ? AND starttime > ?';
    $slots = $DB->get_records_select('scheduler_slots', $select, array($date, $date), 'starttime');
    foreach ($slots as $slot) {
        // get teacher
        $teacher = $DB->get_record('user', array('id' => $slot->teacherid));
        // get scheduler, slot and course
        $scheduler = scheduler_instance::load_by_id($slot->schedulerid);
        $slotm = $scheduler->get_slot($slot->id);
        $course = $DB->get_record('course', array('id' => $scheduler->course));
        // get appointed student list
        $appointments = $DB->get_records('scheduler_appointment', array('slotid' => $slot->id), '', 'id, studentid');
        //if no email previously sent and one is required
        foreach ($appointments as $appointment) {
            $student = $DB->get_record('user', array('id' => $appointment->studentid));
            cron_setup_user($student, $course);
            $vars = scheduler_get_mail_variables($scheduler, $slotm, $teacher, $student, $course, $student);
            scheduler_send_email_from_template($student, $teacher, $course, 'remindtitle', 'reminder', $vars, 'scheduler');
        }
        // mark as sent
        $slot->emaildate = -1;
        $DB->update_record('scheduler_slots', $slot);
    }
    cron_setup_user();
    return true;
}
开发者ID:ninelanterns,项目名称:moodle-mod_scheduler,代码行数:38,代码来源:lib.php

示例5: cron_run

/**
 * Cron functions.
 *
 * @package    core
 * @subpackage admin
 * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        $CFG->debug = DEBUG_DEVELOPER;
        $CFG->debugdisplay = true;
    }
    set_time_limit(0);
    $starttime = microtime();
    /// increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    /// emulate normal session
    cron_setup_user();
    /// Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    /// Session gc
    mtrace("Cleaning up stale sessions");
    session_gc();
    /// Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    /// Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // we will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    /// Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace("Starting quiz reports");
    if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
        foreach ($reports as $report) {
            $cronfile = "{$CFG->dirroot}/mod/quiz/report/{$report->name}/cron.php";
//.........这里部分代码省略.........
开发者ID:vuchannguyen,项目名称:web,代码行数:101,代码来源:cronlib.php

示例6: test_cron_message_includes_courseid

 public function test_cron_message_includes_courseid()
 {
     // First run cron so there are no messages waiting to be sent (from other tests).
     cron_setup_user();
     assign::cron();
     // Now create an assignment.
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance(array('sendstudentnotifications' => 1));
     // Simulate adding a grade.
     $this->setUser($this->teachers[0]);
     $data = new stdClass();
     $data->grade = '50.0';
     $assign->testable_apply_grade_to_user($data, $this->students[0]->id, 0);
     $this->preventResetByRollback();
     $sink = $this->redirectEvents();
     $this->expectOutputRegex('/Done processing 1 assignment submissions/');
     assign::cron();
     $events = $sink->get_events();
     // Two messages are sent, one to student and one to teacher. This generates
     // four events:
     // core\event\message_sent
     // core\event\message_viewed
     // core\event\message_sent
     // core\event\message_viewed.
     $event = reset($events);
     $this->assertInstanceOf('\\core\\event\\message_sent', $event);
     $this->assertEquals($assign->get_course()->id, $event->other['courseid']);
     $sink->close();
 }
开发者ID:lucaboesch,项目名称:moodle,代码行数:29,代码来源:locallib_test.php

示例7: cron_run

/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
//.........这里部分代码省略.........
开发者ID:tyleung,项目名称:CMPUT401MoodleExams,代码行数:101,代码来源:cronlib.php

示例8: assignment_cron

/**
 * Function to be run periodically according to the moodle cron
 *
 * Finds all assignment notifications that have yet to be mailed out, and mails them
 */
function assignment_cron () {
    global $CFG, $USER, $DB;

    /// first execute all crons in plugins
    if ($plugins = get_plugin_list('assignment')) {
        foreach ($plugins as $plugin=>$dir) {
            require_once("$dir/assignment.class.php");
            $assignmentclass = "assignment_$plugin";
            $ass = new $assignmentclass();
            $ass->cron();
        }
    }

    /// Notices older than 1 day will not be mailed.  This is to avoid the problem where
    /// cron has not been running for a long time, and then suddenly people are flooded
    /// with mail from the past few weeks or months

    $timenow   = time();
    $endtime   = $timenow - $CFG->maxeditingtime;
    $starttime = $endtime - 24 * 3600;   /// One day earlier

    if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {

        $realuser = clone($USER);

        foreach ($submissions as $key => $submission) {
            $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
        }

        $timenow = time();

        foreach ($submissions as $submission) {

            echo "Processing assignment submission $submission->id\n";

            if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
                echo "Could not find user $user->id\n";
                continue;
            }

            if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
                echo "Could not find course $submission->course\n";
                continue;
            }

            /// Override the language and timezone of the "current" user, so that
            /// mail is customised for the receiver.
            cron_setup_user($user, $course);

            if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
                echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
                continue;
            }

            if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
                echo "Could not find teacher $submission->teacher\n";
                continue;
            }

            if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
                echo "Could not find course module for assignment id $submission->assignment\n";
                continue;
            }

            if (! $mod->visible) {    /// Hold mail notification for hidden assignments until later
                continue;
            }

            $strassignments = get_string("modulenameplural", "assignment");
            $strassignment  = get_string("modulename", "assignment");

            $assignmentinfo = new stdClass();
            $assignmentinfo->teacher = fullname($teacher);
            $assignmentinfo->assignment = format_string($submission->name,true);
            $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";

            $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
            $posttext  = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
            $posttext .= "---------------------------------------------------------------------\n";

            if ($user->mailformat == 1) {  // HTML
                $posthtml = "<p><font face=\"sans-serif\">".
                "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
                "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
                "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
                $posthtml .= "<hr /><font face=\"sans-serif\">";
                $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
                $posthtml .= "</font><hr />";
            } else {
                $posthtml = "";
            }

            $eventdata = new stdClass();
//.........这里部分代码省略.........
开发者ID:nuckey,项目名称:moodle,代码行数:101,代码来源:lib.php

示例9: cron

 /**
  * Finds all assignment notifications that have yet to be mailed out, and mails them.
  *
  * Cron function to be run periodically according to the moodle cron.
  *
  * @return bool
  */
 public static function cron()
 {
     global $DB;
     // Only ever send a max of one days worth of updates.
     $yesterday = time() - 24 * 3600;
     $timenow = time();
     $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
     // Collect all submissions that require mailing.
     // Submissions are included if all are true:
     //   - The assignment is visible in the gradebook.
     //   - No previous notification has been sent.
     //   - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
     //     if marking workflow is enabled, the workflow state is at 'released'.
     $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,\n                       g.*, g.timemodified as lastmodified, cm.id as cmid\n                 FROM {assign} a\n                 JOIN {assign_grades} g ON g.assignment = a.id\n            LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid\n                 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id\n                 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'\n                 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name\n                 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR\n                        (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND\n                       uf.mailed = 0 AND gri.hidden = 0\n              ORDER BY a.course, cm.id";
     $params = array('yesterday' => $yesterday, 'today' => $timenow, 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
     $submissions = $DB->get_records_sql($sql, $params);
     if (!empty($submissions)) {
         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
         // Preload courses we are going to need those.
         $courseids = array();
         foreach ($submissions as $submission) {
             $courseids[] = $submission->course;
         }
         // Filter out duplicates.
         $courseids = array_unique($courseids);
         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
         $sql = 'SELECT c.*, ' . $ctxselect . ' FROM {course} c
              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
                  WHERE c.id ' . $courseidsql;
         $params['contextlevel'] = CONTEXT_COURSE;
         $courses = $DB->get_records_sql($sql, $params);
         // Clean up... this could go on for a while.
         unset($courseids);
         unset($ctxselect);
         unset($courseidsql);
         unset($params);
         // Message students about new feedback.
         foreach ($submissions as $submission) {
             mtrace("Processing assignment submission {$submission->id} ...");
             // Do not cache user lookups - could be too many.
             if (!($user = $DB->get_record('user', array('id' => $submission->userid)))) {
                 mtrace('Could not find user ' . $submission->userid);
                 continue;
             }
             // Use a cache to prevent the same DB queries happening over and over.
             if (!array_key_exists($submission->course, $courses)) {
                 mtrace('Could not find course ' . $submission->course);
                 continue;
             }
             $course = $courses[$submission->course];
             if (isset($course->ctxid)) {
                 // Context has not yet been preloaded. Do so now.
                 context_helper::preload_from_record($course);
             }
             // Override the language and timezone of the "current" user, so that
             // mail is customised for the receiver.
             cron_setup_user($user, $course);
             // Context lookups are already cached.
             $coursecontext = context_course::instance($course->id);
             if (!is_enrolled($coursecontext, $user->id)) {
                 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
                 continue;
             }
             if (!($grader = $DB->get_record('user', array('id' => $submission->grader)))) {
                 mtrace('Could not find grader ' . $submission->grader);
                 continue;
             }
             $modinfo = get_fast_modinfo($course, $user->id);
             $cm = $modinfo->get_cm($submission->cmid);
             // Context lookups are already cached.
             $contextmodule = context_module::instance($cm->id);
             if (!$cm->uservisible) {
                 // Hold mail notification for assignments the user cannot access until later.
                 continue;
             }
             // Need to send this to the student.
             $messagetype = 'feedbackavailable';
             $eventtype = 'assign_notification';
             $updatetime = $submission->lastmodified;
             $modulename = get_string('modulename', 'assign');
             $uniqueid = 0;
             if ($submission->blindmarking && !$submission->revealidentities) {
                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
             }
             $showusers = $submission->blindmarking && !$submission->revealidentities;
             self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $cm, $contextmodule, $course, $modulename, $submission->name, $showusers, $uniqueid);
             $flags = $DB->get_record('assign_user_flags', array('userid' => $user->id, 'assignment' => $submission->assignment));
             if ($flags) {
                 $flags->mailed = 1;
                 $DB->update_record('assign_user_flags', $flags);
             } else {
//.........这里部分代码省略.........
开发者ID:mercysmart,项目名称:naikelas,代码行数:101,代码来源:locallib.php

示例10: cron

 /**
 * Notify users about enrolments that are going to expire soon!
 * This function is run by admin/cron.php
 * @return void
 */
 function cron()
 {
     global $CFG, $USER, $SITE, $DB;
     if (!isset($CFG->lastexpirynotify)) {
         set_config('lastexpirynotify', 0);
     }
     // notify once a day only - TODO: add some tz handling here, maybe use timestamps
     if ($CFG->lastexpirynotify == date('Ymd')) {
         return;
     }
     if ($rs = $DB->get_recordset_select('course', 'enrolperiod > 0 AND expirynotify > 0 AND expirythreshold > 0')) {
         $admin = get_admin();
         foreach ($rs as $course) {
             $a = new object();
             $a->coursename = $course->shortname . '/' . $course->fullname;
             // must be processed by format_string later
             $a->threshold = $course->expirythreshold / 86400;
             $a->extendurl = $CFG->wwwroot . '/user/index.php?id=' . $course->id;
             $a->current = array();
             $a->past = array();
             $expiry = time() + $course->expirythreshold;
             $cname = $course->fullname;
             /// Get all the manual role assignments for this course that have expired.
             if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) {
                 continue;
             }
             if ($oldenrolments = $DB->get_records_sql("\n                      SELECT u.*, ra.timeend\n                        FROM {user} u\n                             JOIN {role_assignments} ra ON (ra.userid = u.id)\n                        WHERE ra.contextid = {$context->id}\n                              AND ra.timeend > 0 AND ra.timeend <= {$expiry}\n                              AND ra.enrol = 'manual'")) {
                 // inform user who can assign roles or admin
                 if ($teachers = get_users_by_capability($context, 'moodle/role:assign', '', '', '', '', '', '', false)) {
                     $teachers = sort_by_roleassignment_authority($teachers, $context);
                     $teacher = reset($teachers);
                 } else {
                     $teachers = array($admin);
                     $teacher = $admin;
                 }
                 $a->teacherstr = fullname($teacher, true);
                 foreach ($oldenrolments as $user) {
                     /// Email all users about to expire
                     $a->studentstr = fullname($user, true);
                     if ($user->timeend < $expiry - 86400) {
                         $a->past[] = fullname($user) . " <{$user->email}>";
                     } else {
                         $a->current[] = fullname($user) . " <{$user->email}>";
                         if ($course->notifystudents) {
                             // Send this guy notice
                             // setup global $COURSE properly - needed for languages
                             cron_setup_user($user, $course);
                             $a->coursename = format_string($cname);
                             $a->course = $a->coursename;
                             $strexpirynotifystudentsemail = get_string('expirynotifystudentsemail', '', $a);
                             $strexpirynotify = get_string('expirynotify');
                             $eventdata = new object();
                             $eventdata->modulename = 'moodle';
                             $eventdata->userfrom = $teacher;
                             $eventdata->userto = $user;
                             $eventdata->subject = format_string($SITE->fullname) . ' ' . $strexpirynotify;
                             $eventdata->fullmessage = $strexpirynotifystudentsemail;
                             $eventdata->fullmessageformat = FORMAT_PLAIN;
                             $eventdata->fullmessagehtml = '';
                             $eventdata->smallmessage = '';
                             events_trigger('message_send', $eventdata);
                         }
                     }
                 }
                 $a->current = implode("\n", $a->current);
                 $a->past = implode("\n", $a->past);
                 if ($a->current || $a->past) {
                     foreach ($teachers as $teacher) {
                         // setup global $COURSE properly - needed for languages
                         cron_setup_user($teacher, $course);
                         $a->coursename = format_string($cname);
                         $strexpirynotifyemail = get_string('expirynotifyemail', '', $a);
                         $strexpirynotify = get_string('expirynotify');
                         $eventdata = new object();
                         $eventdata->modulename = 'moodle';
                         $eventdata->userfrom = $admin;
                         $eventdata->userto = $teacher;
                         $eventdata->subject = $a->coursename . ' ' . $strexpirynotify;
                         $eventdata->fullmessage = $strexpirynotifyemail;
                         $eventdata->fullmessageformat = FORMAT_PLAIN;
                         $eventdata->fullmessagehtml = '';
                         $eventdata->smallmessage = '';
                         events_trigger('message_send', $eventdata);
                     }
                 }
             }
         }
         $rs->close();
         cron_setup_user();
     }
     set_config('lastexpirynotify', date('Ymd'));
 }
开发者ID:ajv,项目名称:Offline-Caching,代码行数:97,代码来源:enrol.php

示例11: cron_run

/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    core_php_time_limit::raise();
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run all scheduled tasks.
    while (!\core\task\manager::static_caches_cleared_since($timenow) && ($task = \core\task\manager::get_next_scheduled_task($timenow))) {
        mtrace("Execute scheduled task: " . $task->get_name());
        cron_trace_time_and_memory();
        $predbqueries = null;
        $predbqueries = $DB->perf_get_queries();
        $pretime = microtime(1);
        try {
            get_mailer('buffer');
            $task->execute();
            if ($DB->is_transaction_started()) {
                throw new coding_exception("Task left transaction open");
            }
            if (isset($predbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                mtrace("... used " . (microtime(1) - $pretime) . " seconds");
            }
            mtrace("Scheduled task complete: " . $task->get_name());
            \core\task\manager::scheduled_task_complete($task);
        } catch (Exception $e) {
            if ($DB && $DB->is_transaction_started()) {
                error_log('Database transaction aborted automatically in ' . get_class($task));
                $DB->force_transaction_rollback();
            }
            if (isset($predbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                mtrace("... used " . (microtime(1) - $pretime) . " seconds");
            }
            mtrace("Scheduled task failed: " . $task->get_name() . "," . $e->getMessage());
            if ($CFG->debugdeveloper) {
                if (!empty($e->debuginfo)) {
                    mtrace("Debug info:");
                    mtrace($e->debuginfo);
                }
                mtrace("Backtrace:");
                mtrace(format_backtrace($e->getTrace(), true));
            }
            \core\task\manager::scheduled_task_failed($task);
        }
        get_mailer('close');
        unset($task);
    }
    // Run all adhoc tasks.
    while (!\core\task\manager::static_caches_cleared_since($timenow) && ($task = \core\task\manager::get_next_adhoc_task($timenow))) {
        mtrace("Execute adhoc task: " . get_class($task));
        cron_trace_time_and_memory();
        $predbqueries = null;
        $predbqueries = $DB->perf_get_queries();
        $pretime = microtime(1);
        try {
            get_mailer('buffer');
            $task->execute();
            if ($DB->is_transaction_started()) {
                throw new coding_exception("Task left transaction open");
            }
            if (isset($predbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                mtrace("... used " . (microtime(1) - $pretime) . " seconds");
            }
            mtrace("Adhoc task complete: " . get_class($task));
            \core\task\manager::adhoc_task_complete($task);
        } catch (Exception $e) {
            if ($DB && $DB->is_transaction_started()) {
                error_log('Database transaction aborted automatically in ' . get_class($task));
                $DB->force_transaction_rollback();
            }
            if (isset($predbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                mtrace("... used " . (microtime(1) - $pretime) . " seconds");
            }
//.........这里部分代码省略.........
开发者ID:educakanchay,项目名称:campus,代码行数:101,代码来源:cronlib.php

示例12: i_run_all_adhoc_tasks

 /**
  * Runs all ad-hoc tasks in the queue.
  *
  * This is faster and more reliable than running cron (running cron won't
  * work more than once in the same test, for instance). However it is
  * a little less 'realistic'.
  *
  * While the task is running, we suppress mtrace output because it makes
  * the Behat result look ugly.
  *
  * @Given /^I run all adhoc tasks$/
  * @throws DriverException
  */
 public function i_run_all_adhoc_tasks()
 {
     // Do setup for cron task.
     cron_setup_user();
     // Run tasks. Locking is handled by get_next_adhoc_task.
     $now = time();
     ob_start();
     // Discard task output as not appropriate for Behat output!
     while (($task = \core\task\manager::get_next_adhoc_task($now)) !== null) {
         try {
             $task->execute();
             // Mark task complete.
             \core\task\manager::adhoc_task_complete($task);
         } catch (Exception $e) {
             // Mark task failed and throw exception.
             \core\task\manager::adhoc_task_failed($task);
             ob_end_clean();
             throw new DriverException('An adhoc task failed', 0, $e);
         }
     }
     ob_end_clean();
 }
开发者ID:lucaboesch,项目名称:moodle,代码行数:35,代码来源:behat_general.php

示例13: test_cron_setup_user

 public function test_cron_setup_user()
 {
     global $PAGE, $USER, $SESSION, $SITE, $CFG;
     $this->resetAfterTest();
     // NOTE: this function contains some static caches, let's reset first.
     cron_setup_user('reset');
     $admin = get_admin();
     $user1 = $this->getDataGenerator()->create_user();
     $user2 = $this->getDataGenerator()->create_user();
     $course = $this->getDataGenerator()->create_course();
     cron_setup_user();
     $this->assertSame($admin->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertSame($CFG->timezone, $USER->timezone);
     $this->assertSame('', $USER->lang);
     $this->assertSame('', $USER->theme);
     $SESSION->test1 = true;
     $adminsession = $SESSION;
     $adminuser = $USER;
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user(null, $course);
     $this->assertSame($admin->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($course->id));
     $this->assertSame($adminsession, $SESSION);
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user($user1);
     $this->assertSame($user1->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertNotSame($adminsession, $SESSION);
     $this->assertObjectNotHasAttribute('test1', $SESSION);
     $this->assertEmpty((array) $SESSION);
     $usersession1 = $SESSION;
     $SESSION->test2 = true;
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user($user1);
     $this->assertSame($user1->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertNotSame($adminsession, $SESSION);
     $this->assertSame($usersession1, $SESSION);
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user($user2);
     $this->assertSame($user2->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertNotSame($adminsession, $SESSION);
     $this->assertNotSame($usersession1, $SESSION);
     $this->assertEmpty((array) $SESSION);
     $usersession2 = $SESSION;
     $usersession2->test3 = true;
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user($user2, $course);
     $this->assertSame($user2->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($course->id));
     $this->assertNotSame($adminsession, $SESSION);
     $this->assertNotSame($usersession1, $SESSION);
     $this->assertSame($usersession2, $SESSION);
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user($user1);
     $this->assertSame($user1->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertNotSame($adminsession, $SESSION);
     $this->assertNotSame($usersession1, $SESSION);
     $this->assertEmpty((array) $SESSION);
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user();
     $this->assertSame($admin->id, $USER->id);
     $this->assertSame($PAGE->context, context_course::instance($SITE->id));
     $this->assertSame($adminsession, $SESSION);
     $this->assertSame($adminuser, $USER);
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user('reset');
     $this->assertSame($GLOBALS['SESSION'], $_SESSION['SESSION']);
     $this->assertSame($GLOBALS['SESSION'], $SESSION);
     $this->assertSame($GLOBALS['USER'], $_SESSION['USER']);
     $this->assertSame($GLOBALS['USER'], $USER);
     cron_setup_user();
     $this->assertNotSame($adminsession, $SESSION);
//.........这里部分代码省略.........
开发者ID:alanaipe2015,项目名称:moodle,代码行数:101,代码来源:sessionlib_test.php

示例14: notify_users_distribution

 /**
  * Gets called by the adhoc_taskmanager and its task in send_distribution_notification
  * 
  * @param user $userfrom
  */
 public function notify_users_distribution($userfrom)
 {
     global $CFG;
     $userfrom = get_complete_user_data('id', $userfrom);
     // make sure we have not sent them yet
     if ($this->origdbrecord->{this_db\ratingallocate::NOTIFICATIONSEND} != -1) {
         mtrace('seems we have sent them already');
         return true;
     }
     $choices = $this->get_choices_with_allocationcount();
     $allocations = $this->get_allocations();
     foreach ($allocations as $userid => $allocobj) {
         // get the assigned choice_id
         $alloc_choic_id = $allocobj->choiceid;
         // Prepare the email to be sent to the user
         $userto = get_complete_user_data('id', $allocobj->userid);
         cron_setup_user($userto);
         // prepare Text
         $notiftext = $this->make_mail_text($choices[$alloc_choic_id]);
         $notifhtml = $this->make_mail_html($choices[$alloc_choic_id]);
         $notifsubject = format_string($this->course->shortname, true) . ': ' . get_string('allocation_notification_message_subject', 'ratingallocate', $this->ratingallocate->name);
         // Send the post now!
         if (empty($userto->mailformat) || $userto->mailformat != 1) {
             // This user DOESN'T want to receive HTML
             $notifhtml = '';
         }
         $attachment = $attachname = '';
         $mailresult = email_to_user($userto, $userfrom, $notifsubject, $notiftext, $notifhtml, $attachment, $attachname);
         if (!$mailresult) {
             mtrace("ERROR: mod/ratingallocate/locallib.php: Could not send out digest mail to user {$userto->id} " . "({$userto->email})... not trying again.");
         } else {
             mtrace("success.");
         }
     }
     // update the 'notified' flag
     $this->origdbrecord->{this_db\ratingallocate::NOTIFICATIONSEND} = 1;
     $this->ratingallocate = new ratingallocate_db_wrapper($this->origdbrecord);
     $this->db->update_record(this_db\ratingallocate::TABLE, $this->origdbrecord);
 }
开发者ID:Kathrin84,项目名称:moodle-mod_ratingallocate,代码行数:44,代码来源:locallib.php

示例15: test_cron

 public function test_cron()
 {
     // First run cron so there are no messages waiting to be sent (from other tests).
     cron_setup_user();
     assign::cron();
     // Now create an assignment and add some feedback.
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance(array('sendstudentnotifications' => 1));
     // Simulate adding a grade.
     $this->setUser($this->teachers[0]);
     $data = new stdClass();
     $data->grade = '50.0';
     $assign->testable_apply_grade_to_user($data, $this->students[0]->id, 0);
     $assign->testable_apply_grade_to_user($data, $this->students[1]->id, 0);
     $data->sendstudentnotifications = false;
     $assign->testable_apply_grade_to_user($data, $this->students[2]->id, 0);
     // Now run cron and see that one message was sent.
     $this->preventResetByRollback();
     $sink = $this->redirectMessages();
     cron_setup_user();
     $this->expectOutputRegex('/Done processing 2 assignment submissions/');
     assign::cron();
     $messages = $sink->get_messages();
     // The sent count should be 2, because the 3rd one was marked as do not send notifications.
     $this->assertEquals(2, count($messages));
     $this->assertEquals(1, $messages[0]->notification);
     $this->assertEquals($assign->get_instance()->name, $messages[0]->contexturlname);
 }
开发者ID:janaece,项目名称:globalclassroom4_clean,代码行数:28,代码来源:locallib_test.php


注:本文中的cron_setup_user函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。