/**
 * Helper function for sending notification mails
 *
 * @param string $message The message
 * @param int $level Notification level
 * @return
 */
function local_sandbox_inform_admin($message, $level = SANDBOX_LEVEL_NOTICE)
{
    // Get recipients
    $recipients = get_users_from_config(get_config('local_sandbox', 'notifyonerrors'), 'moodle/site:config');
    // If there are no recipients, don't execute.
    if (!is_array($recipients) || count($recipients) <= 0) {
        return false;
    }
    // If message level is below configured notice level, don't execute
    if ($level < get_config('local_sandbox', 'notifylevel')) {
        return false;
    }
    // Get subject
    if ($level > SANDBOX_LEVEL_WARNING) {
        $subject = get_string('emailsubjecterror', 'local_sandbox');
    } else {
        if ($level > SANDBOX_LEVEL_NOTICE) {
            $subject = get_string('emailsubjectwarning', 'local_sandbox');
        } else {
            $subject = get_string('emailsubjectnotice', 'local_sandbox');
        }
    }
    // Send mail
    foreach ($recipients as $r) {
        // Email the admin directly rather than putting these through the messaging system
        email_to_user($r, core_user::get_support_user(), $subject, $message);
    }
}
Exemple #2
0
 public function send($users = null)
 {
     $this->startTime = time();
     $users = empty($users) ? $this->users : $users;
     $noreplyUser = new stdClass();
     $noreplyUser->firstname = 'Moodle';
     $noreplyUser->lastname = 'Administrator';
     $noreplyUser->username = '******';
     $noreplyUser->email = $this->noreply;
     $noreplyUser->maildisplay = 2;
     $noreplyUser->alternatename = "";
     $noreplyUser->firstnamephonetic = "";
     $noreplyUser->lastnamephonetic = "";
     $noreplyUser->middlename = "";
     if (empty($users)) {
         $this->warnings[] = get_string('no_users', 'block_quickmail');
     }
     foreach ($users as $user) {
         $success = email_to_user($user, $noreplyUser, $this->subject, $this->text, $this->html, '', '', true, $this->noreply, get_string('pluginname', 'block_quickmail'));
         if (!$success) {
             $this->warnings[] = get_string('email_error', 'block_quickmail', $user);
             $this->failuserids[] = $user->id;
         } else {
             $this->sentUsers[] = $user->username;
         }
     }
     $this->endTime = time();
     return $this->failuserids;
 }
function send_email_sessiondeleted($webinar, $session_info)
{
    global $CFG;
    foreach ($session_info->sessiondates as $dates) {
        $startdatetime = date('d F Y', $dates->timestart) . " at " . date('h:i A', $dates->timestart);
    }
    if ($attendees = webinar_get_attendees($session_info->id)) {
        foreach ($attendees as $user) {
            $a = new stdClass();
            $a->name = $user->firstname . " " . $user->lastname;
            $a->starttime = $startdatetime;
            $a->webinarname = $webinar->name;
            $a->webinarintro = $webinar->description;
            $a->webinaragenda = $webinar->agenda;
            $a->adminemail = $webinar->adminemail;
            //print_r($a);
            $subject = get_string('sessiondeletedsubject', 'webinar', $a);
            $contact = get_string('sessiondeletedcontact', 'webinar', $a);
            $message = get_string('sessiondeletedmessage', 'webinar', $a);
            //last task - strip <p> and </p> from the message before we send the email
            $message = str_replace('<p>', '', $message);
            $message = str_replace('</p>', '', $message);
            email_to_user($user, $contact, $subject, $message);
        }
    }
}
Exemple #4
0
/**
 *
 * Sends message to administrator listing all updated
 * duplicate custom fields
 * @param array $data
 */
