コード例 #1
0
ファイル: upgrade.php プロジェクト: JP-Git/moodle
function portfolio_picasa_admin_upgrade_notification() {
    $admins = get_admins();

    if (empty($admins)) {
        return;
    }
    $mainadmin = reset($admins);
    $a = new stdClass;
    $a->docsurl = get_docs_url('Google_OAuth_2.0_setup');

    foreach ($admins as $admin) {
        $message = new stdClass();
        $message->component         = 'moodle';
        $message->name              = 'notices';
        $message->userfrom          = $mainadmin;
        $message->userto            = $admin;
        $message->smallmessage      = get_string('oauth2upgrade_message_small', 'portfolio_picasa');
        $message->subject           = get_string('oauth2upgrade_message_subject', 'portfolio_picasa');
        $message->fullmessage       = get_string('oauth2upgrade_message_content', 'portfolio_picasa', $a);
        $message->fullmessagehtml   = get_string('oauth2upgrade_message_content', 'portfolio_picasa', $a);
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->notification      = 1;
        message_send($message);
    }
}
コード例 #2
0
 public function execute()
 {
     global $USER;
     // Check to make sure external communications hasn't been disabled
     $extcom = !!get_config('mod_hvp', 'external_communication');
     $extcomnotify = !!get_config('mod_hvp', 'external_communication_notify');
     if ($extcom || !$extcomnotify) {
         $core = \mod_hvp\framework::instance();
         $core->fetchLibrariesMetadata(!$extcom);
         set_config('external_communication_notify', $extcom ? false : time(), 'mod_hvp');
         // Notify admin if there are updates available!
         $update_available = \get_config('mod_hvp', 'update_available');
         $current_update = \get_config('mod_hvp', 'current_update');
         $admin_notified = \get_config('mod_hvp', 'admin_notified');
         if ($admin_notified !== $update_available && $update_available !== false && $current_update !== false && $current_update < $update_available) {
             // New update is available
             // Send message
             $updatesurl = new \moodle_url('/mod/hvp/library_list.php');
             $message = new \stdClass();
             $message->component = 'mod_hvp';
             $message->name = 'updates';
             $message->userfrom = $USER;
             $message->userto = get_admin();
             $message->subject = get_string('updatesavailabletitle', 'mod_hvp');
             $message->fullmessage = get_string('updatesavailablemsgpt1', 'mod_hvp') . ' ' . get_string('updatesavailablemsgpt2', 'mod_hvp') . "\n\n" . get_string('updatesavailablemsgpt3', 'mod_hvp', date('Y-m-d', $update_available)) . "\n" . get_string('updatesavailablemsgpt4', 'mod_hvp', date('Y-m-d', $current_update)) . "\n\n" . $updatesurl;
             $message->fullmessageformat = FORMAT_PLAIN;
             $message->fullmessagehtml = '<p>' . get_string('updatesavailablemsgpt1', 'mod_hvp') . '<br/>' . get_string('updatesavailablemsgpt2', 'mod_hvp') . '</p>' . '<p>' . get_string('updatesavailablemsgpt3', 'mod_hvp', '<b>' . date('Y-m-d', $update_available) . '</b>') . '<br/>' . get_string('updatesavailablemsgpt4', 'mod_hvp', '<b>' . date('Y-m-d', $current_update) . '</b>') . '</p>' . '<a href="' . $updatesurl . '" target="_blank">' . $updatesurl . '</a>';
             $message->smallmessage = '';
             $message->notification = 1;
             message_send($message);
             // Keep track of which version we've notfied about
             \set_config('admin_notified', $update_available, 'mod_hvp');
         }
     }
 }
コード例 #3
0
 /**
  * Send out messages.
  */
 public function execute()
 {
     foreach ($this->get_custom_data() as $data) {
         $eventobj = $data->event;
         $subscriptionids = $data->subscriptionids;
         foreach ($subscriptionids as $id) {
             if ($message = $this->generate_message($id, $eventobj)) {
                 message_send($message);
             }
         }
     }
 }
コード例 #4
0
 /**
  * Send out messages.
  */
 public function execute()
 {
     foreach ($this->get_custom_data() as $data) {
         $eventobj = $data->event;
         $subscriptionids = $data->subscriptionids;
         foreach ($subscriptionids as $id) {
             if ($message = $this->generate_message($id, $eventobj)) {
                 mtrace("Sending message to the user with id " . $message->userto->id . " for the subscription with id {$id}...");
                 message_send($message);
                 mtrace("Sent.");
             }
         }
     }
 }
コード例 #5
0
 /**
  * Send non-submitters message to students.
  *
  * @param string $message
  * @return void
  */
 public function send_message($userid, $subject, $message)
 {
     $eventdata = new stdClass();
     $eventdata->component = 'mod_turnitintooltwo';
     //your component name
     $eventdata->name = 'nonsubmitters';
     //this is the message name from messages.php
     $eventdata->userfrom = get_admin();
     $eventdata->userto = $userid;
     $eventdata->subject = $subject;
     $eventdata->fullmessage = $message;
     $eventdata->fullmessageformat = FORMAT_HTML;
     $eventdata->fullmessagehtml = $message;
     $eventdata->smallmessage = '';
     $eventdata->notification = 1;
     //this is only set to 0 for personal messages between users
     message_send($eventdata);
 }
コード例 #6
0
ファイル: uploadlib.php プロジェクト: pzhu2004/moodle
/**
 * Emails admins about a clam outcome
 *
 * @param string $notice The body of the email to be sent.
 */
function clam_message_admins($notice)
{
    $site = get_site();
    $subject = get_string('clamemailsubject', 'moodle', format_string($site->fullname));
    $admins = get_admins();
    foreach ($admins as $admin) {
        $eventdata = new stdClass();
        $eventdata->component = 'moodle';
        $eventdata->name = 'errors';
        $eventdata->userfrom = get_admin();
        $eventdata->userto = $admin;
        $eventdata->subject = $subject;
        $eventdata->fullmessage = $notice;
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml = '';
        $eventdata->smallmessage = '';
        message_send($eventdata);
    }
}
コード例 #7
0
 /**
  * Send digital receipt to submitter
  *
  * @param string $message
  * @return void
  */
 public function send_message($userid, $message)
 {
     global $CFG;
     $subject = get_string('digital_receipt_subject', 'turnitintooltwo');
     $eventdata = new stdClass();
     $eventdata->component = 'mod_turnitintooltwo';
     //your component name
     $eventdata->name = 'submission';
     //this is the message name from messages.php
     $eventdata->userfrom = \core_user::get_noreply_user();
     $eventdata->userto = $userid;
     $eventdata->subject = $subject;
     $eventdata->fullmessage = $message;
     $eventdata->fullmessageformat = FORMAT_HTML;
     $eventdata->fullmessagehtml = $message;
     $eventdata->smallmessage = '';
     $eventdata->notification = 1;
     //this is only set to 0 for personal messages between users
     message_send($eventdata);
 }
コード例 #8
0
ファイル: upgradelib.php プロジェクト: krysnuvadga/moodle
/**
 * Send a message to the admin in regard with the APIv1 migration.
 *
 * @return void
 */
function repository_alfresco_admin_security_key_notice()
{
    $admins = get_admins();
    if (empty($admins)) {
        return;
    }
    foreach ($admins as $admin) {
        $message = new stdClass();
        $message->component = 'moodle';
        $message->name = 'notices';
        $message->userfrom = get_admin();
        $message->userto = $admin;
        $message->smallmessage = get_string('security_key_notice_message_small', 'repository_alfresco');
        $message->subject = get_string('security_key_notice_message_subject', 'repository_alfresco');
        $message->fullmessage = get_string('security_key_notice_message_content', 'repository_alfresco');
        $message->fullmessagehtml = get_string('security_key_notice_message_content', 'repository_alfresco');
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->notification = 1;
        message_send($message);
    }
}
コード例 #9
0
ファイル: util.php プロジェクト: janeklb/moodle
 /**
  * Alerts site admin of potential problems.
  *
  * @param string   $subject email subject
  * @param stdClass $data    PayPal IPN data
  */
 public static function message_paypal_error_to_admin($subject, $data)
 {
     $admin = get_admin();
     $site = get_site();
     $message = "{$site->fullname}:  Transaction failed.\n\n{$subject}\n\n";
     foreach ($data as $key => $value) {
         $message .= "{$key} => {$value}\n";
     }
     $eventdata = new \stdClass();
     $eventdata->modulename = 'moodle';
     $eventdata->component = 'enrol_paypal';
     $eventdata->name = 'paypal_enrolment';
     $eventdata->userfrom = $admin;
     $eventdata->userto = $admin;
     $eventdata->subject = "PAYPAL ERROR: " . $subject;
     $eventdata->fullmessage = $message;
     $eventdata->fullmessageformat = FORMAT_PLAIN;
     $eventdata->fullmessagehtml = '';
     $eventdata->smallmessage = '';
     message_send($eventdata);
 }
コード例 #10
0
 /**
  * Send instructor message to instructors on course.
  *
  * @param array $instructors
  * @param string $message
  * @return void
  */
 public function send_instructor_message($instructors, $message)
 {
     $subject = get_string('receipt_instructor_copy_subject', 'turnitintooltwo');
     $eventdata = new stdClass();
     $eventdata->component = 'mod_turnitintooltwo';
     //your component name
     $eventdata->name = 'submission';
     //this is the message name from messages.php
     $eventdata->userfrom = \core_user::get_noreply_user();
     $eventdata->subject = $subject;
     $eventdata->fullmessage = $message;
     $eventdata->fullmessageformat = FORMAT_HTML;
     $eventdata->fullmessagehtml = $message;
     $eventdata->smallmessage = '';
     $eventdata->notification = 1;
     //this is only set to 0 for personal messages between users
     foreach ($instructors as $instructor) {
         $eventdata->userto = $instructor->id;
         message_send($eventdata);
     }
     unset($instructor);
 }
コード例 #11
0
ファイル: upgrade.php プロジェクト: nicusX/moodle
function repository_googledocs_admin_upgrade_notification() {
    $admins = get_admins();

    if (empty($admins)) {
        return;
    }
    $mainadmin = reset($admins);

    foreach ($admins as $admin) {
        $message = new stdClass();
        $message->component         = 'moodle';
        $message->name              = 'notices';
        $message->userfrom          = $mainadmin;
        $message->userto            = $admin;
        $message->smallmessage      = get_string('oauth2upgrade_message_small', 'repository_googledocs');
        $message->subject           = get_string('oauth2upgrade_message_subject', 'repository_googledocs');
        $message->fullmessage       = get_string('oauth2upgrade_message_content', 'repository_googledocs');
        $message->fullmessagehtml   = get_string('oauth2upgrade_message_content', 'repository_googledocs');
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->notification      = 1;
        message_send($message);
    }
}
コード例 #12
0
ファイル: upgradelib.php プロジェクト: alanaipe2015/moodle
/**
 * Send a message to the admin in regard with the APIv1 migration.
 *
 * @return void
 */
function repository_boxnet_admin_upgrade_notification()
{
    $admins = get_admins();
    if (empty($admins)) {
        return;
    }
    $a = new stdClass();
    $a->docsurl = get_docs_url('Box.net_APIv1_migration');
    foreach ($admins as $admin) {
        $message = new stdClass();
        $message->component = 'moodle';
        $message->name = 'notices';
        $message->userfrom = get_admin();
        $message->userto = $admin;
        $message->smallmessage = get_string('apiv1migration_message_small', 'repository_boxnet');
        $message->subject = get_string('apiv1migration_message_subject', 'repository_boxnet');
        $message->fullmessage = get_string('apiv1migration_message_content', 'repository_boxnet', $a);
        $message->fullmessagehtml = get_string('apiv1migration_message_content', 'repository_boxnet', $a);
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->notification = 1;
        message_send($message);
    }
}
コード例 #13
0
ファイル: upgradelib.php プロジェクト: alanaipe2015/moodle
/**
 * Inform admins about assignments that still need upgrading.
 */
