]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mail.php
Merge branch '1.0.x' of gitorious.org:statusnet/mainline into 1.0.x
[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
48 function mail_backend()
49 {
50     static $backend = null;
51
52     if (!$backend) {
53         $backend = Mail::factory(common_config('mail', 'backend'),
54                                  (common_config('mail', 'params')) ?
55                                  common_config('mail', 'params') :
56                                  array());
57         if (PEAR::isError($backend)) {
58             common_server_error($backend->getMessage(), 500);
59         }
60     }
61     return $backend;
62 }
63
64 /**
65  * send an email to one or more recipients
66  *
67  * @param array  $recipients array of strings with email addresses of recipients
68  * @param array  $headers    array mapping strings to strings for email headers
69  * @param string $body       body of the email
70  *
71  * @return boolean success flag
72  */
73
74 function mail_send($recipients, $headers, $body)
75 {
76     // XXX: use Mail_Queue... maybe
77     $backend = mail_backend();
78     if (!isset($headers['Content-Type'])) {
79         $headers['Content-Type'] = 'text/plain; charset=UTF-8';
80     }
81     assert($backend); // throws an error if it's bad
82     $sent = $backend->send($recipients, $headers, $body);
83     if (PEAR::isError($sent)) {
84         common_log(LOG_ERR, 'Email error: ' . $sent->getMessage());
85         return false;
86     }
87     return true;
88 }
89
90 /**
91  * returns the configured mail domain
92  *
93  * Defaults to the server name.
94  *
95  * @return string mail domain, suitable for making email addresses.
96  */
97
98 function mail_domain()
99 {
100     $maildomain = common_config('mail', 'domain');
101     if (!$maildomain) {
102         $maildomain = common_config('site', 'server');
103     }
104     return $maildomain;
105 }
106
107 /**
108  * returns a good address for sending email from this server
109  *
110  * Uses either the configured value or a faked-up value made
111  * from the mail domain.
112  *
113  * @return string notify from address
114  */
115
116 function mail_notify_from()
117 {
118     $notifyfrom = common_config('mail', 'notifyfrom');
119
120     if (!$notifyfrom) {
121
122         $domain = mail_domain();
123
124         $notifyfrom = '"'.common_config('site', 'name') .'" <noreply@'.$domain.'>';
125     }
126
127     return $notifyfrom;
128 }
129
130 /**
131  * sends email to a user
132  *
133  * @param User   &$user   user to send email to
134  * @param string $subject subject of the email
135  * @param string $body    body of the email
136  * @param array  $headers optional list of email headers
137  * @param string $address optional specification of email address
138  *
139  * @return boolean success flag
140  */
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
171 function mail_confirm_address($user, $code, $nickname, $address)
172 {
173     // TRANS: Subject for address confirmation email
174     $subject = _('Email address confirmation');
175
176     // TRANS: Body for address confirmation email.
177     $body = sprintf(_("Hey, %s.\n\n".
178                       "Someone just entered this email address on %s.\n\n" .
179                       "If it was you, and you want to confirm your entry, ".
180                       "use the URL below:\n\n\t%s\n\n" .
181                       "If not, just ignore this message.\n\n".
182                       "Thanks for your time, \n%s\n"),
183                     $nickname, common_config('site', 'name'),
184                     common_local_url('confirmaddress', array('code' => $code)),
185                     common_config('site', 'name'));
186     $headers = array();
187
188     return mail_to_user($user, $subject, $body, $headers, $address);
189 }
190
191 /**
192  * notify a user of subscription by another user
193  *
194  * This is just a wrapper around the profile-based version.
195  *
196  * @param User $listenee user who is being subscribed to
197  * @param User $listener user who is subscribing
198  *
199  * @see mail_subscribe_notify_profile()
200  *
201  * @return void
202  */
203
204 function mail_subscribe_notify($listenee, $listener)
205 {
206     $other = $listener->getProfile();
207     mail_subscribe_notify_profile($listenee, $other);
208 }
209
210 /**
211  * notify a user of subscription by a profile (remote or local)
212  *
213  * This function checks to see if the listenee has an email
214  * address and wants subscription notices.
215  *
216  * @param User    $listenee user who's being subscribed to
217  * @param Profile $other    profile of person who's listening
218  *
219  * @return void
220  */
221
222 function mail_subscribe_notify_profile($listenee, $other)
223 {
224     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
225         $listenee->email && $listenee->emailnotifysub) {
226
227         // use the recipient's localization
228         common_init_locale($listenee->language);
229
230         $profile = $listenee->getProfile();
231
232         $name = $profile->getBestName();
233
234         $long_name = ($other->fullname) ?
235           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
236
237         $recipients = $listenee->email;
238
239         $headers = _mail_prepare_headers('subscribe', $listenee->nickname, $other->nickname);
240         $headers['From']    = mail_notify_from();
241         $headers['To']      = $name . ' <' . $listenee->email . '>';
242         // TRANS: Subject of new-subscriber notification e-mail
243         $headers['Subject'] = sprintf(_('%1$s is now listening to '.
244                                         'your notices on %2$s.'),
245                                       $other->getBestName(),
246                                       common_config('site', 'name'));
247
248         // TRANS: Main body of new-subscriber notification e-mail
249         $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n".
250                           "\t".'%3$s'."\n\n".
251                           '%4$s'.
252                           '%5$s'.
253                           '%6$s'.
254                           "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n".
255                           "----\n".
256                           "Change your email address or ".
257                           "notification options at ".'%8$s' ."\n"),
258                         $long_name,
259                         common_config('site', 'name'),
260                         $other->profileurl,
261                         ($other->location) ?
262                         // TRANS: Profile info line in new-subscriber notification e-mail
263                         sprintf(_("Location: %s"), $other->location) . "\n" : '',
264                         ($other->homepage) ?
265                         // TRANS: Profile info line in new-subscriber notification e-mail
266                         sprintf(_("Homepage: %s"), $other->homepage) . "\n" : '',
267                         ($other->bio) ?
268                         // TRANS: Profile info line in new-subscriber notification e-mail
269                         sprintf(_("Bio: %s"), $other->bio) . "\n\n" : '',
270                         common_config('site', 'name'),
271                         common_local_url('emailsettings'));
272
273         // reset localization
274         common_init_locale();
275         mail_send($recipients, $headers, $body);
276     }
277 }
278
279 /**
280  * notify a user of their new incoming email address
281  *
282  * User's email and incoming fields should already be updated.
283  *
284  * @param User $user user with the new address
285  *
286  * @return void
287  */
288
289 function mail_new_incoming_notify($user)
290 {
291     $profile = $user->getProfile();
292
293     $name = $profile->getBestName();
294
295     $headers['From']    = $user->incomingemail;
296     $headers['To']      = $name . ' <' . $user->email . '>';
297     // TRANS: Subject of notification mail for new posting email address
298     $headers['Subject'] = sprintf(_('New email address for posting to %s'),
299                                   common_config('site', 'name'));
300
301     // TRANS: Body of notification mail for new posting email address
302     $body = sprintf(_("You have a new posting address on %1\$s.\n\n".
303                       "Send email to %2\$s to post new messages.\n\n".
304                       "More email instructions at %3\$s.\n\n".
305                       "Faithfully yours,\n%4\$s"),
306                     common_config('site', 'name'),
307                     $user->incomingemail,
308                     common_local_url('doc', array('title' => 'email')),
309                     common_config('site', 'name'));
310
311     mail_send($user->email, $headers, $body);
312 }
313
314 /**
315  * generate a new address for incoming messages
316  *
317  * @todo check the database for uniqueness
318  *
319  * @return string new email address for incoming messages
320  */
321
322 function mail_new_incoming_address()
323 {
324     $prefix = common_confirmation_code(64);
325     $suffix = mail_domain();
326     return $prefix . '@' . $suffix;
327 }
328
329 /**
330  * broadcast a notice to all subscribers with SMS notification on
331  *
332  * This function sends SMS messages to all users who have sms addresses;
333  * have sms notification on; and have sms enabled for this particular
334  * subscription.
335  *
336  * @param Notice $notice The notice to broadcast
337  *
338  * @return success flag
339  */
340
341 function mail_broadcast_notice_sms($notice)
342 {
343     // Now, get users subscribed to this profile
344
345     $user = new User();
346
347     $UT = common_config('db','type')=='pgsql'?'"user"':'user';
348     $user->query('SELECT nickname, smsemail, incomingemail ' .
349                  "FROM $UT JOIN subscription " .
350                  "ON $UT.id = subscription.subscriber " .
351                  'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' .
352                  'AND subscription.subscribed != subscription.subscriber ' .
353                  "AND $UT.smsemail IS NOT null " .
354                  "AND $UT.smsnotify = 1 " .
355                  'AND subscription.sms = 1 ');
356
357     while ($user->fetch()) {
358         common_log(LOG_INFO,
359                    'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
360                    __FILE__);
361         $success = mail_send_sms_notice_address($notice,
362                                                 $user->smsemail,
363                                                 $user->incomingemail);
364         if (!$success) {
365             // XXX: Not sure, but I think that's the right thing to do
366             common_log(LOG_WARNING,
367                        'Sending notice ' . $notice->id . ' to ' .
368                        $user->smsemail . ' FAILED, cancelling.',
369                        __FILE__);
370             return false;
371         }
372     }
373
374     $user->free();
375     unset($user);
376
377     return true;
378 }
379
380 /**
381  * send a notice to a user via SMS
382  *
383  * A convenience wrapper around mail_send_sms_notice_address()
384  *
385  * @param Notice $notice notice to send
386  * @param User   $user   user to receive notice
387  *
388  * @see mail_send_sms_notice_address()
389  *
390  * @return boolean success flag
391  */
392
393 function mail_send_sms_notice($notice, $user)
394 {
395     return mail_send_sms_notice_address($notice,
396                                         $user->smsemail,
397                                         $user->incomingemail);
398 }
399
400 /**
401  * send a notice to an SMS email address from a given address
402  *
403  * We use the user's incoming email address as the "From" address to make
404  * replying to notices easier.
405  *
406  * @param Notice $notice        notice to send
407  * @param string $smsemail      email address to send to
408  * @param string $incomingemail email address to set as 'from'
409  *
410  * @return boolean success flag
411  */
412
413 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail)
414 {
415     $to = $nickname . ' <' . $smsemail . '>';
416
417     $other = $notice->getProfile();
418
419     common_log(LOG_INFO, 'Sending notice ' . $notice->id .
420                ' to ' . $smsemail, __FILE__);
421
422     $headers = array();
423
424     $headers['From']    = ($incomingemail) ? $incomingemail : mail_notify_from();
425     $headers['To']      = $to;
426     // TRANS: Subject line for SMS-by-email notification messages
427     $headers['Subject'] = sprintf(_('%s status'),
428                                   $other->getBestName());
429
430     $body = $notice->content;
431
432     return mail_send($smsemail, $headers, $body);
433 }
434
435 /**
436  * send a message to confirm a claim for an SMS number
437  *
438  * @param string $code     confirmation code
439  * @param string $nickname nickname of user claiming number
440  * @param string $address  email address to send the confirmation to
441  *
442  * @see common_confirmation_code()
443  *
444  * @return void
445  */
446
447 function mail_confirm_sms($code, $nickname, $address)
448 {
449     $recipients = $address;
450
451     $headers['From']    = mail_notify_from();
452     $headers['To']      = $nickname . ' <' . $address . '>';
453     // TRANS: Subject line for SMS-by-email address confirmation message
454     $headers['Subject'] = _('SMS confirmation');
455
456     // TRANS: Main body heading for SMS-by-email address confirmation message
457     $body  = sprintf(_("%s: confirm you own this phone number with this code:"), $nickname);
458     $body .= "\n\n";
459     $body .= $code;
460     $body .= "\n\n";
461
462     mail_send($recipients, $headers, $body);
463 }
464
465 /**
466  * send a mail message to notify a user of a 'nudge'
467  *
468  * @param User $from user nudging
469  * @param User $to   user being nudged
470  *
471  * @return boolean success flag
472  */
473
474 function mail_notify_nudge($from, $to)
475 {
476     common_init_locale($to->language);
477     // TRANS: Subject for 'nudge' notification email
478     $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname);
479
480     $from_profile = $from->getProfile();
481
482     // TRANS: Body for 'nudge' notification email
483     $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ".
484                       "these days and is inviting you to post some news.\n\n".
485                       "So let's hear from you :)\n\n".
486                       "%3\$s\n\n".
487                       "Don't reply to this email; it won't get to them.\n\n".
488                       "With kind regards,\n".
489                       "%4\$s\n"),
490                     $from_profile->getBestName(),
491                     $from->nickname,
492                     common_local_url('all', array('nickname' => $to->nickname)),
493                     common_config('site', 'name'));
494     common_init_locale();
495
496     $headers = _mail_prepare_headers('nudge', $to->nickname, $from->nickname);
497
498     return mail_to_user($to, $subject, $body, $headers);
499 }
500
501 /**
502  * send a message to notify a user of a direct message (DM)
503  *
504  * This function checks to see if the recipient wants notification
505  * of DMs and has a configured email address.
506  *
507  * @param Message $message message to notify about
508  * @param User    $from    user sending message; default to sender
509  * @param User    $to      user receiving message; default to recipient
510  *
511  * @return boolean success code
512  */
513
514 function mail_notify_message($message, $from=null, $to=null)
515 {
516     if (is_null($from)) {
517         $from = User::staticGet('id', $message->from_profile);
518     }
519
520     if (is_null($to)) {
521         $to = User::staticGet('id', $message->to_profile);
522     }
523
524     if (is_null($to->email) || !$to->emailnotifymsg) {
525         return true;
526     }
527
528     common_init_locale($to->language);
529     // TRANS: Subject for direct-message notification email
530     $subject = sprintf(_('New private message from %s'), $from->nickname);
531
532     $from_profile = $from->getProfile();
533
534     // TRANS: Body for direct-message notification email
535     $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n".
536                       "------------------------------------------------------\n".
537                       "%3\$s\n".
538                       "------------------------------------------------------\n\n".
539                       "You can reply to their message here:\n\n".
540                       "%4\$s\n\n".
541                       "Don't reply to this email; it won't get to them.\n\n".
542                       "With kind regards,\n".
543                       "%5\$s\n"),
544                     $from_profile->getBestName(),
545                     $from->nickname,
546                     $message->content,
547                     common_local_url('newmessage', array('to' => $from->id)),
548                     common_config('site', 'name'));
549
550     $headers = _mail_prepare_headers('message', $to->nickname, $from->nickname);
551
552     common_init_locale();
553     return mail_to_user($to, $subject, $body, $headers);
554 }
555
556 /**
557  * notify a user that one of their notices has been chosen as a 'fave'
558  *
559  * Doesn't check that the user has an email address nor if they
560  * want to receive notification of faves. Maybe this happens higher
561  * up the stack...?
562  *
563  * @param User   $other  The user whose notice was faved
564  * @param User   $user   The user who faved the notice
565  * @param Notice $notice The notice that was faved
566  *
567  * @return void
568  */
569
570 function mail_notify_fave($other, $user, $notice)
571 {
572     if (!$user->hasRight(Right::EMAILONFAVE)) {
573         return;
574     }
575
576     $profile = $user->getProfile();
577
578     $bestname = $profile->getBestName();
579
580     common_init_locale($other->language);
581
582     // TRANS: Subject for favorite notification email
583     $subject = sprintf(_('%s (@%s) added your notice as a favorite'), $bestname, $user->nickname);
584
585     // TRANS: Body for favorite notification email
586     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
587                       " as one of their favorites.\n\n" .
588                       "The URL of your notice is:\n\n" .
589                       "%3\$s\n\n" .
590                       "The text of your notice is:\n\n" .
591                       "%4\$s\n\n" .
592                       "You can see the list of %1\$s's favorites here:\n\n" .
593                       "%5\$s\n\n" .
594                       "Faithfully yours,\n" .
595                       "%6\$s\n"),
596                     $bestname,
597                     common_exact_date($notice->created),
598                     common_local_url('shownotice',
599                                      array('notice' => $notice->id)),
600                     $notice->content,
601                     common_local_url('showfavorites',
602                                      array('nickname' => $user->nickname)),
603                     common_config('site', 'name'),
604                     $user->nickname);
605
606     $headers = _mail_prepare_headers('fave', $other->nickname, $user->nickname);
607
608     common_init_locale();
609     mail_to_user($other, $subject, $body, $headers);
610 }
611
612 /**
613  * notify a user that they have received an "attn:" message AKA "@-reply"
614  *
615  * @param User   $user   The user who recevied the notice
616  * @param Notice $notice The notice that was sent
617  *
618  * @return void
619  */
620
621 function mail_notify_attn($user, $notice)
622 {
623     if (!$user->email || !$user->emailnotifyattn) {
624         return;
625     }
626
627     $sender = $notice->getProfile();
628
629     if ($sender->id == $user->id) {
630         return;
631     }
632
633     if (!$sender->hasRight(Right::EMAILONREPLY)) {
634         return;
635     }
636
637     $bestname = $sender->getBestName();
638
639     common_init_locale($user->language);
640
641     if ($notice->hasConversation()) {
642         $conversationUrl = common_local_url('conversation',
643                          array('id' => $notice->conversation)).'#notice-'.$notice->id;
644         // TRANS: Line in @-reply notification e-mail. %s is conversation URL.
645         $conversationEmailText = sprintf(_("The full conversation can be read here:\n\n".
646                                            "\t%s"), $conversationUrl) . "\n\n";
647     } else {
648         $conversationEmailText = '';
649     }
650
651     $subject = sprintf(_('%s (@%s) sent a notice to your attention'), $bestname, $sender->nickname);
652
653         // TRANS: Body of @-reply notification e-mail.
654         $body = sprintf(_("%1\$s (@%9\$s) just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
655                       "The notice is here:\n\n".
656                       "\t%3\$s\n\n" .
657                       "It reads:\n\n".
658                       "\t%4\$s\n\n" .
659                       "%5\$s" .
660                       "You can reply back here:\n\n".
661                       "\t%6\$s\n\n" .
662                       "The list of all @-replies for you here:\n\n" .
663                       "%7\$s\n\n" .
664                       "Faithfully yours,\n" .
665                       "%2\$s\n\n" .
666                       "P.S. You can turn off these email notifications here: %8\$s\n"),
667                     $bestname,//%1
668                     common_config('site', 'name'),//%2
669                     common_local_url('shownotice',
670                                      array('notice' => $notice->id)),//%3
671                     $notice->content,//%4
672                     $conversationEmailText,//%5
673                     common_local_url('newnotice',
674                                      array('replyto' => $sender->nickname, 'inreplyto' => $notice->id)),//%6
675                     common_local_url('replies',
676                                      array('nickname' => $user->nickname)),//%7
677                     common_local_url('emailsettings'), //%8
678                     $sender->nickname); //%9
679
680     $headers = _mail_prepare_headers('mention', $user->nickname, $sender->nickname);
681
682     common_init_locale();
683     mail_to_user($user, $subject, $body, $headers);
684 }
685
686 /**
687  * Prepare the common mail headers used in notification emails
688  *
689  * @param string $msg_type type of message being sent to the user
690  * @param string $to       nickname of the receipient
691  * @param string $from     nickname of the user triggering the notification
692  *
693  * @return array list of mail headers to include in the message
694  */
695 function _mail_prepare_headers($msg_type, $to, $from)
696 {
697     $headers = array(
698         'X-StatusNet-MessageType' => $msg_type,
699         'X-StatusNet-TargetUser'  => $to,
700         'X-StatusNet-SourceUser'  => $from,
701         'X-StatusNet-Domain'      => common_config('site', 'server')
702     );
703
704     return $headers;
705 }
706