function facetoface_send_admin_upgrade_msg($data)
{
    global $SITE;
    // No data - no need to send email.
    if (empty($data)) {
        return;
    }
    $table = new html_table();
    $table->head = array('Custom field ID', 'Custom field original shortname', 'Custom field new shortname');
    $table->data = $data;
    $table->align = array('center', 'center', 'center');
    $title = "{$SITE->fullname}: Face to Face upgrade info";
    $note = 'During the last site upgrade the face-to-face module has been modified. It now
requires session custom fields to have unique shortnames. Since some of your
custom fields had duplicate shortnames, they have been renamed to remove
duplicates (see table below). This could impact on your email messages if you
reference those custom fields in the message templates.';
    $message = html_writer::start_tag('html');
    $message .= html_writer::start_tag('head') . html_writer::tag('title', $title) . html_writer::end_tag('head');
    $message .= html_writer::start_tag('body');
    $message .= html_writer::tag('p', $note) . html_writer::table($table, true);
    $message .= html_writer::end_tag('body');
    $message .= html_writer::end_tag('html');
    $admin = get_admin();
    email_to_user($admin, $admin, $title, '', $message);
}
    /**
     * Processes the message (sends by email).
     * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
     */
    function send_message($eventdata) {
        global $CFG;

        if (!empty($CFG->noemailever)) {
            // hidden setting for development sites, set in config.php if needed
            debugging('$CFG->noemailever active, no email message sent.', DEBUG_MINIMAL);
            return true;
        }

        //the user the email is going to
        $recipient = null;

        //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
        $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
        if (!empty($emailmessagingpreference)) {
            //clone to avoid altering the actual user object
            $recipient = clone($eventdata->userto);
            $recipient->email = $emailmessagingpreference;
        } else {
            $recipient = $eventdata->userto;
        }
        $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml);

        return $result;
    }
    /**
     * Processes the message (sends by email).
     * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
     */
    function send_message($eventdata) {
        global $CFG;

        if (!empty($CFG->noemailever)) {
            // hidden setting for development sites, set in config.php if needed
            debugging('$CFG->noemailever active, no email message sent.', DEBUG_MINIMAL);
            return true;
        }

        //hold onto email preference because /admin/cron.php sends a lot of messages at once
        static $useremailaddresses = array();

        //check user preference for where user wants email sent
        if (!array_key_exists($eventdata->userto->id, $useremailaddresses)) {
            $useremailaddresses[$eventdata->userto->id] = get_user_preferences('message_processor_email_email', $eventdata->userto->email, $eventdata->userto->id);
        }
        $usertoemailaddress = $useremailaddresses[$eventdata->userto->id];

        if ( !empty($usertoemailaddress)) {
            $userto->email = $usertoemailaddress;
        }

        $result = email_to_user($eventdata->userto, $eventdata->userfrom,
            $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml);

        return $result;
    }
 /**
  * Processes the message (sends by email).
  * @param object $message the message to be sent
  */
 function send_message($message)
 {
     //send an email
     //if fails saved as read message
     //first try to get preference
     $usertoemail = get_user_preferences('message_processor_email_email', '', $message->useridto);
     //if fails use user profile default
     if ($usertoemail == NULL) {
         $userto = get_record('user', 'id', $message->useridto);
         $usertoemail = $userto->email;
     }
     $userfrom = get_record('user', 'id', $message->useridfrom);
     if (email_to_user($usertoemail, $userfrom->email, $message->subject, $message->fullmessage, $message->fullmessagehtml)) {
         /// Move the entry to the other table
         $message->timeread = time();
         $messageid = $message->id;
         unset($message->id);
         //if there is no more processor that want to process this can move message
         if (count_records('message_working', array('unreadmessageid' => $messageid)) == 0) {
             if (insert_record('message_read', $message)) {
                 delete_records('message', 'id', $messageid);
             }
         }
     } else {
         //delete what we've processed and check if can move message
         if (count_records('message_working', 'unreadmessageid', $messageid) == 0) {
             if (insert_record('message_read', $message)) {
                 delete_records('message', 'id', $messageid);
             }
         }
     }
     return true;
 }
    /**
     * Processes the message (sends by email).
     * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
     */
    function send_message($eventdata) {
        global $CFG;

        if (!empty($CFG->noemailever)) {
            // hidden setting for development sites, set in config.php if needed
            debugging('$CFG->noemailever active, no email message sent.', DEBUG_MINIMAL);
            return true;
        }

        // skip any messaging suspended and deleted users
        if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
            return true;
        }

        //the user the email is going to
        $recipient = null;

        //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
        $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
        $emailmessagingpreference = clean_param($emailmessagingpreference, PARAM_EMAIL);

        // If the recipient has set an email address in their preferences use that instead of the one in their profile
        // but only if overriding the notification email address is allowed
        if (!empty($emailmessagingpreference) && !empty($CFG->messagingallowemailoverride)) {
            //clone to avoid altering the actual user object
            $recipient = clone($eventdata->userto);
            $recipient->email = $emailmessagingpreference;
        } else {
            $recipient = $eventdata->userto;
        }
        $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml);

        return $result;
    }
 function notify($changelist, $user, $course)
 {
     $html_message = $this->html_mail($changelist, $course);
     $text_message = $this->text_mail($changelist, $course);
     $subject = get_string('mailsubject', 'block_moodle_notifications');
     $subject .= ": " . format_string($course->fullname, true);
     email_to_user($user, '', $subject, $text_message, $html_message);
 }
function notify_admins_unknown($file, $a)
{
    global $site;
    $admins = get_admins();
    $subject = get_string('virusfoundsubject', 'moodle', format_string($site->fullname));
    $body = get_string('virusfoundlateradminnolog', 'moodle', $a);
    foreach ($admins as $admin) {
        email_to_user($admin, $admin, $subject, $body);
    }
}
 function notify($changelist, $user, $course)
 {
     $admin = current(get_admins());
     $html_message = $this->html_mail($changelist, $course);
     $text_message = $this->text_mail($changelist, $course);
     $subject = get_string('mailsubject', 'block_notifications');
     $subject .= ": " . format_string($course->fullname, true);
     //$this->test_email_to_user( $user, $admin, $subject, $text_message, $html_message );
     email_to_user($user, $admin, $subject, $text_message, $html_message);
 }
 function apply($discussion, $all, $selected, $formdata)
 {
     global $COURSE, $USER, $CFG;
     // Begin with standard text
     $a = (object) array('name' => fullname($USER, true));
     $allhtml = "<head>";
     foreach ($CFG->stylesheets as $stylesheet) {
         $allhtml .= '<link rel="stylesheet" type="text/css" href="' . $stylesheet . '" />' . "\n";
     }
     $allhtml .= "</head>\n<body id='forumng-email'>\n";
     $preface = get_string('forward_preface', 'forumng', $a);
     $allhtml .= $preface;
     $alltext = format_text_email($preface, FORMAT_HTML);
     // Include intro if specified
     if (!preg_match('~^(<br[^>]*>|<p>|</p>|\\s)*$~', $formdata->message)) {
         $alltext .= "\n" . forum_cron::EMAIL_DIVIDER . "\n";
         $allhtml .= '<hr size="1" noshade="noshade" />';
         // Add intro
         $message = trusttext_strip(stripslashes($formdata->message));
         $allhtml .= format_text($message, $formdata->format);
         $alltext .= format_text_email($message, $formdata->format);
     }
     // Get list of all post ids in discussion order
     $alltext .= "\n" . forum_cron::EMAIL_DIVIDER . "\n";
     $allhtml .= '<hr size="1" noshade="noshade" />';
     $poststext = '';
     $postshtml = '';
     $discussion->build_selected_posts_email($selected, $poststext, $postshtml);
     $alltext .= $poststext;
     $allhtml .= $postshtml . '</body>';
     $emails = preg_split('~[; ]+~', $formdata->email);
     $subject = stripslashes($formdata->subject);
     foreach ($emails as $email) {
         $fakeuser = (object) array('email' => $email, 'mailformat' => 1, 'id' => 0);
         $from = $USER;
         $from->maildisplay = 999;
         // Nasty hack required for OU moodle
         if (!email_to_user($fakeuser, $from, $subject, $alltext, $allhtml)) {
             print_error('error_forwardemail', 'forumng', $formdata->email);
         }
     }
     // Log that it was sent
     $discussion->log('forward discussion', $formdata->email);
     if (!empty($formdata->ccme)) {
         if (!email_to_user($USER, $from, $subject, $alltext, $allhtml)) {
             print_error('error_forwardemail', 'forumng', $USER->email);
         }
     }
     $discussion->print_subpage_header($this->get_page_name());
     print_box(get_string('forward_done', 'forumng'));
     print_continue('../../discuss.php?' . $discussion->get_link_params(forum::PARAM_PLAIN));
     print_footer($COURSE);
 }
 /**
  * Send's an anonymous email to some address, preferably the Mediabird team or a user
  * @param $to Id of user to which to deliver email
  * @param $subject Subject of email
  * @param $body Body of email
  * @return bool Success
  */
 function sendMail($to, $subject, $body)
 {
     if ($to == -1) {
         return false;
     }
     if ($account_link = get_record("studynotes_account_links", "system", "moodle", "internal_id", $to)) {
         if ($destination = get_record("user", "id", $account_link->external_id)) {
             $supportuser = generate_email_supportuser();
             return email_to_user($destination, $supportuser, $subject, $body);
         }
     }
     return false;
 }