function mod_assignment_pending_upgrades_notification($count)
{
    $admins = get_admins();
    if (empty($admins)) {
        return;
    }
    $a = new stdClass();
    $a->count = $count;
    $a->docsurl = get_docs_url('Assignment_upgrade_tool');
    foreach ($admins as $admin) {
        $message = new stdClass();
        $message->component = 'moodle';
        $message->name = 'notices';
        $message->userfrom = \core_user::get_noreply_user();
        $message->userto = $admin;
        $message->smallmessage = get_string('pendingupgrades_message_small', 'mod_assignment');
        $message->subject = get_string('pendingupgrades_message_subject', 'mod_assignment');
        $message->fullmessage = get_string('pendingupgrades_message_content', 'mod_assignment', $a);
        $message->fullmessagehtml = get_string('pendingupgrades_message_content', 'mod_assignment', $a);
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->notification = 1;
        message_send($message);
    }
}
コード例 #14
0
 public function test_message_attachment_send()
 {
     global $CFG;
     $this->preventResetByRollback();
     $this->resetAfterTest();
     // Set config setting to allow attachments.
     $CFG->allowattachments = true;
     unset_config('noemailever');
     $user = $this->getDataGenerator()->create_user();
     $context = context_user::instance($user->id);
     // Create a test file.
     $fs = get_file_storage();
     $filerecord = array('contextid' => $context->id, 'component' => 'core', 'filearea' => 'unittest', 'itemid' => 99999, 'filepath' => '/', 'filename' => 'emailtest.txt');
     $file = $fs->create_file_from_string($filerecord, 'Test content');
     $message = new stdClass();
     $message->component = 'moodle';
     $message->name = 'instantmessage';
     $message->userfrom = get_admin();
     $message->userto = $user;
     $message->subject = 'message subject 1';
     $message->fullmessage = 'message body';
     $message->fullmessageformat = FORMAT_MARKDOWN;
     $message->fullmessagehtml = '<p>message body</p>';
     $message->smallmessage = 'small message';
     $message->attachment = $file;
     $message->attachname = 'emailtest.txt';
     $message->notification = 0;
     // Make sure we are redirecting emails.
     $sink = $this->redirectEmails();
     $this->assertTrue(phpunit_util::is_redirecting_phpmailer());
     message_send($message);
     // Get the email that we just sent.
     $emails = $sink->get_messages();
     $email = reset($emails);
     $this->assertTrue(strpos($email->body, 'Content-Disposition: attachment;') !== false);
     $this->assertTrue(strpos($email->body, 'emailtest.txt') !== false);
     // Check if the stored file still exists after remove the temporary attachment.
     $storedfileexists = $fs->file_exists($filerecord['contextid'], $filerecord['component'], $filerecord['filearea'], $filerecord['itemid'], $filerecord['filepath'], $filerecord['filename']);
     $this->assertTrue($storedfileexists);
 }
コード例 #15
0
ファイル: lib.php プロジェクト: nfreear/moodle
/**
 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
 * @param object $userfrom the message sender
 * @param object $userto the message recipient
 * @param string $message the message
 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
 * @return int|false the ID of the new message or false
 */
function message_post_message($userfrom, $userto, $message, $format) {
    global $SITE, $CFG, $USER;

    $eventdata = new stdClass();
    $eventdata->component        = 'moodle';
    $eventdata->name             = 'instantmessage';
    $eventdata->userfrom         = $userfrom;
    $eventdata->userto           = $userto;

    //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
    $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);

    if ($format == FORMAT_HTML) {
        $eventdata->fullmessage      = '';
        $eventdata->fullmessagehtml  = $message;
    } else {
        $eventdata->fullmessage      = $message;
        $eventdata->fullmessagehtml  = '';
    }

    $eventdata->fullmessageformat = $format;
    $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.

    $s = new stdClass();
    $s->sitename = $SITE->shortname;
    $s->url = $CFG->wwwroot.'/message/index.php?user='******'&id='.$userfrom->id;

    $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
    if (!empty($eventdata->fullmessage)) {
        $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
    }
    if (!empty($eventdata->fullmessagehtml)) {
        $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
    }

    $eventdata->timecreated     = time();
    return message_send($eventdata);
}
コード例 #16
0
ファイル: lib.php プロジェクト: Jtgadbois/Pedadida
/**
 * Function to be run periodically according to the moodle cron
 * Finds all posts that have yet to be mailed out, and mails them
 * out to all subscribers
 *
 * @global object
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @uses CONTEXT_COURSE
 * @uses SITEID
 * @uses FORMAT_PLAIN
 * @return void
 */
function forum_cron() {
    global $CFG, $USER, $DB;

    $site = get_site();

    // All users that are subscribed to any post that needs sending,
    // please increase $CFG->extramemorylimit on large sites that
    // send notifications to a large number of users.
    $users = array();
    $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!

    // status arrays
    $mailcount  = array();
    $errorcount = array();

    // caches
    $discussions     = array();
    $forums          = array();
    $courses         = array();
    $coursemodules   = array();
    $subscribedusers = array();


    // Posts older than 2 days will not be mailed.  This is to avoid the problem where
    // cron has not been running for a long time, and then suddenly people are flooded
    // with mail from the past few weeks or months
    $timenow   = time();
    $endtime   = $timenow - $CFG->maxeditingtime;
    $starttime = $endtime - 48 * 3600;   // Two days earlier

    if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
        // Mark them all now as being mailed.  It's unlikely but possible there
        // might be an error later so that a post is NOT actually mailed out,
        // but since mail isn't crucial, we can accept this risk.  Doing it now
        // prevents the risk of duplicated mails, which is a worse problem.

        if (!forum_mark_old_posts_as_mailed($endtime)) {
            mtrace('Errors occurred while trying to mark some posts as being mailed.');
            return false;  // Don't continue trying to mail them, in case we are in a cron loop
        }

        // checking post validity, and adding users to loop through later
        foreach ($posts as $pid => $post) {

            $discussionid = $post->discussion;
            if (!isset($discussions[$discussionid])) {
                if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
                    $discussions[$discussionid] = $discussion;
                } else {
                    mtrace('Could not find discussion '.$discussionid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $forumid = $discussions[$discussionid]->forum;
            if (!isset($forums[$forumid])) {
                if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
                    $forums[$forumid] = $forum;
                } else {
                    mtrace('Could not find forum '.$forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $courseid = $forums[$forumid]->course;
            if (!isset($courses[$courseid])) {
                if ($course = $DB->get_record('course', array('id' => $courseid))) {
                    $courses[$courseid] = $course;
                } else {
                    mtrace('Could not find course '.$courseid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            if (!isset($coursemodules[$forumid])) {
                if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                    $coursemodules[$forumid] = $cm;
                } else {
                    mtrace('Could not find course module for forum '.$forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }


            // caching subscribed users of each forum
            if (!isset($subscribedusers[$forumid])) {
                $modcontext = context_module::instance($coursemodules[$forumid]->id);
                if ($subusers = forum_subscribed_users($courses[$courseid], $forums[$forumid], 0, $modcontext, "u.*")) {
                    foreach ($subusers as $postuser) {
                        // this user is subscribed to this forum
                        $subscribedusers[$forumid][$postuser->id] = $postuser->id;
                        $userscount++;
                        if ($userscount > FORUM_CRON_USER_CACHE) {
                            // Store minimal user info.
                            $minuser = new stdClass();
                            $minuser->id = $postuser->id;
                            $users[$postuser->id] = $minuser;
                        } else {
                            // Cache full user record.
                            forum_cron_minimise_user_record($postuser);
                            $users[$postuser->id] = $postuser;
                        }
                    }
                    // Release memory.
                    unset($subusers);
                    unset($postuser);
                }
            }

            $mailcount[$pid] = 0;
            $errorcount[$pid] = 0;
        }
    }

    if ($users && $posts) {

        $urlinfo = parse_url($CFG->wwwroot);
        $hostname = $urlinfo['host'];

        foreach ($users as $userto) {

            @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes

            mtrace('Processing user '.$userto->id);

            // Init user caches - we keep the cache for one cycle only,
            // otherwise it could consume too much memory.
            if (isset($userto->username)) {
                $userto = clone($userto);
            } else {
                $userto = $DB->get_record('user', array('id' => $userto->id));
                forum_cron_minimise_user_record($userto);
            }
            $userto->viewfullnames = array();
            $userto->canpost       = array();
            $userto->markposts     = array();

            // set this so that the capabilities are cached, and environment matches receiving user
            cron_setup_user($userto);

            // reset the caches
            foreach ($coursemodules as $forumid=>$unused) {
                $coursemodules[$forumid]->cache       = new stdClass();
                $coursemodules[$forumid]->cache->caps = array();
                unset($coursemodules[$forumid]->uservisible);
            }

            foreach ($posts as $pid => $post) {

                // Set up the environment for the post, discussion, forum, course
                $discussion = $discussions[$post->discussion];
                $forum      = $forums[$discussion->forum];
                $course     = $courses[$forum->course];
                $cm         =& $coursemodules[$forum->id];

                // Do some checks  to see if we can bail out now
                // Only active enrolled users are in the list of subscribers
                if (!isset($subscribedusers[$forum->id][$userto->id])) {
                    continue; // user does not subscribe to this forum
                }

                // Don't send email if the forum is Q&A and the user has not posted
                // Initial topics are still mailed
                if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
                    mtrace('Did not email '.$userto->id.' because user has not posted in discussion');
                    continue;
                }

                // Get info about the sending user
                if (array_key_exists($post->userid, $users)) { // we might know him/her already
                    $userfrom = $users[$post->userid];
                    if (!isset($userfrom->idnumber)) {
                        // Minimalised user info, fetch full record.
                        $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                        forum_cron_minimise_user_record($userfrom);
                    }

                } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                    forum_cron_minimise_user_record($userfrom);
                    // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
                    if ($userscount <= FORUM_CRON_USER_CACHE) {
                        $userscount++;
                        $users[$userfrom->id] = $userfrom;
                    }

                } else {
                    mtrace('Could not find user '.$post->userid);
                    continue;
                }

                //if we want to check that userto and userfrom are not the same person this is probably the spot to do it

                // setup global $COURSE properly - needed for roles and languages
                cron_setup_user($userto, $course);

                // Fill caches
                if (!isset($userto->viewfullnames[$forum->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userto->canpost[$discussion->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                }
                if (!isset($userfrom->groups[$forum->id])) {
                    if (!isset($userfrom->groups)) {
                        $userfrom->groups = array();
                        if (isset($users[$userfrom->id])) {
                            $users[$userfrom->id]->groups = array();
                        }
                    }
                    $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    if (isset($users[$userfrom->id])) {
                        $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                    }
                }

                // Make sure groups allow this user to see this email
                if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
                    if (!groups_group_exists($discussion->groupid)) { // Can't find group
                        continue;                           // Be safe and don't send it to anyone
                    }

                    if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
                        // do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
                        continue;
                    }
                }

                // Make sure we're allowed to see it...
                if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
                    mtrace('user '.$userto->id. ' can not see '.$post->id);
                    continue;
                }

                // OK so we need to send the email.

                // Does the user want this post in a digest?  If so postpone it for now.
                if ($userto->maildigest > 0) {
                    // This user wants the mails to be in digest form
                    $queue = new stdClass();
                    $queue->userid       = $userto->id;
                    $queue->discussionid = $discussion->id;
                    $queue->postid       = $post->id;
                    $queue->timemodified = $post->created;
                    $DB->insert_record('forum_queue', $queue);
                    continue;
                }


                // Prepare to actually send the post now, and build up the content

                $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));

                $userfrom->customheaders = array (  // Headers to make emails easier to track
                           'Precedence: Bulk',
                           'List-Id: "'.$cleanforumname.'" <moodleforum'.$forum->id.'@'.$hostname.'>',
                           'List-Help: '.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id,
                           'Message-ID: '.forum_get_email_message_id($post->id, $userto->id, $hostname),
                           'X-Course-Id: '.$course->id,
                           'X-Course-Name: '.format_string($course->fullname, true)
                );

                if ($post->parent) {  // This post is a reply, so add headers for threading (see MDL-22551)
                    $userfrom->customheaders[] = 'In-Reply-To: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
                    $userfrom->customheaders[] = 'References: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
                }

                $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));

                $postsubject = html_to_text("$shortname: ".format_string($post->subject, true));
                $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
                $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto);

                // Send the post now!

                mtrace('Sending ', '');

                $eventdata = new stdClass();
                $eventdata->component        = 'mod_forum';
                $eventdata->name             = 'posts';
                $eventdata->userfrom         = $userfrom;
                $eventdata->userto           = $userto;
                $eventdata->subject          = $postsubject;
                $eventdata->fullmessage      = $posttext;
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml  = $posthtml;
                $eventdata->notification = 1;

                // If forum_replytouser is not set then send mail using the noreplyaddress.
                if (empty($CFG->forum_replytouser)) {
                    // Clone userfrom as it is referenced by $users.
                    $cloneduserfrom = clone($userfrom);
                    $cloneduserfrom->email = $CFG->noreplyaddress;
                    $eventdata->userfrom = $cloneduserfrom;
                }

                $smallmessagestrings = new stdClass();
                $smallmessagestrings->user = fullname($userfrom);
                $smallmessagestrings->forumname = "$shortname: ".format_string($forum->name,true).": ".$discussion->name;
                $smallmessagestrings->message = $post->message;
                //make sure strings are in message recipients language
                $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);

                $eventdata->contexturl = "{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}#p{$post->id}";
                $eventdata->contexturlname = $discussion->name;

                $mailresult = message_send($eventdata);
                if (!$mailresult){
                    mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
                         " ($userto->email) .. not trying again.");
                    add_to_log($course->id, 'forum', 'mail error', "discuss.php?d=$discussion->id#p$post->id",
                               substr(format_string($post->subject,true),0,30), $cm->id, $userto->id);
                    $errorcount[$post->id]++;
                } else {
                    $mailcount[$post->id]++;

                // Mark post as read if forum_usermarksread is set off
                    if (!$CFG->forum_usermarksread) {
                        $userto->markposts[$post->id] = $post->id;
                    }
                }

                mtrace('post '.$post->id. ': '.$post->subject);
            }

            // mark processed posts as read
            forum_tp_mark_posts_read($userto, $userto->markposts);
            unset($userto);
        }
    }

    if ($posts) {
        foreach ($posts as $post) {
            mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
            if ($errorcount[$post->id]) {
                $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
            }
        }
    }

    // release some memory
    unset($subscribedusers);
    unset($mailcount);
    unset($errorcount);

    cron_setup_user();

    $sitetimezone = $CFG->timezone;

    // Now see if there are any digest mails waiting to be sent, and if we should send them

    mtrace('Starting digest processing...');

    @set_time_limit(300); // terminate if not able to fetch all digests in 5 minutes

    if (!isset($CFG->digestmailtimelast)) {    // To catch the first time
        set_config('digestmailtimelast', 0);
    }

    $timenow = time();
    $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);

    // Delete any really old ones (normally there shouldn't be any)
    $weekago = $timenow - (7 * 24 * 3600);
    $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
    mtrace ('Cleaned old digest records');

    if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {

        mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));

        $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));

        if ($digestposts_rs->valid()) {

            // We have work to do
            $usermailcount = 0;

            //caches - reuse the those filled before too
            $discussionposts = array();
            $userdiscussions = array();

            foreach ($digestposts_rs as $digestpost) {
                if (!isset($posts[$digestpost->postid])) {
                    if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
                        $posts[$digestpost->postid] = $post;
                    } else {
                        continue;
                    }
                }
                $discussionid = $digestpost->discussionid;
                if (!isset($discussions[$discussionid])) {
                    if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
                        $discussions[$discussionid] = $discussion;
                    } else {
                        continue;
                    }
                }
                $forumid = $discussions[$discussionid]->forum;
                if (!isset($forums[$forumid])) {
                    if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
                        $forums[$forumid] = $forum;
                    } else {
                        continue;
                    }
                }

                $courseid = $forums[$forumid]->course;
                if (!isset($courses[$courseid])) {
                    if ($course = $DB->get_record('course', array('id' => $courseid))) {
                        $courses[$courseid] = $course;
                    } else {
                        continue;
                    }
                }

                if (!isset($coursemodules[$forumid])) {
                    if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                        $coursemodules[$forumid] = $cm;
                    } else {
                        continue;
                    }
                }
                $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
                $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
            }
            $digestposts_rs->close(); /// Finished iteration, let's close the resultset

            // Data collected, start sending out emails to each user
            foreach ($userdiscussions as $userid => $thesediscussions) {

                @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes

                cron_setup_user();

                mtrace(get_string('processingdigest', 'forum', $userid), '... ');

                // First of all delete all the queue entries for this user
                $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));

                // Init user caches - we keep the cache for one cycle only,
                // otherwise it would unnecessarily consume memory.
                if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
                    $userto = clone($users[$userid]);
                } else {
                    $userto = $DB->get_record('user', array('id' => $userid));
                    forum_cron_minimise_user_record($userto);
                }
                $userto->viewfullnames = array();
                $userto->canpost       = array();
                $userto->markposts     = array();

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

                $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));

                $headerdata = new stdClass();
                $headerdata->sitename = format_string($site->fullname, true);
                $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&amp;course='.$site->id;

                $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
                $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';

                $posthtml = "<head>";
