]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mail.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.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 string $address optional specification of email address
137  *
138  * @return boolean success flag
139  */
140
141 function mail_to_user(&$user, $subject, $body, $address=null)
142 {
143     if (!$address) {
144         $address = $user->email;
145     }
146
147     $recipients = $address;
148     $profile    = $user->getProfile();
149
150     $headers['From']    = mail_notify_from();
151     $headers['To']      = $profile->getBestName() . ' <' . $address . '>';
152     $headers['Subject'] = $subject;
153
154     return mail_send($recipients, $headers, $body);
155 }
156
157 /**
158  * Send an email to confirm a user's control of an email address
159  *
160  * @param User   $user     User claiming the email address
161  * @param string $code     Confirmation code
162  * @param string $nickname Nickname of user
163  * @param string $address  email address to confirm
164  *
165  * @see common_confirmation_code()
166  *
167  * @return success flag
168  */
169
170 function mail_confirm_address($user, $code, $nickname, $address)
171 {
172     $subject = _('Email address confirmation');
173
174     $body = sprintf(_("Hey, %s.\n\n".
175                       "Someone just entered this email address on %s.\n\n" .
176                       "If it was you, and you want to confirm your entry, ".
177                       "use the URL below:\n\n\t%s\n\n" .
178                       "If not, just ignore this message.\n\n".
179                       "Thanks for your time, \n%s\n"),
180                     $nickname, common_config('site', 'name'),
181                     common_local_url('confirmaddress', array('code' => $code)),
182                     common_config('site', 'name'));
183     return mail_to_user($user, $subject, $body, $address);
184 }
185
186 /**
187  * notify a user of subscription by another user
188  *
189  * This is just a wrapper around the profile-based version.
190  *
191  * @param User $listenee user who is being subscribed to
192  * @param User $listener user who is subscribing
193  *
194  * @see mail_subscribe_notify_profile()
195  *
196  * @return void
197  */
198
199 function mail_subscribe_notify($listenee, $listener)
200 {
201     $other = $listener->getProfile();
202     mail_subscribe_notify_profile($listenee, $other);
203 }
204
205 /**
206  * notify a user of subscription by a profile (remote or local)
207  *
208  * This function checks to see if the listenee has an email
209  * address and wants subscription notices.
210  *
211  * @param User    $listenee user who's being subscribed to
212  * @param Profile $other    profile of person who's listening
213  *
214  * @return void
215  */
216
217 function mail_subscribe_notify_profile($listenee, $other)
218 {
219     if ($other->hasRight(Right::EMAILONSUBSCRIBE) &&
220         $listenee->email && $listenee->emailnotifysub) {
221
222         // use the recipient's localization
223         common_init_locale($listenee->language);
224
225         $profile = $listenee->getProfile();
226
227         $name = $profile->getBestName();
228
229         $long_name = ($other->fullname) ?
230           ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname;
231
232         $recipients = $listenee->email;
233
234         $headers['From']    = mail_notify_from();
235         $headers['To']      = $name . ' <' . $listenee->email . '>';
236         $headers['Subject'] = sprintf(_('%1$s is now listening to '.
237                                         'your notices on %2$s.'),
238                                       $other->getBestName(),
239                                       common_config('site', 'name'));
240
241         $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n".
242                           "\t".'%3$s'."\n\n".
243                           '%4$s'.
244                           '%5$s'.
245                           '%6$s'.
246                           "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n".
247                           "----\n".
248                           "Change your email address or ".
249                           "notification options at ".'%8$s' ."\n"),
250                         $long_name,
251                         common_config('site', 'name'),
252                         $other->profileurl,
253                         ($other->location) ?
254                         sprintf(_("Location: %s"), $other->location) . "\n" : '',
255                         ($other->homepage) ?
256                         sprintf(_("Homepage: %s"), $other->homepage) . "\n" : '',
257                         ($other->bio) ?
258                         sprintf(_("Bio: %s"), $other->bio) . "\n\n" : '',
259                         common_config('site', 'name'),
260                         common_local_url('emailsettings'));
261
262         // reset localization
263         common_init_locale();
264         mail_send($recipients, $headers, $body);
265     }
266 }
267
268 /**
269  * notify a user of their new incoming email address
270  *
271  * User's email and incoming fields should already be updated.
272  *
273  * @param User $user user with the new address
274  *
275  * @return void
276  */
277
278 function mail_new_incoming_notify($user)
279 {
280     $profile = $user->getProfile();
281
282     $name = $profile->getBestName();
283
284     $headers['From']    = $user->incomingemail;
285     $headers['To']      = $name . ' <' . $user->email . '>';
286     $headers['Subject'] = sprintf(_('New email address for posting to %s'),
287                                   common_config('site', 'name'));
288
289     $body = sprintf(_("You have a new posting address on %1\$s.\n\n".
290                       "Send email to %2\$s to post new messages.\n\n".
291                       "More email instructions at %3\$s.\n\n".
292                       "Faithfully yours,\n%4\$s"),
293                     common_config('site', 'name'),
294                     $user->incomingemail,
295                     common_local_url('doc', array('title' => 'email')),
296                     common_config('site', 'name'));
297
298     mail_send($user->email, $headers, $body);
299 }
300
301 /**
302  * generate a new address for incoming messages
303  *
304  * @todo check the database for uniqueness
305  *
306  * @return string new email address for incoming messages
307  */
308
309 function mail_new_incoming_address()
310 {
311     $prefix = common_confirmation_code(64);
312     $suffix = mail_domain();
313     return $prefix . '@' . $suffix;
314 }
315
316 /**
317  * broadcast a notice to all subscribers with SMS notification on
318  *
319  * This function sends SMS messages to all users who have sms addresses;
320  * have sms notification on; and have sms enabled for this particular
321  * subscription.
322  *
323  * @param Notice $notice The notice to broadcast
324  *
325  * @return success flag
326  */
327
328 function mail_broadcast_notice_sms($notice)
329 {
330     // Now, get users subscribed to this profile
331
332     $user = new User();
333
334     $UT = common_config('db','type')=='pgsql'?'"user"':'user';
335     $user->query('SELECT nickname, smsemail, incomingemail ' .
336                  "FROM $UT JOIN subscription " .
337                  "ON $UT.id = subscription.subscriber " .
338                  'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' .
339                  'AND subscription.subscribed != subscription.subscriber ' .
340                  "AND $UT.smsemail IS NOT null " .
341                  "AND $UT.smsnotify = 1 " .
342                  'AND subscription.sms = 1 ');
343
344     while ($user->fetch()) {
345         common_log(LOG_INFO,
346                    'Sending notice ' . $notice->id . ' to ' . $user->smsemail,
347                    __FILE__);
348         $success = mail_send_sms_notice_address($notice,
349                                                 $user->smsemail,
350                                                 $user->incomingemail);
351         if (!$success) {
352             // XXX: Not sure, but I think that's the right thing to do
353             common_log(LOG_WARNING,
354                        'Sending notice ' . $notice->id . ' to ' .
355                        $user->smsemail . ' FAILED, cancelling.',
356                        __FILE__);
357             return false;
358         }
359     }
360
361     $user->free();
362     unset($user);
363
364     return true;
365 }
366
367 /**
368  * send a notice to a user via SMS
369  *
370  * A convenience wrapper around mail_send_sms_notice_address()
371  *
372  * @param Notice $notice notice to send
373  * @param User   $user   user to receive notice
374  *
375  * @see mail_send_sms_notice_address()
376  *
377  * @return boolean success flag
378  */
379
380 function mail_send_sms_notice($notice, $user)
381 {
382     return mail_send_sms_notice_address($notice,
383                                         $user->smsemail,
384                                         $user->incomingemail);
385 }
386
387 /**
388  * send a notice to an SMS email address from a given address
389  *
390  * We use the user's incoming email address as the "From" address to make
391  * replying to notices easier.
392  *
393  * @param Notice $notice        notice to send
394  * @param string $smsemail      email address to send to
395  * @param string $incomingemail email address to set as 'from'
396  *
397  * @return boolean success flag
398  */
399
400 function mail_send_sms_notice_address($notice, $smsemail, $incomingemail)
401 {
402     $to = $nickname . ' <' . $smsemail . '>';
403
404     $other = $notice->getProfile();
405
406     common_log(LOG_INFO, 'Sending notice ' . $notice->id .
407                ' to ' . $smsemail, __FILE__);
408
409     $headers = array();
410
411     $headers['From']    = ($incomingemail) ? $incomingemail : mail_notify_from();
412     $headers['To']      = $to;
413     $headers['Subject'] = sprintf(_('%s status'),
414                                   $other->getBestName());
415
416     $body = $notice->content;
417
418     return mail_send($smsemail, $headers, $body);
419 }
420
421 /**
422  * send a message to confirm a claim for an SMS number
423  *
424  * @param string $code     confirmation code
425  * @param string $nickname nickname of user claiming number
426  * @param string $address  email address to send the confirmation to
427  *
428  * @see common_confirmation_code()
429  *
430  * @return void
431  */
432
433 function mail_confirm_sms($code, $nickname, $address)
434 {
435     $recipients = $address;
436
437     $headers['From']    = mail_notify_from();
438     $headers['To']      = $nickname . ' <' . $address . '>';
439     $headers['Subject'] = _('SMS confirmation');
440
441     // FIXME: I18N
442
443     $body  = "$nickname: confirm you own this phone number with this code:";
444     $body .= "\n\n";
445     $body .= $code;
446     $body .= "\n\n";
447
448     mail_send($recipients, $headers, $body);
449 }
450
451 /**
452  * send a mail message to notify a user of a 'nudge'
453  *
454  * @param User $from user nudging
455  * @param User $to   user being nudged
456  *
457  * @return boolean success flag
458  */
459
460 function mail_notify_nudge($from, $to)
461 {
462     common_init_locale($to->language);
463     $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname);
464
465     $from_profile = $from->getProfile();
466
467     $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ".
468                       "these days and is inviting you to post some news.\n\n".
469                       "So let's hear from you :)\n\n".
470                       "%3\$s\n\n".
471                       "Don't reply to this email; it won't get to them.\n\n".
472                       "With kind regards,\n".
473                       "%4\$s\n"),
474                     $from_profile->getBestName(),
475                     $from->nickname,
476                     common_local_url('all', array('nickname' => $to->nickname)),
477                     common_config('site', 'name'));
478     common_init_locale();
479     return mail_to_user($to, $subject, $body);
480 }
481
482 /**
483  * send a message to notify a user of a direct message (DM)
484  *
485  * This function checks to see if the recipient wants notification
486  * of DMs and has a configured email address.
487  *
488  * @param Message $message message to notify about
489  * @param User    $from    user sending message; default to sender
490  * @param User    $to      user receiving message; default to recipient
491  *
492  * @return boolean success code
493  */
494
495 function mail_notify_message($message, $from=null, $to=null)
496 {
497     if (is_null($from)) {
498         $from = User::staticGet('id', $message->from_profile);
499     }
500
501     if (is_null($to)) {
502         $to = User::staticGet('id', $message->to_profile);
503     }
504
505     if (is_null($to->email) || !$to->emailnotifymsg) {
506         return true;
507     }
508
509     common_init_locale($to->language);
510     $subject = sprintf(_('New private message from %s'), $from->nickname);
511
512     $from_profile = $from->getProfile();
513
514     $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n".
515                       "------------------------------------------------------\n".
516                       "%3\$s\n".
517                       "------------------------------------------------------\n\n".
518                       "You can reply to their message here:\n\n".
519                       "%4\$s\n\n".
520                       "Don't reply to this email; it won't get to them.\n\n".
521                       "With kind regards,\n".
522                       "%5\$s\n"),
523                     $from_profile->getBestName(),
524                     $from->nickname,
525                     $message->content,
526                     common_local_url('newmessage', array('to' => $from->id)),
527                     common_config('site', 'name'));
528
529     common_init_locale();
530     return mail_to_user($to, $subject, $body);
531 }
532
533 /**
534  * notify a user that one of their notices has been chosen as a 'fave'
535  *
536  * Doesn't check that the user has an email address nor if they
537  * want to receive notification of faves. Maybe this happens higher
538  * up the stack...?
539  *
540  * @param User   $other  The user whose notice was faved
541  * @param User   $user   The user who faved the notice
542  * @param Notice $notice The notice that was faved
543  *
544  * @return void
545  */
546
547 function mail_notify_fave($other, $user, $notice)
548 {
549     if (!$user->hasRight(Right::EMAILONFAVE)) {
550         return;
551     }
552
553     $profile = $user->getProfile();
554
555     $bestname = $profile->getBestName();
556
557     common_init_locale($other->language);
558
559     $subject = sprintf(_('%s (@%s) added your notice as a favorite'), $bestname, $user->nickname);
560
561     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
562                       " as one of their favorites.\n\n" .
563                       "The URL of your notice is:\n\n" .
564                       "%3\$s\n\n" .
565                       "The text of your notice is:\n\n" .
566                       "%4\$s\n\n" .
567                       "You can see the list of %1\$s's favorites here:\n\n" .
568                       "%5\$s\n\n" .
569                       "Faithfully yours,\n" .
570                       "%6\$s\n"),
571                     $bestname,
572                     common_exact_date($notice->created),
573                     common_local_url('shownotice',
574                                      array('notice' => $notice->id)),
575                     $notice->content,
576                     common_local_url('showfavorites',
577                                      array('nickname' => $user->nickname)),
578                     common_config('site', 'name'),
579                     $user->nickname);
580
581     common_init_locale();
582     mail_to_user($other, $subject, $body);
583 }
584
585 /**
586  * notify a user that they have received an "attn:" message AKA "@-reply"
587  *
588  * @param User   $user   The user who recevied the notice
589  * @param Notice $notice The notice that was sent
590  *
591  * @return void
592  */
593
594 function mail_notify_attn($user, $notice)
595 {
596     if (!$user->email || !$user->emailnotifyattn) {
597         return;
598     }
599
600     $sender = $notice->getProfile();
601
602     if ($sender->id == $user->id) {
603         return;
604     }
605
606     if (!$sender->hasRight(Right::EMAILONREPLY)) {
607         return;
608     }
609
610     $bestname = $sender->getBestName();
611
612     common_init_locale($user->language);
613
614         if ($notice->conversation != $notice->id) {
615                 $conversationEmailText = "The full conversation can be read here:\n\n".
616                                                                  "\t%5\$s\n\n ";
617                 $conversationUrl           = common_local_url('conversation',
618                                  array('id' => $notice->conversation)).'#notice-'.$notice->id;
619         } else {
620                 $conversationEmailText = "%5\$s";
621                 $conversationUrl = null;
622         }
623
624     $subject = sprintf(_('%s (@%s) sent a notice to your attention'), $bestname, $sender->nickname);
625
626         $body = sprintf(_("%1\$s (@%9\$s) just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
627                       "The notice is here:\n\n".
628                       "\t%3\$s\n\n" .
629                       "It reads:\n\n".
630                       "\t%4\$s\n\n" .
631                       $conversationEmailText .
632                       "You can reply back here:\n\n".
633                       "\t%6\$s\n\n" .
634                       "The list of all @-replies for you here:\n\n" .
635                       "%7\$s\n\n" .
636                       "Faithfully yours,\n" .
637                       "%2\$s\n\n" .
638                       "P.S. You can turn off these email notifications here: %8\$s\n"),
639                     $bestname,//%1
640                     common_config('site', 'name'),//%2
641                     common_local_url('shownotice',
642                                      array('notice' => $notice->id)),//%3
643                     $notice->content,//%4
644                                         $conversationUrl,//%5
645                     common_local_url('newnotice',
646                                      array('replyto' => $sender->nickname, 'inreplyto' => $notice->id)),//%6
647                     common_local_url('replies',
648                                      array('nickname' => $user->nickname)),//%7
649                     common_local_url('emailsettings'), //%8
650                     $sender->nickname); //%9
651
652     common_init_locale();
653     mail_to_user($user, $subject, $body);
654 }