/**
  *    发送邮件
  *
  *    @author    Garbin
  *    @param     int $limit
  *    @return    void
  */
 function send($limit = 5)
 {
     /* 清除不能发送的邮件 */
     $this->clear();
     /* 获取待发送的邮件,按发送时间,优先及除序,错误次数升序 */
     $gmtime = gmtime();
     /* 取出所有未锁定的 */
     $mails = $this->find(array('conditions' => "lock_expiry < {$gmtime}", 'order' => 'add_time DESC, priority DESC, err_num ASC', 'limit' => "0, {$limit}"));
     if (!$mails) {
         /* 没有邮件,不需要发送 */
         return 0;
     }
     /* 锁定待发送邮件 */
     $queue_ids = array_keys($mails);
     $lock_expiry = $gmtime + 30;
     //锁定30秒
     $this->edit($queue_ids, "err_num = err_num + 1, lock_expiry = {$lock_expiry}");
     /* 获取邮件发送接口 */
     $mailer =& get_mailer();
     $mail_count = count($queue_ids);
     $error_count = 0;
     $error = '';
     /* 逐条发送 */
     for ($i = 0; $i < $mail_count; $i++) {
         $mail = $mails[$queue_ids[$i]];
         $result = $mailer->send($mail['mail_to'], $mail['mail_subject'], $mail['mail_body'], $mail['mail_encoding'], 1);
         if ($result) {
             /* 发送成功,从队列中删除 */
             $this->drop($queue_ids[$i]);
         } else {
             $error_count++;
         }
     }
     return array('mail_count' => $mail_count, 'error_count' => $error_count, 'error' => $mailer->errors);
 }
 public function notify($changelist, $user, $course)
 {
     $message_size = 160;
     // 160 chars
     $course_shortname_limit = 10;
     $subject_overhead = ' () ';
     // space()space -> overhead of 4 chars in the subject
     $from = '*****@*****.**';
     $to = "{$user->phone2}@smsprovider.tec";
     // replace all occurences of ++ with 00
     $to = str_replace('++', '00', $to);
     // replace all occurences of + with 00
     $to = str_replace('+', '00', $to);
     $subject = substr($course->shortname, 0, $course_shortname_limit);
     $smsmessage = $this->message($changelist, $course);
     // if the sms message is longer than 160 chars then cut and put ... at the end of the message
     $message_length = strlen($from . $subject_overhead . $subject . $smsmessage);
     //echo $message_length."\n";
     if ($message_length > $message_size) {
         $proper_size = $message_size - strlen($from . $subject_overhead . $subject) - 3;
         $smsmessage = substr($smsmessage, 0, $proper_size) . '...';
     }
     /*
     echo "\n\n";
     echo "$from\n\n";
     echo "$to\n\n";
     echo "$subject\n\n";
     echo "$smsmessage\n\n";
     echo "\n\n";
     return;
     */
     $mail = get_mailer();
     $mail->Sender = $from;
     $mail->From = $from;
     $mail->AddReplyTo($from);
     $mail->Subject = $subject;
     $mail->AddAddress($to);
     //to $phone.self::$emailsuffix
     $mail->Body = $smsmessage;
     $mail->IsHTML(false);
     if ($mail->Send()) {
         $mail->IsSMTP();
         // use SMTP directly
         if (!empty($mail->SMTPDebug)) {
             echo '</pre>';
             echo 'mail sent';
         }
     } else {
         if (!empty($mail->SMTPDebug)) {
             echo '</pre>';
         }
         //Send Error
         return $mail->ErrorInfo;
     }
 }