/*                foreach ($CFG->stylesheets as $stylesheet) {
                    //TODO: MDL-21120
                    $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
                }*/
                $posthtml .= "</head>\n<body id=\"email\">\n";
                $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';

                foreach ($thesediscussions as $discussionid) {

                    @set_time_limit(120);   // to be reset for each post

                    $discussion = $discussions[$discussionid];
                    $forum      = $forums[$discussion->forum];
                    $course     = $courses[$forum->course];
                    $cm         = $coursemodules[$forum->id];

                    //override language
                    cron_setup_user($userto, $course);

                    // Fill caches
                    if (!isset($userto->viewfullnames[$forum->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                    }
                    if (!isset($userto->canpost[$discussion->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                    }

                    $strforums      = get_string('forums', 'forum');
                    $canunsubscribe = ! forum_is_forcesubscribed($forum);
                    $canreply       = $userto->canpost[$discussion->id];
                    $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));

                    $posttext .= "\n \n";
                    $posttext .= '=====================================================================';
                    $posttext .= "\n \n";
                    $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
                    if ($discussion->name != $forum->name) {
                        $posttext  .= " -> ".format_string($discussion->name,true);
                    }
                    $posttext .= "\n";

                    $posthtml .= "<p><font face=\"sans-serif\">".
                    "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
                    "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
                    "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
                    if ($discussion->name == $forum->name) {
                        $posthtml .= "</font></p>";
                    } else {
                        $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
                    }
                    $posthtml .= '<p>';

                    $postsarray = $discussionposts[$discussionid];
                    sort($postsarray);

                    foreach ($postsarray as $postid) {
                        $post = $posts[$postid];

                        if (array_key_exists($post->userid, $users)) { // we might know him/her already
                            $userfrom = $users[$post->userid];
                            if (!isset($userfrom->idnumber)) {
                                $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                                forum_cron_minimise_user_record($userfrom);
                            }

                        } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                            forum_cron_minimise_user_record($userfrom);
                            if ($userscount <= FORUM_CRON_USER_CACHE) {
                                $userscount++;
                                $users[$userfrom->id] = $userfrom;
                            }

                        } else {
                            mtrace('Could not find user '.$post->userid);
                            continue;
                        }

                        if (!isset($userfrom->groups[$forum->id])) {
                            if (!isset($userfrom->groups)) {
                                $userfrom->groups = array();
                                if (isset($users[$userfrom->id])) {
                                    $users[$userfrom->id]->groups = array();
                                }
                            }
                            $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                            if (isset($users[$userfrom->id])) {
                                $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                            }
                        }

                        $userfrom->customheaders = array ("Precedence: Bulk");

                        if ($userto->maildigest == 2) {
                            // Subjects only
                            $by = new stdClass();
                            $by->name = fullname($userfrom);
                            $by->date = userdate($post->modified);
                            $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
                            $posttext .= "\n---------------------------------------------------------------------";

                            $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&amp;course=$course->id\">$by->name</a>";
                            $posthtml .= '<div><a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'#p'.$post->id.'">'.format_string($post->subject,true).'</a> '.get_string("bynameondate", "forum", $by).'</div>';

                        } else {
                            // The full treatment
                            $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
                            $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);

                        // Create an array of postid's for this user to mark as read.
                            if (!$CFG->forum_usermarksread) {
                                $userto->markposts[$post->id] = $post->id;
                            }
                        }
                    }
                    if ($canunsubscribe) {
                        $posthtml .= "\n<div class='mdl-right'><font size=\"1\"><a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">".get_string("unsubscribe", "forum")."</a></font></div>";
                    } else {
                        $posthtml .= "\n<div class='mdl-right'><font size=\"1\">".get_string("everyoneissubscribed", "forum")."</font></div>";
                    }
                    $posthtml .= '<hr size="1" noshade="noshade" /></p>';
                }
                $posthtml .= '</body>';

                if (empty($userto->mailformat) || $userto->mailformat != 1) {
                    // This user DOESN'T want to receive HTML
                    $posthtml = '';
                }

                $attachment = $attachname='';
                // Directly email forum digests rather than sending them via messaging, use the
                // site shortname as 'from name', the noreply address will be used by email_to_user.
                $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);

                if (!$mailresult) {
                    mtrace("ERROR!");
                    echo "Error: mod/forum/cron.php: Could not send out digest mail to user $userto->id ($userto->email)... not trying again.\n";
                    add_to_log($course->id, 'forum', 'mail digest error', '', '', $cm->id, $userto->id);
                } else {
                    mtrace("success.");
                    $usermailcount++;

                    // Mark post as read if forum_usermarksread is set off
                    forum_tp_mark_posts_read($userto, $userto->markposts);
                }
            }
        }
    /// We have finishied all digest emails, update $CFG->digestmailtimelast
        set_config('digestmailtimelast', $timenow);
    }

    cron_setup_user();

    if (!empty($usermailcount)) {
        mtrace(get_string('digestsentusers', 'forum', $usermailcount));
    }

    if (!empty($CFG->forum_lastreadclean)) {
        $timenow = time();
        if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
            set_config('forum_lastreadclean', $timenow);
            mtrace('Removing old forum read tracking info...');
            forum_tp_clean_read_records();
        }
    } else {
        set_config('forum_lastreadclean', time());
    }


    return true;
}
コード例 #17
0
ファイル: lib.php プロジェクト: numbas/moodle
/**
 * sends an email to the teachers of the course where the given feedback is placed.
 *
 * @global object
 * @uses FORMAT_PLAIN
 * @param object $cm the coursemodule-record
 * @param object $feedback
 * @param object $course
 * @return void
 */
