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