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