function feedback_send_email_anonym($cm, $feedback, $course) {
    global $CFG;

    if ($feedback->email_notification == 0) { // No need to do anything
        return;
    }

    $teachers = feedback_get_receivemail_users($cm->id);

    if ($teachers) {

        $strfeedbacks = get_string('modulenameplural', 'feedback');
        $strfeedback  = get_string('modulename', 'feedback');
        $strcompleted  = get_string('completed', 'feedback');
        $printusername = get_string('anonymous_user', 'feedback');

        foreach ($teachers as $teacher) {
            $info = new stdClass();
            $info->username = $printusername;
            $info->feedback = format_string($feedback->name, true);
            $info->url = $CFG->wwwroot.'/mod/feedback/show_entries_anonym.php?id='.$cm->id;

            $postsubject = $strcompleted.': '.$info->username.' -> '.$feedback->name;
            $posttext = feedback_send_email_text($info, $course);

            if ($teacher->mailformat == 1) {
                $posthtml = feedback_send_email_html($info, $course, $cm);
            } else {
                $posthtml = '';
            }

            $eventdata = new stdClass();
            $eventdata->name             = 'submission';
            $eventdata->component        = 'mod_feedback';
            $eventdata->userfrom         = $teacher;
            $eventdata->userto           = $teacher;
            $eventdata->subject          = $postsubject;
            $eventdata->fullmessage      = $posttext;
            $eventdata->fullmessageformat = FORMAT_PLAIN;
            $eventdata->fullmessagehtml  = $posthtml;
            $eventdata->smallmessage     = '';
            message_send($eventdata);
        }
    }
}
コード例 #18
0
ファイル: advanced_test.php プロジェクト: rushi963/moodle
 /**
  * @depends test_message_redirection
  */
 public function test_message_redirection_noreset($sink)
 {
     $this->preventResetByRollback();
     // Messaging is not compatible with transactions...
     $this->resetAfterTest();
     $this->assertTrue(phpunit_util::is_redirecting_messages());
     $this->assertEquals(1, $sink->count());
     $message = new stdClass();
     $message->component = 'moodle';
     $message->name = 'instantmessage';
     $message->userfrom = get_admin();
     $message->userto = get_admin();
     $message->subject = 'message subject 1';
     $message->fullmessage = 'message body';
     $message->fullmessageformat = FORMAT_MARKDOWN;
     $message->fullmessagehtml = '<p>message body</p>';
     $message->smallmessage = 'small message';
     $message->notification = 0;
     message_send($message);
     $this->assertEquals(2, $sink->count());
 }
コード例 #19
0
ファイル: lib.php プロジェクト: rezaies/moodle
/**
 * Function to be run periodically according to the scheduled task.
 *
 * Finds all posts that have yet to be mailed out, and mails them
 * out to all subscribers as well as other maintance tasks.
 *
 * NOTE: Since 2.7.2 this function is run by scheduled task rather
 * than standard cron.
 *
 * @todo MDL-44734 The function will be split up into seperate tasks.
 */