Exemple #14
0
 /**
  *
  * @param stdClass $user  A {@link $USER} object
  * @param stdClass $user  A {@link $USER} object
  */
 public function mailToUser($userto, $userfrom)
 {
     $html = $this->makeMailHtml($this->html, $userto);
     $plain = $this->makeMailText($this->plain, $userto);
     $site = get_site();
     $subject = format_string($site->shortname) . ": " . $this->subject;
     $result = email_to_user($userto, $userfrom, $subject, $plain, $html);
     if ($result === true) {
         return true;
     }
     //$this->error .= "<div>".var_dump($result, true)."</div>";
     return false;
 }
 /**
  * Processes the message (sends by email).
  * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
  */
 function send_message($eventdata)
 {
     global $CFG;
     // Ignore $CFG->noemailever here because we want to test this code,
     // the message sending fails later in email_to_user().
     // skip any messaging suspended and deleted users
     if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
         return true;
     }
     //the user the email is going to
     $recipient = null;
     //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
     $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
     $emailmessagingpreference = clean_param($emailmessagingpreference, PARAM_EMAIL);
     // If the recipient has set an email address in their preferences use that instead of the one in their profile
     // but only if overriding the notification email address is allowed
     if (!empty($emailmessagingpreference) && !empty($CFG->messagingallowemailoverride)) {
         //clone to avoid altering the actual user object
         $recipient = clone $eventdata->userto;
         $recipient->email = $emailmessagingpreference;
     } else {
         $recipient = $eventdata->userto;
     }
     // Check if we have attachments to send.
     $attachment = '';
     $attachname = '';
     if (!empty($CFG->allowattachments) && !empty($eventdata->attachment)) {
         if (empty($eventdata->attachname)) {
             // Attachment needs a file name.
             debugging('Attachments should have a file name. No attachments have been sent.', DEBUG_DEVELOPER);
         } else {
             if (!$eventdata->attachment instanceof stored_file) {
                 // Attachment should be of a type stored_file.
                 debugging('Attachments should be of type stored_file. No attachments have been sent.', DEBUG_DEVELOPER);
             } else {
                 // Copy attachment file to a temporary directory and get the file path.
                 $attachment = $eventdata->attachment->copy_content_to_temp();
                 // Get attachment file name.
                 $attachname = clean_filename($eventdata->attachname);
             }
         }
     }
     $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml, $attachment, $attachname);
     // Remove an attachment file if any.
     if (!empty($attachment) && file_exists($attachment)) {
         unlink($attachment);
     }
     return $result;
 }
