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