Exemplo n.º 1
0
/** 
 * Always use this function for all emails to users
 * 
 * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email
 * @param object $userfrom user object to send email from. If null, email will come from mahara
 * @param string $subject email subject
 * @param string $messagetext text version of email
 * @param string $messagehtml html version of email (will send both html and text)
 * @param array  $customheaders email headers
 * @throws EmailException
 * @throws EmailDisabledException
 */
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml = '', $customheaders = null)
{
    global $IDPJUMPURL;
    static $mnetjumps = array();
    if (!get_config('sendemail')) {
        // You can entirely disable Mahara from sending any e-mail via the
        // 'sendemail' configuration variable
        return true;
    }
    if (empty($userto)) {
        throw new InvalidArgumentException("empty user given to email_user");
    }
    if (!($mailinfo = can_receive_email($userto))) {
        throw new EmailDisabledException("email for this user has been disabled");
    }
    // If the user is a remote xmlrpc user, trawl through the email text for URLs
    // to our wwwroot and modify the url to direct the user's browser to login at
    // their home site before hitting the link on this site
    if (!empty($userto->mnethostwwwroot) && !empty($userto->mnethostapp)) {
        require_once get_config('docroot') . 'auth/xmlrpc/lib.php';
        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$userto->mnethostwwwroot])) {
            $IDPJUMPURL = $mnetjumps[$userto->mnethostwwwroot];
        } else {
            $mnetjumps[$userto->mnethostwwwroot] = $IDPJUMPURL = PluginAuthXmlrpc::get_jump_url_prefix($userto->mnethostwwwroot, $userto->mnethostapp);
        }
        $wwwroot = get_config('wwwroot');
        $messagetext = preg_replace_callback('%(' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))%', 'localurl_to_jumpurl', $messagetext);
        $messagehtml = preg_replace_callback('%href=["\'`](' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))["\'`]%', 'localurl_to_jumpurl', $messagehtml);
    }
    require_once 'phpmailer/class.phpmailer.php';
    $mail = new phpmailer();
    // Leaving this commented out - there's no reason for people to know this
    //$mail->Version = 'Mahara ' . get_config('release');
    $mail->PluginDir = get_config('libroot') . 'phpmailer/';
    $mail->CharSet = 'UTF-8';
    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
    } else {
        if (empty($smtphosts)) {
            // use PHP mail() = sendmail
            $mail->IsMail();
        } else {
            $mail->IsSMTP();
            // use SMTP directly
            $mail->Host = get_config('smtphosts');
            if (get_config('smtpuser')) {
                // Use SMTP authentication
                $mail->SMTPAuth = true;
                $mail->Username = get_config('smtpuser');
                $mail->Password = get_config('smtppass');
            }
        }
    }
    if (get_config('bounces_handle') && isset($mailinfo->owner)) {
        $mail->Sender = generate_email_processing_address($mailinfo->owner, $userto);
    }
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
        $mail->FromName = isset($userfrom->id) ? display_name($userfrom, $userto) : get_config('sitename');
        $customheaders[] = 'Precedence: Bulk';
        // Try to avoid pesky out of office responses
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
        if ($messagehtml) {
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
        }
    } else {
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
        $mail->FromName = display_name($userfrom, $userto);
    }
    $replytoset = false;
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
            $mail->AddCustomHeader($customheader);
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
        }
    }
    if (!$replytoset) {
        $mail->AddReplyTo($mail->From, $mail->FromName);
    }
    $mail->Subject = substr(stripslashes($subject), 0, 900);
    if ($to = get_config('sendallemailto')) {
        // Admins can configure the system to send all email to a given address
        // instead of whoever would receive it, useful for debugging.
        $mail->addAddress($to);
        $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email);
        $messagetext = $notice . "\n\n" . $messagetext;
        if ($messagehtml) {
            $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml;
        }
        $usertoname = display_name($userto, $userto, true) . ' (' . get_string('divertingemailto', 'mahara', $to) . ')';
    } else {
        $usertoname = display_name($userto, $userto);
        if (empty($userto->email)) {
            throw new EmailException("Cannot send email to {$usertoname} with subject {$subject}.  User has no primary email address set.");
        }
        $mail->AddAddress($userto->email, $usertoname);
        $to = $userto->email;
    }
    $mail->WordWrap = 79;
    if ($messagehtml) {
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = $messagetext;
    } else {
        $mail->IsHTML(false);
        $mail->Body = $messagetext;
    }
    if ($mail->Send()) {
        if ($logfile = get_config('emaillog')) {
            $docroot = get_config('docroot');
            @($client = (string) $_SERVER['REMOTE_ADDR']);
            @($script = (string) $_SERVER['SCRIPT_FILENAME']);
            if (strpos($script, $docroot) === 0) {
                $script = substr($script, strlen($docroot));
            }
            $line = "{$to} <- {$mail->From} - " . str_shorten_text($mail->Subject, 200);
            @error_log('[' . date("Y-m-d h:i:s") . "] [{$client}] [{$script}] {$line}\n", 3, $logfile);
        }
        // Update the count of sent mail
        update_send_count($userto);
        return true;
    }
    throw new EmailException("Couldn't send email to {$usertoname} with subject {$subject}. " . "Error from phpmailer was: " . $mail->ErrorInfo);
}
Exemplo n.º 2
0
/**
 * Always use this function for all emails to users
 *
 * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email
 * @param object $userfrom user object to send email from. If null, email will come from mahara
 * @param string $subject email subject
 * @param string $messagetext text version of email
 * @param string $messagehtml html version of email (will send both html and text)
 * @param array  $customheaders email headers
 * @throws EmailException
 * @throws EmailDisabledException
 */
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml = '', $customheaders = null)
{
    global $IDPJUMPURL;
    static $mnetjumps = array();
    if (!get_config('sendemail')) {
        // You can entirely disable Mahara from sending any e-mail via the
        // 'sendemail' configuration variable
        return true;
    }
    if (empty($userto)) {
        throw new InvalidArgumentException("empty user given to email_user");
    }
    if (isset($userto->id) && empty($userto->ignoredisabled)) {
        $maildisabled = property_exists($userto, 'maildisabled') ? $userto->maildisabled : get_account_preference($userto->id, 'maildisabled') == 1;
        if ($maildisabled) {
            throw new EmailDisabledException("email for this user has been disabled");
        }
    }
    // If the user is a remote xmlrpc user, trawl through the email text for URLs
    // to our wwwroot and modify the url to direct the user's browser to login at
    // their home site before hitting the link on this site
    if (!empty($userto->mnethostwwwroot) && !empty($userto->mnethostapp)) {
        require_once get_config('docroot') . 'auth/xmlrpc/lib.php';
        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$userto->mnethostwwwroot])) {
            $IDPJUMPURL = $mnetjumps[$userto->mnethostwwwroot];
        } else {
            $mnetjumps[$userto->mnethostwwwroot] = $IDPJUMPURL = PluginAuthXmlrpc::get_jump_url_prefix($userto->mnethostwwwroot, $userto->mnethostapp);
        }
        $wwwroot = get_config('wwwroot');
        $messagetext = preg_replace_callback('%(' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))%', 'localurl_to_jumpurl', $messagetext);
        $messagehtml = preg_replace_callback('%href=["\'`](' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))["\'`]%', 'localurl_to_jumpurl', $messagehtml);
    }
    require_once 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer(true);
    $mail->CharSet = 'UTF-8';
    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
    } else {
        if (empty($smtphosts)) {
            // use PHP mail() = sendmail
            $mail->IsMail();
        } else {
            $mail->IsSMTP();
            // use SMTP directly
            $mail->Host = get_config('smtphosts');
            if (get_config('smtpuser')) {
                // Use SMTP authentication
                $mail->SMTPAuth = true;
                $mail->Username = get_config('smtpuser');
                $mail->Password = get_config('smtppass');
                $mail->SMTPSecure = get_config('smtpsecure');
                $mail->Port = get_config('smtpport');
                if (get_config('smtpsecure') && !get_config('smtpport')) {
                    // Encrypted connection with no port. Use default one.
                    if (get_config('smtpsecure') == 'ssl') {
                        $mail->Port = 465;
                    } elseif (get_config('smtpsecure') == 'tls') {
                        $mail->Port = 587;
                    }
                }
            }
        }
    }
    if (get_config('bounces_handle') && !empty($userto->id) && empty($maildisabled)) {
        $mail->Sender = generate_email_processing_address($userto->id, $userto);
    }
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
        $mail->FromName = isset($userfrom->id) ? display_name($userfrom, $userto) : get_config('sitename');
        $customheaders[] = 'Precedence: Bulk';
        // Try to avoid pesky out of office responses
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
        if ($messagehtml) {
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
        }
    } else {
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
        $mail->FromName = display_name($userfrom, $userto);
    }
    $replytoset = false;
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
            // To prevent duplicated declaration of the field "Message-ID",
            // don't add it into the $mail->CustomHeader[].
            if (false === stripos($customheader, 'message-id')) {
                // Hack the fields "In-Reply-To" and "References":
                // add touser<userID>
                if (0 === stripos($customheader, 'in-reply-to') || 0 === stripos($customheader, 'references')) {
                    $customheader = preg_replace('/<forumpost(\\d+)/', '<forumpost${1}touser' . $userto->id, $customheader);
                }
                $mail->AddCustomHeader($customheader);
            } else {
                list($h, $msgid) = explode(':', $customheader, 2);
                // Hack the "Message-ID": add touser<userID> to make sure
                // the "Message-ID" is unique
                $msgid = preg_replace('/<forumpost(\\d+)/', '<forumpost${1}touser' . $userto->id, $msgid);
                $mail->MessageID = trim($msgid);
            }
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
        }
    }
    $mail->Subject = substr(stripslashes($subject), 0, 900);
    try {
        if ($to = get_config('sendallemailto')) {
            // Admins can configure the system to send all email to a given address
            // instead of whoever would receive it, useful for debugging.
            $usertoname = display_name($userto, $userto, true) . ' (' . get_string('divertingemailto', 'mahara', $to) . ')';
            $mail->addAddress($to);
            $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email);
            $messagetext = $notice . "\n\n" . $messagetext;
            if ($messagehtml) {
                $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml;
            }
        } else {
            $usertoname = display_name($userto, $userto);
            $mail->AddAddress($userto->email, $usertoname);
            $to = $userto->email;
        }
        if (!$replytoset) {
            $mail->AddReplyTo($mail->From, $mail->FromName);
        }
    } catch (phpmailerException $e) {
        // If there's a phpmailer error already, assume it's an invalid address
        throw new InvalidEmailException("Cannot send email to {$usertoname} with subject {$subject}. Error from phpmailer was: " . $mail->ErrorInfo);
    }
    $mail->WordWrap = 79;
    if ($messagehtml) {
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = $messagetext;
    } else {
        $mail->IsHTML(false);
        $mail->Body = $messagetext;
    }
    try {
        $sent = $mail->Send();
    } catch (phpmailerException $e) {
        $sent = false;
    }
    if ($sent) {
        if ($logfile = get_config('emaillog')) {
            $docroot = get_config('docroot');
            @($client = (string) $_SERVER['REMOTE_ADDR']);
            @($script = (string) $_SERVER['SCRIPT_FILENAME']);
            if (strpos($script, $docroot) === 0) {
                $script = substr($script, strlen($docroot));
            }
            $line = "{$to} <- {$mail->From} - " . str_shorten_text($mail->Subject, 200);
            @error_log('[' . date("Y-m-d h:i:s") . "] [{$client}] [{$script}] {$line}\n", 3, $logfile);
        }
        if (get_config('bounces_handle')) {
            // Update the count of sent mail
            update_send_count($userto);
        }
        return true;
    }
    throw new EmailException("Couldn't send email to {$usertoname} with subject {$subject}. " . "Error from phpmailer was: " . $mail->ErrorInfo);
}