/**
 * This plugin sends users a welcome message after logging in
 * and notify a moderator a new user has been added
 * it has a settings page that allow you to configure the messages
 * send.
 *
 * @package    local
 * @subpackage welcome
 * @copyright  2014 Bas Brands, basbrands.nl, bas@sonsbeekmedia.nl
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function send_welcome($user)
{
    global $CFG, $SITE;
    $moderator = get_admin();
    $sender = get_admin();
    if (!empty($user->email)) {
        $config = get_config('local_welcome');
        if (!empty($config->auth_plugins)) {
            $auths = explode(',', $config->auth_plugins);
            if (!in_array($user->auth, $auths)) {
                return '';
            }
        } else {
            return '';
        }
        $moderator->email = $config->moderator_email;
        $sender->email = $config->sender_email;
        $sender->firstname = $config->sender_firstname;
        $sender->lastname = $config->sender_lastname;
        $message_user_enabled = $config->message_user_enabled;
        $message_user = $config->message_user;
        $message_user_subject = $config->message_user_subject;
        $message_moderator_enabled = $config->message_moderator_enabled;
        $message_moderator = $config->message_moderator;
        $message_moderator_subject = $config->message_moderator_subject;
        if (!empty($user->country)) {
            $user->country = get_string($user->country, 'countries');
        } else {
            $user->country = '';
        }
        $sitelink = html_writer::link(new moodle_url('/'), $SITE->fullname);
        $resetpasswordlink = html_writer::link(new moodle_url('/login/forgot_password.php'), get_string('resetpass', 'local_welcome'));
        $fields = array('[[fullname]]', '[[username]]', '[[firstname]]', '[[lastname]]', '[[email]]', '[[city]]', '[[country]]', '[[sitelink]]', '[[sitename]]', '[[resetpasswordlink]]');
        $values = array(fullname($user), $user->username, $user->firstname, $user->lastname, $user->email, $user->city, $user->country, $sitelink, $SITE->fullname, $resetpasswordlink);
        $message_user = str_replace($fields, $values, $message_user);
        $message_user_subject = str_replace($fields, $values, $message_user_subject);
        $message_moderator = str_replace($fields, $values, $message_moderator);
        $message_moderator_subject = str_replace($fields, $values, $message_moderator_subject);
        if (!empty($message_user) && !empty($sender->email) && $message_user_enabled) {
            email_to_user($user, $sender, $message_user_subject, html_to_text($message_user), $message_user);
        }
        if (!empty($message_moderator) && !empty($sender->email) && $message_moderator_enabled) {
            email_to_user($moderator, $sender, $message_moderator_subject, html_to_text($message_moderator), $message_moderator);
        }
    }
}
/**
 * Runs and exports, through email, the report instance specified by the
 * provided report schedule
 *
 * @param   stdClass  $report_schedule  The PHP report schedule containing the information
 *                                      about the specific report to be exported
 *
 * @return  boolean                     true on success, otherwise false
 */
function php_report_schedule_export_instance($report_schedule, $now = 0)
{
    global $CFG;
    if ($now == 0) {
        $now = gmmktime();
        // time();
    }
    $data = unserialize($report_schedule->config);
    // Create report to be emailed to recipient
    $shortname = $report_schedule->report;
    $format = $data['format'];
    // Initialize a temp path name
    $tmppath = '/temp';
    // Create a unique temporary filename to use for this schedule
    $filename = tempnam($CFG->dataroot . $tmppath, 'php_report_');
    $parameterdata = $data['parameters'];
    // Generate the report file
    $result = php_report::export_default_instance($shortname, $format, $filename, $parameterdata, $report_schedule->userid, php_report::EXECUTION_MODE_SCHEDULED);
    if (!$result) {
        //handle failure case
        unlink($filename);
        return false;
    }
    // Attach filename to an email - so get recipient...
    $recipients_array = explode(',', $data['recipients']);
    $from = get_string('noreplyname');
    $subject = get_string('email_subject', 'block_php_report') . $data['label'];
    $messagetext = html_to_text($data['message']);
    $messagehtml = $data['message'];
    $start = strlen($CFG->dataroot);
    $attachment = substr($filename, $start);
    $attachname = $report_schedule->report . $now . '.' . $data['format'];
    // Attach the file to the recipients
    foreach ($recipients_array as $recipient) {
        $user = new stdClass();
        $user->email = $recipient;
        $user->mailformat = 1;
        email_to_user($user, $from, $subject, $messagetext, $messagehtml, $attachment, $attachname);
    }
    // Remove the file that was created for this report
    unlink($filename);
    return true;
}
function send_batch_activiation($f2fid){
    global $DB;
$batchuser=$DB->get_records('local_batch_users',array('f2fid'=>$f2fid));
//print_object($batchuser);
    foreach($batchuser as $batchusers){
	   $sessions=getsession_list($f2fid);
           $subject='Active Notification';
           $messagetext = get_string('batchactivemessage', 'facetoface');
           $messagetext .=$sessions;
           $messagehtml = text_to_html($messagetext, null, false, true);
        // echo $sessions;
         $user=$DB->get_record('user',array('id'=>$batchusers->userid));

         $from = $DB->get_record('user',array('id'=>2));
echo $messagehtml;
      $sent=   email_to_user($user, $from, $subject, $messagetext, $messagehtml);
echo "mail sent";
    }

}
 function run()
 {
     $notificationdays = get_config('block_ilp', 'deadlinenotification');
     if (!empty($notificationdays)) {
         $lowertimestamp = mktime(0, 0, 0, date('n'), date('j') + $notificationdays);
         $uppertimestamp = mktime(23, 59, 59, date('n'), date('j') + $notificationdays);
         $reportentries = $this->get_list($lowertimestamp, $uppertimestamp);
         mtrace("running cron");
         foreach ($reportentries as $r) {
             mtrace($r->name);
             $user = $this->dbc->get_user_by_id($r->user_id);
             mtrace($user->firstname);
             $email = new stdClass();
             $email->reportname = $r->name;
             $email->firsttname = $user->firstname;
             $email->lasttname = $user->lastname;
             $email->deadline = userdate($r->deadline);
             $subject = get_string('cronemailsubject', 'block_ilp', $email);
             $messagetext = get_string('cronemailhtml', 'block_ilp', $email);
             email_to_user($user, get_string('cronemailsender', 'block_ilp'), $subject, $messagetext);
         }
     }
 }
