]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mail.php
Merge branch '0.9.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         $profile = $listenee->getProfile();
228
229         $name = $profile->getBestName();
230
231         $long_name = ($other->fullname) ?
232           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
233
234         $recipients = $listenee->email;
235
236         // use the recipient's localization
237         common_switch_locale($listenee->language);
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         $blocklink = sprintf(_("If you believe this account is being used abusively, " .
249                                "you can block them from your subscribers list and " .
250                                "report as spam to site administrators at %s"),
251                              common_local_url('block', array('profileid' => $other->id)));
252
253         // TRANS: Main body of new-subscriber notification e-mail
254         $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n".
255                           "\t".'%3$s'."\n\n".
256                           '%4$s'.
257                           '%5$s'.
258                           '%6$s'.
259                           "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n".
260                           "----\n".
261                           "Change your email address or ".
262                           "notification options at ".'%8$s' ."\n"),
263                         $long_name,
264                         common_config('site', 'name'),
265                         $other->profileurl,
266                         ($other->location) ?
267                         // TRANS: Profile info line in new-subscriber notification e-mail
268                         sprintf(_("Location: %s"), $other->location) . "\n" : '',
269                         ($other->homepage) ?
270                         // TRANS: Profile info line in new-subscriber notification e-mail
271                         sprintf(_("Homepage: %s"), $other->homepage) . "\n" : '',
272                         (($other->bio) ?
273                         // TRANS: Profile info line in new-subscriber notification e-mail
274                             sprintf(_("Bio: %s"), $other->bio) . "\n" : '') .
275                             "\n\n" . $blocklink . "\n",
276                         common_config('site', 'name'),
277                         common_local_url('emailsettings'));
278
279         // reset localization
280         common_switch_locale();
281         mail_send($recipients, $headers, $body);
282     }
283 }
284
285 /**
286  * notify a user of their new incoming email address
287  *
288  * User's email and incoming fields should already be updated.
289  *
290  * @param User $user user with the new address
291  *
292  * @return void
293  */
294
295 function mail_new_incoming_notify($user)
296 {
297     $profile = $user->getProfile();
298
299     $name = $profile->getBestName();
300
301     $headers['From']    = $user->incomingemail;
302     $headers['To']      = $name . ' <' . $user->email . '>';
303     // TRANS: Subject of notification mail for new posting email address
304     $headers['Subject'] = sprintf(_('New email address for posting to %s'),
305                                   common_config('site', 'name'));
306
307     // TRANS: Body of notification mail for new posting email address
308     $body = sprintf(_("You have a new posting address on %1\$s.\n\n".
309                       "Send email to %2\$s to post new messages.\n\n".
310                       "More email instructions at %3\$s.\n\n".
311                       "Faithfully yours,\n%4\$s"),
312                     common_config('site', 'name'),
313                     $user->incomingemail,
314                     common_local_url('doc', array('title' => 'email')),
315                     common_config('site', 'name'));
316
317     mail_send($user->email, $headers, $body);
318 }
319
320 /**
321  * generate a new address for incoming messages
322  *
323  * @todo check the database for uniqueness
324  *
325  * @return string new email address for incoming messages
326  */
327
328 function mail_new_incoming_address()
329 {
330     $prefix = common_confirmation_code(64);
331     $suffix = mail_domain();
332     return $prefix . '@' . $suffix;
333 }
334
335 /**
336  * broadcast a notice to all subscribers with SMS notification on
337  *
338  * This function sends SMS messages to all users who have sms addresses;
339  * have sms notification on; and have sms enabled for this particular
340  * subscription.
341  *
342  * @param Notice $notice The notice to broadcast
343  *
344  * @return success flag
345  */
346
347 function mail_broadcast_notice_sms($notice)
348 {
349     // Now, get users subscribed to this profile
350
351     $user = new User();
352
353     $UT = common_config('db','type')=='pgsql'?'"user"':'user';
354     $user->query('SELECT nickname, smsemail, incomingemail ' .
355                  "FROM $UT JOIN subscription " .
356                  "ON $UT.id = subscription.subscriber " .
357                  'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' .
358                  'AND subscription.subscribed != subscription.subscriber ' .
359                  "AND $UT.smsemail IS NOT null " .
360                  "AND $UT.smsnotify = 1 " .
361                  'AND subscription.sms = 1 ');
362
363     while ($user->fetch()) {
364         common_log(LOG_INFO,
365                    'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
366                    __FILE__);
367         $success = mail_send_sms_notice_address($notice,
368                                                 $user->smsemail,
369                                                 $user->incomingemail);
370         if (!$success) {
371             // XXX: Not sure, but I think that's the right thing to do
372             common_log(LOG_WARNING,
373                        'Sending notice ' . $notice->id . ' to ' .
374                        $user->smsemail . ' FAILED, cancelling.',
375                        __FILE__);
376             return false;
377         }
378     }
379
380     $user->free();
381     unset($user);
382
383     return true;
384 }
385
386 /**
387  * send a notice to a user via SMS
388  *
389  * A convenience wrapper around mail_send_sms_notice_address()
390  *
391  * @param Notice $notice notice to send
392  * @param User   $user   user to receive notice
393  *
394  * @see mail_send_sms_notice_address()
395  *
396  * @return boolean success flag
397  */
398
399 function mail_send_sms_notice($notice, $user)
400 {
401     return mail_send_sms_notice_address($notice,
402                                         $user->smsemail,
403                                         $user->incomingemail);
404 }
405
406 /**
407  * send a notice to an SMS email address from a given address
408  *
409  * We use the user's incoming email address as the "From" address to make
410  * replying to notices easier.
411  *
412  * @param Notice $notice        notice to send
413  * @param string $smsemail      email address to send to
414  * @param string $incomingemail email address to set as 'from'
415  *
416  * @return boolean success flag
417  */
418
419 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail)
420 {
421     $to = $nickname . ' <' . $smsemail . '>';
422
423     $other = $notice->getProfile();
424
425     common_log(LOG_INFO, 'Sending notice ' . $notice->id .
426                ' to ' . $smsemail, __FILE__);
427
428     $headers = array();
429
430     $headers['From']    = ($incomingemail) ? $incomingemail : mail_notify_from();
431     $headers['To']      = $to;
432     // TRANS: Subject line for SMS-by-email notification messages
433     $headers['Subject'] = sprintf(_('%s status'),
434                                   $other->getBestName());
435
436     $body = $notice->content;
437
438     return mail_send($smsemail, $headers, $body);
439 }
440
441 /**
442  * send a message to confirm a claim for an SMS number
443  *
444  * @param string $code     confirmation code
445  * @param string $nickname nickname of user claiming number
446  * @param string $address  email address to send the confirmation to
447  *
448  * @see common_confirmation_code()
449  *
450  * @return void
451  */
452
453 function mail_confirm_sms($code, $nickname, $address)
454 {
455     $recipients = $address;
456
457     $headers['From']    = mail_notify_from();
458     $headers['To']      = $nickname . ' <' . $address . '>';
459     // TRANS: Subject line for SMS-by-email address confirmation message
460     $headers['Subject'] = _('SMS confirmation');
461
462     // TRANS: Main body heading for SMS-by-email address confirmation message
463     $body  = sprintf(_("%s: confirm you own this phone number with this code:"), $nickname);
464     $body .= "\n\n";
465     $body .= $code;
466     $body .= "\n\n";
467
468     mail_send($recipients, $headers, $body);
469 }
470
471 /**
472  * send a mail message to notify a user of a 'nudge'
473  *
474  * @param User $from user nudging
475  * @param User $to   user being nudged
476  *
477  * @return boolean success flag
478  */
479
480 function mail_notify_nudge($from, $to)
481 {
482     common_switch_locale($to->language);
483     // TRANS: Subject for 'nudge' notification email
484     $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname);
485
486     $from_profile = $from->getProfile();
487
488     // TRANS: Body for 'nudge' notification email
489     $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ".
490                       "these days and is inviting you to post some news.\n\n".
491                       "So let's hear from you :)\n\n".
492                       "%3\$s\n\n".
493                       "Don't reply to this email; it won't get to them.\n\n".
494                       "With kind regards,\n".
495                       "%4\$s\n"),
496                     $from_profile->getBestName(),
497                     $from->nickname,
498                     common_local_url('all', array('nickname' => $to->nickname)),
499                     common_config('site', 'name'));
500     common_switch_locale();
501
502     $headers = _mail_prepare_headers('nudge', $to->nickname, $from->nickname);
503
504     return mail_to_user($to, $subject, $body, $headers);
505 }
506
507 /**
508  * send a message to notify a user of a direct message (DM)
509  *
510  * This function checks to see if the recipient wants notification
511  * of DMs and has a configured email address.
512  *
513  * @param Message $message message to notify about
514  * @param User    $from    user sending message; default to sender
515  * @param User    $to      user receiving message; default to recipient
516  *
517  * @return boolean success code
518  */
519
520 function mail_notify_message($message, $from=null, $to=null)
521 {
522     if (is_null($from)) {
523         $from = User::staticGet('id', $message->from_profile);
524     }
525
526     if (is_null($to)) {
527         $to = User::staticGet('id', $message->to_profile);
528     }
529
530     if (is_null($to->email) || !$to->emailnotifymsg) {
531         return true;
532     }
533
534     common_switch_locale($to->language);
535     // TRANS: Subject for direct-message notification email
536     $subject = sprintf(_('New private message from %s'), $from->nickname);
537
538     $from_profile = $from->getProfile();
539
540     // TRANS: Body for direct-message notification email
541     $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n".
542                       "------------------------------------------------------\n".
543                       "%3\$s\n".
544                       "------------------------------------------------------\n\n".
545                       "You can reply to their message here:\n\n".
546                       "%4\$s\n\n".
547                       "Don't reply to this email; it won't get to them.\n\n".
548                       "With kind regards,\n".
549                       "%5\$s\n"),
550                     $from_profile->getBestName(),
551                     $from->nickname,
552                     $message->content,
553                     common_local_url('newmessage', array('to' => $from->id)),
554                     common_config('site', 'name'));
555
556     $headers = _mail_prepare_headers('message', $to->nickname, $from->nickname);
557
558     common_switch_locale();
559     return mail_to_user($to, $subject, $body, $headers);
560 }
561
562 /**
563  * notify a user that one of their notices has been chosen as a 'fave'
564  *
565  * Doesn't check that the user has an email address nor if they
566  * want to receive notification of faves. Maybe this happens higher
567  * up the stack...?
568  *
569  * @param User   $other  The user whose notice was faved
570  * @param User   $user   The user who faved the notice
571  * @param Notice $notice The notice that was faved
572  *
573  * @return void
574  */
575
576 function mail_notify_fave($other, $user, $notice)
577 {
578     if (!$user->hasRight(Right::EMAILONFAVE)) {
579         return;
580     }
581
582     $profile = $user->getProfile();
583
584     $bestname = $profile->getBestName();
585
586     common_switch_locale($other->language);
587
588     // TRANS: Subject for favorite notification email
589     $subject = sprintf(_('%s (@%s) added your notice as a favorite'), $bestname, $user->nickname);
590
591     // TRANS: Body for favorite notification email
592     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
593                       " as one of their favorites.\n\n" .
594                       "The URL of your notice is:\n\n" .
595                       "%3\$s\n\n" .
596                       "The text of your notice is:\n\n" .
597                       "%4\$s\n\n" .
598                       "You can see the list of %1\$s's favorites here:\n\n" .
599                       "%5\$s\n\n" .
600                       "Faithfully yours,\n" .
601                       "%6\$s\n"),
602                     $bestname,
603                     common_exact_date($notice->created),
604                     common_local_url('shownotice',
605                                      array('notice' => $notice->id)),
606                     $notice->content,
607                     common_local_url('showfavorites',
608                                      array('nickname' => $user->nickname)),
609                     common_config('site', 'name'),
610                     $user->nickname);
611
612     $headers = _mail_prepare_headers('fave', $other->nickname, $user->nickname);
613
614     common_switch_locale();
615     mail_to_user($other, $subject, $body, $headers);
616 }
617
618 /**
619  * notify a user that they have received an "attn:" message AKA "@-reply"
620  *
621  * @param User   $user   The user who recevied the notice
622  * @param Notice $notice The notice that was sent
623  *
624  * @return void
625  */
626
627 function mail_notify_attn($user, $notice)
628 {
629     if (!$user->email || !$user->emailnotifyattn) {
630         return;
631     }
632
633     $sender = $notice->getProfile();
634
635     if ($sender->id == $user->id) {
636         return;
637     }
638
639     if (!$sender->hasRight(Right::EMAILONREPLY)) {
640         return;
641     }
642
643     $bestname = $sender->getBestName();
644
645     common_switch_locale($user->language);
646
647     if ($notice->hasConversation()) {
648         $conversationUrl = common_local_url('conversation',
649                          array('id' => $notice->conversation)).'#notice-'.$notice->id;
650         // TRANS: Line in @-reply notification e-mail. %s is conversation URL.
651         $conversationEmailText = sprintf(_("The full conversation can be read here:\n\n".
652                                            "\t%s"), $conversationUrl) . "\n\n";
653     } else {
654         $conversationEmailText = '';
655     }
656
657     $subject = sprintf(_('%s (@%s) sent a notice to your attention'), $bestname, $sender->nickname);
658
659         // TRANS: Body of @-reply notification e-mail.
660         $body = sprintf(_("%1\$s (@%9\$s) just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
661                       "The notice is here:\n\n".
662                       "\t%3\$s\n\n" .
663                       "It reads:\n\n".
664                       "\t%4\$s\n\n" .
665                       "%5\$s" .
666                       "You can reply back here:\n\n".
667                       "\t%6\$s\n\n" .
668                       "The list of all @-replies for you here:\n\n" .
669                       "%7\$s\n\n" .
670                       "Faithfully yours,\n" .
671                       "%2\$s\n\n" .
672                       "P.S. You can turn off these email notifications here: %8\$s\n"),
673                     $bestname,//%1
674                     common_config('site', 'name'),//%2
675                     common_local_url('shownotice',
676                                      array('notice' => $notice->id)),//%3
677                     $notice->content,//%4
678                     $conversationEmailText,//%5
679                     common_local_url('newnotice',
680                                      array('replyto' => $sender->nickname, 'inreplyto' => $notice->id)),//%6
681                     common_local_url('replies',
682                                      array('nickname' => $user->nickname)),//%7
683                     common_local_url('emailsettings'), //%8
684                     $sender->nickname); //%9
685
686     $headers = _mail_prepare_headers('mention', $user->nickname, $sender->nickname);
687
688     common_switch_locale();
689     mail_to_user($user, $subject, $body, $headers);
690 }
691
692 /**
693  * Prepare the common mail headers used in notification emails
694  *
695  * @param string $msg_type type of message being sent to the user
696  * @param string $to       nickname of the receipient
697  * @param string $from     nickname of the user triggering the notification
698  *
699  * @return array list of mail headers to include in the message
700  */
701 function _mail_prepare_headers($msg_type, $to, $from)
702 {
703     $headers = array(
704         'X-StatusNet-MessageType' => $msg_type,
705         'X-StatusNet-TargetUser'  => $to,
706         'X-StatusNet-SourceUser'  => $from,
707         'X-StatusNet-Domain'      => common_config('site', 'server')
708     );
709
710     return $headers;
711 }
712