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