function send_email_sessionupdated($webinar, $session_info, $cm, $date)
{
    global $CFG;
    if ($attendees = webinar_get_attendees($session_info->id)) {
        foreach ($attendees as $user) {
            $a = new stdClass();
            $a->name = $user->firstname . " " . $user->lastname;
            $a->starttime = date('d F Y h:i A', $date->timestart);
            $a->webinarname = $webinar->name;
            $a->webinarintro = $webinar->description;
            $a->webinaragenda = $webinar->agenda;
            $a->sessionurl = $CFG->wwwroot . "/mod/" . $cm->modname . "/view.php?id=" . $cm->id;
            $a->adminemail = $webinar->adminemail;
            //print_r($a);
            $subject = get_string('sessionupdatedsubject', 'webinar', $a);
            $contact = get_string('sessionupdatedcontact', 'webinar', $a);
            $message = get_string('sessionupdatedmessage', 'webinar', $a);
            //last task - strip <p> and </p> from the message before we send the email
            $message = str_replace('<p>', '', $message);
            $message = str_replace('</p>', '', $message);
            email_to_user($user, $contact, $subject, $message);
        }
    }
}
function send_email_signup($webinar, $session_info, $cm, $user)
{
    global $CFG;
    foreach ($session_info->sessiondates as $dates) {
        $startdatetime = date('d F Y', $dates->timestart) . " at " . date('h:i A', $dates->timestart);
    }
    $a = new stdClass();
    $a->name = $user->firstname . " " . $user->lastname;
    $a->starttime = $startdatetime;
    $a->webinarname = $webinar->name;
    $a->webinarintro = $webinar->description;
    $a->webinaragenda = $webinar->agenda;
    //$a->sessionurl = $webinar->sitexmlapiurl  . $session_info->urlpath;
    $a->sessionurl = $CFG->wwwroot . "/mod/" . $cm->modname . "/view.php?id=" . $cm->id;
    $a->adminemail = $webinar->adminemail;
    //print_r($a);
    $subject = get_string('sessionregistersubject', 'webinar', $a);
    $contact = get_string('sessionregistercontact', 'webinar', $a);
    $message = get_string('sessionregistermessage', 'webinar', $a);
    //last task - strip <p> and </p> from the message before we send the email
    $message = str_replace('<p>', '', $message);
    $message = str_replace('</p>', '', $message);
    email_to_user($user, $contact, $subject, $message);
}
Exemple #22
0
/**
 * Lockout user and send notification email.
 *
 * @param stdClass $user
 */
function login_lock_account($user)
{
    global $CFG;
    if ($user->mnethostid != $CFG->mnet_localhost_id) {
        return;
    }
    if (isguestuser($user)) {
        return;
    }
    if (get_user_preferences('login_lockout_ignored', 0, $user)) {
        // This user can not be locked out.
        return;
    }
    $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
    set_user_preference('login_lockout', time(), $user);
    if ($alreadylockedout == 0) {
        $secret = random_string(15);
        set_user_preference('login_lockout_secret', $secret, $user);
        $oldforcelang = force_current_language($user->lang);
        $site = get_site();
        $supportuser = core_user::get_support_user();
        $data = new stdClass();
        $data->firstname = $user->firstname;
        $data->lastname = $user->lastname;
        $data->username = $user->username;
        $data->sitename = format_string($site->fullname);
        $data->link = $CFG->wwwroot . '/login/unlock_account.php?u=' . $user->id . '&s=' . $secret;
        $data->admin = generate_email_signoff();
        $message = get_string('lockoutemailbody', 'admin', $data);
        $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
        if ($message) {
            // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
            email_to_user($user, $supportuser, $subject, $message);
        }
        force_current_language($oldforcelang);
    }
}
 profile_save_data($usernew);
 // Trigger event.
 \core\event\user_updated::create_from_userid($user->id)->trigger();
 // If email was changed and confirmation is required, send confirmation email now to the new address.
 if ($emailchanged && $CFG->emailchangeconfirmation) {
     $tempuser = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST);
     $tempuser->email = $usernew->preference_newemail;
     $a = new stdClass();
     $a->url = $CFG->wwwroot . '/user/emailupdate.php?key=' . $usernew->preference_newemailkey . '&id=' . $user->id;
     $a->site = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
     $a->fullname = fullname($tempuser, true);
     $emailupdatemessage = get_string('emailupdatemessage', 'auth', $a);
     $emailupdatetitle = get_string('emailupdatetitle', 'auth', $a);
     // Email confirmation directly rather than using messaging so they will definitely get an email.
     $supportuser = core_user::get_support_user();
     if (!($mailresults = email_to_user($tempuser, $supportuser, $emailupdatetitle, $emailupdatemessage))) {
         die("could not send email!");
     }
 }
 // Reload from db, we need new full name on this page if we do not redirect.
 $user = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST);
 if ($USER->id == $user->id) {
     // Override old $USER session variable if needed.
     foreach ((array) $user as $variable => $value) {
         if ($variable === 'description' or $variable === 'password') {
             // These are not set for security nad perf reasons.
             continue;
         }
         $USER->{$variable} = $value;
     }
     // Preload custom fields.
Exemple #24
0
 /**
  * Send welcome email to specified user.
  *
  * @param stdClass $instance
  * @param stdClass $user user record
  * @return void
  */
 protected function email_welcome_message($instance, $user)
 {
     global $CFG, $DB;
     $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST);
     $context = context_course::instance($course->id);
     $a = new stdClass();
     $a->coursename = format_string($course->fullname, true, array('context' => $context));
     $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}";
     if (trim($instance->customtext1) !== '') {
         $message = $instance->customtext1;
         $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
         $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
         $message = str_replace($key, $value, $message);
         if (strpos($message, '<') === false) {
             // Plain text only.
             $messagetext = $message;
             $messagehtml = text_to_html($messagetext, null, false, true);
         } else {
             // This is most probably the tag/newline soup known as FORMAT_MOODLE.
             $messagehtml = format_text($message, FORMAT_MOODLE, array('context' => $context, 'para' => false, 'newlines' => true, 'filter' => true));
             $messagetext = html_to_text($messagehtml);
         }
     } else {
         $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
         $messagehtml = text_to_html($messagetext, null, false, true);
     }
     $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context' => $context)));
     $rusers = array();
     if (!empty($CFG->coursecontact)) {
         $croles = explode(',', $CFG->coursecontact);
         list($sort, $sortparams) = users_order_by_sql('u');
         // We only use the first user.
         $i = 0;
         do {
             $rusers = get_role_users($croles[$i], $context, true, '', 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
             $i++;
         } while (empty($rusers) && !empty($croles[$i]));
     }
     if ($rusers) {
         $contact = reset($rusers);
     } else {
         $contact = core_user::get_support_user();
     }
     // Directly emailing welcome message rather than using messaging.
     email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
 }
