3 * StatusNet, the distributed open-source microblogging tool
5 * utilities for sending email
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @author Zach Copley <zach@status.net>
26 * @author Robin Millette <millette@status.net>
27 * @author Sarven Capadisli <csarven@status.net>
28 * @copyright 2008 StatusNet, Inc.
29 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
30 * @link http://status.net/
33 if (!defined('GNUSOCIAL')) { exit(1); }
35 require_once 'Mail.php';
38 * return the configured mail backend
40 * Uses the $config array to make a mail backend. Cached so it is safe to call
43 * @return Mail backend
45 function mail_backend()
47 static $backend = null;
52 $backend = $mail->factory(common_config('mail', 'backend'),
53 common_config('mail', 'params') ?: array());
54 if ($_PEAR->isError($backend)) {
55 throw new EmailException($backend->getMessage(), $backend->getCode());
62 * send an email to one or more recipients
64 * @param array $recipients array of strings with email addresses of recipients
65 * @param array $headers array mapping strings to strings for email headers
66 * @param string $body body of the email
68 * @return boolean success flag
70 function mail_send($recipients, $headers, $body)
75 // XXX: use Mail_Queue... maybe
76 $backend = mail_backend();
78 if (!isset($headers['Content-Type'])) {
79 $headers['Content-Type'] = 'text/plain; charset=UTF-8';
82 assert($backend); // throws an error if it's bad
83 $sent = $backend->send($recipients, $headers, $body);
84 if ($_PEAR->isError($sent)) {
85 throw new EmailException($sent->getMessage(), $sent->getCode());
88 } catch (PEAR_Exception $e) {
91 "Unable to send email - '{$e->getMessage()}'. "
92 . 'Is your mail subsystem set up correctly?'
99 * returns the configured mail domain
101 * Defaults to the server name.
103 * @return string mail domain, suitable for making email addresses.
105 function mail_domain()
107 $maildomain = common_config('mail', 'domain');
109 $maildomain = common_config('site', 'server');
115 * returns a good address for sending email from this server
117 * Uses either the configured value or a faked-up value made
118 * from the mail domain.
120 * @return string notify from address
122 function mail_notify_from()
124 $notifyfrom = common_config('mail', 'notifyfrom');
128 $domain = mail_domain();
130 $notifyfrom = '"'. str_replace('"', '\\"', common_config('site', 'name')) .'" <noreply@'.$domain.'>';
137 * sends email to a user
139 * @param User &$user user to send email to
140 * @param string $subject subject of the email
141 * @param string $body body of the email
142 * @param array $headers optional list of email headers
143 * @param string $address optional specification of email address
145 * @return boolean success flag
147 function mail_to_user($user, $subject, $body, $headers=array(), $address=null)
150 $address = $user->email;
153 $recipients = $address;
154 $profile = $user->getProfile();
156 $headers['Date'] = date("r", time());
157 $headers['From'] = mail_notify_from();
158 $headers['To'] = $profile->getBestName() . ' <' . $address . '>';
159 $headers['Subject'] = $subject;
161 return mail_send($recipients, $headers, $body);
165 * notify a user of subscription by another user
167 * This is just a wrapper around the profile-based version.
169 * @param User $listenee user who is being subscribed to
170 * @param User $listener user who is subscribing
172 * @see mail_subscribe_notify_profile()
176 function mail_subscribe_notify($listenee, $listener)
178 $other = $listener->getProfile();
179 mail_subscribe_notify_profile($listenee, $other);
183 * notify a user of subscription by a profile (remote or local)
185 * This function checks to see if the listenee has an email
186 * address and wants subscription notices.
188 * @param User $listenee user who's being subscribed to
189 * @param Profile $other profile of person who's listening
193 function mail_subscribe_notify_profile($listenee, $other)
195 if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
196 $listenee->email && $listenee->emailnotifysub) {
198 $profile = $listenee->getProfile();
200 $name = $profile->getBestName();
202 $long_name = ($other->fullname) ?
203 ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
205 $recipients = $listenee->email;
207 // use the recipient's localization
208 common_switch_locale($listenee->language);
210 $headers = _mail_prepare_headers('subscribe', $listenee->nickname, $other->nickname);
211 $headers['From'] = mail_notify_from();
212 $headers['To'] = $name . ' <' . $listenee->email . '>';
213 // TRANS: Subject of new-subscriber notification e-mail.
214 // TRANS: %1$s is the subscribing user's nickname, %2$s is the StatusNet sitename.
215 $headers['Subject'] = sprintf(_('%1$s is now following you on %2$s.'),
216 $other->getBestName(),
217 common_config('site', 'name'));
219 // TRANS: Main body of new-subscriber notification e-mail.
220 // TRANS: %1$s is the subscriber's long name, %2$s is the StatusNet sitename.
221 $body = sprintf(_('%1$s is now following you on %2$s.'),
223 common_config('site', 'name')) .
224 mail_profile_block($other) .
227 // reset localization
228 common_switch_locale();
229 mail_send($recipients, $headers, $body);
233 function mail_subscribe_pending_notify_profile($listenee, $other)
235 if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
236 $listenee->email && $listenee->emailnotifysub) {
238 $profile = $listenee->getProfile();
240 $name = $profile->getBestName();
242 $long_name = ($other->fullname) ?
243 ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
245 $recipients = $listenee->email;
247 // use the recipient's localization
248 common_switch_locale($listenee->language);
250 $headers = _mail_prepare_headers('subscribe', $listenee->nickname, $other->nickname);
251 $headers['From'] = mail_notify_from();
252 $headers['To'] = $name . ' <' . $listenee->email . '>';
253 // TRANS: Subject of pending new-subscriber notification e-mail.
254 // TRANS: %1$s is the subscribing user's nickname, %2$s is the StatusNet sitename.
255 $headers['Subject'] = sprintf(_('%1$s would like to listen to '.
256 'your notices on %2$s.'),
257 $other->getBestName(),
258 common_config('site', 'name'));
260 // TRANS: Main body of pending new-subscriber notification e-mail.
261 // TRANS: %1$s is the subscriber's long name, %2$s is the StatusNet sitename.
262 $body = sprintf(_('%1$s would like to listen to your notices on %2$s. ' .
263 'You may approve or reject their subscription at %3$s'),
265 common_config('site', 'name'),
266 common_local_url('subqueue', array('nickname' => $listenee->nickname))) .
267 mail_profile_block($other) .
270 // reset localization
271 common_switch_locale();
272 mail_send($recipients, $headers, $body);
276 function mail_footer_block()
278 // TRANS: Common footer block for StatusNet notification emails.
279 // TRANS: %1$s is the StatusNet sitename,
280 // TRANS: %2$s is a link to the addressed user's e-mail settings.
281 return "\n\n" . sprintf(_('Faithfully yours,'.
284 "Change your email address or ".
285 "notification options at ".'%2$s'),
286 common_config('site', 'name'),
287 common_local_url('emailsettings')) . "\n";
291 * Format a block of profile info for a plaintext notification email.
293 * @param Profile $profile
296 function mail_profile_block($profile)
299 // TRANS: %1$s is the subscriber's profile URL, %2$s is the subscriber's location (or empty)
300 // TRANS: %3$s is the subscriber's homepage URL (or empty), %4%s is the subscriber's bio (or empty)
304 // TRANS: Profile info line in notification e-mail.
305 // TRANS: %s is a URL.
306 $out[] = sprintf(_("Profile: %s"), $profile->profileurl);
307 if ($profile->location) {
308 // TRANS: Profile info line in notification e-mail.
309 // TRANS: %s is a location.
310 $out[] = sprintf(_("Location: %s"), $profile->location);
312 if ($profile->homepage) {
313 // TRANS: Profile info line in notification e-mail.
314 // TRANS: %s is a homepage.
315 $out[] = sprintf(_("Homepage: %s"), $profile->homepage);
318 // TRANS: Profile info line in notification e-mail.
319 // TRANS: %s is biographical information.
320 $out[] = sprintf(_("Bio: %s"), $profile->bio);
323 $blocklink = common_local_url('block', array('profileid' => $profile->id));
324 // This'll let ModPlus add the remote profile info so it's possible
325 // to block remote users directly...
326 Event::handle('MailProfileInfoBlockLink', array($profile, &$blocklink));
328 // TRANS: This is a paragraph in a new-subscriber e-mail.
329 // TRANS: %s is a URL where the subscriber can be reported as abusive.
330 $out[] = sprintf(_('If you believe this account is being used abusively, ' .
331 'you can block them from your subscribers list and ' .
332 'report as spam to site administrators at %s.'),
336 return implode("\n", $out);
340 * notify a user of their new incoming email address
342 * User's email and incoming fields should already be updated.
344 * @param User $user user with the new address
348 function mail_new_incoming_notify($user)
350 $profile = $user->getProfile();
352 $name = $profile->getBestName();
354 $headers['From'] = $user->incomingemail;
355 $headers['To'] = $name . ' <' . $user->email . '>';
356 // TRANS: Subject of notification mail for new posting email address.
357 // TRANS: %s is the StatusNet sitename.
358 $headers['Subject'] = sprintf(_('New email address for posting to %s'),
359 common_config('site', 'name'));
361 // TRANS: Body of notification mail for new posting email address.
362 // TRANS: %1$s is the StatusNet sitename, %2$s is the e-mail address to send
363 // TRANS: to to post by e-mail, %3$s is a URL to more instructions.
364 $body = sprintf(_("You have a new posting address on %1\$s.\n\n".
365 "Send email to %2\$s to post new messages.\n\n".
366 "More email instructions at %3\$s."),
367 common_config('site', 'name'),
368 $user->incomingemail,
369 common_local_url('doc', array('title' => 'email'))) .
372 mail_send($user->email, $headers, $body);
376 * generate a new address for incoming messages
378 * @todo check the database for uniqueness
380 * @return string new email address for incoming messages
382 function mail_new_incoming_address()
384 $prefix = common_confirmation_code(64);
385 $suffix = mail_domain();
386 return $prefix . '@' . $suffix;
390 * broadcast a notice to all subscribers with SMS notification on
392 * This function sends SMS messages to all users who have sms addresses;
393 * have sms notification on; and have sms enabled for this particular
396 * @param Notice $notice The notice to broadcast
398 * @return success flag
400 function mail_broadcast_notice_sms($notice)
402 // Now, get users subscribed to this profile
406 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
407 $replies = $notice->getReplies();
408 $user->query('SELECT nickname, smsemail, incomingemail ' .
409 "FROM $UT LEFT OUTER JOIN subscription " .
410 "ON $UT.id = subscription.subscriber " .
411 'AND subscription.subscribed = ' . $notice->profile_id . ' ' .
412 'AND subscription.subscribed != subscription.subscriber ' .
413 // Users (other than the sender) who `want SMS notices':
414 "WHERE $UT.id != " . $notice->profile_id . ' ' .
415 "AND $UT.smsemail IS NOT null " .
416 "AND $UT.smsnotify = 1 " .
417 // ... where either the user _is_ subscribed to the sender
418 // (any of the "subscription" fields IS NOT null)
419 // and wants to get SMS for all of this scribe's notices...
420 'AND (subscription.sms = 1 ' .
421 // ... or where the user was mentioned in
422 // or replied-to with the notice:
423 ($replies ? sprintf("OR $UT.id in (%s)",
424 implode(',', $replies))
428 while ($user->fetch()) {
430 'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
432 $success = mail_send_sms_notice_address($notice,
434 $user->incomingemail,
437 // XXX: Not sure, but I think that's the right thing to do
438 common_log(LOG_WARNING,
439 'Sending notice ' . $notice->id . ' to ' .
440 $user->smsemail . ' FAILED, cancelling.',
453 * send a notice to a user via SMS
455 * A convenience wrapper around mail_send_sms_notice_address()
457 * @param Notice $notice notice to send
458 * @param User $user user to receive notice
460 * @see mail_send_sms_notice_address()
462 * @return boolean success flag
464 function mail_send_sms_notice($notice, $user)
466 return mail_send_sms_notice_address($notice,
468 $user->incomingemail,
473 * send a notice to an SMS email address from a given address
475 * We use the user's incoming email address as the "From" address to make
476 * replying to notices easier.
478 * @param Notice $notice notice to send
479 * @param string $smsemail email address to send to
480 * @param string $incomingemail email address to set as 'from'
481 * @param string $nickname nickname to add to beginning
483 * @return boolean success flag
485 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail, $nickname)
487 $to = $nickname . ' <' . $smsemail . '>';
489 $other = $notice->getProfile();
491 common_log(LOG_INFO, 'Sending notice ' . $notice->id .
492 ' to ' . $smsemail, __FILE__);
496 $headers['From'] = ($incomingemail) ? $incomingemail : mail_notify_from();
497 $headers['To'] = $to;
498 // TRANS: Subject line for SMS-by-email notification messages.
499 // TRANS: %s is the posting user's nickname.
500 $headers['Subject'] = sprintf(_('%s status'),
501 $other->getBestName());
503 $body = $notice->content;
505 return mail_send($smsemail, $headers, $body);
509 * send a message to confirm a claim for an SMS number
511 * @param string $code confirmation code
512 * @param string $nickname nickname of user claiming number
513 * @param string $address email address to send the confirmation to
515 * @see common_confirmation_code()
519 function mail_confirm_sms($code, $nickname, $address)
521 $recipients = $address;
523 $headers['From'] = mail_notify_from();
524 $headers['To'] = $nickname . ' <' . $address . '>';
525 // TRANS: Subject line for SMS-by-email address confirmation message.
526 $headers['Subject'] = _('SMS confirmation');
528 // TRANS: Main body heading for SMS-by-email address confirmation message.
529 // TRANS: %s is the addressed user's nickname.
530 $body = sprintf(_('%s: confirm you own this phone number with this code:'), $nickname);
535 mail_send($recipients, $headers, $body);
539 * send a mail message to notify a user of a 'nudge'
541 * @param User $from user nudging
542 * @param User $to user being nudged
544 * @return boolean success flag
546 function mail_notify_nudge($from, $to)
548 common_switch_locale($to->language);
549 // TRANS: Subject for 'nudge' notification email.
550 // TRANS: %s is the nudging user.
551 $subject = sprintf(_('You have been nudged by %s'), $from->nickname);
553 $from_profile = $from->getProfile();
555 // TRANS: Body for 'nudge' notification email.
556 // TRANS: %1$s is the nuding user's long name, $2$s is the nudging user's nickname,
557 // TRANS: %3$s is a URL to post notices at.
558 $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ".
559 "these days and is inviting you to post some news.\n\n".
560 "So let's hear from you :)\n\n".
562 "Don't reply to this email; it won't get to them."),
563 $from_profile->getBestName(),
565 common_local_url('all', array('nickname' => $to->nickname))) .
567 common_switch_locale();
569 $headers = _mail_prepare_headers('nudge', $to->nickname, $from->nickname);
571 return mail_to_user($to, $subject, $body, $headers);
575 * send a message to notify a user of a direct message (DM)
577 * This function checks to see if the recipient wants notification
578 * of DMs and has a configured email address.
580 * @param Message $message message to notify about
581 * @param User $from user sending message; default to sender
582 * @param User $to user receiving message; default to recipient
584 * @return boolean success code
586 function mail_notify_message($message, $from=null, $to=null)
588 if (is_null($from)) {
589 $from = User::getKV('id', $message->from_profile);
593 $to = User::getKV('id', $message->to_profile);
596 if (is_null($to->email) || !$to->emailnotifymsg) {
600 common_switch_locale($to->language);
601 // TRANS: Subject for direct-message notification email.
602 // TRANS: %s is the sending user's nickname.
603 $subject = sprintf(_('New private message from %s'), $from->nickname);
605 $from_profile = $from->getProfile();
607 // TRANS: Body for direct-message notification email.
608 // TRANS: %1$s is the sending user's long name, %2$s is the sending user's nickname,
609 // TRANS: %3$s is the message content, %4$s a URL to the message,
610 $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n".
611 "------------------------------------------------------\n".
613 "------------------------------------------------------\n\n".
614 "You can reply to their message here:\n\n".
616 "Don't reply to this email; it won't get to them."),
617 $from_profile->getBestName(),
620 common_local_url('newmessage', array('to' => $from->id))) .
623 $headers = _mail_prepare_headers('message', $to->nickname, $from->nickname);
625 common_switch_locale();
626 return mail_to_user($to, $subject, $body, $headers);
630 * Notify a user that they have received an "attn:" message AKA "@-reply"
632 * @param Profile $rcpt The Profile who recevied the notice, should be a local user
633 * @param Notice $notice The notice that was sent
637 function mail_notify_attn(Profile $rcpt, Notice $notice)
639 if (!$rcpt->isLocal()) {
643 $sender = $notice->getProfile();
644 if ($rcpt->sameAs($sender)) {
648 // See if the notice's author who mentions this user is sandboxed
649 if (!$sender->hasRight(Right::EMAILONREPLY)) {
653 // If the author has blocked the author, don't spam them with a notification.
654 if ($rcpt->hasBlocked($sender)) {
658 $user = $rcpt->getUser();
659 if (!$user->receivesEmailNotifications()) {
663 common_switch_locale($user->language);
665 if ($notice->hasConversation()) {
666 $conversationUrl = common_local_url('conversation',
667 array('id' => $notice->conversation)).'#notice-'.$notice->getID();
668 // TRANS: Line in @-reply notification e-mail. %s is conversation URL.
669 $conversationEmailText = sprintf(_("The full conversation can be read here:\n\n".
670 "\t%s"), $conversationUrl) . "\n\n";
672 $conversationEmailText = '';
675 // TRANS: E-mail subject for notice notification.
676 // TRANS: %1$s is the "fancy name" for a profile.
677 $subject = sprintf(_('%1$s sent a notice to your attention'), $sender->getFancyName());
679 // TRANS: Body of @-reply notification e-mail.
680 // TRANS: %1$s is the sending user's name, $2$s is the StatusNet sitename,
681 // TRANS: %3$s is a URL to the notice, %4$s is the notice text,
682 // TRANS: %5$s is the text "The full conversation can be read here:" and a URL to the full conversion if it exists (otherwise empty),
683 // TRANS: %6$s is a URL to reply to the notice, %7$s is a URL to all @-replies for the addressed user,
684 $body = sprintf(_("%1\$s just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
685 "The notice is here:\n\n".
690 "You can reply back here:\n\n".
692 "The list of all @-replies for you here:\n\n" .
694 $sender->getFancyName(),//%1
695 common_config('site', 'name'),//%2
696 common_local_url('shownotice',
697 array('notice' => $notice->getID())),//%3
698 $notice->getContent(),//%4
699 $conversationEmailText,//%5
700 common_local_url('newnotice',
701 array('replyto' => $sender->getNickname(), 'inreplyto' => $notice->getID())),//%6
702 common_local_url('replies',
703 array('nickname' => $rcpt->getNickname()))) . //%7
705 $headers = _mail_prepare_headers('mention', $rcpt->getNickname(), $sender->getNickname());
707 common_switch_locale();
708 mail_to_user($user, $subject, $body, $headers);
712 * Prepare the common mail headers used in notification emails
714 * @param string $msg_type type of message being sent to the user
715 * @param string $to nickname of the receipient
716 * @param string $from nickname of the user triggering the notification
718 * @return array list of mail headers to include in the message
720 function _mail_prepare_headers($msg_type, $to, $from)
723 'X-StatusNet-MessageType' => $msg_type,
724 'X-StatusNet-TargetUser' => $to,
725 'X-StatusNet-SourceUser' => $from,
726 'X-StatusNet-Domain' => common_config('site', 'server')
733 * Send notification emails to group administrator.
735 * @param User_group $group
736 * @param Profile $joiner
738 function mail_notify_group_join($group, $joiner)
740 // This returns a Profile query...
741 $admin = $group->getAdmins();
742 while ($admin->fetch()) {
743 // We need a local user for email notifications...
744 $adminUser = User::getKV('id', $admin->id);
745 // @fixme check for email preference?
746 if ($adminUser && $adminUser->email) {
747 // use the recipient's localization
748 common_switch_locale($adminUser->language);
750 $headers = _mail_prepare_headers('join', $admin->nickname, $joiner->nickname);
751 $headers['From'] = mail_notify_from();
752 $headers['To'] = $admin->getBestName() . ' <' . $adminUser->email . '>';
753 // TRANS: Subject of group join notification e-mail.
754 // TRANS: %1$s is the joining user's nickname, %2$s is the group name, and %3$s is the StatusNet sitename.
755 $headers['Subject'] = sprintf(_('%1$s has joined '.
756 'your group %2$s on %3$s'),
757 $joiner->getBestName(),
758 $group->getBestName(),
759 common_config('site', 'name'));
761 // TRANS: Main body of group join notification e-mail.
762 // TRANS: %1$s is the subscriber's long name, %2$s is the group name, and %3$s is the StatusNet sitename,
763 // TRANS: %4$s is a block of profile info about the subscriber.
764 // TRANS: %5$s is a link to the addressed user's e-mail settings.
765 $body = sprintf(_('%1$s has joined your group %2$s on %3$s.'),
766 $joiner->getFancyName(),
767 $group->getFancyName(),
768 common_config('site', 'name')) .
769 mail_profile_block($joiner) .
772 // reset localization
773 common_switch_locale();
774 mail_send($adminUser->email, $headers, $body);
781 * Send notification emails to group administrator.
783 * @param User_group $group
784 * @param Profile $joiner
786 function mail_notify_group_join_pending($group, $joiner)
788 $admin = $group->getAdmins();
789 while ($admin->fetch()) {
790 // We need a local user for email notifications...
791 $adminUser = User::getKV('id', $admin->id);
792 // @fixme check for email preference?
793 if ($adminUser && $adminUser->email) {
794 // use the recipient's localization
795 common_switch_locale($adminUser->language);
797 $headers = _mail_prepare_headers('join', $admin->nickname, $joiner->nickname);
798 $headers['From'] = mail_notify_from();
799 $headers['To'] = $admin->getBestName() . ' <' . $adminUser->email . '>';
800 // TRANS: Subject of pending group join request notification e-mail.
801 // TRANS: %1$s is the joining user's nickname, %2$s is the group name, and %3$s is the StatusNet sitename.
802 $headers['Subject'] = sprintf(_('%1$s wants to join your group %2$s on %3$s.'),
803 $joiner->getBestName(),
804 $group->getBestName(),
805 common_config('site', 'name'));
807 // TRANS: Main body of pending group join request notification e-mail.
808 // TRANS: %1$s is the subscriber's long name, %2$s is the group name, and %3$s is the StatusNet sitename,
809 // TRANS: %4$s is the URL to the moderation queue page.
810 $body = sprintf(_('%1$s would like to join your group %2$s on %3$s. ' .
811 'You may approve or reject their group membership at %4$s'),
812 $joiner->getFancyName(),
813 $group->getFancyName(),
814 common_config('site', 'name'),
815 common_local_url('groupqueue', array('nickname' => $group->nickname))) .
816 mail_profile_block($joiner) .
819 // reset localization
820 common_switch_locale();
821 mail_send($adminUser->email, $headers, $body);