* (bug 25642) A exception is now thrown instead of a fatal error when using $wgSMTP...
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 */
25
26
27 /**
28 * Stores a single person's name and email address.
29 * These are passed in via the constructor, and will be returned in SMTP
30 * header format when requested.
31 */
32 class MailAddress {
33 /**
34 * @param $address Mixed: string with an email address, or a User object
35 * @param $name String: human-readable name if a string address is given
36 * @param $realName String: human-readable real name if a string address is given
37 */
38 function __construct( $address, $name = null, $realName = null ) {
39 if( is_object( $address ) && $address instanceof User ) {
40 $this->address = $address->getEmail();
41 $this->name = $address->getName();
42 $this->realName = $address->getRealName();
43 } else {
44 $this->address = strval( $address );
45 $this->name = strval( $name );
46 $this->realName = strval( $realName );
47 }
48 }
49
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
53 */
54 function toString() {
55 # PHP's mail() implementation under Windows is somewhat shite, and
56 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
57 # so don't bother generating them
58 if( $this->name != '' && !wfIsWindows() ) {
59 global $wgEnotifUseRealName;
60 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
61 $quoted = wfQuotedPrintable( $name );
62 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
63 $quoted = '"' . $quoted . '"';
64 }
65 return "$quoted <{$this->address}>";
66 } else {
67 return $this->address;
68 }
69 }
70
71 function __toString() {
72 return $this->toString();
73 }
74 }
75
76
77 /**
78 * Collection of static functions for sending mail
79 */
80 class UserMailer {
81 static $mErrorString;
82
83 /**
84 * Send mail using a PEAR mailer
85 */
86 protected static function sendWithPear($mailer, $dest, $headers, $body)
87 {
88 $mailResult = $mailer->send($dest, $headers, $body);
89
90 # Based on the result return an error string,
91 if( PEAR::isError( $mailResult ) ) {
92 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
93 return new WikiError( $mailResult->getMessage() );
94 } else {
95 return true;
96 }
97 }
98
99 /**
100 * This function will perform a direct (authenticated) login to
101 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
102 * array of parameters. It requires PEAR:Mail to do that.
103 * Otherwise it just uses the standard PHP 'mail' function.
104 *
105 * @param $to MailAddress: recipient's email (or an array of them)
106 * @param $from MailAddress: sender's email
107 * @param $subject String: email's subject.
108 * @param $body String: email's text.
109 * @param $replyto MailAddress: optional reply-to email (default: null).
110 * @param $contentType String: optional custom Content-Type
111 * @return mixed True on success, a WikiError object on failure.
112 */
113 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
114 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
115 global $wgEnotifMaxRecips, $wgAdditionalMailParams;
116
117 if ( is_array( $to ) ) {
118 // This wouldn't be necessary if implode() worked on arrays of
119 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
120 foreach( $to as $t ) {
121 $emails .= $t->toString() . ",";
122 }
123 $emails = rtrim( $emails, ',' );
124 wfDebug( __METHOD__.': sending mail to ' . $emails . "\n" );
125 } else {
126 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
127 }
128
129 if (is_array( $wgSMTP )) {
130 $found = false;
131 $pathArray = explode( PATH_SEPARATOR, get_include_path() );
132 foreach ( $pathArray as $path ) {
133 if ( file_exists( $path . DIRECTORY_SEPARATOR . 'Mail.php' ) ) {
134 $found = true;
135 break;
136 }
137 }
138 if ( !$found ) {
139 throw new MWException( 'PEAR mail package is not installed' );
140 }
141 require_once( 'Mail.php' );
142
143 $msgid = str_replace(" ", "_", microtime());
144 if (function_exists('posix_getpid'))
145 $msgid .= '.' . posix_getpid();
146
147 if (is_array($to)) {
148 $dest = array();
149 foreach ($to as $u)
150 $dest[] = $u->address;
151 } else
152 $dest = $to->address;
153
154 $headers['From'] = $from->toString();
155
156 if ($wgEnotifImpersonal) {
157 $headers['To'] = 'undisclosed-recipients:;';
158 }
159 else {
160 $headers['To'] = implode( ", ", (array )$dest );
161 }
162
163 if ( $replyto ) {
164 $headers['Reply-To'] = $replyto->toString();
165 }
166 $headers['Subject'] = wfQuotedPrintable( $subject );
167 $headers['Date'] = date( 'r' );
168 $headers['MIME-Version'] = '1.0';
169 $headers['Content-type'] = (is_null($contentType) ?
170 'text/plain; charset='.$wgOutputEncoding : $contentType);
171 $headers['Content-transfer-encoding'] = '8bit';
172 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
173 $headers['X-Mailer'] = 'MediaWiki mailer';
174
175 // Create the mail object using the Mail::factory method
176 $mail_object =& Mail::factory('smtp', $wgSMTP);
177 if( PEAR::isError( $mail_object ) ) {
178 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
179 return new WikiError( $mail_object->getMessage() );
180 }
181
182 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
183 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
184 foreach ($chunks as $chunk) {
185 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
186 if( WikiError::isError( $e ) )
187 return $e;
188 }
189 } else {
190 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
191 # (fifth parameter of the PHP mail function, see some lines below)
192
193 # Line endings need to be different on Unix and Windows due to
194 # the bug described at http://trac.wordpress.org/ticket/2603
195 if ( wfIsWindows() ) {
196 $body = str_replace( "\n", "\r\n", $body );
197 $endl = "\r\n";
198 } else {
199 $endl = "\n";
200 }
201 $ctype = (is_null($contentType) ?
202 'text/plain; charset='.$wgOutputEncoding : $contentType);
203 $headers =
204 "MIME-Version: 1.0$endl" .
205 "Content-type: $ctype$endl" .
206 "Content-Transfer-Encoding: 8bit$endl" .
207 "X-Mailer: MediaWiki mailer$endl".
208 'From: ' . $from->toString();
209 if ($replyto) {
210 $headers .= "{$endl}Reply-To: " . $replyto->toString();
211 }
212
213 wfDebug( "Sending mail via internal mail() function\n" );
214
215 self::$mErrorString = '';
216 $html_errors = ini_get( 'html_errors' );
217 ini_set( 'html_errors', '0' );
218 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
219
220 if (is_array($to)) {
221 foreach ($to as $recip) {
222 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
223 }
224 } else {
225 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
226 }
227
228 restore_error_handler();
229 ini_set( 'html_errors', $html_errors );
230
231 if ( self::$mErrorString ) {
232 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
233 return new WikiError( self::$mErrorString );
234 } elseif (! $sent ) {
235 //mail function only tells if there's an error
236 wfDebug( "Error sending mail\n" );
237 return new WikiError( 'mail() failed' );
238 } else {
239 return true;
240 }
241 }
242 }
243
244 /**
245 * Set the mail error message in self::$mErrorString
246 *
247 * @param $code Integer: error number
248 * @param $string String: error message
249 */
250 static function errorHandler( $code, $string ) {
251 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
252 }
253
254 /**
255 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
256 */
257 static function rfc822Phrase( $phrase ) {
258 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
259 return '"' . $phrase . '"';
260 }
261 }
262
263 /**
264 * This module processes the email notifications when the current page is
265 * changed. It looks up the table watchlist to find out which users are watching
266 * that page.
267 *
268 * The current implementation sends independent emails to each watching user for
269 * the following reason:
270 *
271 * - Each watching user will be notified about the page edit time expressed in
272 * his/her local time (UTC is shown additionally). To achieve this, we need to
273 * find the individual timeoffset of each watching user from the preferences..
274 *
275 * Suggested improvement to slack down the number of sent emails: We could think
276 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
277 * same timeoffset in their preferences.
278 *
279 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
280 *
281 *
282 */
283 class EmailNotification {
284 protected $to, $subject, $body, $replyto, $from;
285 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
286 protected $mailTargets = array();
287
288 /**
289 * Send emails corresponding to the user $editor editing the page $title.
290 * Also updates wl_notificationtimestamp.
291 *
292 * May be deferred via the job queue.
293 *
294 * @param $editor User object
295 * @param $title Title object
296 * @param $timestamp
297 * @param $summary
298 * @param $minorEdit
299 * @param $oldid (default: false)
300 */
301 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
302 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
303
304 if ($title->getNamespace() < 0)
305 return;
306
307 // Build a list of users to notfiy
308 $watchers = array();
309 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
310 $dbw = wfGetDB( DB_MASTER );
311 $res = $dbw->select( array( 'watchlist' ),
312 array( 'wl_user' ),
313 array(
314 'wl_title' => $title->getDBkey(),
315 'wl_namespace' => $title->getNamespace(),
316 'wl_user != ' . intval( $editor->getID() ),
317 'wl_notificationtimestamp IS NULL',
318 ), __METHOD__
319 );
320 foreach ( $res as $row ) {
321 $watchers[] = intval( $row->wl_user );
322 }
323 if ($watchers) {
324 // Update wl_notificationtimestamp for all watching users except
325 // the editor
326 $dbw->begin();
327 $dbw->update( 'watchlist',
328 array( /* SET */
329 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
330 ), array( /* WHERE */
331 'wl_title' => $title->getDBkey(),
332 'wl_namespace' => $title->getNamespace(),
333 'wl_user' => $watchers
334 ), __METHOD__
335 );
336 $dbw->commit();
337 }
338 }
339
340 if ($wgEnotifUseJobQ) {
341 $params = array(
342 "editor" => $editor->getName(),
343 "editorID" => $editor->getID(),
344 "timestamp" => $timestamp,
345 "summary" => $summary,
346 "minorEdit" => $minorEdit,
347 "oldid" => $oldid,
348 "watchers" => $watchers);
349 $job = new EnotifNotifyJob( $title, $params );
350 $job->insert();
351 } else {
352 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
353 }
354
355 }
356
357 /*
358 * Immediate version of notifyOnPageChange().
359 *
360 * Send emails corresponding to the user $editor editing the page $title.
361 * Also updates wl_notificationtimestamp.
362 *
363 * @param $editor User object
364 * @param $title Title object
365 * @param $timestamp string Edit timestamp
366 * @param $summary string Edit summary
367 * @param $minorEdit bool
368 * @param $oldid int Revision ID
369 * @param $watchers array of user IDs
370 */
371 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
372 # we use $wgPasswordSender as sender's address
373 global $wgEnotifWatchlist;
374 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
375
376 wfProfileIn( __METHOD__ );
377
378 # The following code is only run, if several conditions are met:
379 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
380 # 2. minor edits (changes) are only regarded if the global flag indicates so
381
382 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
383
384 $this->title = $title;
385 $this->timestamp = $timestamp;
386 $this->summary = $summary;
387 $this->minorEdit = $minorEdit;
388 $this->oldid = $oldid;
389 $this->editor = $editor;
390 $this->composed_common = false;
391
392 $userTalkId = false;
393
394 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
395 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
396 $targetUser = User::newFromName( $title->getText() );
397 if ( !$targetUser || $targetUser->isAnon() ) {
398 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
399 } elseif ( $targetUser->getId() == $editor->getId() ) {
400 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
401 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
402 if( $targetUser->isEmailConfirmed() ) {
403 wfDebug( __METHOD__.": sending talk page update notification\n" );
404 $this->compose( $targetUser );
405 $userTalkId = $targetUser->getId();
406 } else {
407 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
408 }
409 } else {
410 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
411 }
412 }
413
414 if ( $wgEnotifWatchlist ) {
415 // Send updates to watchers other than the current editor
416 $userArray = UserArray::newFromIDs( $watchers );
417 foreach ( $userArray as $watchingUser ) {
418 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
419 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
420 $watchingUser->isEmailConfirmed() &&
421 $watchingUser->getID() != $userTalkId )
422 {
423 $this->compose( $watchingUser );
424 }
425 }
426 }
427 }
428
429 global $wgUsersNotifiedOnAllChanges;
430 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
431 $user = User::newFromName( $name );
432 $this->compose( $user );
433 }
434
435 $this->sendMails();
436 wfProfileOut( __METHOD__ );
437 }
438
439 /**
440 * @private
441 */
442 function composeCommonMailtext() {
443 global $wgPasswordSender, $wgNoReplyAddress;
444 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
445 global $wgEnotifImpersonal, $wgEnotifUseRealName;
446
447 $this->composed_common = true;
448
449 $summary = ($this->summary == '') ? ' - ' : $this->summary;
450 $medit = ($this->minorEdit) ? wfMsgForContent( 'minoredit' ) : '';
451
452 # You as the WikiAdmin and Sysops can make use of plenty of
453 # named variables when composing your notification emails while
454 # simply editing the Meta pages
455
456 $subject = wfMsgForContent( 'enotif_subject' );
457 $body = wfMsgForContent( 'enotif_body' );
458 $from = ''; /* fail safe */
459 $replyto = ''; /* fail safe */
460 $keys = array();
461
462 if( $this->oldid ) {
463 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
464 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
465 $keys['$OLDID'] = $this->oldid;
466 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
467 } else {
468 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
469 # clear $OLDID placeholder in the message template
470 $keys['$OLDID'] = '';
471 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
472 }
473
474 if ($wgEnotifImpersonal && $this->oldid)
475 /*
476 * For impersonal mail, show a diff link to the last
477 * revision.
478 */
479 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
480 $this->title->getFullURL("oldid={$this->oldid}&diff=next"));
481
482 $body = strtr( $body, $keys );
483 $pagetitle = $this->title->getPrefixedText();
484 $keys['$PAGETITLE'] = $pagetitle;
485 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
486
487 $keys['$PAGEMINOREDIT'] = $medit;
488 $keys['$PAGESUMMARY'] = $summary;
489 $keys['$UNWATCHURL'] = $this->title->getFullUrl( 'action=unwatch' );
490
491 $subject = strtr( $subject, $keys );
492
493 # Reveal the page editor's address as REPLY-TO address only if
494 # the user has not opted-out and the option is enabled at the
495 # global configuration level.
496 $editor = $this->editor;
497 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
498 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
499 $editorAddress = new MailAddress( $editor );
500 if( $wgEnotifRevealEditorAddress
501 && ( $editor->getEmail() != '' )
502 && $editor->getOption( 'enotifrevealaddr' ) ) {
503 if( $wgEnotifFromEditor ) {
504 $from = $editorAddress;
505 } else {
506 $from = $adminAddress;
507 $replyto = $editorAddress;
508 }
509 } else {
510 $from = $adminAddress;
511 $replyto = new MailAddress( $wgNoReplyAddress );
512 }
513
514 if( $editor->isIP( $name ) ) {
515 #real anon (user:xxx.xxx.xxx.xxx)
516 $utext = wfMsgForContent('enotif_anon_editor', $name);
517 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
518 $keys['$PAGEEDITOR'] = $utext;
519 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
520 } else {
521 $subject = str_replace('$PAGEEDITOR', $name, $subject);
522 $keys['$PAGEEDITOR'] = $name;
523 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
524 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
525 }
526 $userPage = $editor->getUserPage();
527 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
528 $body = strtr( $body, $keys );
529 $body = wordwrap( $body, 72 );
530
531 # now save this as the constant user-independent part of the message
532 $this->from = $from;
533 $this->replyto = $replyto;
534 $this->subject = $subject;
535 $this->body = $body;
536 }
537
538 /**
539 * Compose a mail to a given user and either queue it for sending, or send it now,
540 * depending on settings.
541 *
542 * Call sendMails() to send any mails that were queued.
543 */
544 function compose( $user ) {
545 global $wgEnotifImpersonal;
546
547 if ( !$this->composed_common )
548 $this->composeCommonMailtext();
549
550 if ( $wgEnotifImpersonal ) {
551 $this->mailTargets[] = new MailAddress( $user );
552 } else {
553 $this->sendPersonalised( $user );
554 }
555 }
556
557 /**
558 * Send any queued mails
559 */
560 function sendMails() {
561 global $wgEnotifImpersonal;
562 if ( $wgEnotifImpersonal ) {
563 $this->sendImpersonal( $this->mailTargets );
564 }
565 }
566
567 /**
568 * Does the per-user customizations to a notification e-mail (name,
569 * timestamp in proper timezone, etc) and sends it out.
570 * Returns true if the mail was sent successfully.
571 *
572 * @param $watchingUser User object
573 * @return Boolean
574 * @private
575 */
576 function sendPersonalised( $watchingUser ) {
577 global $wgContLang, $wgEnotifUseRealName;
578 // From the PHP manual:
579 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
580 // The mail command will not parse this properly while talking with the MTA.
581 $to = new MailAddress( $watchingUser );
582 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
583 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
584
585 $timecorrection = $watchingUser->getOption( 'timecorrection' );
586
587 # $PAGEEDITDATE is the time and date of the page change
588 # expressed in terms of individual local time of the notification
589 # recipient, i.e. watching user
590 $body = str_replace(
591 array( '$PAGEEDITDATEANDTIME',
592 '$PAGEEDITDATE',
593 '$PAGEEDITTIME' ),
594 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
595 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
596 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
597 $body);
598
599 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
600 }
601
602 /**
603 * Same as sendPersonalised but does impersonal mail suitable for bulk
604 * mailing. Takes an array of MailAddress objects.
605 */
606 function sendImpersonal( $addresses ) {
607 global $wgContLang;
608
609 if (empty($addresses))
610 return;
611
612 $body = str_replace(
613 array( '$WATCHINGUSERNAME',
614 '$PAGEEDITDATE'),
615 array( wfMsgForContent('enotif_impersonal_salutation'),
616 $wgContLang->timeanddate($this->timestamp, true, false, false)),
617 $this->body);
618
619 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
620 }
621
622 } # end of class EmailNotification
623
624 /**
625 * Backwards compatibility functions
626 */
627 function wfRFC822Phrase( $s ) {
628 return UserMailer::rfc822Phrase( $s );
629 }
630
631 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
632 return UserMailer::send( $to, $from, $subject, $body, $replyto );
633 }