/**
  * 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;
 }
    private function __app_reset_password_and_mail($user)
    {
        global $CFG;
        $site = get_site();
        $supportuser = generate_email_supportuser();
        $userauth = get_auth_plugin($user->auth);
        if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
            trigger_error("Attempt to reset user password for user {$user->username} with Auth {$user->auth}.");
            return false;
        }
        $newpassword = generate_password();
        if (!$userauth->user_update_password($user, $newpassword)) {
            $error->error = true;
            $error->msg = 'fp_passwordgen_failure';
            echo json_encode($error);
            die;
        }
        $a = new stdClass();
        $a->firstname = $user->firstname;
        $a->lastname = $user->lastname;
        $a->sitename = format_string($site->fullname);
        $a->username = $user->username;
        $a->newpassword = $newpassword;
        //$a->signoff = generate_email_signoff();
        $message = 'Hi ' . $a->firstname . ',

Your account password at \'' . $a->sitename . '\' has been reset
and you have been issued with a new temporary password.

Your current login information is now:
   username: '******'
   password: '******'

Cheers from the \'' . $a->sitename . '\' administrator.';
        //$message = get_string('newpasswordtext', '', $a);
        $subject = format_string($site->fullname) . ': ' . get_string('changedpassword');
        unset_user_preference('create_password', $user);
        // prevent cron from generating the password
        //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
        return email_to_user($user, $supportuser, $subject, $message);
    }
Example #3
0
/**
 * Notify admin users or admin user of any failed logins (since last notification).
 *
 * Note that this function must be only executed from the cron script
 * It uses the cache_flags system to store temporary records, deleting them
 * by name before finishing
 *
 * @return bool True if executed, false if not
 */
function notify_login_failures()
{
    global $CFG, $DB, $OUTPUT;
    if (empty($CFG->notifyloginfailures)) {
        return false;
    }
    $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
    if (empty($CFG->lastnotifyfailure)) {
        $CFG->lastnotifyfailure = 0;
    }
    // If it has been less than an hour, or if there are no recipients, don't execute.
    if (time() - HOURSECS < $CFG->lastnotifyfailure || !is_array($recip) || count($recip) <= 0) {
        return false;
    }
    // we need to deal with the threshold stuff first.
    if (empty($CFG->notifyloginthreshold)) {
        $CFG->notifyloginthreshold = 10;
        // default to something sensible.
    }
    // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
    // and insert them into the cache_flags temp table
    $sql = "SELECT ip, COUNT(*)\n              FROM {log}\n             WHERE module = 'login' AND action = 'error'\n                   AND time > ?\n          GROUP BY ip\n            HAVING COUNT(*) >= ?";
    $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $iprec) {
        if (!empty($iprec->ip)) {
            set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
        }
    }
    $rs->close();
    // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
    // and insert them into the cache_flags temp table
    $sql = "SELECT info, count(*)\n              FROM {log}\n             WHERE module = 'login' AND action = 'error'\n                   AND time > ?\n          GROUP BY info\n            HAVING count(*) >= ?";
    $params = array($CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $inforec) {
        if (!empty($inforec->info)) {
            set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
        }
    }
    $rs->close();
    // Now, select all the login error logged records belonging to the ips and infos
    // since lastnotifyfailure, that we have stored in the cache_flags table
    $sql = "SELECT * FROM (\n        SELECT l.*, u.firstname, u.lastname\n              FROM {log} l\n              JOIN {cache_flags} cf ON l.ip = cf.name\n         LEFT JOIN {user} u         ON l.userid = u.id\n             WHERE l.module = 'login' AND l.action = 'error'\n                   AND l.time > ?\n                   AND cf.flagtype = 'login_failure_by_ip'\n        UNION ALL\n            SELECT l.*, u.firstname, u.lastname\n              FROM {log} l\n              JOIN {cache_flags} cf ON l.info = cf.name\n         LEFT JOIN {user} u         ON l.userid = u.id\n             WHERE l.module = 'login' AND l.action = 'error'\n                   AND l.time > ?\n                   AND cf.flagtype = 'login_failure_by_info') t\n        ORDER BY t.time DESC";
    $params = array($CFG->lastnotifyfailure, $CFG->lastnotifyfailure);
    // Init some variables
    $count = 0;
    $messages = '';
    // Iterate over the logs recordset
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $log) {
        $log->time = userdate($log->time);
        $messages .= get_string('notifyloginfailuresmessage', '', $log) . "\n";
        $count++;
    }
    $rs->close();
    // If we have something useful to report.
    if ($count > 0) {
        $site = get_site();
        $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
        // Calculate the complete body of notification (start + messages + end)
        $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) . ($CFG->lastnotifyfailure != 0 ? '(' . userdate($CFG->lastnotifyfailure) . ')' : '') . "\n\n" . $messages . "\n\n" . get_string('notifyloginfailuresmessageend', '', $CFG->wwwroot) . "\n\n";
        // For each destination, send mail
        mtrace('Emailing admins about ' . $count . ' failed login attempts');
        foreach ($recip as $admin) {
            //emailing the admins directly rather than putting these through the messaging system
            email_to_user($admin, generate_email_supportuser(), $subject, $body);
        }
    }
    // Update lastnotifyfailure with current time
    set_config('lastnotifyfailure', time());
    // Finally, delete all the temp records we have created in cache_flags
    $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
    return true;
}
Example #4
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;
         $message = str_replace('{$a->coursename}', $a->coursename, $message);
         $message = str_replace('{$a->profileurl}', $a->profileurl, $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);
         $rusers = get_role_users($croles, $context, true, '', 'r.sortorder ASC, u.lastname ASC');
     }
     if ($rusers) {
         $contact = reset($rusers);
     } else {
         $contact = generate_email_supportuser();
     }
     // Directly emailing welcome message rather than using messaging.
     email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
 }
