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