Exemple #25
0
/**
 * 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;
}
                                   JOIN ' . $CFG->prefix . "users u ON u.ident = pr.owner\n                                   WHERE pr.code = ? AND u.user_type = ?", array($code, 'person'))) {
        $passwordDesc = sprintf(__gettext("A new password has been emailed to you at %s. You should be able to use it immediately; your old one has been deactivated."), $details->email);
        $run_result .= <<<END
    
    <p>
        {$passwordDesc}
    </p>
END;
        $validcharset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz234567898765432";
        $newpassword = "";
        for ($i = 0; $i < 8; $i++) {
            $newpassword .= $validcharset[mt_rand(0, strlen($validcharset) - 1)];
        }
        $newpassword = strtolower($newpassword);
        $sitename = sitename;
        email_to_user($details, null, sprintf(__gettext("Your %s password"), $sitename), sprintf(__gettext("Your %s password has been reset.\n\nFor your records, your new password is:\n\n\tPassword: %s\n\nPlease consider changing your password as soon as you have logged in for security reasons.\n\nWe hope you continue to enjoy using the system.\n\nRegards,\n\nThe %s Team"), $sitename, $newpassword, $sitename));
        $newpassword = md5($newpassword);
        set_field('users', 'password', $newpassword, 'ident', $details->ident);
        delete_records('password_requests', 'owner', $details->ident);
    } else {
        $passwordDesc2 = __gettext("Your password request code appears to be invalid. Try generating a new one?");
        $run_result .= <<<END
    
    <p>
        {$passwordDesc2}
    </p>
    
END;
    }
} else {
    $passwordDesc3 = __gettext("Your password request code appears to be invalid. Try generating a new one?");
Exemple #27
0
function checklist_update_grades($checklist, $userid = 0)
{
    global $CFG, $DB;
    $items = $DB->get_records('checklist_item', array('checklist' => $checklist->id, 'userid' => 0, 'itemoptional' => CHECKLIST_OPTIONAL_NO, 'hidden' => CHECKLIST_HIDDEN_NO), '', 'id, grouping');
    if (!$items) {
        return;
    }
    if (!($course = $DB->get_record('course', array('id' => $checklist->course)))) {
        return;
    }
    if (!($cm = get_coursemodule_from_instance('checklist', $checklist->id, $course->id))) {
        return;
    }
    $checkgroupings = false;
    // Don't check items against groupings unless we really have to
    if (isset($CFG->enablegroupmembersonly) && $CFG->enablegroupmembersonly && $checklist->autopopulate) {
        foreach ($items as $item) {
            if ($item->grouping) {
                $checkgroupings = true;
                break;
            }
        }
    }
    if ($checklist->teacheredit == CHECKLIST_MARKING_STUDENT) {
        $date = ', MAX(c.usertimestamp) AS datesubmitted';
        $where = 'c.usertimestamp > 0';
    } else {
        $date = ', MAX(c.teachertimestamp) AS dategraded';
        $where = 'c.teachermark = ' . CHECKLIST_TEACHERMARK_YES;
    }
    if ($checkgroupings) {
        if ($userid) {
            $users = $DB->get_records('user', array('id' => $userid), null, 'id, firstname, lastname');
        } else {
            if ($CFG->version < 2011120100) {
                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            } else {
                $context = context_module::instance($cm->id);
            }
            if (!($users = get_users_by_capability($context, 'mod/checklist:updateown', 'u.id, u.firstname, u.lastname', '', '', '', '', '', false))) {
                return;
            }
        }
        $grades = array();
        // With groupings, need to update each user individually (as each has different groupings)
        foreach ($users as $userid => $user) {
            $groupings = checklist_class::get_user_groupings($userid, $course->id);
            $total = 0;
            $itemlist = '';
            foreach ($items as $item) {
                if ($item->grouping) {
                    if (!in_array($item->grouping, $groupings)) {
                        continue;
                    }
                }
                $itemlist .= $item->id . ',';
                $total++;
            }
            if (!$total) {
                // No items - set score to 0
                $ugrade = new stdClass();
                $ugrade->userid = $userid;
                $ugrade->rawgrade = 0;
                $ugrade->date = time();
            } else {
                $itemlist = substr($itemlist, 0, -1);
                // Remove trailing ','
                $sql = 'SELECT ? AS userid, (SUM(CASE WHEN ' . $where . ' THEN 1 ELSE 0 END) * ? / ? ) AS rawgrade' . $date;
                $sql .= " FROM {checklist_check} c ";
                $sql .= " WHERE c.item IN ({$itemlist})";
                $sql .= ' AND c.userid = ? ';
                $ugrade = $DB->get_record_sql($sql, array($userid, $checklist->maxgrade, $total, $userid));
                if (!$ugrade) {
                    $ugrade = new stdClass();
                    $ugrade->userid = $userid;
                    $ugrade->rawgrade = 0;
                    $ugrade->date = time();
                }
            }
            $ugrade->firstname = $user->firstname;
            $ugrade->lastname = $user->lastname;
            $grades[$userid] = $ugrade;
        }
    } else {
        // No need to check groupings, so update all student grades at once
        if ($userid) {
            $users = $userid;
        } else {
            if ($CFG->version < 2011120100) {
                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            } else {
                $context = context_module::instance($cm->id);
            }
            if (!($users = get_users_by_capability($context, 'mod/checklist:updateown', 'u.id', '', '', '', '', '', false))) {
                return;
            }
            $users = array_keys($users);
        }
        $total = count($items);
        list($usql, $uparams) = $DB->get_in_or_equal($users);
        list($isql, $iparams) = $DB->get_in_or_equal(array_keys($items));
        $sql = 'SELECT u.id AS userid, (SUM(CASE WHEN ' . $where . ' THEN 1 ELSE 0 END) * ? / ? ) AS rawgrade' . $date;
        $sql .= ' , u.firstname, u.lastname ';
        $sql .= ' FROM {user} u LEFT JOIN {checklist_check} c ON u.id = c.userid';
        $sql .= " WHERE u.id {$usql}";
        $sql .= " AND c.item {$isql}";
        $sql .= ' GROUP BY u.id, u.firstname, u.lastname';
        $params = array_merge($uparams, $iparams);
        $params = array_merge(array($checklist->maxgrade, $total), $params);
        $grades = $DB->get_records_sql($sql, $params);
    }
    foreach ($grades as $grade) {
        // Log completion of checklist
        if ($grade->rawgrade == $checklist->maxgrade) {
            if ($checklist->emailoncomplete) {
                $timelimit = time() - 1 * 60 * 60;
                // Do not send another email if this checklist was already 'completed' in the last hour
                $filter = "l.time > ? AND l.cmid = ? AND l.userid = ? AND l.action = 'complete'";
                get_logs($filter, array($timelimit, $cm->id, $grade->userid), '', 1, 1, $logcount);
                if ($logcount == 0) {
                    if (!isset($context)) {
                        if ($CFG->version < 2011120100) {
                            $context = get_context_instance(CONTEXT_MODULE, $cm->id);
                        } else {
                            $context = context_module::instance($cm->id);
                        }
                    }
                    if ($recipients = get_users_by_capability($context, 'mod/checklist:emailoncomplete', 'u.*', '', '', '', '', '', false)) {
                        foreach ($recipients as $recipient) {
                            $details = new stdClass();
                            $details->user = fullname($grade);
                            $details->checklist = s($checklist->name);
                            $subj = get_string('emailoncompletesubject', 'checklist', $details);
                            $content = get_string('emailoncompletebody', 'checklist', $details);
                            $content .= $CFG->wwwroot . '/mod/checklist/view.php?id=' . $cm->id;
                            email_to_user($recipient, $grade, $subj, $content, '', '', '', false);
                        }
                    }
                }
            }
            add_to_log($checklist->course, 'checklist', 'complete', "view.php?id={$cm->id}", $checklist->name, $cm->id, $grade->userid);
        }
        $ci = new completion_info($course);
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
            $ci->update_state($cm, COMPLETION_UNKNOWN, $grade->userid);
        }
    }
    checklist_grade_item_update($checklist, $grades);
}
Exemple #28
0
 /**
 * Notify users about enrolments that are going to expire soon!
 * This function is run by admin/cron.php
 * @return void
 */
 function cron()
 {
     global $CFG, $USER, $SITE;
     if (!isset($CFG->lastexpirynotify)) {
         set_config('lastexpirynotify', 0);
     }
     // notify once a day only - TODO: add some tz handling here, maybe use timestamps
     if ($CFG->lastexpirynotify == date('Ymd')) {
         return;
     }
     if ($rs = get_recordset_select('course', 'enrolperiod > 0 AND expirynotify > 0 AND expirythreshold > 0')) {
         $cronuser = clone $USER;
         $admin = get_admin();
         while ($course = rs_fetch_next_record($rs)) {
             $a = new object();
             $a->coursename = $course->shortname . '/' . $course->fullname;
             // must be processed by format_string later
             $a->threshold = $course->expirythreshold / 86400;
             $a->extendurl = $CFG->wwwroot . '/user/index.php?id=' . $course->id;
             $a->current = array();
             $a->past = array();
             $expiry = time() + $course->expirythreshold;
             $cname = $course->fullname;
             /// Get all the manual role assignments for this course that have expired.
             if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) {
                 continue;
             }
             if ($oldenrolments = get_records_sql("\n                      SELECT u.*, ra.timeend\n                        FROM {$CFG->prefix}user u\n                             JOIN {$CFG->prefix}role_assignments ra ON (ra.userid = u.id)\n                        WHERE ra.contextid = {$context->id}\n                              AND ra.timeend > 0 AND ra.timeend <= {$expiry}\n                              AND ra.enrol = 'manual'")) {
                 // inform user who can assign roles or admin
                 if ($teachers = get_users_by_capability($context, 'moodle/role:assign', '', '', '', '', '', '', false)) {
                     $teachers = sort_by_roleassignment_authority($teachers, $context);
                     $teacher = reset($teachers);
                 } else {
                     $teachers = array($admin);
                     $teacher = $admin;
                 }
                 $a->teacherstr = fullname($teacher, true);
                 foreach ($oldenrolments as $user) {
                     /// Email all users about to expire
                     $a->studentstr = fullname($user, true);
                     if ($user->timeend < $expiry - 86400) {
                         $a->past[] = fullname($user) . " <{$user->email}>";
                     } else {
                         $a->current[] = fullname($user) . " <{$user->email}>";
                         if ($course->notifystudents) {
                             // Send this guy notice
                             // setup global $COURSE properly - needed for languages
                             $USER = $user;
                             course_setup($course);
                             $a->coursename = format_string($cname);
                             $a->course = $a->coursename;
                             $strexpirynotifystudentsemail = get_string('expirynotifystudentsemail', '', $a);
                             $strexpirynotify = get_string('expirynotify');
                             email_to_user($user, $teacher, format_string($SITE->fullname) . ' ' . $strexpirynotify, $strexpirynotifystudentsemail);
                         }
                     }
                 }
                 $a->current = implode("\n", $a->current);
                 $a->past = implode("\n", $a->past);
                 if ($a->current || $a->past) {
                     foreach ($teachers as $teacher) {
                         // setup global $COURSE properly - needed for languages
                         $USER = $teacher;
                         course_setup($course);
                         $a->coursename = format_string($cname);
                         $strexpirynotifyemail = get_string('expirynotifyemail', '', $a);
                         $strexpirynotify = get_string('expirynotify');
                         email_to_user($teacher, $admin, $a->coursename . ' ' . $strexpirynotify, $strexpirynotifyemail);
                     }
                 }
             }
         }
         $USER = $cronuser;
         course_setup($SITE);
         // More environment
     }
     set_config('lastexpirynotify', date('Ymd'));
 }