Example #5
0
/**
 * send_password_change_info.
 *
 * @uses $CFG
 * @param user $user A {@link $USER} object
 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
 *          was blocked by user and "false" if there was another sort of error.
 */
function send_password_change_info($user)
{
    global $CFG;
    $site = get_site();
    $supportuser = generate_email_supportuser();
    $systemcontext = get_context_instance(CONTEXT_SYSTEM);
    $data = new object();
    $data->firstname = $user->firstname;
    $data->lastname = $user->lastname;
    $data->sitename = format_string($site->fullname);
    $data->admin = generate_email_signoff();
    $userauth = get_auth_plugin($user->auth);
    if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
        $message = get_string('emailpasswordchangeinfodisabled', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
        return email_to_user($user, $supportuser, $subject, $message);
    }
    if ($userauth->can_change_password() and $userauth->change_password_url()) {
        // we have some external url for password changing
        $data->link .= $userauth->change_password_url();
    } else {
        //no way to change password, sorry
        $data->link = '';
    }
    if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
        $message = get_string('emailpasswordchangeinfo', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    } else {
        $message = get_string('emailpasswordchangeinfofail', '', $data);
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
    }
    return email_to_user($user, $supportuser, $subject, $message);
}
Example #6
0
    // If email was changed and confirmation is required, send confirmation email now
    if ($email_changed && $CFG->emailchangeconfirmation) {
        $temp_user = fullclone($user);
        $temp_user->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($user, 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 = generate_email_supportuser();
        if (!$mail_results = email_to_user($temp_user, $supportuser, $emailupdatetitle, $emailupdatemessage)) {
            die("could not send email!");
        }
    }

    // reload from db
    $usernew = $DB->get_record('user', array('id'=>$user->id));
    events_trigger('user_updated', $usernew);

    if ($USER->id == $user->id) {
        // Override old $USER session variable if needed
        foreach ((array)$usernew as $variable => $value) {
            $USER->$variable = $value;
        }
        // preload custom fields
 /**
  * Sends an email to lots of people using BCC.
  * @param array $targets List of target user objects (email, name fields
  *   required)
  * @param mixed $from User or string who sent email
  * @param string $subject Subject of email
  * @param string $html HTML version of email (blank if none)
  * @param string $text Plain text version of email
  * @param string $showerrortext If set, mtraces errors and includes this
  *   extra string about where the error was.
  * @param bool $ishtml If true, email is in HTML format
  * @param bool $viewfullnames If true, these recipients have access to
  *   see the full name
  * @return int Number of emails sent
  */
 private static function email_send_bcc($targets, $from, $subject, $html, $text, $showerrortext, $ishtml, $viewfullnames)
 {
     if (self::DEBUG_VIEW_EMAILS) {
         print "<div style='border:1px solid blue; padding:4px;'>";
         print "<h3>Bulk email sent</h3>";
         print "<ul><li>To: ";
         $first = true;
         foreach ($targets as $target) {
             if ($first) {
                 $first = false;
             } else {
                 print ', ';
             }
             print "<strong>{$target->email}</strong>";
         }
         print "</li><li>Subject: <strong>" . htmlspecialchars($subject) . "</strong></li>";
         print $html;
         print "<pre style='border-top: 1px solid blue; padding-top: 4px;'>";
         print htmlspecialchars($text);
         print "</pre></div>";
         return;
     }
     global $CFG;
     $emailcount = 0;
     // Trim subject length (not sure why but
     // email_to_user does); note that I did it more
     // aggressively due to use of textlib.
     $mail->Subject = core_text::substr($subject, 0, 200);
     // Loop through in batches of specified size
     $copy = array();
     foreach ($targets as $key => $target) {
         $copy[$key] = $target;
     }
     while (count($copy) > 0) {
         $batch = array_splice($copy, 0, $CFG->forumng_usebcc);
         // Prepare email
         $mail = get_mailer();
         // From support user
         static $supportuser;
         if (!$supportuser) {
             $supportuser = generate_email_supportuser();
         }
         $mail->Sender = $supportuser->email;
         // Set the From details similar to email_to_user
         if ($CFG->forumng_replytouser && $from->maildisplay) {
             $mail->From = $from->email;
             $mail->FromName = fullname($from, $viewfullnames);
         } else {
             $mail->From = $CFG->noreplyaddress;
             $mail->FromName = fullname($from, $viewfullnames);
         }
         $mail->ToName = 'Test to name';
         $mail->Subject = $subject;
         if ($ishtml) {
             $mail->IsHTML(true);
             $mail->Encoding = 'quoted-printable';
             $mail->Body = $html;
             $mail->AltBody = "\n{$text}\n";
         } else {
             $mail->IsHTML(false);
             $mail->Body = "\n{$text}\n";
         }
         foreach ($batch as $user) {
             $mail->AddBCC($user->email);
         }
         $emailcount++;
         if (!$mail->Send()) {
             $users = '';
             foreach ($batch as $user) {
                 if ($users) {
                     $users .= ', ';
                 }
                 $users .= $user->id;
             }
             if ($showerrortext) {
                 mtrace('Error sending email "' . $subject . '": "' . $mail->ErrorInfo . '" (' . $showerrortext . '). Users affected: ' . $users);
             }
         } else {
             // Mail send successful; log all users
             foreach ($batch as $user) {
                 // Note this log entry is in the same format as the
                 // main mail function
                 $params = array('other' => array('username' => $user->username, 'subject' => $subject), 'context' => context_system::instance(), 'relateduserid' => $user->id);
                 $event = \mod_forumng\event\mail_sent::create($params);
                 $event->trigger();
             }
         }
     }
     return $emailcount;
 }
Example #8
0
function local_send_confirmation_email($user)
{
    global $CFG, $USER;
    if (function_exists('login_signup_form')) {
        $mform_signup = new login_signup_form();
        $formdata = $mform_signup->get_data();
    }
    $site = get_site();
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    $data = new object();
    $data->firstname = fullname($user);
    $data->sitename = format_string($site->fullname);
    $data->admin = generate_email_signoff();
    $data->custommsg = '';
    $invite = false;
    if (isloggedin() && has_capability('moodle/local:invitenewuser', $sitecontext)) {
        $supportuser = $USER;
        $data->fromuser = fullname($supportuser);
        $invite = true;
    } else {
        $supportuser = generate_email_supportuser();
    }
    if (!empty($formdata->message)) {
        $data->custommsg = $formdata->message;
    }
    $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
    if ($invite) {
        $data->link = $CFG->wwwroot . '/local/login/confirm.php?data=' . $user->secret . '/' . urlencode($user->username);
        $message = get_string('emailconfirmation', 'block_tao_team_groups', $data);
    } else {
        $data->link = $CFG->wwwroot . '/login/confirm.php?data=' . $user->secret . '/' . urlencode($user->username);
        $message = get_string('emailconfirmation', 'block_tao_team_groups', $data);
    }
    $messagehtml = text_to_html($message, false, false, true);
    $user->mailformat = 1;
    // Always send HTML version as well
    return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
}
 /**
  * Send the password to the user via email.
  *
  * @global object
  * @global object
  * @param user $user A {@link $USER} object
  * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
  */
 public function mail_password($user, $password)
 {
     global $CFG, $DB;
     $site = get_site();
     $supportuser = generate_email_supportuser();
     $a = new stdClass();
     $a->firstname = fullname($user, true);
     $a->sitename = format_string($site->fullname);
     $a->username = $user->username;
     $a->newpassword = $password;
     $a->link = $CFG->wwwroot . '/login/';
     $a->signoff = generate_email_signoff();
     $message = get_string('newusernewpasswordtext', '', $a);
     $subject = format_string($site->fullname) . ': ' . get_string('newusernewpasswordsubj');
     return email_to_user($user, $supportuser, $subject, $message);
 }
Example #10
0
    // cannot run accept on message with no accept
    if ($accept && (!isset($metadata->onaccept) || !$metadata->onaccept)) {
        continue;
    }

    // cannot run accept on message type LINK in bulk action
    if ($accept && isset($metadata->onaccept) && $metadata->msgtype == MSG_TYPE_LINK) {
        continue;
    }

    $display = isset($metadata->msgtype) ? message_msgtype_text($metadata->msgtype) : array('icon' => '', 'text' => '');
    $type = $display['icon'];
    $type_alt = $display['text'];

    if ($msg->useridfrom == 0) {
        $from = generate_email_supportuser();
    } else {
        $from = $DB->get_record('user', array('id' => $msg->useridfrom));
    }
    $fromname = fullname($from) . " ({$from->email})";

    $icon = $OUTPUT->pix_icon('/msgicons/'.$metadata->icon, format_string($msg->subject), 'local_core', array('class'=>'msgicon', 'title' => format_string($msg->subject)));
    $cells = array();
    $cell = new html_table_cell(html_writer::tag('div', $icon, array('id' => 'dismiss-type')));
    $cell->attributes['class'] = 'msgs-action-right';
    $cells []= $cell;
    $cell = new html_table_cell(html_writer::tag('div', $fromname, array('id' => 'dismiss-from')));
    $cell->attributes['class'] = 'msgs-action-right';
    $cells []= $cell;
    $cell = new html_table_cell(html_writer::tag('div', $msg->fullmessage, array('id' => 'dismiss-statement')));
    $cell->attributes['class'] = 'msgs-action-right';
Example #11
0
/**
 * Lockout user and send notification email.
 *
 * @param stdClass $user
 */
function login_lock_account($user)
{
    global $CFG, $SESSION;
    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);
        // Some nasty hackery to get strings and dates localised for target user.
        $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null;
        if (get_string_manager()->translation_exists($user->lang, false)) {
            $SESSION->lang = $user->lang;
            moodle_setlocale();
        }
        $site = get_site();
        $supportuser = generate_email_supportuser();
        $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);
        }
        if ($SESSION->lang !== $sessionlang) {
            $SESSION->lang = $sessionlang;
            moodle_setlocale();
        }
    }
}
Example #12
0
 /**
  * Sign up a new user ready for confirmation.
  * Password is passed in plaintext.
  *
  * @param object $user new user object (with system magic quotes)
  * @param boolean $notify print notice with link and terminate
  */
 function user_signup($user, $notify = true)
 {
     global $CFG;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     $user->password = hash_internal_user_password($user->password);
     if (!($user->id = insert_record('user', $user))) {
         print_error('auth_emailnoinsert', 'auth');
     }
     /// Save any custom profile field information
     profile_save_data($user);
     //Added by JAM: 12.02.2010 - Call the set user time-zone for WS, cannot set time-zone until, user is created
     setWSUserDefaultTimeZone($user->username, $user);
     $user = get_record('user', 'id', $user->id);
     events_trigger('user_created', $user);
     //Added by JAM: 01.06.2011 - this is where the user id exists
     if (!addQSUser($user)) {
         admin_signuperror_email($user);
         // Added: JAM - 01.06.2011
         //error('An error has occured, please try again shortly.');
     }
     if (!send_confirmation_email($user)) {
         print_error('auth_emailnoemail', 'auth');
     }
     if ($notify) {
         global $CFG;
         $emailconfirm = get_string('emailconfirm');
         $navlinks = array();
         $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc');
         $navigation = build_navigation($navlinks);
         print_header($emailconfirm, $emailconfirm, $navigation);
         // Added by SMS: 7/28/2011
         $data = new object();
         $data->useremail = $user->email;
         $supportuser = generate_email_supportuser();
         $data->adminemail = $supportuser->email;
         // Edited by SMS: 7/28/2011
         // notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
         notice(get_string('emailconfirmsent', '', $data), "{$CFG->wwwroot}/index.php");
     } else {
         return true;
     }
 }