Esempio n. 3
0
/**
 * 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);
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: context_helper::build_all_paths(true);
        mtrace(' Built context paths');
        // Remove expired cache flags
        gc_cache_flags();
        mtrace(' Cleaned cache flags');
        // Cleanup messaging
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace(' Cleaned up read notifications');
        }
        mtrace(' Deleting temporary files...');
        cron_delete_from_temp();
        // Cleanup user password reset records
        // Delete any reset request records which are expired by more than a day.
        // (We keep recently expired requests around so we can give a different error msg to users who
        // are trying to user a recently expired reset attempt).
        $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
        $earliestvalid = time() - $pwresettime - DAYSECS;
        $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
        mtrace(' Cleaned up old password reset records');
        mtrace("...finished clean-up tasks");
    }
    // End of occasional clean-up tasks
    // Send login failures notification - brute force protection in moodle is weak,
    // we should at least send notices early in each cron execution
    if (notify_login_failures()) {
        mtrace(' Notified login failures');
    }
    // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
    context_helper::create_instances();
    mtrace(' Created missing context instances');
    // Session gc.
    mtrace("Running session gc tasks...");
    \core\session\manager::gc();
    mtrace("...finished stale session cleanup");
    // Run the auth cron, if any before enrolments
    // because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    cron_trace_time_and_memory();
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    // Generate new password emails for users - ppl expect these generated asap
    if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
        mtrace('Creating passwords for new users...');
        $usernamefields = get_all_user_name_fields(true, 'u');
        $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n                                                 {$usernamefields}, u.username, u.lang,\n                                                 p.id as prefid\n                                            FROM {user} u\n                                            JOIN {user_preferences} p ON u.id=p.userid\n                                           WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
        // note: we can not send emails to suspended accounts
        foreach ($newusers as $newuser) {
            // Use a low cost factor when generating bcrypt hash otherwise
            // hashing would be slow when emailing lots of users. Hashes
            // will be automatically updated to a higher cost factor the first
            // time the user logs in.
            if (setnew_password_and_mail($newuser, true)) {
                unset_user_preference('create_password', $newuser);
                set_user_preference('auth_forcepasswordchange', 1, $newuser);
            } else {
                trigger_error("Could not create and mail new user password!");
            }
        }
        $newusers->close();
    }
    // It is very important to run enrol early
    // because other plugins depend on correct enrolment info.
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        cron_trace_time_and_memory();
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    // 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} ...", '');
                    cron_trace_time_and_memory();
                    $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 . '....', '');
                    cron_trace_time_and_memory();
                    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');
    mtrace('Starting admin reports');
    cron_execute_plugin_type('report');
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job...');
    cron_trace_time_and_memory();
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    cron_trace_time_and_memory();
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        cron_trace_time_and_memory();
        require_once $CFG->dirroot . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        cron_trace_time_and_memory();
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace('Starting course reports');
    cron_execute_plugin_type('coursereport');
    mtrace('Finished course reports');
    // run gradebook import/export/report cron
    mtrace('Starting gradebook plugins');
    cron_execute_plugin_type('gradeimport');
    cron_execute_plugin_type('gradeexport');
    cron_execute_plugin_type('gradereport');
    mtrace('Finished gradebook plugins');
    // run calendar cron
    require_once "{$CFG->dirroot}/calendar/lib.php";
    calendar_cron();
    // Run external blog cron if needed
    if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        cron_trace_time_and_memory();
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
        mtrace('done.');
    }
    // Run blog associations cleanup
    if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        cron_trace_time_and_memory();
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
        mtrace('done.');
    }
    // Run question bank clean-up.
    mtrace("Starting the question bank cron...", '');
    cron_trace_time_and_memory();
    require_once $CFG->libdir . '/questionlib.php';
    question_bank::cron();
    mtrace('done.');
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    cron_trace_time_and_memory();
    require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // If enabled, fetch information about available updates and eventually notify site admins
    if (empty($CFG->disableupdatenotifications)) {
        $updateschecker = \core\update\checker::instance();
        $updateschecker->cron();
    }
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    cron_trace_time_and_memory();
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // all other plugins
    cron_execute_plugin_type('message', 'message plugins');
    cron_execute_plugin_type('filter', 'filters');
    cron_execute_plugin_type('editor', 'editors');
    cron_execute_plugin_type('format', 'course formats');
    cron_execute_plugin_type('profilefield', 'profile fields');
    cron_execute_plugin_type('webservice', 'webservices');
    cron_execute_plugin_type('repository', 'repository plugins');
    cron_execute_plugin_type('qbehaviour', 'question behaviours');
    cron_execute_plugin_type('qformat', 'question import/export formats');
    cron_execute_plugin_type('qtype', 'question types');
    cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
    cron_execute_plugin_type('theme', 'themes');
    cron_execute_plugin_type('tool', 'admin tools');
    // and finally run any local cronjobs, if any
    if ($locals = core_component::get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        // new cron functions in lib.php first
        cron_execute_plugin_type('local');
        // legacy cron files are executed directly
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace('Running cache cron routines');
    cache_helper::cron();
    mtrace('done.');
    // Run automated backups if required - these may take a long time to execute
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    // 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 (time() > $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();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // Run badges review cron.
    mtrace("Starting badges cron...");
    require_once $CFG->dirroot . '/badges/cron.php';
    badge_cron();
    mtrace('done.');
    // cleanup file trash - not very important
    $fs = get_file_storage();
    $fs->cron();
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
Esempio n. 4
0
/**
 * Send an email to a specified user
 *
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $PAGE, $SITE;
    if (empty($user) or empty($user->id)) {
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
        return false;
    }
    if (empty($user->email)) {
        debugging('Can not send email to user without email: ' . $user->id, DEBUG_DEVELOPER);
        return false;
    }
    if (!empty($user->deleted)) {
        debugging('Can not send email to deleted user: '******'BEHAT_SITE_RUNNING')) {
        // Fake email sending in behat.
        return true;
    }
    if (!empty($CFG->noemailever)) {
        // Hidden setting for development sites, set in config.php if needed.
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
        return true;
    }
    if (email_should_be_diverted($user->email)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // Skip mail to suspended users.
    if (isset($user->auth) && $user->auth == 'nologin' or isset($user->suspended) && $user->suspended) {
        return true;
    }
    if (!validate_email($user->email)) {
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email ({$user->email}) is invalid! Not sending.");
        return false;
    }
    if (over_bounce_threshold($user)) {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // TLD .invalid  is specifically reserved for invalid domain names.
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
    if (substr($user->email, -8) == '.invalid') {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email domain ({$user->email}) is invalid! Not sending.");
        return true;
        // This is not an error.
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself.
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    // Make sure that we fall back onto some reasonable no-reply address.
    $noreplyaddress = empty($CFG->noreplyaddress) ? 'noreply@' . get_host_from_url($CFG->wwwroot) : $CFG->noreplyaddress;
    // Make up an email address for handling bounces.
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $noreplyaddress;
    }
    $alloweddomains = null;
    if (!empty($CFG->allowedemaildomains)) {
        $alloweddomains = explode(PHP_EOL, $CFG->allowedemaildomains);
    }
    // Email will be sent using no reply address.
    if (empty($alloweddomains)) {
        $usetrueaddress = false;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need.
        $mail->From = $noreplyaddress;
        $mail->FromName = $from;
        // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
        // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
        // in a course with the sender.
    } else {
        if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
            $mail->From = $from->email;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($from->email, fullname($from));
            }
        } else {
            $mail->From = $noreplyaddress;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $temprecipients[] = array($user->email, fullname($user));
    // Set word wrap.
    $mail->WordWrap = $wordwrapwidth;
    if (!empty($from->customheaders)) {
        // Add custom headers.
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->addCustomHeader($customheader);
            }
        } else {
            $mail->addCustomHeader($from->customheaders);
        }
    }
    // If the X-PHP-Originating-Script email header is on then also add an additional
    // header with details of where exactly in moodle the email was triggered from,
    // either a call to message_send() or to email_to_user().
    if (ini_get('mail.add_x_header')) {
        $stack = debug_backtrace(false);
        $origin = $stack[0];
        foreach ($stack as $depth => $call) {
            if ($call['function'] == 'message_send') {
                $origin = $call;
            }
        }
        $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
        $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    $renderer = $PAGE->get_renderer('core');
    $context = array('sitefullname' => $SITE->fullname, 'siteshortname' => $SITE->shortname, 'sitewwwroot' => $CFG->wwwroot, 'subject' => $subject, 'to' => $user->email, 'toname' => fullname($user), 'from' => $mail->From, 'fromname' => $mail->FromName);
    if (!empty($tempreplyto[0])) {
        $context['replyto'] = $tempreplyto[0][0];
        $context['replytoname'] = $tempreplyto[0][1];
    }
    if ($user->id > 0) {
        $context['touserid'] = $user->id;
        $context['tousername'] = $user->username;
    }
    if (!empty($user->mailformat) && $user->mailformat == 1) {
        // Only process html templates if the user preferences allow html email.
        if ($messagehtml) {
            // If html has been given then pass it through the template.
            $context['body'] = $messagehtml;
            $messagehtml = $renderer->render_from_template('core/email_html', $context);
        } else {
            // If no html has been given, BUT there is an html wrapping template then
            // auto convert the text to html and then wrap it.
            $autohtml = trim(text_to_html($messagetext));
            $context['body'] = $autohtml;
            $temphtml = $renderer->render_from_template('core/email_html', $context);
            if ($autohtml != $temphtml) {
                $messagehtml = $temphtml;
            }
        }
    }
    $context['body'] = $messagetext;
    $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
    $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
    $messagetext = $renderer->render_from_template('core/email_text', $context);
    // Autogenerate a MessageID if it's missing.
    if (empty($mail->MessageID)) {
        $mail->MessageID = generate_email_messageid();
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it.
        $mail->isHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path.
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $attachmentpath = $attachment;
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
            $attachpath = str_replace('\\', '/', $attachmentpath);
            // Make sure both variables are normalised before comparing.
            $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
            // If the attachment is a full path to a file in the tempdir, use it as is,
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
            if (strpos($attachpath, $temppath) !== 0) {
                $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
            }
            $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8.
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // Use the defined site mail charset or eventually the one preferred by the recipient.
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // Convert all the necessary strings if the charset is supported.
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $mail->CharSet = $charset;
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->addAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->addReplyTo($values[0], $values[1]);
    }
    if ($mail->send()) {
        set_send_count($user);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        // Trigger event for failing to send email.
        $event = \core\event\email_failed::create(array('context' => context_system::instance(), 'userid' => $from->id, 'relateduserid' => $user->id, 'other' => array('subject' => $subject, 'message' => $messagetext, 'errorinfo' => $mail->ErrorInfo)));
        $event->trigger();
        if (CLI_SCRIPT) {
            mtrace('Error: lib/moodlelib.php email_to_user(): ' . $mail->ErrorInfo);
        }
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Esempio n. 5
0
/**
 * Send an email to a specified user
 *
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG;
    if (empty($user) or empty($user->id)) {
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
        return false;
    }
    if (empty($user->email)) {
        debugging('Can not send email to user without email: ' . $user->id, DEBUG_DEVELOPER);
        return false;
    }
    if (!empty($user->deleted)) {
        debugging('Can not send email to deleted user: '******'BEHAT_SITE_RUNNING')) {
        // Fake email sending in behat.
        return true;
    }
    if (!empty($CFG->noemailever)) {
        // Hidden setting for development sites, set in config.php if needed.
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
        return true;
    }
    if (!empty($CFG->divertallemailsto)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // Skip mail to suspended users.
    if (isset($user->auth) && $user->auth == 'nologin' or isset($user->suspended) && $user->suspended) {
        return true;
    }
    if (!validate_email($user->email)) {
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email ({$user->email}) is invalid! Not sending.");
        return false;
    }
    if (over_bounce_threshold($user)) {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // TLD .invalid  is specifically reserved for invalid domain names.
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
    if (substr($user->email, -8) == '.invalid') {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email domain ({$user->email}) is invalid! Not sending.");
        return true;
        // This is not an error.
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself.
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    $supportuser = core_user::get_support_user();
    // Make up an email address for handling bounces.
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (!empty($CFG->emailonlyfromnoreplyaddress)) {
        $usetrueaddress = false;
        if (empty($replyto) && $from->maildisplay) {
            $replyto = $from->email;
            $replytoname = fullname($from);
        }
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need.
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = $from->email;
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $mail->Subject = substr($subject, 0, 900);
    $temprecipients[] = array($user->email, fullname($user));
    // Set word wrap.
    $mail->WordWrap = $wordwrapwidth;
    if (!empty($from->customheaders)) {
        // Add custom headers.
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->addCustomHeader($customheader);
            }
        } else {
            $mail->addCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it.
        $mail->isHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path.
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $attachmentpath = $attachment;
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
            $attachpath = str_replace('\\', '/', $attachmentpath);
            // Make sure both variables are normalised before comparing.
            $temppath = str_replace('\\', '/', $CFG->tempdir);
            // If the attachment is a full path to a file in the tempdir, use it as is,
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
            if (strpos($attachpath, realpath($temppath)) !== 0) {
                $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
            }
            $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8.
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // Use the defined site mail charset or eventually the one preferred by the recipient.
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // Convert all the necessary strings if the charset is supported.
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $mail->CharSet = $charset;
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->addAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->addReplyTo($values[0], $values[1]);
    }
    if ($mail->send()) {
        set_send_count($user);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        // Trigger event for failing to send email.
        $event = \core\event\email_failed::create(array('context' => context_system::instance(), 'userid' => $from->id, 'relateduserid' => $user->id, 'other' => array('subject' => $subject, 'message' => $messagetext, 'errorinfo' => $mail->ErrorInfo)));
        $event->trigger();
        if (CLI_SCRIPT) {
            mtrace('Error: lib/moodlelib.php email_to_user(): ' . $mail->ErrorInfo);
        }
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Esempio n. 6
0
/**
 * Send an email to a specified user
 *
 * @uses $CFG
 * @uses $FULLME
 * @uses $MNETIDPJUMPURL IdentityProvider(IDP) URL user hits to jump to mnet peer.
 * @uses SITEID
 * @param user $user  A {@link $USER} object
 * @param user $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param int $wordwrapwidth custom word wrap width
 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
 *          was blocked by user and "false" if there was another sort of error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $FULLME, $MNETIDPJUMPURL;
    static $mnetjumps = array();
    if (empty($user) || empty($user->email)) {
        return false;
    }
    if (!empty($user->deleted)) {
        // do not mail delted users
        return false;
    }
    if (!empty($CFG->noemailever)) {
        // hidden setting for development sites, set in config.php if needed
        return true;
    }
    // skip mail to suspended users
    if (isset($user->auth) && $user->auth == 'nologin') {
        return true;
    }
    if (!empty($user->emailstop)) {
        return 'emailstop';
    }
    if (over_bounce_threshold($user)) {
        error_log("User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$user->mnethostid])) {
            $MNETIDPJUMPURL = $mnetjumps[$user->mnethostid];
        } else {
            $idp = mnet_get_peer_host($user->mnethostid);
            $idpjumppath = '/auth/mnet/jump.php';
            $MNETIDPJUMPURL = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
            $mnetjumps[$user->mnethostid] = $MNETIDPJUMPURL;
        }
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", 'mnet_sso_apply_indirection', $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", 'mnet_sso_apply_indirection', $messagehtml);
    }
    $mail =& get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    /// We are going to use textlib services here
    $textlib = textlib_get_instance();
    $supportuser = generate_email_supportuser();
    // make up an email address for handling bounces
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = stripslashes($from->email);
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $mail->AddReplyTo($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $mail->AddReplyTo($replyto, $replytoname);
    }
    $mail->Subject = substr(stripslashes($subject), 0, 900);
    $mail->AddAddress(stripslashes($user->email), fullname($user));
    $mail->WordWrap = $wordwrapwidth;
    // set word wrap
    if (!empty($from->customheaders)) {
        // Add custom headers
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->AddCustomHeader($customheader);
            }
        } else {
            $mail->AddCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        // Encoding to use
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (ereg("\\.\\.", $attachment)) {
            // Security check for ".." in dir path
            $mail->AddAddress($supportuser->email, fullname($supportuser, true));
            $mail->AddStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $mail->AddAttachment($CFG->dataroot . '/' . $attachment, $attachname, 'base64', $mimetype);
        }
    }
    /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
    /// encoding to the specified one
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        /// Set it to site mail charset
        $charset = $CFG->sitemailcharset;
        /// Overwrite it with the user mail charset
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        /// If it has changed, convert all the necessary strings
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            /// Save the new mail charset
            $mail->CharSet = $charset;
            /// And convert some strings
            $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet);
            //From Name
            foreach ($mail->ReplyTo as $key => $rt) {
                //ReplyTo Names
                $mail->ReplyTo[$key][1] = $textlib->convert($rt[1], 'utf-8', $mail->CharSet);
            }
            $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet);
            //Subject
            foreach ($mail->to as $key => $to) {
                $mail->to[$key][1] = $textlib->convert($to[1], 'utf-8', $mail->CharSet);
                //To Names
            }
            $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet);
            //Body
            $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet);
            //Subject
        }
    }
    if ($mail->Send()) {
        set_send_count($user);
        $mail->IsSMTP();
        // use SMTP directly
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        mtrace('ERROR: ' . $mail->ErrorInfo);
        add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: ' . $mail->ErrorInfo);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Esempio n. 7
0
/**
 * Send an email to a specified user
 *
 * @global object
 * @global string
 * @global string IdentityProvider(IDP) URL user hits to jump to mnet peer.
 * @uses SITEID
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $FULLME;
    if (empty($user) || empty($user->email)) {
        mtrace('Error: lib/moodlelib.php email_to_user(): User is null or has no email');
        return false;
    }
    if (!empty($user->deleted)) {
        // do not mail delted users
        mtrace('Error: lib/moodlelib.php email_to_user(): User is deleted');
        return false;
    }
    if (!empty($CFG->noemailever)) {
        // hidden setting for development sites, set in config.php if needed
        mtrace('Error: lib/moodlelib.php email_to_user(): Not sending email due to noemailever config setting');
        return true;
    }
    if (!empty($CFG->divertallemailsto)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // skip mail to suspended users
    if (isset($user->auth) && $user->auth == 'nologin') {
        return true;
    }
    if (over_bounce_threshold($user)) {
        $bouncemsg = "User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.";
        error_log($bouncemsg);
        mtrace('Error: lib/moodlelib.php email_to_user(): ' . $bouncemsg);
        return false;
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    $supportuser = generate_email_supportuser();
    // make up an email address for handling bounces
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = $from->email;
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $mail->Subject = substr($subject, 0, 900);
    $temprecipients[] = array($user->email, fullname($user));
    $mail->WordWrap = $wordwrapwidth;
    // set word wrap
    if (!empty($from->customheaders)) {
        // Add custom headers
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->AddCustomHeader($customheader);
            }
        } else {
            $mail->AddCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        // Encoding to use
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->AddStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $mail->AddAttachment($CFG->dataroot . '/' . $attachment, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // use the defined site mail charset or eventually the one preferred by the recipient
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // convert all the necessary strings if the charset is supported
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $textlib = textlib_get_instance();
            $mail->CharSet = $charset;
            $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = $textlib->convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->AddAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->AddReplyTo($values[0], $values[1]);
    }
    if ($mail->Send()) {
        set_send_count($user);
        $mail->IsSMTP();
        // use SMTP directly
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        mtrace('ERROR: ' . $mail->ErrorInfo);
        add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: ' . $mail->ErrorInfo);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Esempio n. 8
0
/**
 * 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";
            if (file_exists($cronfile)) {
                include_once $cronfile;
                $cron_function = 'quiz_report_' . $report->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing quiz report cron function {$cron_function} ...", '');
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field('quiz_report', "lastcron", $timenow, array("id" => $report->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    mtrace("done.");
                }
            }
        }
    }
    mtrace("Finished quiz reports");
    mtrace('Starting admin reports');
    // Admin reports do not have a database table that lists them. Instead a
    // report includes cron.php with function report_reportname_cron() if it wishes
    // to be cronned. It is up to cron.php to handle e.g. if it only needs to
    // actually do anything occasionally.
    $reports = get_plugin_list('report');
    foreach ($reports as $report => $reportdir) {
        $cronfile = $reportdir . '/cron.php';
        if (file_exists($cronfile)) {
            require_once $cronfile;
            $cronfunction = 'report_' . $report . '_cron';
            mtrace('Processing cron function for ' . $report . '...', '');
            $pre_dbqueries = null;
            $pre_dbqueries = $DB->perf_get_queries();
            $pre_time = microtime(true);
            $cronfunction();
            if (isset($pre_dbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                mtrace("... used " . round(microtime(true) - $pre_time, 2) . " seconds");
            }
            mtrace('done.');
        }
    }
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job ...');
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        require_once $CFG->libdir . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    /// Run all 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.
    srand((double) microtime() * 10000000);
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        /// Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT id, firstname, lastname\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                if ($DB->delete_records('user', array('id' => $user->id))) {
                    mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
                }
            }
            $rs->close();
        }
        flush();
        /// 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 id, username\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 (delete_user($user)) {
                    mtrace("Deleted not fully setup user {$user->username} ({$user->id})");
                }
            }
            $rs->close();
        }
        flush();
        /// 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;
            if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) {
                mtrace("Deleted old log records");
            }
        }
        flush();
        // Delete old backup_controllers and logs
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->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");
        }
        flush();
        /// 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
            if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) {
                mtrace("Deleted old cache_text records");
            }
        }
        flush();
        if (!empty($CFG->notifyloginfailures)) {
            notify_login_failures();
            mtrace('Notified login failured');
        }
        flush();
        //
        // generate new password emails for users
        //
        mtrace('checking for create_password');
        if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
            mtrace('creating passwords for new users');
            $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,\n                                                     u.lastname, u.username,\n                                                     p.id as prefid\n                                                FROM {user} u\n                                                JOIN {user_preferences} p ON u.id=p.userid\n                                               WHERE p.name='create_password' AND p.value='1' AND u.email !='' ");
            foreach ($newusers as $newuserid => $newuser) {
                // email user
                if (setnew_password_and_mail($newuser)) {
                    // remove user pref
                    $DB->delete_records('user_preferences', array('id' => $newuser->prefid));
                } else {
                    trigger_error("Could not create and mail new user password!");
                }
            }
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace('Executed tag cron');
        }
        // Accesslib stuff
        cleanup_contexts();
        mtrace('Cleaned up contexts');
        gc_cache_flags();
        mtrace('Cleaned cache flags');
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: build_context_path(true);
        build_context_path();
        mtrace('Built context paths');
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace('Cleaned up read notifications');
        }
        mtrace("Finished clean-up tasks...");
    }
    // End of occasional clean-up tasks
    // Run automated backups if required.
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    /// Run the auth cron, if any
    /// before enrolments because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    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 (time() > $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();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // run gradebook import/export/report cron
    if ($gradeimports = get_plugin_list('gradeimport')) {
        foreach ($gradeimports as $gradeimport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_import_' . $gradeimport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook import function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    if ($gradeexports = get_plugin_list('gradeexport')) {
        foreach ($gradeexports as $gradeexport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_export_' . $gradeexport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook export function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    if ($gradereports = get_plugin_list('gradereport')) {
        foreach ($gradereports as $gradereport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_report_' . $gradereport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook report function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    // Run external blog cron if needed
    if ($CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
    }
    // Run blog associations cleanup
    if ($CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
    }
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    require_once $CFG->dirroot . '/admin/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // cleanup file trash
    $fs = get_file_storage();
    $fs->cron();
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // run any customized cronjobs, if any
    if ($locals = get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace("Cron script completed correctly");
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
Esempio n. 9
0
                    if (!set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
                        mtrace("Error: could not update timestamp for {$mod->fullname}");
                    }
                }
                if (isset($pre_dbqueries)) {
                    mtrace("... used " . ($PERF->dbqueries - $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 = get_records_select("block", "cron > 0 AND (({$timenow} - lastcron) > cron) AND visible = 1")) {
    // 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()) {
                    if (!set_field('block', 'lastcron', $timenow, 'id', $block->id)) {
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG, $DB;
     $timenow = time();
     // Run the auth cron, if any before enrolments
     // because it might add users that will be needed in enrol plugins.
     $auths = get_enabled_auth_plugins();
     mtrace("Running auth crons if required...");
     foreach ($auths as $auth) {
         $authplugin = get_auth_plugin($auth);
         if (method_exists($authplugin, 'cron')) {
             mtrace("Running cron for auth/{$auth}...");
             $authplugin->cron();
             if (!empty($authplugin->log)) {
                 mtrace($authplugin->log);
             }
         }
         unset($authplugin);
     }
     // It is very important to run enrol early
     // because other plugins depend on correct enrolment info.
     mtrace("Running enrol crons if required...");
     $enrols = enrol_get_plugins(true);
     foreach ($enrols as $ename => $enrol) {
         // Do this for all plugins, disabled plugins might want to cleanup stuff such as roles.
         if (!$enrol->is_cron_required()) {
             continue;
         }
         mtrace("Running cron for enrol_{$ename}...");
         $enrol->cron();
         $enrol->set_config('lastcron', time());
     }
     // 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;
                 $cronfunction = $mod->name . "_cron";
                 if (function_exists($cronfunction)) {
                     mtrace("Processing module function {$cronfunction} ...\n", '');
                     $predbqueries = null;
                     $predbqueries = $DB->perf_get_queries();
                     $pretime = microtime(1);
                     if ($cronfunction()) {
                         $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                     }
                     if (isset($predbqueries)) {
                         mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                         mtrace("... used " . (microtime(1) - $pretime) . " seconds");
                     }
                     // Reset possible changes by modules to time_limit. MDL-11597.
                     \core_php_time_limit::raise();
                     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.
                     \core_php_time_limit::raise();
                     mtrace('done.');
                 }
             }
         }
     }
     mtrace('Finished blocks');
     mtrace('Starting admin reports');
     cron_execute_plugin_type('report');
     mtrace('Finished admin reports');
     mtrace('Starting course reports');
     cron_execute_plugin_type('coursereport');
     mtrace('Finished course reports');
     // Run gradebook import/export/report cron.
     mtrace('Starting gradebook plugins');
     cron_execute_plugin_type('gradeimport');
     cron_execute_plugin_type('gradeexport');
     cron_execute_plugin_type('gradereport');
     mtrace('Finished gradebook plugins');
     // All other plugins.
     cron_execute_plugin_type('message', 'message plugins');
     cron_execute_plugin_type('filter', 'filters');
     cron_execute_plugin_type('editor', 'editors');
     cron_execute_plugin_type('format', 'course formats');
     cron_execute_plugin_type('profilefield', 'profile fields');
     cron_execute_plugin_type('webservice', 'webservices');
     cron_execute_plugin_type('repository', 'repository plugins');
     cron_execute_plugin_type('qbehaviour', 'question behaviours');
     cron_execute_plugin_type('qformat', 'question import/export formats');
     cron_execute_plugin_type('qtype', 'question types');
     cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
     cron_execute_plugin_type('theme', 'themes');
     cron_execute_plugin_type('tool', 'admin tools');
     cron_execute_plugin_type('local', 'local plugins');
 }
Esempio n. 11
0
 /**
  * Function to send out registration emails.
  *
  */
 function send_confirmation_email($fromadmin, $toadmins)
 {
     global $CFG;
     $a = new Object();
     $a->fullname = fullname($this);
     $a->username = $this->username;
     $a->password = $this->password;
     $messagehtml = get_string('welcomeemail', 'block_curr_admin', $a);
     $messagetext = html_to_text($messagehtml);
     $subject = get_string('emailwelcomesubject', 'block_curr_admin');
     $this->mailformat = 1;
     // Always send HTML version as well
     email_to_user($this, $fromadmin, $subject, $messagetext, $messagehtml);
     $messagetext = "New registration:\n\n";
     $countries = cm_get_list_of_countries();
     $objectvars = array('username', 'password', 'firstname', 'lastname', 'email', 'email2', 'address', 'address2', 'city', 'state', 'country', 'postalcode', 'birthdate', 'gender', 'language', 'comments');
     foreach ($objectvars as $varname) {
         if ($varname == 'country') {
             if (isset($countries[$this->{$varname}])) {
                 $messagetext .= "{$varname}: {$countries[$this->{$varname}]}\n";
             } else {
                 $messagetext .= "{$varname}: {$this->{$varname}}\n";
             }
         } else {
             $messagetext .= "{$varname}: {$this->{$varname}}\n";
         }
     }
     $toaddresses = explode(',', $toadmins);
     $mail =& get_mailer();
     $mail->Sender = $fromadmin;
     $mail->From = $fromadmin;
     foreach ($toaddresses as $address) {
         $mail->AddAddress($address);
     }
     $mail->Subject = get_string('new_registration', 'block_curr_admin') . $mail->IsHTML(false);
     $mail->Body = "\n{$messagetext}\n";
     return $mail->Send();
 }
 /**
  * Sends an email to lots of people using BCC.
  * @param array $targets List of target user objects (email, name fields
  *   required)
  * @param mixed $from User or string who sent email
  * @param string $subject Subject of email
  * @param string $html HTML version of email (blank if none)
  * @param string $text Plain text version of email
  * @param string $showerrortext If set, mtraces errors and includes this
  *   extra string about where the error was.
  * @param bool $ishtml If true, email is in HTML format
  * @param bool $viewfullnames If true, these recipients have access to
  *   see the full name
  * @return int Number of emails sent
  */
 private static function email_send_bcc($targets, $from, $subject, $html, $text, $showerrortext, $ishtml, $viewfullnames)
 {
     if (self::DEBUG_VIEW_EMAILS) {
         print "<div style='border:1px solid blue; padding:4px;'>";
         print "<h3>Bulk email sent</h3>";
         print "<ul><li>To: ";
         $first = true;
         foreach ($targets as $target) {
             if ($first) {
                 $first = false;
             } else {
                 print ', ';
             }
             print "<strong>{$target->email}</strong>";
         }
         print "</li><li>Subject: <strong>" . htmlspecialchars($subject) . "</strong></li>";
         print $html;
         print "<pre style='border-top: 1px solid blue; padding-top: 4px;'>";
         print htmlspecialchars($text);
         print "</pre></div>";
         return;
     }
     global $CFG;
     $emailcount = 0;
     // Trim subject length (not sure why but
     // email_to_user does); note that I did it more
     // aggressively due to use of textlib.
     $mail->Subject = core_text::substr($subject, 0, 200);
     // Loop through in batches of specified size
     $copy = array();
     foreach ($targets as $key => $target) {
         $copy[$key] = $target;
     }
     while (count($copy) > 0) {
         $batch = array_splice($copy, 0, $CFG->forumng_usebcc);
         // Prepare email
         $mail = get_mailer();
         // From support user
         static $supportuser;
         if (!$supportuser) {
             $supportuser = generate_email_supportuser();
         }
         $mail->Sender = $supportuser->email;
         // Set the From details similar to email_to_user
         if ($CFG->forumng_replytouser && $from->maildisplay) {
             $mail->From = $from->email;
             $mail->FromName = fullname($from, $viewfullnames);
         } else {
             $mail->From = $CFG->noreplyaddress;
             $mail->FromName = fullname($from, $viewfullnames);
         }
         $mail->ToName = 'Test to name';
         $mail->Subject = $subject;
         if ($ishtml) {
             $mail->IsHTML(true);
             $mail->Encoding = 'quoted-printable';
             $mail->Body = $html;
             $mail->AltBody = "\n{$text}\n";
         } else {
             $mail->IsHTML(false);
             $mail->Body = "\n{$text}\n";
         }
         foreach ($batch as $user) {
             $mail->AddBCC($user->email);
         }
         $emailcount++;
         if (!$mail->Send()) {
             $users = '';
             foreach ($batch as $user) {
                 if ($users) {
                     $users .= ', ';
                 }
                 $users .= $user->id;
             }
             if ($showerrortext) {
                 mtrace('Error sending email "' . $subject . '": "' . $mail->ErrorInfo . '" (' . $showerrortext . '). Users affected: ' . $users);
             }
         } else {
             // Mail send successful; log all users
             foreach ($batch as $user) {
                 // Note this log entry is in the same format as the
                 // main mail function
                 $params = array('other' => array('username' => $user->username, 'subject' => $subject), 'context' => context_system::instance(), 'relateduserid' => $user->id);
                 $event = \mod_forumng\event\mail_sent::create($params);
                 $event->trigger();
             }
         }
     }
     return $emailcount;
 }