function forum_cron()
{
    global $CFG, $USER, $DB, $PAGE;
    $site = get_site();
    // The main renderers.
    $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
    $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
    $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
    $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
    $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
    $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
    // All users that are subscribed to any post that needs sending,
    // please increase $CFG->extramemorylimit on large sites that
    // send notifications to a large number of users.
    $users = array();
    $userscount = 0;
    // Cached user counter - count($users) in PHP is horribly slow!!!
    // Status arrays.
    $mailcount = array();
    $errorcount = array();
    // caches
    $discussions = array();
    $forums = array();
    $courses = array();
    $coursemodules = array();
    $subscribedusers = array();
    $messageinboundhandlers = array();
    // Posts older than 2 days will not be mailed.  This is to avoid the problem where
    // cron has not been running for a long time, and then suddenly people are flooded
    // with mail from the past few weeks or months
    $timenow = time();
    $endtime = $timenow - $CFG->maxeditingtime;
    $starttime = $endtime - 48 * 3600;
    // Two days earlier
    // Get the list of forum subscriptions for per-user per-forum maildigest settings.
    $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
    $digests = array();
    foreach ($digestsset as $thisrow) {
        if (!isset($digests[$thisrow->forum])) {
            $digests[$thisrow->forum] = array();
        }
        $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
    }
    $digestsset->close();
    // Create the generic messageinboundgenerator.
    $messageinboundgenerator = new \core\message\inbound\address_manager();
    $messageinboundgenerator->set_handler('\\mod_forum\\message\\inbound\\reply_handler');
    if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
        // Mark them all now as being mailed.  It's unlikely but possible there
        // might be an error later so that a post is NOT actually mailed out,
        // but since mail isn't crucial, we can accept this risk.  Doing it now
        // prevents the risk of duplicated mails, which is a worse problem.
        if (!forum_mark_old_posts_as_mailed($endtime)) {
            mtrace('Errors occurred while trying to mark some posts as being mailed.');
            return false;
            // Don't continue trying to mail them, in case we are in a cron loop
        }
        // checking post validity, and adding users to loop through later
        foreach ($posts as $pid => $post) {
            $discussionid = $post->discussion;
            if (!isset($discussions[$discussionid])) {
                if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
                    $discussions[$discussionid] = $discussion;
                    \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
                    \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
                } else {
                    mtrace('Could not find discussion ' . $discussionid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $forumid = $discussions[$discussionid]->forum;
            if (!isset($forums[$forumid])) {
                if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
                    $forums[$forumid] = $forum;
                } else {
                    mtrace('Could not find forum ' . $forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            $courseid = $forums[$forumid]->course;
            if (!isset($courses[$courseid])) {
                if ($course = $DB->get_record('course', array('id' => $courseid))) {
                    $courses[$courseid] = $course;
                } else {
                    mtrace('Could not find course ' . $courseid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            if (!isset($coursemodules[$forumid])) {
                if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                    $coursemodules[$forumid] = $cm;
                } else {
                    mtrace('Could not find course module for forum ' . $forumid);
                    unset($posts[$pid]);
                    continue;
                }
            }
            // Save the Inbound Message datakey here to reduce DB queries later.
            $messageinboundgenerator->set_data($pid);
            $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
            // Caching subscribed users of each forum.
            if (!isset($subscribedusers[$forumid])) {
                $modcontext = context_module::instance($coursemodules[$forumid]->id);
                if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
                    foreach ($subusers as $postuser) {
                        // this user is subscribed to this forum
                        $subscribedusers[$forumid][$postuser->id] = $postuser->id;
                        $userscount++;
                        if ($userscount > FORUM_CRON_USER_CACHE) {
                            // Store minimal user info.
                            $minuser = new stdClass();
                            $minuser->id = $postuser->id;
                            $users[$postuser->id] = $minuser;
                        } else {
                            // Cache full user record.
                            forum_cron_minimise_user_record($postuser);
                            $users[$postuser->id] = $postuser;
                        }
                    }
                    // Release memory.
                    unset($subusers);
                    unset($postuser);
                }
            }
            $mailcount[$pid] = 0;
            $errorcount[$pid] = 0;
        }
    }
    if ($users && $posts) {
        foreach ($users as $userto) {
            // Terminate if processing of any account takes longer than 2 minutes.
            core_php_time_limit::raise(120);
            mtrace('Processing user ' . $userto->id);
            // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
            if (isset($userto->username)) {
                $userto = clone $userto;
            } else {
                $userto = $DB->get_record('user', array('id' => $userto->id));
                forum_cron_minimise_user_record($userto);
            }
            $userto->viewfullnames = array();
            $userto->canpost = array();
            $userto->markposts = array();
            // Setup this user so that the capabilities are cached, and environment matches receiving user.
            cron_setup_user($userto);
            // Reset the caches.
            foreach ($coursemodules as $forumid => $unused) {
                $coursemodules[$forumid]->cache = new stdClass();
                $coursemodules[$forumid]->cache->caps = array();
                unset($coursemodules[$forumid]->uservisible);
            }
            foreach ($posts as $pid => $post) {
                $discussion = $discussions[$post->discussion];
                $forum = $forums[$discussion->forum];
                $course = $courses[$forum->course];
                $cm =& $coursemodules[$forum->id];
                // Do some checks to see if we can bail out now.
                // Only active enrolled users are in the list of subscribers.
                // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
                if (!isset($subscribedusers[$forum->id][$userto->id])) {
                    // The user does not subscribe to this forum.
                    continue;
                }
                if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
                    // The user does not subscribe to this forum, or to this specific discussion.
                    continue;
                }
                if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
                    // Skip posts if the user subscribed to the discussion after it was created.
                    if (isset($subscriptiontime[$post->discussion]) && $subscriptiontime[$post->discussion] > $post->created) {
                        continue;
                    }
                }
                // Don't send email if the forum is Q&A and the user has not posted.
                // Initial topics are still mailed.
                if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
                    mtrace('Did not email ' . $userto->id . ' because user has not posted in discussion');
                    continue;
                }
                // Get info about the sending user.
                if (array_key_exists($post->userid, $users)) {
                    // We might know the user already.
                    $userfrom = $users[$post->userid];
                    if (!isset($userfrom->idnumber)) {
                        // Minimalised user info, fetch full record.
                        $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                        forum_cron_minimise_user_record($userfrom);
                    }
                } else {
                    if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                        forum_cron_minimise_user_record($userfrom);
                        // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
                        if ($userscount <= FORUM_CRON_USER_CACHE) {
                            $userscount++;
                            $users[$userfrom->id] = $userfrom;
                        }
                    } else {
                        mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
                        continue;
                    }
                }
                // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
                // Setup global $COURSE properly - needed for roles and languages.
                cron_setup_user($userto, $course);
                // Fill caches.
                if (!isset($userto->viewfullnames[$forum->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                }
                if (!isset($userto->canpost[$discussion->id])) {
                    $modcontext = context_module::instance($cm->id);
                    $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                }
                if (!isset($userfrom->groups[$forum->id])) {
                    if (!isset($userfrom->groups)) {
                        $userfrom->groups = array();
                        if (isset($users[$userfrom->id])) {
                            $users[$userfrom->id]->groups = array();
                        }
                    }
                    $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                    if (isset($users[$userfrom->id])) {
                        $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                    }
                }
                // Make sure groups allow this user to see this email.
                if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
                    // Groups are being used.
                    if (!groups_group_exists($discussion->groupid)) {
                        // Can't find group - be safe and don't this message.
                        continue;
                    }
                    if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
                        // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
                        continue;
                    }
                }
                // Make sure we're allowed to see the post.
                if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
                    mtrace('User ' . $userto->id . ' can not see ' . $post->id . '. Not sending message.');
                    continue;
                }
                // OK so we need to send the email.
                // Does the user want this post in a digest?  If so postpone it for now.
                $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
                if ($maildigest > 0) {
                    // This user wants the mails to be in digest form.
                    $queue = new stdClass();
                    $queue->userid = $userto->id;
                    $queue->discussionid = $discussion->id;
                    $queue->postid = $post->id;
                    $queue->timemodified = $post->created;
                    $DB->insert_record('forum_queue', $queue);
                    continue;
                }
                // Prepare to actually send the post now, and build up the content.
                $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
                $userfrom->customheaders = array('List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id), 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id, 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id), 'X-Course-Id: ' . $course->id, 'X-Course-Name: ' . format_string($course->fullname, true), 'Precedence: Bulk', 'X-Auto-Response-Suppress: All', 'Auto-Submitted: auto-generated');
                $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
                // Generate a reply-to address from using the Inbound Message handler.
                $replyaddress = null;
                if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
                    $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
                    $replyaddress = $messageinboundgenerator->generate($userto->id);
                }
                if (!isset($userto->canpost[$discussion->id])) {
                    $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                } else {
                    $canreply = $userto->canpost[$discussion->id];
                }
                $data = new \mod_forum\output\forum_post_email($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $canreply);
                $userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>', $data->get_unsubscribediscussionlink());
                if (!isset($userto->viewfullnames[$forum->id])) {
                    $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
                } else {
                    $data->viewfullnames = $userto->viewfullnames[$forum->id];
                }
                // Not all of these variables are used in the default language
                // string but are made available to support custom subjects.
                $a = new stdClass();
                $a->subject = $data->get_subject();
                $a->forumname = $cleanforumname;
                $a->sitefullname = format_string($site->fullname);
                $a->siteshortname = format_string($site->shortname);
                $a->courseidnumber = $data->get_courseidnumber();
                $a->coursefullname = $data->get_coursefullname();
                $a->courseshortname = $data->get_coursename();
                $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
                $rootid = forum_get_email_message_id($discussion->firstpost, $userto->id);
                if ($post->parent) {
                    // This post is a reply, so add reply header (RFC 2822).
                    $parentid = forum_get_email_message_id($post->parent, $userto->id);
                    $userfrom->customheaders[] = "In-Reply-To: {$parentid}";
                    // If the post is deeply nested we also reference the parent message id and
                    // the root message id (if different) to aid threading when parts of the email
                    // conversation have been deleted (RFC1036).
                    if ($post->parent != $discussion->firstpost) {
                        $userfrom->customheaders[] = "References: {$rootid} {$parentid}";
                    } else {
                        $userfrom->customheaders[] = "References: {$parentid}";
                    }
                }
                // MS Outlook / Office uses poorly documented and non standard headers, including
                // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
                $a->subject = $discussion->name;
                $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
                $userfrom->customheaders[] = "Thread-Topic: {$threadtopic}";
                $userfrom->customheaders[] = "Thread-Index: " . substr($rootid, 1, 28);
                // Send the post now!
                mtrace('Sending ', '');
                $eventdata = new \core\message\message();
                $eventdata->courseid = $course->id;
                $eventdata->component = 'mod_forum';
                $eventdata->name = 'posts';
                $eventdata->userfrom = $userfrom;
                $eventdata->userto = $userto;
                $eventdata->subject = $postsubject;
                $eventdata->fullmessage = $textout->render($data);
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml = $htmlout->render($data);
                $eventdata->notification = 1;
                $eventdata->replyto = $replyaddress;
                if (!empty($replyaddress)) {
                    // Add extra text to email messages if they can reply back.
                    $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
                    $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
                    $additionalcontent = array('fullmessage' => array('footer' => $textfooter), 'fullmessagehtml' => array('footer' => $htmlfooter));
                    $eventdata->set_additional_content('email', $additionalcontent);
                }
                $smallmessagestrings = new stdClass();
                $smallmessagestrings->user = fullname($userfrom);
                $smallmessagestrings->forumname = "{$shortname}: " . format_string($forum->name, true) . ": " . $discussion->name;
                $smallmessagestrings->message = $post->message;
                // Make sure strings are in message recipients language.
                $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
                $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
                $eventdata->contexturl = $contexturl->out();
                $eventdata->contexturlname = $discussion->name;
                $mailresult = message_send($eventdata);
                if (!$mailresult) {
                    mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id {$post->id} to user {$userto->id}" . " ({$userto->email}) .. not trying again.");
                    $errorcount[$post->id]++;
                } else {
                    $mailcount[$post->id]++;
                    // Mark post as read if forum_usermarksread is set off.
                    if (!$CFG->forum_usermarksread) {
                        $userto->markposts[$post->id] = $post->id;
                    }
                }
                mtrace('post ' . $post->id . ': ' . $post->subject);
            }
            // Mark processed posts as read.
            if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
                forum_tp_mark_posts_read($userto, $userto->markposts);
            }
            unset($userto);
        }
    }
    if ($posts) {
        foreach ($posts as $post) {
            mtrace($mailcount[$post->id] . " users were sent post {$post->id}, '{$post->subject}'");
            if ($errorcount[$post->id]) {
                $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
            }
        }
    }
    // release some memory
    unset($subscribedusers);
    unset($mailcount);
    unset($errorcount);
    cron_setup_user();
    $sitetimezone = core_date::get_server_timezone();
    // Now see if there are any digest mails waiting to be sent, and if we should send them
    mtrace('Starting digest processing...');
    core_php_time_limit::raise(300);
    // terminate if not able to fetch all digests in 5 minutes
    if (!isset($CFG->digestmailtimelast)) {
        // To catch the first time
        set_config('digestmailtimelast', 0);
    }
    $timenow = time();
    $digesttime = usergetmidnight($timenow, $sitetimezone) + $CFG->digestmailtime * 3600;
    // Delete any really old ones (normally there shouldn't be any)
    $weekago = $timenow - 7 * 24 * 3600;
    $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
    mtrace('Cleaned old digest records');
    if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
        mtrace('Sending forum digests: ' . userdate($timenow, '', $sitetimezone));
        $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
        if ($digestposts_rs->valid()) {
            // We have work to do
            $usermailcount = 0;
            //caches - reuse the those filled before too
            $discussionposts = array();
            $userdiscussions = array();
            foreach ($digestposts_rs as $digestpost) {
                if (!isset($posts[$digestpost->postid])) {
                    if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
                        $posts[$digestpost->postid] = $post;
                    } else {
                        continue;
                    }
                }
                $discussionid = $digestpost->discussionid;
                if (!isset($discussions[$discussionid])) {
                    if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
                        $discussions[$discussionid] = $discussion;
                    } else {
                        continue;
                    }
                }
                $forumid = $discussions[$discussionid]->forum;
                if (!isset($forums[$forumid])) {
                    if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
                        $forums[$forumid] = $forum;
                    } else {
                        continue;
                    }
                }
                $courseid = $forums[$forumid]->course;
                if (!isset($courses[$courseid])) {
                    if ($course = $DB->get_record('course', array('id' => $courseid))) {
                        $courses[$courseid] = $course;
                    } else {
                        continue;
                    }
                }
                if (!isset($coursemodules[$forumid])) {
                    if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
                        $coursemodules[$forumid] = $cm;
                    } else {
                        continue;
                    }
                }
                $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
                $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
            }
            $digestposts_rs->close();
            /// Finished iteration, let's close the resultset
            // Data collected, start sending out emails to each user
            foreach ($userdiscussions as $userid => $thesediscussions) {
                core_php_time_limit::raise(120);
                // terminate if processing of any account takes longer than 2 minutes
                cron_setup_user();
                mtrace(get_string('processingdigest', 'forum', $userid), '... ');
                // First of all delete all the queue entries for this user
                $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
                // Init user caches - we keep the cache for one cycle only,
                // otherwise it would unnecessarily consume memory.
                if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
                    $userto = clone $users[$userid];
                } else {
                    $userto = $DB->get_record('user', array('id' => $userid));
                    forum_cron_minimise_user_record($userto);
                }
                $userto->viewfullnames = array();
                $userto->canpost = array();
                $userto->markposts = array();
                // Override the language and timezone of the "current" user, so that
                // mail is customised for the receiver.
                cron_setup_user($userto);
                $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
                $headerdata = new stdClass();
                $headerdata->sitename = format_string($site->fullname, true);
                $headerdata->userprefs = $CFG->wwwroot . '/user/forum.php?id=' . $userid . '&amp;course=' . $site->id;
                $posttext = get_string('digestmailheader', 'forum', $headerdata) . "\n\n";
                $headerdata->userprefs = '<a target="_blank" href="' . $headerdata->userprefs . '">' . get_string('digestmailprefs', 'forum') . '</a>';
                $posthtml = '<p>' . get_string('digestmailheader', 'forum', $headerdata) . '</p>' . '<br /><hr size="1" noshade="noshade" />';
                foreach ($thesediscussions as $discussionid) {
                    core_php_time_limit::raise(120);
                    // to be reset for each post
                    $discussion = $discussions[$discussionid];
                    $forum = $forums[$discussion->forum];
                    $course = $courses[$forum->course];
                    $cm = $coursemodules[$forum->id];
                    //override language
                    cron_setup_user($userto, $course);
                    // Fill caches
                    if (!isset($userto->viewfullnames[$forum->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
                    }
                    if (!isset($userto->canpost[$discussion->id])) {
                        $modcontext = context_module::instance($cm->id);
                        $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                    }
                    $strforums = get_string('forums', 'forum');
                    $canunsubscribe = !\mod_forum\subscriptions::is_forcesubscribed($forum);
                    $canreply = $userto->canpost[$discussion->id];
                    $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
                    $posttext .= "\n \n";
                    $posttext .= '=====================================================================';
                    $posttext .= "\n \n";
                    $posttext .= "{$shortname} -> {$strforums} -> " . format_string($forum->name, true);
                    if ($discussion->name != $forum->name) {
                        $posttext .= " -> " . format_string($discussion->name, true);
                    }
                    $posttext .= "\n";
                    $posttext .= $CFG->wwwroot . '/mod/forum/discuss.php?d=' . $discussion->id;
                    $posttext .= "\n";
                    $posthtml .= "<p><font face=\"sans-serif\">" . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">{$shortname}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/index.php?id={$course->id}\">{$strforums}</a> -> " . "<a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/view.php?f={$forum->id}\">" . format_string($forum->name, true) . "</a>";
                    if ($discussion->name == $forum->name) {
                        $posthtml .= "</font></p>";
                    } else {
                        $posthtml .= " -> <a target=\"_blank\" href=\"{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}\">" . format_string($discussion->name, true) . "</a></font></p>";
                    }
                    $posthtml .= '<p>';
                    $postsarray = $discussionposts[$discussionid];
                    sort($postsarray);
                    $sentcount = 0;
                    foreach ($postsarray as $postid) {
                        $post = $posts[$postid];
                        if (array_key_exists($post->userid, $users)) {
                            // we might know him/her already
                            $userfrom = $users[$post->userid];
                            if (!isset($userfrom->idnumber)) {
                                $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
                                forum_cron_minimise_user_record($userfrom);
                            }
                        } else {
                            if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
                                forum_cron_minimise_user_record($userfrom);
                                if ($userscount <= FORUM_CRON_USER_CACHE) {
                                    $userscount++;
                                    $users[$userfrom->id] = $userfrom;
                                }
                            } else {
                                mtrace('Could not find user ' . $post->userid);
                                continue;
                            }
                        }
                        if (!isset($userfrom->groups[$forum->id])) {
                            if (!isset($userfrom->groups)) {
                                $userfrom->groups = array();
                                if (isset($users[$userfrom->id])) {
                                    $users[$userfrom->id]->groups = array();
                                }
                            }
                            $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
                            if (isset($users[$userfrom->id])) {
                                $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
                            }
                        }
                        // Headers to help prevent auto-responders.
                        $userfrom->customheaders = array("Precedence: Bulk", 'X-Auto-Response-Suppress: All', 'Auto-Submitted: auto-generated');
                        $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
                        if (!isset($userto->canpost[$discussion->id])) {
                            $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
                        } else {
                            $canreply = $userto->canpost[$discussion->id];
                        }
                        $data = new \mod_forum\output\forum_post_email($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $canreply);
                        if (!isset($userto->viewfullnames[$forum->id])) {
                            $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
                        } else {
                            $data->viewfullnames = $userto->viewfullnames[$forum->id];
                        }
                        if ($maildigest == 2) {
                            // Subjects and link only.
                            $posttext .= $textdigestbasicout->render($data);
                            $posthtml .= $htmldigestbasicout->render($data);
                        } else {
                            // The full treatment.
                            $posttext .= $textdigestfullout->render($data);
                            $posthtml .= $htmldigestfullout->render($data);
                            // Create an array of postid's for this user to mark as read.
                            if (!$CFG->forum_usermarksread) {
                                $userto->markposts[$post->id] = $post->id;
                            }
                        }
                        $sentcount++;
                    }
                    $footerlinks = array();
                    if ($canunsubscribe) {
                        $footerlinks[] = "<a href=\"{$CFG->wwwroot}/mod/forum/subscribe.php?id={$forum->id}\">" . get_string("unsubscribe", "forum") . "</a>";
                    } else {
                        $footerlinks[] = get_string("everyoneissubscribed", "forum");
                    }
                    $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
                    $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode('&nbsp;', $footerlinks) . '</font></div>';
                    $posthtml .= '<hr size="1" noshade="noshade" /></p>';
                }
                if (empty($userto->mailformat) || $userto->mailformat != 1) {
                    // This user DOESN'T want to receive HTML
                    $posthtml = '';
                }
                $eventdata = new \core\message\message();
                $eventdata->courseid = SITEID;
                $eventdata->component = 'mod_forum';
                $eventdata->name = 'digests';
                $eventdata->userfrom = core_user::get_noreply_user();
                $eventdata->userto = $userto;
                $eventdata->subject = $postsubject;
                $eventdata->fullmessage = $posttext;
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml = $posthtml;
                $eventdata->notification = 1;
                $eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $sentcount);
                $mailresult = message_send($eventdata);
                if (!$mailresult) {
                    mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user {$userto->id} " . "({$userto->email})... not trying again.");
                } else {
                    mtrace("success.");
                    $usermailcount++;
                    // Mark post as read if forum_usermarksread is set off
                    if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
                        forum_tp_mark_posts_read($userto, $userto->markposts);
                    }
                }
            }
        }
        /// We have finishied all digest emails, update $CFG->digestmailtimelast
        set_config('digestmailtimelast', $timenow);
    }
    cron_setup_user();
    if (!empty($usermailcount)) {
        mtrace(get_string('digestsentusers', 'forum', $usermailcount));
    }
    if (!empty($CFG->forum_lastreadclean)) {
        $timenow = time();
        if ($CFG->forum_lastreadclean + 24 * 3600 < $timenow) {
            set_config('forum_lastreadclean', $timenow);
            mtrace('Removing old forum read tracking info...');
            forum_tp_clean_read_records();
        }
    } else {
        set_config('forum_lastreadclean', time());
    }
    return true;
}
コード例 #20
0
ファイル: lib.php プロジェクト: numbas/moodle
 /**
  * Send a message from one user to another using events_trigger
  *
  * @param object $touser
  * @param object $fromuser
  * @param string $name
  * @param string $subject
  * @param string $message
  */
 protected function notify($touser, $fromuser, $name = 'courserequested', $subject, $message)
 {
     $eventdata = new stdClass();
     $eventdata->component = 'moodle';
     $eventdata->name = $name;
     $eventdata->userfrom = $fromuser;
     $eventdata->userto = $touser;
     $eventdata->subject = $subject;
     $eventdata->fullmessage = $message;
     $eventdata->fullmessageformat = FORMAT_PLAIN;
     $eventdata->fullmessagehtml = '';
     $eventdata->smallmessage = '';
     $eventdata->notification = 1;
     message_send($eventdata);
 }
