]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mail.php
Don't accept non-objects before testing with "instanceof".
[quix0rs-gnu-social.git] / lib / mail.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * utilities for sending email
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Mail
23  * @package   StatusNet
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/
31  */
32
33 if (!defined('GNUSOCIAL')) { exit(1); }
34
35 require_once 'Mail.php';
36
37 /**
38  * return the configured mail backend
39  *
40  * Uses the $config array to make a mail backend. Cached so it is safe to call
41  * more than once.
42  *
43  * @return Mail backend
44  */
45 function mail_backend()
46 {
47     static $backend = null;
48     global $_PEAR;
49
50     if (!$backend) {
51         $mail = new Mail();
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());
56         }
57     }
58     return $backend;
59 }
60
61 /**
62  * send an email to one or more recipients
63  *
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
67  *
68  * @return boolean success flag
69  */
70 function mail_send($recipients, $headers, $body)
71 {
72     global $_PEAR;
73
74     try {
75         // XXX: use Mail_Queue... maybe
76         $backend = mail_backend();
77
78         if (!isset($headers['Content-Type'])) {
79            $headers['Content-Type'] = 'text/plain; charset=UTF-8';
80         }
81
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());
86         }
87         return true;
88     } catch (PEAR_Exception $e) {
89         common_log(
90             LOG_ERR,
91             "Unable to send email - '{$e->getMessage()}'. "
92             . 'Is your mail subsystem set up correctly?'
93         );
94         return false;
95     }
96 }
97
98 /**
99  * returns the configured mail domain
100  *
101  * Defaults to the server name.
102  *
103  * @return string mail domain, suitable for making email addresses.
104  */
105 function mail_domain()
106 {
107     $maildomain = common_config('mail', 'domain');
108     if (!$maildomain) {
109         $maildomain = common_config('site', 'server');
110     }
111     return $maildomain;
112 }
113
114 /**
115  * returns a good address for sending email from this server
116  *
117  * Uses either the configured value or a faked-up value made
118  * from the mail domain.
119  *
120  * @return string notify from address
121  */
122 function mail_notify_from()
123 {
124     $notifyfrom = common_config('mail', 'notifyfrom');
125
126     if (!$notifyfrom) {
127
128         $domain = mail_domain();
129
130         $notifyfrom = '"'. str_replace('"', '\\"', common_config('site', 'name')) .'" <noreply@'.$domain.'>';
131     }
132
133     return $notifyfrom;
134 }
135
136 /**
137  * sends email to a user
138  *
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
144  *
145  * @return boolean success flag
146  */
147 function mail_to_user(&$user, $subject, $body, $headers=array(), $address=null)
148 {
149     if (!$address) {
150         $address = $user->email;
151     }
152
153     $recipients = $address;
154     $profile    = $user->getProfile();
155
156     $headers['Date']    = date("r", time());
157     $headers['From']    = mail_notify_from();
158     $headers['To']      = $profile->getBestName() . ' <' . $address . '>';
159     $headers['Subject'] = $subject;
160
161     return mail_send($recipients, $headers, $body);
162 }
163
164 /**
165  * Send an email to confirm a user's control of an email address
166  *
167  * @param User   $user     User claiming the email address
168  * @param string $code     Confirmation code
169  * @param string $nickname Nickname of user
170  * @param string $address  email address to confirm
171  *
172  * @see common_confirmation_code()
173  *
174  * @return success flag
175  */
176 function mail_confirm_address($user, $code, $nickname, $address, $url=null)
177 {
178     if (empty($url)) {
179         $url = common_local_url('confirmaddress', array('code' => $code));
180     }
181
182     // TRANS: Subject for address confirmation email.
183     $subject = _('Email address confirmation');
184
185     // TRANS: Body for address confirmation email.
186     // TRANS: %1$s is the addressed user's nickname, %2$s is the StatusNet sitename,
187     // TRANS: %3$s is the URL to confirm at.
188     $body = sprintf(_("Hey, %1\$s.\n\n".
189                       "Someone just entered this email address on %2\$s.\n\n" .
190                       "If it was you, and you want to confirm your entry, ".
191                       "use the URL below:\n\n\t%3\$s\n\n" .
192                       "If not, just ignore this message.\n\n".
193                       "Thanks for your time, \n%2\$s\n"),
194                     $nickname,
195                     common_config('site', 'name'),
196                     $url);
197
198     $headers = array();
199
200     return mail_to_user($user, $subject, $body, $headers, $address);
201 }
202
203 /**
204  * notify a user of subscription by another user
205  *
206  * This is just a wrapper around the profile-based version.
207  *
208  * @param User $listenee user who is being subscribed to
209  * @param User $listener user who is subscribing
210  *
211  * @see mail_subscribe_notify_profile()
212  *
213  * @return void
214  */
215 function mail_subscribe_notify($listenee, $listener)
216 {
217     $other = $listener->getProfile();
218     mail_subscribe_notify_profile($listenee, $other);
219 }
220
221 /**
222  * notify a user of subscription by a profile (remote or local)
223  *
224  * This function checks to see if the listenee has an email
225  * address and wants subscription notices.
226  *
227  * @param User    $listenee user who's being subscribed to
228  * @param Profile $other    profile of person who's listening
229  *
230  * @return void
231  */
232 function mail_subscribe_notify_profile($listenee, $other)
233 {
234     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
235         $listenee->email && $listenee->emailnotifysub) {
236
237         $profile = $listenee->getProfile();
238
239         $name = $profile->getBestName();
240
241         $long_name = ($other->fullname) ?
242           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
243
244         $recipients = $listenee->email;
245
246         // use the recipient's localization
247         common_switch_locale($listenee->language);
248
249         $headers = _mail_prepare_headers('subscribe', $listenee->nickname, $other->nickname);
250         $headers['From']    = mail_notify_from();
251         $headers['To']      = $name . ' <' . $listenee->email . '>';
252         // TRANS: Subject of new-subscriber notification e-mail.
253         // TRANS: %1$s is the subscribing user's nickname, %2$s is the StatusNet sitename.
254         $headers['Subject'] = sprintf(_('%1$s is now following you on %2$s.'),
255                                       $other->getBestName(),
256                                       common_config('site', 'name'));
257
258         // TRANS: Main body of new-subscriber notification e-mail.
259         // TRANS: %1$s is the subscriber's long name, %2$s is the StatusNet sitename.
260         $body = sprintf(_('%1$s is now following you on %2$s.'),
261                         $long_name,
262                         common_config('site', 'name')) .
263                 mail_profile_block($other) .
264                 mail_footer_block();
265
266         // reset localization
267         common_switch_locale();
268         mail_send($recipients, $headers, $body);
269     }
270 }
271
272 function mail_subscribe_pending_notify_profile($listenee, $other)
273 {
274     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
275         $listenee->email && $listenee->emailnotifysub) {
276
277         $profile = $listenee->getProfile();
278
279         $name = $profile->getBestName();
280
281         $long_name = ($other->fullname) ?
282           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
283
284         $recipients = $listenee->email;
285
286         // use the recipient's localization
287         common_switch_locale($listenee->language);
288
289         $headers = _mail_prepare_headers('subscribe', $listenee->nickname, $other->nickname);
290         $headers['From']    = mail_notify_from();
291         $headers['To']      = $name . ' <' . $listenee->email . '>';
292         // TRANS: Subject of pending new-subscriber notification e-mail.
293         // TRANS: %1$s is the subscribing user's nickname, %2$s is the StatusNet sitename.
294         $headers['Subject'] = sprintf(_('%1$s would like to listen to '.
295                                         'your notices on %2$s.'),
296                                       $other->getBestName(),
297                                       common_config('site', 'name'));
298
299         // TRANS: Main body of pending new-subscriber notification e-mail.
300         // TRANS: %1$s is the subscriber's long name, %2$s is the StatusNet sitename.
301         $body = sprintf(_('%1$s would like to listen to your notices on %2$s. ' .
302                           'You may approve or reject their subscription at %3$s'),
303                         $long_name,
304                         common_config('site', 'name'),
305                         common_local_url('subqueue', array('nickname' => $listenee->nickname))) .
306                 mail_profile_block($other) .
307                 mail_footer_block();
308
309         // reset localization
310         common_switch_locale();
311         mail_send($recipients, $headers, $body);
312     }
313 }
314
315 function mail_footer_block()
316 {
317     // TRANS: Common footer block for StatusNet notification emails.
318     // TRANS: %1$s is the StatusNet sitename,
319     // TRANS: %2$s is a link to the addressed user's e-mail settings.
320     return "\n\n" . sprintf(_('Faithfully yours,'.
321                               "\n".'%1$s.'."\n\n".
322                               "----\n".
323                               "Change your email address or ".
324                               "notification options at ".'%2$s'),
325                             common_config('site', 'name'),
326                             common_local_url('emailsettings')) . "\n";
327 }
328
329 /**
330  * Format a block of profile info for a plaintext notification email.
331  *
332  * @param Profile $profile
333  * @return string
334  */
335 function mail_profile_block($profile)
336 {
337     // TRANS: Layout for
338     // TRANS: %1$s is the subscriber's profile URL, %2$s is the subscriber's location (or empty)
339     // TRANS: %3$s is the subscriber's homepage URL (or empty), %4%s is the subscriber's bio (or empty)
340     $out = array();
341     $out[] = "";
342     $out[] = "";
343     // TRANS: Profile info line in notification e-mail.
344     // TRANS: %s is a URL.
345     $out[] = sprintf(_("Profile: %s"), $profile->profileurl);
346     if ($profile->location) {
347         // TRANS: Profile info line in notification e-mail.
348         // TRANS: %s is a location.
349         $out[] = sprintf(_("Location: %s"), $profile->location);
350     }
351     if ($profile->homepage) {
352         // TRANS: Profile info line in notification e-mail.
353         // TRANS: %s is a homepage.
354         $out[] = sprintf(_("Homepage: %s"), $profile->homepage);
355     }
356     if ($profile->bio) {
357         // TRANS: Profile info line in notification e-mail.
358         // TRANS: %s is biographical information.
359         $out[] = sprintf(_("Bio: %s"), $profile->bio);
360     }
361
362     $blocklink = common_local_url('block', array('profileid' => $profile->id));
363     // This'll let ModPlus add the remote profile info so it's possible
364     // to block remote users directly...
365     Event::handle('MailProfileInfoBlockLink', array($profile, &$blocklink));
366
367     // TRANS: This is a paragraph in a new-subscriber e-mail.
368     // TRANS: %s is a URL where the subscriber can be reported as abusive.
369     $out[] = sprintf(_('If you believe this account is being used abusively, ' .
370                        'you can block them from your subscribers list and ' .
371                        'report as spam to site administrators at %s.'),
372                      $blocklink);
373     $out[] = "";
374
375     return implode("\n", $out);
376 }
377
378 /**
379  * notify a user of their new incoming email address
380  *
381  * User's email and incoming fields should already be updated.
382  *
383  * @param User $user user with the new address
384  *
385  * @return void
386  */
387 function mail_new_incoming_notify($user)
388 {
389     $profile = $user->getProfile();
390
391     $name = $profile->getBestName();
392
393     $headers['From']    = $user->incomingemail;
394     $headers['To']      = $name . ' <' . $user->email . '>';
395     // TRANS: Subject of notification mail for new posting email address.
396     // TRANS: %s is the StatusNet sitename.
397     $headers['Subject'] = sprintf(_('New email address for posting to %s'),
398                                   common_config('site', 'name'));
399
400     // TRANS: Body of notification mail for new posting email address.
401     // TRANS: %1$s is the StatusNet sitename, %2$s is the e-mail address to send
402     // TRANS: to to post by e-mail, %3$s is a URL to more instructions.
403     $body = sprintf(_("You have a new posting address on %1\$s.\n\n".
404                       "Send email to %2\$s to post new messages.\n\n".
405                       "More email instructions at %3\$s."),
406                     common_config('site', 'name'),
407                     $user->incomingemail,
408                     common_local_url('doc', array('title' => 'email'))) .
409             mail_footer_block();
410
411     mail_send($user->email, $headers, $body);
412 }
413
414 /**
415  * generate a new address for incoming messages
416  *
417  * @todo check the database for uniqueness
418  *
419  * @return string new email address for incoming messages
420  */
421 function mail_new_incoming_address()
422 {
423     $prefix = common_confirmation_code(64);
424     $suffix = mail_domain();
425     return $prefix . '@' . $suffix;
426 }
427
428 /**
429  * broadcast a notice to all subscribers with SMS notification on
430  *
431  * This function sends SMS messages to all users who have sms addresses;
432  * have sms notification on; and have sms enabled for this particular
433  * subscription.
434  *
435  * @param Notice $notice The notice to broadcast
436  *
437  * @return success flag
438  */
439 function mail_broadcast_notice_sms($notice)
440 {
441     // Now, get users subscribed to this profile
442
443     $user = new User();
444
445     $UT = common_config('db','type')=='pgsql'?'"user"':'user';
446     $replies = $notice->getReplies();
447     $user->query('SELECT nickname, smsemail, incomingemail ' .
448                  "FROM $UT LEFT OUTER JOIN subscription " .
449                  "ON $UT.id = subscription.subscriber " .
450                  'AND subscription.subscribed = ' . $notice->profile_id . ' ' .
451                  'AND subscription.subscribed != subscription.subscriber ' .
452                  // Users (other than the sender) who `want SMS notices':
453                  "WHERE $UT.id != " . $notice->profile_id . ' ' .
454                  "AND $UT.smsemail IS NOT null " .
455                  "AND $UT.smsnotify = 1 " .
456                  // ... where either the user _is_ subscribed to the sender
457                  // (any of the "subscription" fields IS NOT null)
458                  // and wants to get SMS for all of this scribe's notices...
459                  'AND (subscription.sms = 1 ' .
460                  // ... or where the user was mentioned in
461                  // or replied-to with the notice:
462                  ($replies ? sprintf("OR $UT.id in (%s)",
463                                      implode(',', $replies))
464                            : '') .
465                  ')');
466
467     while ($user->fetch()) {
468         common_log(LOG_INFO,
469                    'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
470                    __FILE__);
471         $success = mail_send_sms_notice_address($notice,
472                                                 $user->smsemail,
473                                                 $user->incomingemail,
474                                                 $user->nickname);
475         if (!$success) {
476             // XXX: Not sure, but I think that's the right thing to do
477             common_log(LOG_WARNING,
478                        'Sending notice ' . $notice->id . ' to ' .
479                        $user->smsemail . ' FAILED, cancelling.',
480                        __FILE__);
481             return false;
482         }
483     }
484
485     $user->free();
486     unset($user);
487
488     return true;
489 }
490
491 /**
492  * send a notice to a user via SMS
493  *
494  * A convenience wrapper around mail_send_sms_notice_address()
495  *
496  * @param Notice $notice notice to send
497  * @param User   $user   user to receive notice
498  *
499  * @see mail_send_sms_notice_address()
500  *
501  * @return boolean success flag
502  */
503 function mail_send_sms_notice($notice, $user)
504 {
505     return mail_send_sms_notice_address($notice,
506                                         $user->smsemail,
507                                         $user->incomingemail,
508                                         $user->nickname);
509 }
510
511 /**
512  * send a notice to an SMS email address from a given address
513  *
514  * We use the user's incoming email address as the "From" address to make
515  * replying to notices easier.
516  *
517  * @param Notice $notice        notice to send
518  * @param string $smsemail      email address to send to
519  * @param string $incomingemail email address to set as 'from'
520  * @param string $nickname      nickname to add to beginning
521  *
522  * @return boolean success flag
523  */
524 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail, $nickname)
525 {
526     $to = $nickname . ' <' . $smsemail . '>';
527
528     $other = $notice->getProfile();
529
530     common_log(LOG_INFO, 'Sending notice ' . $notice->id .
531                ' to ' . $smsemail, __FILE__);
532
533     $headers = array();
534
535     $headers['From']    = ($incomingemail) ? $incomingemail : mail_notify_from();
536     $headers['To']      = $to;
537     // TRANS: Subject line for SMS-by-email notification messages.
538     // TRANS: %s is the posting user's nickname.
539     $headers['Subject'] = sprintf(_('%s status'),
540                                   $other->getBestName());
541
542     $body = $notice->content;
543
544     return mail_send($smsemail, $headers, $body);
545 }
546
547 /**
548  * send a message to confirm a claim for an SMS number
549  *
550  * @param string $code     confirmation code
551  * @param string $nickname nickname of user claiming number
552  * @param string $address  email address to send the confirmation to
553  *
554  * @see common_confirmation_code()
555  *
556  * @return void
557  */
558 function mail_confirm_sms($code, $nickname, $address)
559 {
560     $recipients = $address;
561
562     $headers['From']    = mail_notify_from();
563     $headers['To']      = $nickname . ' <' . $address . '>';
564     // TRANS: Subject line for SMS-by-email address confirmation message.
565     $headers['Subject'] = _('SMS confirmation');
566
567     // TRANS: Main body heading for SMS-by-email address confirmation message.
568     // TRANS: %s is the addressed user's nickname.
569     $body  = sprintf(_('%s: confirm you own this phone number with this code:'), $nickname);
570     $body .= "\n\n";
571     $body .= $code;
572     $body .= "\n\n";
573
574     mail_send($recipients, $headers, $body);
575 }
576
577 /**
578  * send a mail message to notify a user of a 'nudge'
579  *
580  * @param User $from user nudging
581  * @param User $to   user being nudged
582  *
583  * @return boolean success flag
584  */
585 function mail_notify_nudge($from, $to)
586 {
587     common_switch_locale($to->language);
588     // TRANS: Subject for 'nudge' notification email.
589     // TRANS: %s is the nudging user.
590     $subject = sprintf(_('You have been nudged by %s'), $from->nickname);
591
592     $from_profile = $from->getProfile();
593
594     // TRANS: Body for 'nudge' notification email.
595     // TRANS: %1$s is the nuding user's long name, $2$s is the nudging user's nickname,
596     // TRANS: %3$s is a URL to post notices at.
597     $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ".
598                       "these days and is inviting you to post some news.\n\n".
599                       "So let's hear from you :)\n\n".
600                       "%3\$s\n\n".
601                       "Don't reply to this email; it won't get to them."),
602                     $from_profile->getBestName(),
603                     $from->nickname,
604                     common_local_url('all', array('nickname' => $to->nickname))) .
605             mail_footer_block();
606     common_switch_locale();
607
608     $headers = _mail_prepare_headers('nudge', $to->nickname, $from->nickname);
609
610     return mail_to_user($to, $subject, $body, $headers);
611 }
612
613 /**
614  * send a message to notify a user of a direct message (DM)
615  *
616  * This function checks to see if the recipient wants notification
617  * of DMs and has a configured email address.
618  *
619  * @param Message $message message to notify about
620  * @param User    $from    user sending message; default to sender
621  * @param User    $to      user receiving message; default to recipient
622  *
623  * @return boolean success code
624  */
625 function mail_notify_message($message, $from=null, $to=null)
626 {
627     if (is_null($from)) {
628         $from = User::getKV('id', $message->from_profile);
629     }
630
631     if (is_null($to)) {
632         $to = User::getKV('id', $message->to_profile);
633     }
634
635     if (is_null($to->email) || !$to->emailnotifymsg) {
636         return true;
637     }
638
639     common_switch_locale($to->language);
640     // TRANS: Subject for direct-message notification email.
641     // TRANS: %s is the sending user's nickname.
642     $subject = sprintf(_('New private message from %s'), $from->nickname);
643
644     $from_profile = $from->getProfile();
645
646     // TRANS: Body for direct-message notification email.
647     // TRANS: %1$s is the sending user's long name, %2$s is the sending user's nickname,
648     // TRANS: %3$s is the message content, %4$s a URL to the message,
649     $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n".
650                       "------------------------------------------------------\n".
651                       "%3\$s\n".
652                       "------------------------------------------------------\n\n".
653                       "You can reply to their message here:\n\n".
654                       "%4\$s\n\n".
655                       "Don't reply to this email; it won't get to them."),
656                     $from_profile->getBestName(),
657                     $from->nickname,
658                     $message->content,
659                     common_local_url('newmessage', array('to' => $from->id))) .
660             mail_footer_block();
661
662     $headers = _mail_prepare_headers('message', $to->nickname, $from->nickname);
663
664     common_switch_locale();
665     return mail_to_user($to, $subject, $body, $headers);
666 }
667
668 /**
669  * Notify a user that they have received an "attn:" message AKA "@-reply"
670  *
671  * @param User   $user   The user who recevied the notice
672  * @param Notice $notice The notice that was sent
673  *
674  * @return void
675  */
676 function mail_notify_attn($user, $notice)
677 {
678     if (!$user->receivesEmailNotifications()) {
679         return;
680     }
681
682     $sender = $notice->getProfile();
683
684     if ($sender->id == $user->id) {
685         return;
686     }
687
688     // See if the notice's author who mentions this user is sandboxed
689     if (!$sender->hasRight(Right::EMAILONREPLY)) {
690         return;
691     }
692
693     // If the author has blocked the author, don't spam them with a notification.
694     if ($user->hasBlocked($sender)) {
695         return;
696     }
697
698     $bestname = $sender->getBestName();
699
700     common_switch_locale($user->language);
701
702     if ($notice->hasConversation()) {
703         $conversationUrl = common_local_url('conversation',
704                          array('id' => $notice->conversation)).'#notice-'.$notice->id;
705         // TRANS: Line in @-reply notification e-mail. %s is conversation URL.
706         $conversationEmailText = sprintf(_("The full conversation can be read here:\n\n".
707                                            "\t%s"), $conversationUrl) . "\n\n";
708     } else {
709         $conversationEmailText = '';
710     }
711
712     // TRANS: E-mail subject for notice notification.
713     // TRANS: %1$s is the sending user's long name, %2$s is the adding user's nickname.
714     $subject = sprintf(_('%1$s (@%2$s) sent a notice to your attention'), $bestname, $sender->nickname);
715
716         // TRANS: Body of @-reply notification e-mail.
717         // TRANS: %1$s is the sending user's name, $2$s is the StatusNet sitename,
718         // TRANS: %3$s is a URL to the notice, %4$s is the notice text,
719         // 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),
720         // TRANS: %6$s is a URL to reply to the notice, %7$s is a URL to all @-replies for the addressed user,
721         $body = sprintf(_("%1\$s just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
722                       "The notice is here:\n\n".
723                       "\t%3\$s\n\n" .
724                       "It reads:\n\n".
725                       "\t%4\$s\n\n" .
726                       "%5\$s" .
727                       "You can reply back here:\n\n".
728                       "\t%6\$s\n\n" .
729                       "The list of all @-replies for you here:\n\n" .
730                       "%7\$s"),
731                     $sender->getFancyName(),//%1
732                     common_config('site', 'name'),//%2
733                     common_local_url('shownotice',
734                                      array('notice' => $notice->id)),//%3
735                     $notice->content,//%4
736                     $conversationEmailText,//%5
737                     common_local_url('newnotice',
738                                      array('replyto' => $sender->nickname, 'inreplyto' => $notice->id)),//%6
739                     common_local_url('replies',
740                                      array('nickname' => $user->nickname))) . //%7
741                 mail_footer_block();
742     $headers = _mail_prepare_headers('mention', $user->nickname, $sender->nickname);
743
744     common_switch_locale();
745     mail_to_user($user, $subject, $body, $headers);
746 }
747
748 /**
749  * Prepare the common mail headers used in notification emails
750  *
751  * @param string $msg_type type of message being sent to the user
752  * @param string $to       nickname of the receipient
753  * @param string $from     nickname of the user triggering the notification
754  *
755  * @return array list of mail headers to include in the message
756  */
757 function _mail_prepare_headers($msg_type, $to, $from)
758 {
759     $headers = array(
760         'X-StatusNet-MessageType' => $msg_type,
761         'X-StatusNet-TargetUser'  => $to,
762         'X-StatusNet-SourceUser'  => $from,
763         'X-StatusNet-Domain'      => common_config('site', 'server')
764     );
765
766     return $headers;
767 }
768
769 /**
770  * Send notification emails to group administrator.
771  *
772  * @param User_group $group
773  * @param Profile $joiner
774  */
775 function mail_notify_group_join($group, $joiner)
776 {
777     // This returns a Profile query...
778     $admin = $group->getAdmins();
779     while ($admin->fetch()) {
780         // We need a local user for email notifications...
781         $adminUser = User::getKV('id', $admin->id);
782         // @fixme check for email preference?
783         if ($adminUser && $adminUser->email) {
784             // use the recipient's localization
785             common_switch_locale($adminUser->language);
786
787             $headers = _mail_prepare_headers('join', $admin->nickname, $joiner->nickname);
788             $headers['From']    = mail_notify_from();
789             $headers['To']      = $admin->getBestName() . ' <' . $adminUser->email . '>';
790             // TRANS: Subject of group join notification e-mail.
791             // TRANS: %1$s is the joining user's nickname, %2$s is the group name, and %3$s is the StatusNet sitename.
792             $headers['Subject'] = sprintf(_('%1$s has joined '.
793                                             'your group %2$s on %3$s'),
794                                           $joiner->getBestName(),
795                                           $group->getBestName(),
796                                           common_config('site', 'name'));
797
798             // TRANS: Main body of group join notification e-mail.
799             // TRANS: %1$s is the subscriber's long name, %2$s is the group name, and %3$s is the StatusNet sitename,
800             // TRANS: %4$s is a block of profile info about the subscriber.
801             // TRANS: %5$s is a link to the addressed user's e-mail settings.
802             $body = sprintf(_('%1$s has joined your group %2$s on %3$s.'),
803                             $joiner->getFancyName(),
804                             $group->getFancyName(),
805                             common_config('site', 'name')) .
806                     mail_profile_block($joiner) .
807                     mail_footer_block();
808
809             // reset localization
810             common_switch_locale();
811             mail_send($adminUser->email, $headers, $body);
812         }
813     }
814 }
815
816
817 /**
818  * Send notification emails to group administrator.
819  *
820  * @param User_group $group
821  * @param Profile $joiner
822  */
823 function mail_notify_group_join_pending($group, $joiner)
824 {
825     $admin = $group->getAdmins();
826     while ($admin->fetch()) {
827         // We need a local user for email notifications...
828         $adminUser = User::getKV('id', $admin->id);
829         // @fixme check for email preference?
830         if ($adminUser && $adminUser->email) {
831             // use the recipient's localization
832             common_switch_locale($adminUser->language);
833
834             $headers = _mail_prepare_headers('join', $admin->nickname, $joiner->nickname);
835             $headers['From']    = mail_notify_from();
836             $headers['To']      = $admin->getBestName() . ' <' . $adminUser->email . '>';
837             // TRANS: Subject of pending group join request notification e-mail.
838             // TRANS: %1$s is the joining user's nickname, %2$s is the group name, and %3$s is the StatusNet sitename.
839             $headers['Subject'] = sprintf(_('%1$s wants to join your group %2$s on %3$s.'),
840                                           $joiner->getBestName(),
841                                           $group->getBestName(),
842                                           common_config('site', 'name'));
843
844             // TRANS: Main body of pending group join request notification e-mail.
845             // TRANS: %1$s is the subscriber's long name, %2$s is the group name, and %3$s is the StatusNet sitename,
846             // TRANS: %4$s is the URL to the moderation queue page.
847             $body = sprintf(_('%1$s would like to join your group %2$s on %3$s. ' .
848                               'You may approve or reject their group membership at %4$s'),
849                             $joiner->getFancyName(),
850                             $group->getFancyName(),
851                             common_config('site', 'name'),
852                             common_local_url('groupqueue', array('nickname' => $group->nickname))) .
853                     mail_profile_block($joiner) .
854                     mail_footer_block();
855
856             // reset localization
857             common_switch_locale();
858             mail_send($adminUser->email, $headers, $body);
859         }
860     }
861 }