Esempio n. 13
0
/**
 * 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");
            }
            mtrace("Adhoc task failed: " . get_class($task) . "," . $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::adhoc_task_failed($task);
        }
        get_mailer('close');
        unset($task);
    }
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
Esempio n. 14
0
 /**
  * send registraion email
  * @param string $password
  * @return string
  */
 public function send_registration_email()
 {
     $mail = get_mailer('smtp');
     $mail->Subject = sprintf('%s %s', $mail->Subject, __('New Registration'));
     $mail->MsgHTML(render_to_response('mail/registration.html', array('registration_user' => $this), true));
     $mail->AddAddress($this->email, $this->displayname);
     $mail->Send();
 }
 function sendemail()
 {
     if (!IS_POST) {
         $this->show_warning('Hacking Attempt');
         return;
     } else {
         $code = trim($_POST['code']);
         $email = trim($_POST['email']);
         $username = trim($_POST['username']);
         $ms =& ms();
         $info = $ms->user->get($username, true);
         $mail = get_mail('touser_send_code', array('user' => $info, 'word' => $code));
         $mailer =& get_mailer();
         $mail_result = $mailer->send($email, addslashes($mail['subject']), addslashes($mail['message']), CHARSET, 1);
         if ($mail_result) {
             $_SESSION['email_code'] = md5($email . $code);
             $_SESSION['last_send_time_email_code'] = time();
             $this->json_result('', 'mail_send_succeed');
         } else {
             $this->json_error('mail_send_failure', implode("\n", $mailer->errors));
         }
     }
 }