コード例 #21
0
 /**
  * Sends the given notifications to site admins via messaging API
  *
  * @param array $notifications array of available_update_info objects to send
  */
 protected function cron_notify(array $notifications)
 {
     global $CFG;
     if (empty($notifications)) {
         return;
     }
     $admins = get_admins();
     if (empty($admins)) {
         return;
     }
     $this->cron_mtrace('sending notifications ... ', '');
     $text = get_string('updatenotifications', 'core_admin') . PHP_EOL;
     $html = html_writer::tag('h1', get_string('updatenotifications', 'core_admin')) . PHP_EOL;
     $coreupdates = array();
     $pluginupdates = array();
     foreach ($notifications as $notification) {
         if ($notification->component == 'core') {
             $coreupdates[] = $notification;
         } else {
             $pluginupdates[] = $notification;
         }
     }
     if (!empty($coreupdates)) {
         $text .= PHP_EOL . get_string('updateavailable', 'core_admin') . PHP_EOL;
         $html .= html_writer::tag('h2', get_string('updateavailable', 'core_admin')) . PHP_EOL;
         $html .= html_writer::start_tag('ul') . PHP_EOL;
         foreach ($coreupdates as $coreupdate) {
             $html .= html_writer::start_tag('li');
             if (isset($coreupdate->release)) {
                 $text .= get_string('updateavailable_release', 'core_admin', $coreupdate->release);
                 $html .= html_writer::tag('strong', get_string('updateavailable_release', 'core_admin', $coreupdate->release));
             }
             if (isset($coreupdate->version)) {
                 $text .= ' ' . get_string('updateavailable_version', 'core_admin', $coreupdate->version);
                 $html .= ' ' . get_string('updateavailable_version', 'core_admin', $coreupdate->version);
             }
             if (isset($coreupdate->maturity)) {
                 $text .= ' (' . get_string('maturity' . $coreupdate->maturity, 'core_admin') . ')';
                 $html .= ' (' . get_string('maturity' . $coreupdate->maturity, 'core_admin') . ')';
             }
             $text .= PHP_EOL;
             $html .= html_writer::end_tag('li') . PHP_EOL;
         }
         $text .= PHP_EOL;
         $html .= html_writer::end_tag('ul') . PHP_EOL;
         $a = array('url' => $CFG->wwwroot . '/' . $CFG->admin . '/index.php');
         $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL;
         $a = array('url' => html_writer::link($CFG->wwwroot . '/' . $CFG->admin . '/index.php', $CFG->wwwroot . '/' . $CFG->admin . '/index.php'));
         $html .= html_writer::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL;
     }
     if (!empty($pluginupdates)) {
         $text .= PHP_EOL . get_string('updateavailableforplugin', 'core_admin') . PHP_EOL;
         $html .= html_writer::tag('h2', get_string('updateavailableforplugin', 'core_admin')) . PHP_EOL;
         $html .= html_writer::start_tag('ul') . PHP_EOL;
         foreach ($pluginupdates as $pluginupdate) {
             $html .= html_writer::start_tag('li');
             $text .= get_string('pluginname', $pluginupdate->component);
             $html .= html_writer::tag('strong', get_string('pluginname', $pluginupdate->component));
             $text .= ' (' . $pluginupdate->component . ')';
             $html .= ' (' . $pluginupdate->component . ')';
             $text .= ' ' . get_string('updateavailable', 'core_plugin', $pluginupdate->version);
             $html .= ' ' . get_string('updateavailable', 'core_plugin', $pluginupdate->version);
             $text .= PHP_EOL;
             $html .= html_writer::end_tag('li') . PHP_EOL;
         }
         $text .= PHP_EOL;
         $html .= html_writer::end_tag('ul') . PHP_EOL;
         $a = array('url' => $CFG->wwwroot . '/' . $CFG->admin . '/plugins.php');
         $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL;
         $a = array('url' => html_writer::link($CFG->wwwroot . '/' . $CFG->admin . '/plugins.php', $CFG->wwwroot . '/' . $CFG->admin . '/plugins.php'));
         $html .= html_writer::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL;
     }
     $a = array('siteurl' => $CFG->wwwroot);
     $text .= get_string('updatenotificationfooter', 'core_admin', $a) . PHP_EOL;
     $a = array('siteurl' => html_writer::link($CFG->wwwroot, $CFG->wwwroot));
     $html .= html_writer::tag('footer', html_writer::tag('p', get_string('updatenotificationfooter', 'core_admin', $a), array('style' => 'font-size:smaller; color:#333;')));
     foreach ($admins as $admin) {
         $message = new stdClass();
         $message->component = 'moodle';
         $message->name = 'availableupdate';
         $message->userfrom = get_admin();
         $message->userto = $admin;
         $message->subject = get_string('updatenotificationsubject', 'core_admin', array('siteurl' => $CFG->wwwroot));
         $message->fullmessage = $text;
         $message->fullmessageformat = FORMAT_PLAIN;
         $message->fullmessagehtml = $html;
         $message->smallmessage = get_string('updatenotifications', 'core_admin');
         $message->notification = 1;
         message_send($message);
     }
 }
コード例 #22
0
function reservasalas_sendMail($values, $error, $user, $asistentes, $eventname, $buildingid)
{
    global $USER, $DB;
    $userfrom = core_user::get_noreply_user();
    $userfrom->maildisplay = true;
    $sql = "SELECT s.nombre as sedenombre, e.nombre as edificionombre\n\t\t\tFROM {reservasalas_edificios} AS e JOIN {reservasalas_sedes} AS s ON (e.sedes_id = s.id)\n\t\t\tWHERE s.id = ?";
    $names = $DB->get_record_sql($sql, array($buildingid));
    $message = get_string("dear", "local_reservasalas") . $USER->firstname . " " . $USER->lastname . ": \n \n";
    $message .= get_string("bookinginformation", "local_reservasalas") . "\n \n";
    $message .= get_string("site", "local_reservasalas") . ": " . $names->sedenombre . "\n";
    $message .= get_string("buildings", "local_reservasalas") . ": " . $names->edificionombre . "\n";
    $message .= get_string("roomtype", "local_reservasalas") . ": Estudio \n";
    $message .= get_string("event", "local_reservasalas") . ": " . $eventname . "\n";
    $message .= get_string("assistants", "local_reservasalas") . ": " . $asistentes . "\n";
    $message .= get_string("responsibility", "local_reservasalas") . ": " . $USER->firstname . " " . $USER->lastname . "\n";
    $message .= get_string("rooms", "local_reservasalas") . ": \n";
    foreach ($values as $value) {
        $stamp = strtotime($value["fecha"]);
        $day = date("l", $stamp);
        $message .= get_string("date", "local_reservasalas") . ": " . $day . " " . $value["fecha"] . " - " . get_string("room", "local_reservasalas") . ": " . $value["nombresala"] . " - " . get_string("module", "local_reservasalas") . ": " . $value["nombremodulo"] . "\n";
    }
    // Format each "\n" into a line break
    $formattedMessage = nl2br($message);
    $eventdata = new stdClass();
    $eventdata->component = "local_reservasalas";
    // your component name
    $eventdata->name = "reservenotification";
    // this is the message name from messages.php
    $eventdata->userfrom = $userfrom;
    $eventdata->userto = $user;
    $eventdata->subject = get_string("confirmationbooking", "local_reservasalas");
    $eventdata->fullmessage = format_text_email($formattedMessage, FORMAT_HTML);
    $eventdata->fullmessageformat = FORMAT_HTML;
    $eventdata->fullmessagehtml = "";
    $eventdata->smallmessage = "";
    $eventdata->notification = 1;
    // this is only set to 0 for personal messages between users
    message_send($eventdata);
}
コード例 #23
0
ファイル: lib.php プロジェクト: nuckey/moodle
    /**
     * Alerts teachers by email of new or changed assignments that need grading
     *
     * First checks whether the option to email teachers is set for this assignment.
     * Sends an email to ALL teachers in the course (or in the group if using separate groups).
     * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
     *
     * @global object
     * @global object
     * @param $submission object The submission that has changed
     * @return void
     */
    function email_teachers($submission) {
        global $CFG, $DB;

        if (empty($this->assignment->emailteachers)) {          // No need to do anything
            return;
        }

        $user = $DB->get_record('user', array('id'=>$submission->userid));

        if ($teachers = $this->get_graders($user)) {

            $strassignments = get_string('modulenameplural', 'assignment');
            $strassignment  = get_string('modulename', 'assignment');
            $strsubmitted  = get_string('submitted', 'assignment');

            foreach ($teachers as $teacher) {
                $info = new stdClass();
                $info->username = fullname($user, true);
                $info->assignment = format_string($this->assignment->name,true);
                $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
                $info->timeupdated = strftime('%c',$submission->timemodified);

                $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
                $posttext = $this->email_teachers_text($info);
                $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';

                $eventdata = new stdClass();
                $eventdata->modulename       = 'assignment';
                $eventdata->userfrom         = $user;
                $eventdata->userto           = $teacher;
                $eventdata->subject          = $postsubject;
                $eventdata->fullmessage      = $posttext;
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml  = $posthtml;
                $eventdata->smallmessage     = '';

                $eventdata->name            = 'assignment_updates';
                $eventdata->component       = 'mod_assignment';
                $eventdata->notification    = 1;
                $eventdata->contexturl      = $info->url;
                $eventdata->contexturlname  = $info->assignment;
                
                message_send($eventdata);
            }
        }
    }
