]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mail.php
Merge remote-tracking branch 'upstream/nightly' into nightly
[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  * notify a user of subscription by another user
166  *
167  * This is just a wrapper around the profile-based version.
168  *
169  * @param User $listenee user who is being subscribed to
170  * @param User $listener user who is subscribing
171  *
172  * @see mail_subscribe_notify_profile()
173  *
174  * @return void
175  */
176 function mail_subscribe_notify($listenee, $listener)
177 {
178     $other = $listener->getProfile();
179     mail_subscribe_notify_profile($listenee, $other);
180 }
181
182 /**
183  * notify a user of subscription by a profile (remote or local)
184  *
185  * This function checks to see if the listenee has an email
186  * address and wants subscription notices.
187  *
188  * @param User    $listenee user who's being subscribed to
189  * @param Profile $other    profile of person who's listening
190  *
191  * @return void
192  */
193 function mail_subscribe_notify_profile($listenee, $other)
194 {
195     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
196         $listenee->email && $listenee->emailnotifysub) {
197
198         $profile = $listenee->getProfile();
199
200         $name = $profile->getBestName();
201
202         $long_name = ($other->fullname) ?
203           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
204
205         $recipients = $listenee->email;
206
207         // use the recipient's localization
208         common_switch_locale($listenee->language);
209
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'));
218
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.'),
222                         $long_name,
223                         common_config('site', 'name')) .
224                 mail_profile_block($other) .
225                 mail_footer_block();
226
227         // reset localization
228         common_switch_locale();
229         mail_send($recipients, $headers, $body);
230     }
231 }
232
233 function mail_subscribe_pending_notify_profile($listenee, $other)
234 {
235     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
236         $listenee->email && $listenee->emailnotifysub) {
237
238         $profile = $listenee->getProfile();
239
240         $name = $profile->getBestName();
241
242         $long_name = ($other->fullname) ?
243           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
244
245         $recipients = $listenee->email;
246
247         // use the recipient's localization
248         common_switch_locale($listenee->language);
249
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'));
259
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'),
264                         $long_name,
265                         common_config('site', 'name'),
266                         common_local_url('subqueue', array('nickname' => $listenee->nickname))) .
267                 mail_profile_block($other) .
268                 mail_footer_block();
269
270         // reset localization
271         common_switch_locale();
272         mail_send($recipients, $headers, $body);
273     }
274 }
275
276 function mail_footer_block()
277 {
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,'.
282                               "\n".'%1$s.'."\n\n".
283                               "----\n".
284                               "Change your email address or ".
285                               "notification options at ".'%2$s'),
286                             common_config('site', 'name'),
287                             common_local_url('emailsettings')) . "\n";
288 }
289
290 /**
291  * Format a block of profile info for a plaintext notification email.
292  *
293  * @param Profile $profile
294  * @return string
295  */
296 function mail_profile_block($profile)
297 {
298     // TRANS: Layout for
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)
301     $out = array();
302     $out[] = "";
303     $out[] = "";
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);
311     }
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);
316     }
317     if ($profile->bio) {
318         // TRANS: Profile info line in notification e-mail.
319         // TRANS: %s is biographical information.
320         $out[] = sprintf(_("Bio: %s"), $profile->bio);
321     }
322
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));
327
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.'),
333                      $blocklink);
334     $out[] = "";
335
336     return implode("\n", $out);
337 }
338
339 /**
340  * notify a user of their new incoming email address
341  *
342  * User's email and incoming fields should already be updated.
343  *
344  * @param User $user user with the new address
345  *
346  * @return void
347  */
348 function mail_new_incoming_notify($user)
349 {
350     $profile = $user->getProfile();
351
352     $name = $profile->getBestName();
353
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'));
360
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'))) .
370             mail_footer_block();
371
372     mail_send($user->email, $headers, $body);
373 }
374
375 /**
376  * generate a new address for incoming messages
377  *
378  * @todo check the database for uniqueness
379  *
380  * @return string new email address for incoming messages
381  */
382 function mail_new_incoming_address()
383 {
384     $prefix = common_confirmation_code(64);
385     $suffix = mail_domain();
386     return $prefix . '@' . $suffix;
387 }
388
389 /**
390  * broadcast a notice to all subscribers with SMS notification on
391  *
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
394  * subscription.
395  *
396  * @param Notice $notice The notice to broadcast
397  *
398  * @return success flag
399  */
400 function mail_broadcast_notice_sms($notice)
401 {
402     // Now, get users subscribed to this profile
403
404     $user = new User();
405
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))
425                            : '') .
426                  ')');
427
428     while ($user->fetch()) {
429         common_log(LOG_INFO,
430                    'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
431                    __FILE__);
432         $success = mail_send_sms_notice_address($notice,
433                                                 $user->smsemail,
434                                                 $user->incomingemail,
435                                                 $user->nickname);
436         if (!$success) {
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.',
441                        __FILE__);
442             return false;
443         }
444     }
445
446     $user->free();
447     unset($user);
448
449     return true;
450 }
451
452 /**
453  * send a notice to a user via SMS
454  *
455  * A convenience wrapper around mail_send_sms_notice_address()
456  *
457  * @param Notice $notice notice to send
458  * @param User   $user   user to receive notice
459  *
460  * @see mail_send_sms_notice_address()
461  *
462  * @return boolean success flag
463  */
464 function mail_send_sms_notice($notice, $user)
465 {
466     return mail_send_sms_notice_address($notice,
467                                         $user->smsemail,
468                                         $user->incomingemail,
469                                         $user->nickname);
470 }
471
472 /**
473  * send a notice to an SMS email address from a given address
474  *
475  * We use the user's incoming email address as the "From" address to make
476  * replying to notices easier.
477  *
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
482  *
483  * @return boolean success flag
484  */
485 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail, $nickname)
486 {
487     $to = $nickname . ' <' . $smsemail . '>';
488
489     $other = $notice->getProfile();
490
491     common_log(LOG_INFO, 'Sending notice ' . $notice->id .
492                ' to ' . $smsemail, __FILE__);
493
494     $headers = array();
495
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());
502
503     $body = $notice->content;
504
505     return mail_send($smsemail, $headers, $body);
506 }
507
508 /**
509  * send a message to confirm a claim for an SMS number
510  *
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
514  *
515  * @see common_confirmation_code()
516  *
517  * @return void
518  */
519 function mail_confirm_sms($code, $nickname, $address)
520 {
521     $recipients = $address;
522
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');
527
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);
531     $body .= "\n\n";
532     $body .= $code;
533     $body .= "\n\n";
534
535     mail_send($recipients, $headers, $body);
536 }
537
538 /**
539  * send a mail message to notify a user of a 'nudge'
540  *
541  * @param User $from user nudging
542  * @param User $to   user being nudged
543  *
544  * @return boolean success flag
545  */
546 function mail_notify_nudge($from, $to)
547 {
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);
552
553     $from_profile = $from->getProfile();
554
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".
561                       "%3\$s\n\n".
562                       "Don't reply to this email; it won't get to them."),
563                     $from_profile->getBestName(),
564                     $from->nickname,
565                     common_local_url('all', array('nickname' => $to->nickname))) .
566             mail_footer_block();
567     common_switch_locale();
568
569     $headers = _mail_prepare_headers('nudge', $to->nickname, $from->nickname);
570
571     return mail_to_user($to, $subject, $body, $headers);
572 }
573
574 /**
575  * send a message to notify a user of a direct message (DM)
576  *
577  * This function checks to see if the recipient wants notification
578  * of DMs and has a configured email address.
579  *
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
583  *
584  * @return boolean success code
585  */
586 function mail_notify_message($message, $from=null, $to=null)
587 {
588     if (is_null($from)) {
589         $from = User::getKV('id', $message->from_profile);
590     }
591
592     if (is_null($to)) {
593         $to = User::getKV('id', $message->to_profile);
594     }
595
596     if (is_null($to->email) || !$to->emailnotifymsg) {
597         return true;
598     }
599
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);
604
605     $from_profile = $from->getProfile();
606
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".
612                       "%3\$s\n".
613                       "------------------------------------------------------\n\n".
614                       "You can reply to their message here:\n\n".
615                       "%4\$s\n\n".
616                       "Don't reply to this email; it won't get to them."),
617                     $from_profile->getBestName(),
618                     $from->nickname,
619                     $message->content,
620                     common_local_url('newmessage', array('to' => $from->id))) .
621             mail_footer_block();
622
623     $headers = _mail_prepare_headers('message', $to->nickname, $from->nickname);
624
625     common_switch_locale();
626     return mail_to_user($to, $subject, $body, $headers);
627 }
628
629 /**
630  * Notify a user that they have received an "attn:" message AKA "@-reply"
631  *
632  * @param Profile $rcpt  The Profile who recevied the notice, should be a local user
633  * @param Notice $notice The notice that was sent
634  *
635  * @return void
636  */
637 function mail_notify_attn(Profile $rcpt, Notice $notice)
638 {
639     if (!$rcpt->isLocal()) {
640         return;
641     }
642
643     $sender = $notice->getProfile();
644     if ($rcpt->sameAs($sender)) {
645         return;
646     }
647
648     // See if the notice's author who mentions this user is sandboxed
649     if (!$sender->hasRight(Right::EMAILONREPLY)) {
650         return;
651     }
652
653     // If the author has blocked the author, don't spam them with a notification.
654     if ($rcpt->hasBlocked($sender)) {
655         return;
656     }
657
658     $user = $rcpt->getUser();
659     if (!$user->receivesEmailNotifications()) {
660         return;
661     }
662
663     common_switch_locale($user->language);
664
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";
671     } else {
672         $conversationEmailText = '';
673     }
674
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());
678
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".
686                       "\t%3\$s\n\n" .
687                       "It reads:\n\n".
688                       "\t%4\$s\n\n" .
689                       "%5\$s" .
690                       "You can reply back here:\n\n".
691                       "\t%6\$s\n\n" .
692                       "The list of all @-replies for you here:\n\n" .
693                       "%7\$s"),
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
704                 mail_footer_block();
705     $headers = _mail_prepare_headers('mention', $rcpt->getNickname(), $sender->getNickname());
706
707     common_switch_locale();
708     mail_to_user($user, $subject, $body, $headers);
709 }
710
711 /**
712  * Prepare the common mail headers used in notification emails
713  *
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
717  *
718  * @return array list of mail headers to include in the message
719  */
720 function _mail_prepare_headers($msg_type, $to, $from)
721 {
722     $headers = array(
723         'X-StatusNet-MessageType' => $msg_type,
724         'X-StatusNet-TargetUser'  => $to,
725         'X-StatusNet-SourceUser'  => $from,
726         'X-StatusNet-Domain'      => common_config('site', 'server')
727     );
728
729     return $headers;
730 }
731
732 /**
733  * Send notification emails to group administrator.
734  *
735  * @param User_group $group
736  * @param Profile $joiner
737  */
738 function mail_notify_group_join($group, $joiner)
739 {
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);
749
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'));
760
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) .
770                     mail_footer_block();
771
772             // reset localization
773             common_switch_locale();
774             mail_send($adminUser->email, $headers, $body);
775         }
776     }
777 }
778
779
780 /**
781  * Send notification emails to group administrator.
782  *
783  * @param User_group $group
784  * @param Profile $joiner
785  */
786 function mail_notify_group_join_pending($group, $joiner)
787 {
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);
796
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'));
806
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) .
817                     mail_footer_block();
818
819             // reset localization
820             common_switch_locale();
821             mail_send($adminUser->email, $headers, $body);
822         }
823     }
824 }