mail() sending was not chucking recips properly in array path, from Nick Jenkins
[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 $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
105 global $wgEnotifMaxRecips;
106
107 if (is_array( $wgSMTP )) {
108 require_once( 'Mail.php' );
109
110 $timestamp = time();
111
112 if (is_array($to)) {
113 $dest = array();
114 foreach ($to as $u)
115 $dest[] = $u->address;
116 } else
117 $dest = $to->address;
118
119 $headers['From'] = $from->toString();
120
121 if ($wgEnotifImpersonal)
122 $headers['To'] = 'undisclosed-recipients:;';
123 else
124 $headers['To'] = $to->toString();
125
126 if ( $replyto ) {
127 $headers['Reply-To'] = $replyto->toString();
128 }
129 $headers['Subject'] = wfQuotedPrintable( $subject );
130 $headers['Date'] = date( 'r' );
131 $headers['MIME-Version'] = '1.0';
132 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
133 $headers['Content-transfer-encoding'] = '8bit';
134 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
135 $headers['X-Mailer'] = 'MediaWiki mailer';
136
137 // Create the mail object using the Mail::factory method
138 $mail_object =& Mail::factory('smtp', $wgSMTP);
139 if( PEAR::isError( $mail_object ) ) {
140 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
141 return $mail_object->getMessage();
142 }
143
144 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
145 if (is_array($dest)) {
146 $chunks = array_chunk($dest, $wgEnotifMaxRecips);
147 foreach ($chunks as $chunk) {
148 $e = send_mail($mail_object, $chunk, $headers, $body);
149 if ($e != '')
150 return $e;
151 }
152 } else
153 return $mail_object->send($dest, $headers, $body);
154
155 } else {
156 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
157 # (fifth parameter of the PHP mail function, see some lines below)
158
159 # Line endings need to be different on Unix and Windows due to
160 # the bug described at http://trac.wordpress.org/ticket/2603
161 if ( wfIsWindows() ) {
162 $body = str_replace( "\n", "\r\n", $body );
163 $endl = "\r\n";
164 } else {
165 $endl = "\n";
166 }
167 $headers =
168 "MIME-Version: 1.0$endl" .
169 "Content-type: text/plain; charset={$wgOutputEncoding}$endl" .
170 "Content-Transfer-Encoding: 8bit$endl" .
171 "X-Mailer: MediaWiki mailer$endl".
172 'From: ' . $from->toString();
173 if ($replyto) {
174 $headers .= "{$endl}Reply-To: " . $replyto->toString();
175 }
176
177 $wgErrorString = '';
178 set_error_handler( 'mailErrorHandler' );
179 wfDebug( "Sending mail via internal mail() function\n" );
180
181 if (is_array($to))
182 foreach ($to as $recip)
183 mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
184 else
185 mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
186
187 restore_error_handler();
188
189 if ( $wgErrorString ) {
190 wfDebug( "Error sending mail: $wgErrorString\n" );
191 }
192 return $wgErrorString;
193 }
194 }
195
196 /**
197 * Get the mail error message in global $wgErrorString
198 *
199 * @param $code Integer: error number
200 * @param $string String: error message
201 */
202 function mailErrorHandler( $code, $string ) {
203 global $wgErrorString;
204 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
205 }
206
207
208 /**
209 * This module processes the email notifications when the current page is
210 * changed. It looks up the table watchlist to find out which users are watching
211 * that page.
212 *
213 * The current implementation sends independent emails to each watching user for
214 * the following reason:
215 *
216 * - Each watching user will be notified about the page edit time expressed in
217 * his/her local time (UTC is shown additionally). To achieve this, we need to
218 * find the individual timeoffset of each watching user from the preferences..
219 *
220 * Suggested improvement to slack down the number of sent emails: We could think
221 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
222 * same timeoffset in their preferences.
223 *
224 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
225 *
226 *
227 */
228 class EmailNotification {
229 /**@{{
230 * @private
231 */
232 var $to, $subject, $body, $replyto, $from;
233 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
234
235 /**@}}*/
236
237 /**
238 * @todo document
239 * @param $title Title object
240 * @param $timestamp
241 * @param $summary
242 * @param $minorEdit
243 * @param $oldid (default: false)
244 */
245 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
246
247 # we use $wgEmergencyContact as sender's address
248 global $wgUser, $wgEnotifWatchlist;
249 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
250 global $wgEnotifImpersonal;
251
252 $fname = 'UserMailer::notifyOnPageChange';
253 wfProfileIn( $fname );
254
255 # The following code is only run, if several conditions are met:
256 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
257 # 2. minor edits (changes) are only regarded if the global flag indicates so
258
259 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
260 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
261 $enotifwatchlistpage = $wgEnotifWatchlist;
262
263 $this->title =& $title;
264 $this->timestamp = $timestamp;
265 $this->summary = $summary;
266 $this->minorEdit = $minorEdit;
267 $this->oldid = $oldid;
268 $this->composeCommonMailtext();
269
270 $impersonals = array();
271
272 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
273 if( $wgEnotifWatchlist ) {
274 // Send updates to watchers other than the current editor
275 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
276 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
277 $targetUser = User::newFromName( $title->getText() );
278 if( is_null( $targetUser ) ) {
279 wfDebug( "$fname: user-talk-only mode; no such user\n" );
280 $userCondition = false;
281 } elseif( $targetUser->getId() == $wgUser->getId() ) {
282 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
283 $userCondition = false;
284 } else {
285 // Don't notify anyone other than the owner of the talk page
286 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
287 }
288 } else {
289 // Notifications disabled
290 $userCondition = false;
291 }
292 if( $userCondition ) {
293 $dbr = wfGetDB( DB_MASTER );
294
295 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
296 array(
297 'wl_title' => $title->getDBkey(),
298 'wl_namespace' => $title->getNamespace(),
299 $userCondition,
300 'wl_notificationtimestamp IS NULL',
301 ), $fname );
302
303 # if anyone is watching ... set up the email message text which is
304 # common for all receipients ...
305 if ( $dbr->numRows( $res ) > 0 ) {
306
307 $watchingUser = new User();
308
309 # ... now do for all watching users ... if the options fit
310 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
311
312 $wuser = $dbr->fetchObject( $res );
313 $watchingUser->setID($wuser->wl_user);
314
315 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
316 ( $enotifusertalkpage
317 && $watchingUser->getOption('enotifusertalkpages')
318 && $title->equals( $watchingUser->getTalkPage() ) )
319 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
320 && ($watchingUser->isEmailConfirmed() ) ) {
321 # ... adjust remaining text and page edit time placeholders
322 # which needs to be personalized for each user
323 if ($wgEnotifImpersonal)
324 $impersonals[] = $watchingUser;
325 else
326 $this->composeAndSendPersonalisedMail( $watchingUser );
327
328 } # if the watching user has an email address in the preferences
329 }
330 }
331 } # if anyone is watching
332 } # if $wgEnotifWatchlist = true
333
334 global $wgUsersNotifedOnAllChanges;
335 foreach ( $wgUsersNotifedOnAllChanges as $name ) {
336 $user = User::newFromName( $name );
337 if ($wgEnotifImpersonal)
338 $impersonals[] = $user;
339 else
340 $this->composeAndSendPersonalisedMail( $user );
341 }
342
343 $this->composeAndSendImpersonalMail($impersonals);
344
345 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
346 # mark the changed watch-listed page with a timestamp, so that the page is
347 # listed with an "updated since your last visit" icon in the watch list, ...
348 $dbw = wfGetDB( DB_MASTER );
349 $success = $dbw->update( 'watchlist',
350 array( /* SET */
351 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
352 ), array( /* WHERE */
353 'wl_title' => $title->getDBkey(),
354 'wl_namespace' => $title->getNamespace(),
355 ), 'UserMailer::NotifyOnChange'
356 );
357 # FIXME what do we do on failure ?
358 }
359 wfProfileOut( $fname );
360 } # function NotifyOnChange
361
362 /**
363 * @private
364 */
365 function composeCommonMailtext() {
366 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
367 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
368 global $wgEnotifImpersonal;
369
370 $summary = ($this->summary == '') ? ' - ' : $this->summary;
371 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
372
373 # You as the WikiAdmin and Sysops can make use of plenty of
374 # named variables when composing your notification emails while
375 # simply editing the Meta pages
376
377 $subject = wfMsgForContent( 'enotif_subject' );
378 $body = wfMsgForContent( 'enotif_body' );
379 $from = ''; /* fail safe */
380 $replyto = ''; /* fail safe */
381 $keys = array();
382
383 # regarding the use of oldid as an indicator for the last visited version, see also
384 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
385 # However, in the case of a new page which is already watched, we have no previous version to compare
386 if( $this->oldid ) {
387 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
388 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
389 $keys['$OLDID'] = $this->oldid;
390 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
391 } else {
392 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
393 # clear $OLDID placeholder in the message template
394 $keys['$OLDID'] = '';
395 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
396 }
397
398 if ($wgEnotifImpersonal && $this->oldid)
399 /*
400 * For impersonal mail, show a diff link to the last
401 * revision.
402 */
403 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
404 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
405
406 $body = strtr( $body, $keys );
407 $pagetitle = $this->title->getPrefixedText();
408 $keys['$PAGETITLE'] = $pagetitle;
409 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
410
411 $keys['$PAGEMINOREDIT'] = $medit;
412 $keys['$PAGESUMMARY'] = $summary;
413
414 $subject = strtr( $subject, $keys );
415
416 # Reveal the page editor's address as REPLY-TO address only if
417 # the user has not opted-out and the option is enabled at the
418 # global configuration level.
419 $name = $wgUser->getName();
420 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
421 $editorAddress = new MailAddress( $wgUser );
422 if( $wgEnotifRevealEditorAddress
423 && ( $wgUser->getEmail() != '' )
424 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
425 if( $wgEnotifFromEditor ) {
426 $from = $editorAddress;
427 } else {
428 $from = $adminAddress;
429 $replyto = $editorAddress;
430 }
431 } else {
432 $from = $adminAddress;
433 $replyto = new MailAddress( $wgNoReplyAddress );
434 }
435
436 if( $wgUser->isIP( $name ) ) {
437 #real anon (user:xxx.xxx.xxx.xxx)
438 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
439 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
440 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
441 } else {
442 $subject = str_replace('$PAGEEDITOR', $name, $subject);
443 $keys['$PAGEEDITOR'] = $name;
444 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
445 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
446 }
447 $userPage = $wgUser->getUserPage();
448 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
449 $body = strtr( $body, $keys );
450 $body = wordwrap( $body, 72 );
451
452 # now save this as the constant user-independent part of the message
453 $this->from = $from;
454 $this->replyto = $replyto;
455 $this->subject = $subject;
456 $this->body = $body;
457 }
458
459 /**
460 * Does the per-user customizations to a notification e-mail (name,
461 * timestamp in proper timezone, etc) and sends it out.
462 * Returns true if the mail was sent successfully.
463 *
464 * @param User $watchingUser
465 * @param object $mail
466 * @return bool
467 * @private
468 */
469 function composeAndSendPersonalisedMail( $watchingUser ) {
470 global $wgLang;
471 // From the PHP manual:
472 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
473 // The mail command will not parse this properly while talking with the MTA.
474 $to = new MailAddress( $watchingUser );
475 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
476
477 $timecorrection = $watchingUser->getOption( 'timecorrection' );
478
479 # $PAGEEDITDATE is the time and date of the page change
480 # expressed in terms of individual local time of the notification
481 # recipient, i.e. watching user
482 $body = str_replace('$PAGEEDITDATE',
483 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
484 $body);
485
486 return $this->send_or_queue_mail($to, $this->from, $this->subject, $body, $this->replyto);
487 }
488
489 /**
490 * Same as composeAndSendPersonalisedMail but does impersonal mail
491 * suitable for bulk mailing. Takes an array of users.
492 */
493 function composeAndSendImpersonalMail($users) {
494 global $wgLang;
495
496 if (empty($users))
497 return;
498
499 $to = array();
500 foreach ($users as $user)
501 $to[] = new MailAddress($user);
502
503 $body = str_replace(
504 array( '$WATCHINGUSERNAME',
505 '$PAGEEDITDATE'),
506 array( wfMsgForContent('enotif_impersonal_salutation'),
507 $wgLang->timeanddate($this->timestamp, true, false, false)),
508 $this->body);
509
510 return $this->send_or_queue_mail($to, $this->from, $this->subject, $body, $this->replyto);
511 }
512
513 /**
514 * Either send an email or add it to the job queue to be sent later.
515 */
516 function send_or_queue_mail($to, $from, $subj, $body, $replyto) {
517 global $wgEnotifUseJobQ, $wgEnotifMaxRecips;
518
519 if (!$wgEnotifUseJobQ)
520 return '' != userMailer($to, $from, $subj, $body, $replyto);
521
522 if (!is_array($to))
523 $to = array($to);
524
525 $chunks = array_chunk($to, $wgEnotifMaxRecips);
526 foreach ($chunks as $chunk) {
527 $job = new EmaillingJob(array(
528 'to' => $chunk,
529 'from' => $from,
530 'subj' => $subj,
531 'body' => $body,
532 'replyto' => $replyto));
533 $job->insert();
534 }
535
536 return true;
537 }
538 } # end of class EmailNotification
539 ?>