コード例 #24
0
ファイル: querylib.php プロジェクト: eduagdo/reservasalas
function send_mail($values, $error, $user, $asistentes, $eventname, $campusId)
{
    global $USER, $DB;
    $userfrom = core_user::get_noreply_user();
    $userfrom->maildisplay = true;
    $sql = "SELECT e.nombre AS edificio, \n\t\t\ts.nombre AS sede\n\t\t\tFROM {reservasalas_edificios} AS e, \n\t\t\t{reservasalas_sedes} AS s \n\t\t\tWHERE e.sedes_id=s.id\n\t\t\tAND e.id=?";
    $campus = $DB->get_record_sql($sql, array($campusId));
    $message = get_string('dear', 'local_reservasalas') . $USER->firstname . ' ' . $USER->lastname . ': ';
    $message .= '<br></br>';
    $message .= '<br></br>';
    $message .= get_string('bookinginformation', 'local_reservasalas');
    $message .= '<br></br>';
    $message .= '<br></br>';
    $message .= get_string('site', 'local_reservasalas') . ': ' . $campus->sede;
    $message .= '<br></br>';
    $message .= get_string('buildings', 'local_reservasalas') . ': ' . $campus->edificio;
    $message .= '<br></br>';
    $message .= get_string('roomtype', 'local_reservasalas') . ': Estudio';
    $message .= '<br></br>';
    $message .= get_string('event', 'local_reservasalas') . ': ' . $eventname;
    $message .= '<br></br>';
    $message .= get_string('assistants', 'local_reservasalas') . ': ' . $asistentes;
    $message .= '<br></br>';
    $message .= get_string('responsibility', 'local_reservasalas') . ': ' . $USER->firstname . ' ' . $USER->lastname;
    $message .= '<br></br>';
    $message .= get_string('rooms', 'local_reservasalas') . ': ';
    $message .= '<br></br>';
    foreach ($values as $value) {
        $stamp = strtotime($value["fecha"]);
        $day = date("l", $stamp);
        $message .= get_string('date', 'local_reservasalas') . ': ' . $day . ' ' . $value["fecha"] . ' - ' . get_string('room', 'local_reservasalas') . ': ' . $value['nombresala'] . ' - ' . get_string('module', 'local_reservasalas') . ': ' . $value['nombremodulo'];
        $message .= '<br></br>';
    }
    $eventdata = new stdClass();
    $eventdata->component = 'local_reservasalas';
    // your component name
    $eventdata->name = 'reservenotification';
    // this is the message name from messages.php
    $eventdata->userfrom = $userfrom;
    $eventdata->userto = $user;
    $eventdata->subject = get_string('confirmationbooking', 'local_reservasalas');
    $eventdata->fullmessage = format_text_email($message, FORMAT_HTML);
    $eventdata->fullmessageformat = FORMAT_HTML;
    $eventdata->fullmessagehtml = '';
    $eventdata->smallmessage = '';
    $eventdata->notification = 1;
    // this is only set to 0 for personal messages between users
    message_send($eventdata);
}
コード例 #25
0
ファイル: locallib.php プロジェクト: covex-nn/moodle
 /**
  * Message someone about something (static so it can be called from cron).
  *
  * @param stdClass $userfrom
  * @param stdClass $userto
  * @param string $messagetype
  * @param string $eventtype
  * @param int $updatetime
  * @param stdClass $coursemodule
  * @param stdClass $context
  * @param stdClass $course
  * @param string $modulename
  * @param string $assignmentname
  * @param bool $blindmarking
  * @param int $uniqueidforuser
  * @return void
  */
 public static function send_assignment_notification($userfrom, $userto, $messagetype, $eventtype, $updatetime, $coursemodule, $context, $course, $modulename, $assignmentname, $blindmarking, $uniqueidforuser)
 {
     global $CFG;
     $info = new stdClass();
     if ($blindmarking) {
         $info->username = get_string('participant', 'assign') . ' ' . $uniqueidforuser;
         $userfrom->firstname = get_string('participant', 'assign');
         $userfrom->lastname = $uniqueidforuser;
         $userfrom->email = $CFG->noreplyaddress;
     } else {
         $info->username = fullname($userfrom, true);
     }
     $info->assignment = format_string($assignmentname, true, array('context' => $context));
     $info->url = $CFG->wwwroot . '/mod/assign/view.php?id=' . $coursemodule->id;
     $info->timeupdated = userdate($updatetime, get_string('strftimerecentfull'));
     $postsubject = get_string($messagetype . 'small', 'assign', $info);
     $posttext = self::format_notification_message_text($messagetype, $info, $course, $context, $modulename, $assignmentname);
     $posthtml = '';
     if ($userto->mailformat == 1) {
         $posthtml = self::format_notification_message_html($messagetype, $info, $course, $context, $modulename, $coursemodule, $assignmentname);
     }
     $eventdata = new stdClass();
     $eventdata->modulename = 'assign';
     $eventdata->userfrom = $userfrom;
     $eventdata->userto = $userto;
     $eventdata->subject = $postsubject;
     $eventdata->fullmessage = $posttext;
     $eventdata->fullmessageformat = FORMAT_PLAIN;
     $eventdata->fullmessagehtml = $posthtml;
     $eventdata->smallmessage = $postsubject;
     $eventdata->name = $eventtype;
     $eventdata->component = 'mod_assign';
     $eventdata->notification = 1;
     $eventdata->contexturl = $info->url;
     $eventdata->contexturlname = $info->assignment;
     message_send($eventdata);
 }
コード例 #26
0
 /**
  * Runs the automated backups if required
  *
  * @global moodle_database $DB
  */
 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE)
 {
     global $CFG, $DB;
     $status = true;
     $emailpending = false;
     $now = time();
     mtrace("Checking automated backup status", '...');
     $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
     if ($state === backup_cron_automated_helper::STATE_DISABLED) {
         mtrace('INACTIVE');
         return $state;
     } else {
         if ($state === backup_cron_automated_helper::STATE_RUNNING) {
             mtrace('RUNNING');
             if ($rundirective == self::RUN_IMMEDIATELY) {
                 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
             } else {
                 mtrace("automated backup are already running. Execution delayed");
             }
             return $state;
         } else {
             mtrace('OK');
         }
     }
     backup_cron_automated_helper::set_state_running();
     mtrace("Getting admin info");
     $admin = get_admin();
     if (!$admin) {
         mtrace("Error: No admin account was found");
         $state = false;
     }
     if ($status) {
         mtrace("Checking courses");
         mtrace("Skipping deleted courses", '...');
         mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
     }
     if ($status) {
         mtrace('Running required automated backups...');
         // This could take a while!
         @set_time_limit(0);
         raise_memory_limit(MEMORY_EXTRA);
         $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
         $showtime = "undefined";
         if ($nextstarttime > 0) {
             $showtime = userdate($nextstarttime, "", $admin->timezone);
         }
         $rs = $DB->get_recordset('course');
         foreach ($rs as $course) {
             $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             if (!$backupcourse) {
                 $backupcourse = new stdClass();
                 $backupcourse->courseid = $course->id;
                 $DB->insert_record('backup_courses', $backupcourse);
                 $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             }
             // Skip courses that do not yet need backup
             $skipped = !($backupcourse->nextstarttime >= 0 && $backupcourse->nextstarttime < $now || $rundirective == self::RUN_IMMEDIATELY);
             // Skip backup of unavailable courses that have remained unmodified in a month
             if (!$skipped && empty($course->visible) && $now - $course->timemodified > 31 * 24 * 60 * 60) {
                 //Hidden + settings were unmodified last month
                 //Check log if there were any modifications to the course content
                 $sqlwhere = "course=:courseid AND time>:time AND " . $DB->sql_like('action', ':action', false, true, true);
                 $params = array('courseid' => $course->id, 'time' => $now - 31 * 24 * 60 * 60, 'action' => '%view%');
                 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
                 if (!$logexists) {
                     $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_SKIPPED;
                     $backupcourse->nextstarttime = $nextstarttime;
                     $DB->update_record('backup_courses', $backupcourse);
                     mtrace('Skipping unchanged course ' . $course->fullname);
                     $skipped = true;
                 }
             }
             //Now we backup every non-skipped course
             if (!$skipped) {
                 mtrace('Backing up ' . $course->fullname, '...');
                 //We have to send a email because we have included at least one backup
                 $emailpending = true;
                 //Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error)
                 if ($backupcourse->laststatus != 2) {
                     //Set laststarttime
                     $starttime = time();
                     $backupcourse->laststarttime = time();
                     $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED;
                     $DB->update_record('backup_courses', $backupcourse);
                     $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
                     $backupcourse->lastendtime = time();
                     $backupcourse->nextstarttime = $nextstarttime;
                     $DB->update_record('backup_courses', $backupcourse);
                     if ($backupcourse->laststatus) {
                         // Clean up any excess course backups now that we have
                         // taken a successful backup.
                         $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
                     }
                 }
                 mtrace("complete - next execution: {$showtime}");
             }
         }
         $rs->close();
     }
     //Send email to admin if necessary
     if ($emailpending) {
         mtrace("Sending email to admin");
         $message = "";
         $count = backup_cron_automated_helper::get_backup_status_array();
         $haserrors = $count[backup_cron_automated_helper::BACKUP_STATUS_ERROR] != 0 || $count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED] != 0;
         //Build the message text
         //Summary
         $message .= get_string('summary') . "\n";
         $message .= "==================================================\n";
         $message .= "  " . get_string('courses') . ": " . array_sum($count) . "\n";
         $message .= "  " . get_string('ok') . ": " . $count[backup_cron_automated_helper::BACKUP_STATUS_OK] . "\n";
         $message .= "  " . get_string('skipped') . ": " . $count[backup_cron_automated_helper::BACKUP_STATUS_SKIPPED] . "\n";
         $message .= "  " . get_string('error') . ": " . $count[backup_cron_automated_helper::BACKUP_STATUS_ERROR] . "\n";
         $message .= "  " . get_string('unfinished') . ": " . $count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED] . "\n\n";
         //Reference
         if ($haserrors) {
             $message .= "  " . get_string('backupfailed') . "\n\n";
             $dest_url = "{$CFG->wwwroot}/report/backups/index.php";
             $message .= "  " . get_string('backuptakealook', '', $dest_url) . "\n\n";
             //Set message priority
             $admin->priority = 1;
             //Reset unfinished to error
             $DB->set_field('backup_courses', 'laststatus', '0', array('laststatus' => '2'));
         } else {
             $message .= "  " . get_string('backupfinished') . "\n";
         }
         //Build the message subject
         $site = get_site();
         $prefix = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))) . ": ";
         if ($haserrors) {
             $prefix .= "[" . strtoupper(get_string('error')) . "] ";
         }
         $subject = $prefix . get_string('automatedbackupstatus', 'backup');
         //Send the message
         $eventdata = new stdClass();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $admin;
         $eventdata->userto = $admin;
         $eventdata->subject = $subject;
         $eventdata->fullmessage = $message;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         $eventdata->component = 'moodle';
         $eventdata->name = 'backup';
         message_send($eventdata);
     }
     //Everything is finished stop backup_auto_running
     backup_cron_automated_helper::set_state_running(false);
     mtrace('Automated backups complete.');
     return $status;
 }