/**
 * This plugin sends users a welcome message after logging in
 * and notify a moderator a new user has been added
 * it has a settings page that allow you to configure the messages
 * send.
 *
 * @package    local
 * @subpackage welcome
 * @copyright  2015 Bas Brands, basbrands.nl, bas@sonsbeekmedia.nl
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function send_welcome($user)
{
    global $CFG, $SITE;
    require_once $CFG->dirroot . '/local/welcome/locallib.php';
    $sender = get_admin();
    if (!empty($user->email)) {
        $config = get_config('local_welcome');
        $moderator = clone $sender;
        if (!empty($config->auth_plugins)) {
            $auths = explode(',', $config->auth_plugins);
            if (!in_array($user->auth, $auths)) {
                return '';
            }
        } else {
            return '';
        }
        $moderator->email = $config->moderator_email;
        $sender->email = $config->sender_email;
        $sender->firstname = $config->sender_firstname;
        $sender->lastname = $config->sender_lastname;
        $message_user_enabled = $config->message_user_enabled;
        $message_user = $config->message_user;
        $message_user_subject = $config->message_user_subject;
        $message_moderator_enabled = $config->message_moderator_enabled;
        $message_moderator = $config->message_moderator;
        $message_moderator_subject = $config->message_moderator_subject;
        $welcome = new local_welcome();
        $message_user = $welcome->replace_values($user, $message_user);
        $message_user_subject = $welcome->replace_values($user, $message_user_subject);
        $message_moderator = $welcome->replace_values($user, $message_moderator);
        $message_moderator_subject = $welcome->replace_values($user, $message_moderator_subject);
        if (!empty($message_user) && !empty($sender->email) && $message_user_enabled) {
            email_to_user($user, $sender, $message_user_subject, html_to_text($message_user), $message_user);
        }
        if (!empty($message_moderator) && !empty($sender->email) && $message_moderator_enabled) {
            email_to_user($moderator, $sender, $message_moderator_subject, html_to_text($message_moderator), $message_moderator);
        }
    }
}
Exemple #30
-2
 public function apply($discussion, $all, $selected, $formdata)
 {
     global $COURSE, $USER, $CFG;
     // Begin with standard text
     $a = (object) array('name' => fullname($USER, true));
     $allhtml = "<body id='forumng-email'>\n";
     $preface = get_string('forward_preface', 'forumngfeature_forward', $a);
     $allhtml .= $preface;
     $alltext = format_text_email($preface, FORMAT_HTML);
     // Include intro if specified
     if (!preg_match('~^(<br[^>]*>|<p>|</p>|\\s)*$~', $formdata->message['text'])) {
         $alltext .= "\n" . mod_forumng_cron::EMAIL_DIVIDER . "\n";
         $allhtml .= '<hr size="1" noshade="noshade" />';
         // Add intro
         $message = trusttext_strip($formdata->message['text']);
         $allhtml .= format_text($message, $formdata->message['format']);
         $alltext .= format_text_email($message, $formdata->message['format']);
     }
     // Get list of all post ids in discussion order
     $alltext .= "\n" . mod_forumng_cron::EMAIL_DIVIDER . "\n";
     $allhtml .= '<hr size="1" noshade="noshade" />';
     $poststext = '';
     $postshtml = '';
     $discussion->build_selected_posts_email($selected, $poststext, $postshtml);
     $alltext .= $poststext;
     $allhtml .= $postshtml . '</body>';
     $emails = preg_split('~[; ]+~', $formdata->email);
     $subject = $formdata->subject;
     foreach ($emails as $email) {
         $fakeuser = (object) array('email' => $email, 'mailformat' => 1, 'id' => -1);
         $from = $USER;
         $from->maildisplay = 999;
         // Nasty hack required for OU moodle
         if (!email_to_user($fakeuser, $from, $subject, $alltext, $allhtml)) {
             print_error('error_forwardemail', 'forumng', $discussion->get_moodle_url(), $formdata->email);
         }
     }
     // Log that it was sent
     $params = array('context' => $discussion->get_forum()->get_context(), 'objectid' => $discussion->get_id(), 'other' => array('logurl' => $discussion->get_log_url(), 'info' => $formdata->email));
     $event = \forumngfeature_forward\event\discussion_forwarded::create($params);
     $event->add_record_snapshot('course_modules', $discussion->get_course_module());
     $event->add_record_snapshot('course', $discussion->get_course());
     $event->trigger();
     if (!empty($formdata->ccme)) {
         if (!email_to_user($USER, $from, $subject, $alltext, $allhtml)) {
             print_error('error_forwardemail', 'forumng', $discussion->get_moodle_url(), $USER->email);
         }
     }
     $out = $discussion->init_page($discussion->get_moodle_url(), $this->get_page_name());
     print $out->header();
     print $out->box(get_string('forward_done', 'forumngfeature_forward'));
     print $out->continue_button(new moodle_url('/mod/forumng/discuss.php', $discussion->get_link_params_array()));
     print $out->footer();
 }