コード例 #27
0
ファイル: index.php プロジェクト: esyacelga/sisadmaca
    $supportuser->lastname = $CFG->supportname ? '' : $admin->lastname;
    //emailstop could be hard coded "false" to ensure error reports are sent
    //but then admin's would have to alter their messaging preferences to temporarily stop them
    $supportuser->emailstop = $admin->emailstop;
    $supportuser->maildisplay = true;
    /// Send the message and redirect
    $eventdata = new stdClass();
    $eventdata->modulename = 'moodle';
    $eventdata->userfrom = $USER;
    $eventdata->userto = $supportuser;
    $eventdata->subject = 'Error: ' . $form->referer . ' -> ' . $form->requested;
    $eventdata->fullmessage = $form->text;
    $eventdata->fullmessageformat = FORMAT_PLAIN;
    $eventdata->fullmessagehtml = '';
    $eventdata->smallmessage = '';
    message_send($eventdata);
    redirect($CFG->wwwroot . '/course/', 'Message sent, thanks', 3);
    exit;
}
$site = get_site();
$redirecturl = empty($_SERVER['REDIRECT_URL']) ? '' : $_SERVER['REDIRECT_URL'];
$httpreferer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER'];
$requesturi = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
header("HTTP/1.0 404 Not Found");
header("Status: 404 Not Found");
$PAGE->set_url('/error/');
$PAGE->set_title($site->fullname . ':Error');
$PAGE->set_heading($site->fullname . ': Error 404');
$PAGE->set_context(get_system_context());
$PAGE->navbar->add('Error 404 - File not Found');
echo $OUTPUT->header();
コード例 #28
0
function organizer_send_message($sender, $receiver, $slot, $type, $digest = null, $customdata = array())
{
    global $DB;
    if ($type == 'register_reminder:student') {
        $organizer = $slot;
    } else {
        $organizer = $DB->get_record('organizer', array('id' => $slot->organizerid));
    }
    $sender = is_int($sender) ? $DB->get_record('user', array('id' => $sender)) : $sender;
    $receiver = is_int($receiver) ? $DB->get_record('user', array('id' => $receiver)) : $receiver;
    $module = $DB->get_record('modules', array('name' => 'organizer'));
    $cm = $DB->get_record('course_modules', array('module' => $module->id, 'instance' => $organizer->id));
    $course = $DB->get_record('course', array('id' => $cm->course));
    $context = context_course::instance($cm->course);
    $roles = get_user_roles($context, $receiver->id);
    $now = time();
    if (!$cm->visible || $cm->availablefrom && $cm->availablefrom > $now || $cm->availableuntil && $cm->availableuntil < $now || count($roles) == 0) {
        return false;
    }
    $namesplit = explode(':', $type);
    $strings = new stdClass();
    $strings->sendername = fullname($sender);
    $strings->receivername = fullname($receiver);
    if ($type != 'register_reminder:student') {
        $strings->date = userdate($slot->starttime, get_string('datetemplate', 'organizer'));
        $strings->time = userdate($slot->starttime, get_string('timetemplate', 'organizer'));
        $strings->location = $slot->location;
    }
    $strings->organizername = $organizer->name;
    $strings->coursefullname = $course->fullname;
    $strings->courseshortname = $course->shortname;
    $strings->courseid = $course->idnumber == "" ? "" : $course->idnumber . ' ';
    if ($namesplit[0] == "edit_notify") {
        $strings->slot_teacher = $slot->teachervisible == 1 ? fullname($DB->get_record('user', array('id' => $slot->teacherid))) : get_string('teacherinvisible', 'organizer');
        $strings->slot_location = organizer_location_link($slot);
        $strings->slot_maxparticipants = $slot->maxparticipants;
        $strings->slot_comments = $slot->comments;
    }
    $courseurl = new moodle_url('/mod/organizer/view.php', array('id' => $cm->id));
    $strings->courselink = html_writer::link($courseurl, $course->fullname);
    if ($organizer->isgrouporganizer) {
        if (strpos($type, 'register_notify') !== false || strpos($type, 'group_registration_notify') !== false) {
            $group = groups_get_user_groups($organizer->course, $sender->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        } else {
            $group = groups_get_user_groups($organizer->course, $receiver->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        }
        $strings->groupname = $group->name;
        $type .= ":group";
    }
    if ($namesplit[0] == "eval_notify_newappointment") {
        $namesplit[0] = "eval_notify";
    }
    $message = new stdClass();
    $message->modulename = 'organizer';
    $message->component = 'mod_organizer';
    $message->name = "{$namesplit['0']}:{$namesplit['1']}";
    $message->notification = 1;
    $message->fullmessageformat = FORMAT_PLAIN;
    $message->userfrom = $sender;
    $message->userto = $receiver;
    if (isset($digest)) {
        $strings->digest = $digest;
        $type .= ":digest";
    }
    $message->subject = get_string("{$type}:subject", 'organizer', $strings);
    $message->message = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessage = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessagehtml = organizer_make_html(get_string("{$type}:fullmessage", 'organizer', $strings), $organizer, $cm, $course);
    if (isset($customdata['custommessage'])) {
        $message->fullmessage = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessage);
        $message->fullmessagehtml = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessagehtml);
    }
    $message->smallmessage = get_string("{$type}:smallmessage", 'organizer', $strings);
    if (ORGANIZER_ENABLE_MESSAGING) {
        return message_send($message);
    } else {
        return false;
    }
}
コード例 #29
0
 /**
  * Runs the automated backups if required
  *
  * @global moodle_database $DB
  */
 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE)
 {
     global $CFG, $DB;
     $status = true;
     $emailpending = false;
     $now = time();
     $config = get_config('backup');
     mtrace("Checking automated backup status", '...');
     $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
     if ($state === backup_cron_automated_helper::STATE_DISABLED) {
         mtrace('INACTIVE');
         return $state;
     } else {
         if ($state === backup_cron_automated_helper::STATE_RUNNING) {
             mtrace('RUNNING');
             if ($rundirective == self::RUN_IMMEDIATELY) {
                 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
             } else {
                 mtrace("automated backup are already running. Execution delayed");
             }
             return $state;
         } else {
             mtrace('OK');
         }
     }
     backup_cron_automated_helper::set_state_running();
     mtrace("Getting admin info");
     $admin = get_admin();
     if (!$admin) {
         mtrace("Error: No admin account was found");
         $state = false;
     }
     if ($status) {
         mtrace("Checking courses");
         mtrace("Skipping deleted courses", '...');
         mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
     }
     if ($status) {
         mtrace('Running required automated backups...');
         cron_trace_time_and_memory();
         // This could take a while!
         core_php_time_limit::raise();
         raise_memory_limit(MEMORY_EXTRA);
         $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
         $showtime = "undefined";
         if ($nextstarttime > 0) {
             $showtime = date('r', $nextstarttime);
         }
         $rs = $DB->get_recordset('course');
         foreach ($rs as $course) {
             $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             if (!$backupcourse) {
                 $backupcourse = new stdClass();
                 $backupcourse->courseid = $course->id;
                 $backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
                 $DB->insert_record('backup_courses', $backupcourse);
                 $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
             }
             // The last backup is considered as successful when OK or SKIPPED.
             $lastbackupwassuccessful = ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED || $backupcourse->laststatus == self::BACKUP_STATUS_OK) && ($backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);
             // Assume that we are not skipping anything.
             $skipped = false;
             $skippedmessage = '';
             // Check if we are going to be running the backup now.
             $shouldrunnow = $backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now || $rundirective == self::RUN_IMMEDIATELY;
             // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
             if ($shouldrunnow && $config->backup_auto_skip_hidden) {
                 $skipped = $config->backup_auto_skip_hidden && !$course->visible;
                 $skippedmessage = 'Not visible';
             }
             // If config backup_auto_skip_modif_days is set to true, skip courses
             // that have not been modified since the number of days defined.
             if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
                 $timenotmodifsincedays = $now - $config->backup_auto_skip_modif_days * DAYSECS;
                 // Check log if there were any modifications to the course content.
                 $logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
                 $skipped = $course->timemodified <= $timenotmodifsincedays && !$logexists;
                 $skippedmessage = 'Not modified in the past ' . $config->backup_auto_skip_modif_days . ' days';
             }
             // If config backup_auto_skip_modif_prev is set to true, skip courses
             // that have not been modified since previous backup.
             if ($shouldrunnow && !$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
                 // Check log if there were any modifications to the course content.
                 $logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
                 $skipped = $course->timemodified <= $backupcourse->laststarttime && !$logexists;
                 $skippedmessage = 'Not modified since previous backup';
             }
             // Check if the course is not scheduled to run right now.
             if (!$shouldrunnow) {
                 $backupcourse->nextstarttime = $nextstarttime;
                 $DB->update_record('backup_courses', $backupcourse);
                 mtrace('Skipping ' . $course->fullname . ' (Not scheduled for backup until ' . $showtime . ')');
             } else {
                 if ($skipped) {
                     // Must have been skipped for a reason.
                     $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
                     $backupcourse->nextstarttime = $nextstarttime;
                     $DB->update_record('backup_courses', $backupcourse);
                     mtrace('Skipping ' . $course->fullname . ' (' . $skippedmessage . ')');
                     mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
                 } else {
                     // Backup every non-skipped courses.
                     mtrace('Backing up ' . $course->fullname . '...');
                     // We have to send an email because we have included at least one backup.
                     $emailpending = true;
                     // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error).
                     if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
                         // Set laststarttime.
                         $starttime = time();
                         $backupcourse->laststarttime = time();
                         $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
                         $DB->update_record('backup_courses', $backupcourse);
                         $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
                         $backupcourse->lastendtime = time();
                         $backupcourse->nextstarttime = $nextstarttime;
                         $DB->update_record('backup_courses', $backupcourse);
                         if ($backupcourse->laststatus === self::BACKUP_STATUS_OK) {
                             // Clean up any excess course backups now that we have
                             // taken a successful backup.
                             $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
                         }
                     }
                     mtrace("complete - next execution: {$showtime}");
                 }
             }
         }
         $rs->close();
     }
     //Send email to admin if necessary
     if ($emailpending) {
         mtrace("Sending email to admin");
         $message = "";
         $count = backup_cron_automated_helper::get_backup_status_array();
         $haserrors = $count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0;
         // Build the message text.
         // Summary.
         $message .= get_string('summary') . "\n";
         $message .= "==================================================\n";
         $message .= '  ' . get_string('courses') . '; ' . array_sum($count) . "\n";
         $message .= '  ' . get_string('ok') . '; ' . $count[self::BACKUP_STATUS_OK] . "\n";
         $message .= '  ' . get_string('skipped') . '; ' . $count[self::BACKUP_STATUS_SKIPPED] . "\n";
         $message .= '  ' . get_string('error') . '; ' . $count[self::BACKUP_STATUS_ERROR] . "\n";
         $message .= '  ' . get_string('unfinished') . '; ' . $count[self::BACKUP_STATUS_UNFINISHED] . "\n";
         $message .= '  ' . get_string('warning') . '; ' . $count[self::BACKUP_STATUS_WARNING] . "\n";
         $message .= '  ' . get_string('backupnotyetrun') . '; ' . $count[self::BACKUP_STATUS_NOTYETRUN] . "\n\n";
         //Reference
         if ($haserrors) {
             $message .= "  " . get_string('backupfailed') . "\n\n";
             $dest_url = "{$CFG->wwwroot}/report/backups/index.php";
             $message .= "  " . get_string('backuptakealook', '', $dest_url) . "\n\n";
             //Set message priority
             $admin->priority = 1;
             //Reset unfinished to error
             $DB->set_field('backup_courses', 'laststatus', '0', array('laststatus' => '2'));
         } else {
             $message .= "  " . get_string('backupfinished') . "\n";
         }
         //Build the message subject
         $site = get_site();
         $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))) . ": ";
         if ($haserrors) {
             $prefix .= "[" . strtoupper(get_string('error')) . "] ";
         }
         $subject = $prefix . get_string('automatedbackupstatus', 'backup');
         //Send the message
         $eventdata = new stdClass();
         $eventdata->modulename = 'moodle';
         $eventdata->userfrom = $admin;
         $eventdata->userto = $admin;
         $eventdata->subject = $subject;
         $eventdata->fullmessage = $message;
         $eventdata->fullmessageformat = FORMAT_PLAIN;
         $eventdata->fullmessagehtml = '';
         $eventdata->smallmessage = '';
         $eventdata->component = 'moodle';
         $eventdata->name = 'backup';
         message_send($eventdata);
     }
     //Everything is finished stop backup_auto_running
     backup_cron_automated_helper::set_state_running(false);
     mtrace('Automated backups complete.');
     return $status;
 }
コード例 #30
0
ファイル: lib.php プロジェクト: nickbert77/moodle
/**
 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
 *
 * @param object $userfrom the message sender
 * @param object $userto the message recipient
 * @param string $message the message
 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
 * @return int|false the ID of the new message or false
 */
function message_post_message($userfrom, $userto, $message, $format) {
    global $SITE, $CFG, $USER;

    $eventdata = new stdClass();
    $eventdata->component        = 'moodle';
    $eventdata->name             = 'instantmessage';
    $eventdata->userfrom         = $userfrom;
    $eventdata->userto           = $userto;

    //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
    $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);

    if ($format == FORMAT_HTML) {
        $eventdata->fullmessagehtml  = $message;
        //some message processors may revert to sending plain text even if html is supplied
        //so we keep both plain and html versions if we're intending to send html
        $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
    } else {
        $eventdata->fullmessage      = $message;
        $eventdata->fullmessagehtml  = '';
    }

    $eventdata->fullmessageformat = $format;
    $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.

    $s = new stdClass();
    $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
    $s->url = $CFG->wwwroot.'/message/index.php?user='******'&id='.$userfrom->id;

    $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
    if (!empty($eventdata->fullmessage)) {
        $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
    }
    if (!empty($eventdata->fullmessagehtml)) {
        $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
    }

    $eventdata->timecreated     = time();
    $eventdata->notification    = 0;
    return message_send($eventdata);
}