* Short circuit EmailNotification::notify() to not call EmailNotification::commonMess...
[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, $realName = null ) {
36 if( is_object( $address ) && $address instanceof User ) {
37 $this->address = $address->getEmail();
38 $this->name = $address->getName();
39 $this->realName = $address->getRealName();
40 } else {
41 $this->address = strval( $address );
42 $this->name = strval( $name );
43 $this->reaName = strval( $realName );
44 }
45 }
46
47 /**
48 * Return formatted and quoted address to insert into SMTP headers
49 * @return string
50 */
51 function toString() {
52 # PHP's mail() implementation under Windows is somewhat shite, and
53 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
54 # so don't bother generating them
55 if( $this->name != '' && !wfIsWindows() ) {
56 global $wgEnotifUseRealName;
57 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
58 $quoted = wfQuotedPrintable( $name );
59 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
60 $quoted = '"' . $quoted . '"';
61 }
62 return "$quoted <{$this->address}>";
63 } else {
64 return $this->address;
65 }
66 }
67
68 function __toString() {
69 return $this->toString();
70 }
71 }
72
73
74 /**
75 * Collection of static functions for sending mail
76 */
77 class UserMailer {
78 /**
79 * Send mail using a PEAR mailer
80 */
81 protected static function sendWithPear($mailer, $dest, $headers, $body)
82 {
83 $mailResult = $mailer->send($dest, $headers, $body);
84
85 # Based on the result return an error string,
86 if( PEAR::isError( $mailResult ) ) {
87 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
88 return new WikiError( $mailResult->getMessage() );
89 } else {
90 return true;
91 }
92 }
93
94 /**
95 * This function will perform a direct (authenticated) login to
96 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
97 * array of parameters. It requires PEAR:Mail to do that.
98 * Otherwise it just uses the standard PHP 'mail' function.
99 *
100 * @param $to MailAddress: recipient's email
101 * @param $from MailAddress: sender's email
102 * @param $subject String: email's subject.
103 * @param $body String: email's text.
104 * @param $replyto String: optional reply-to email (default: null).
105 * @param $contentType String: optional custom Content-Type
106 * @return mixed True on success, a WikiError object on failure.
107 */
108 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
109 global $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
110 global $wgEnotifMaxRecips;
111
112 if ( is_array( $to ) ) {
113 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
114 } else {
115 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
116 }
117
118 if (is_array( $wgSMTP )) {
119 require_once( 'Mail.php' );
120
121 $msgid = str_replace(" ", "_", microtime());
122 if (function_exists('posix_getpid'))
123 $msgid .= '.' . posix_getpid();
124
125 if (is_array($to)) {
126 $dest = array();
127 foreach ($to as $u)
128 $dest[] = $u->address;
129 } else
130 $dest = $to->address;
131
132 $headers['From'] = $from->toString();
133
134 if ($wgEnotifImpersonal) {
135 $headers['To'] = 'undisclosed-recipients:;';
136 }
137 else {
138 $headers['To'] = implode( ", ", (array )$dest );
139 }
140
141 if ( $replyto ) {
142 $headers['Reply-To'] = $replyto->toString();
143 }
144 $headers['Subject'] = wfQuotedPrintable( $subject );
145 $headers['Date'] = date( 'r' );
146 $headers['MIME-Version'] = '1.0';
147 $headers['Content-type'] = (is_null($contentType) ?
148 'text/plain; charset='.$wgOutputEncoding : $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 class EmailNotification {
247
248 /*
249 * Send users an email.
250 *
251 * @param $editor User whose action precipitated the notification.
252 * @param $timestamp of the event.
253 * @param Callback that returns an an array of Users who will recieve the notification.
254 * @param Callback that returns an array($keys, $body, $subject) where
255 * * $keys is a dictionary whose keys will be replaced with the corresponding
256 * values within the subject and body of the message.
257 * * $body is the name of the message that will be used for the email body.
258 * * $subject is the name of the message that will be used for the subject.
259 * Both messages are resolved using the content language.
260 * The messageCompositionFunction is invoked for each recipient user;
261 * The keys returned are merged with those given by EmailNotification::commonMessageKeys().
262 * The recipient is appended to the arguments given to messageCompositionFunction.
263 * Both callbacks are to be given in the same formats accepted by the hook system.
264 */
265 static function notify( $editor, $timestamp, $userListFunction, $messageCompositionFunction ) {
266 global $wgEnotifUseRealName, $wgEnotifImpersonal;
267 global $wgLang;
268
269 $users = wfInvoke( 'userList', $userListFunction );
270 if( !count( $users ) )
271 return;
272
273 $common_keys = self::commonMessageKeys( $editor );
274 foreach( $users as $u ) {
275 list( $user_keys, $body_msg_name, $subj_msg_name ) =
276 wfInvoke( 'message', $messageCompositionFunction, array( $u ) );
277 $keys = array_merge( $common_keys, $user_keys );
278
279 if( $wgEnotifImpersonal ) {
280 $keys['$WATCHINGUSERNAME'] = wfMsgForContent( 'enotif_impersonal_salutation' );
281 $keys['$PAGEEDITDATE'] = $wgLang->timeanddate( $timestamp, true, false, false );
282 } else {
283 $keys['$WATCHINGUSERNAME'] = $wgEnotifUseRealName ? $u->getRealName() : $u->getName();
284 $keys['$PAGEEDITDATE'] = $wgLang->timeAndDate( $timestamp, true, false,
285 $u->getOption( 'timecorrection' ) );
286 }
287
288 $subject = strtr( wfMsgForContent( $subj_msg_name ), $keys );
289 $body = wordwrap( strtr( wfMsgForContent( $body_msg_name ), $keys ), 72 );
290
291 $to = new MailAddress( $u );
292 $from = $keys['$FROM_HEADER'];
293 $replyto = $keys['$REPLYTO_HEADER'];
294 UserMailer::send( $to, $from, $subject, $body, $replyto );
295 }
296 }
297
298
299 static function commonMessageKeys( $editor ) {
300 global $wgEnotifUseRealName, $wgEnotifRevealEditorAddress;
301 global $wgNoReplyAddress, $wgPasswordSender;
302
303 $keys = array();
304
305 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
306
307 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
308 $editorAddress = new MailAddress( $editor );
309 if( $wgEnotifRevealEditorAddress
310 && $editor->getEmail() != ''
311 && $editor->getOption( 'enotifrevealaddr' ) ) {
312 if( $wgEnotifFromEditor ) {
313 $from = $editorAddress;
314 } else {
315 $from = $adminAddress;
316 $replyto = $editorAddress;
317 }
318 } else {
319 $from = $adminAddress;
320 $replyto = new MailAddress( $wgNoReplyAddress );
321 }
322 $keys['$FROM_HEADER'] = $from;
323 $keys['$REPLYTO_HEADER'] = $replyto;
324
325 if( $editor->isAnon() ) {
326 $keys['$PAGEEDITOR'] = wfMsgForContent( 'enotif_anon_editor', $name );
327 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
328 } else{
329 $keys['$PAGEEDITOR'] = $name;
330 $keys['$PAGEEDITOR_EMAIL'] = SpecialPage::getSafeTitleFor( 'Emailuser', $name )->getFullUrl();
331 }
332 $keys['$PAGEEDITOR_WIKI'] = $editor->getUserPage()->getFullUrl();
333
334 return $keys;
335 }
336
337
338
339 /*
340 * @deprecated
341 * Use PageChangeNotification::notifyOnPageChange instead.
342 */
343 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
344 PageChangeNotification::notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
345 }
346 }
347
348 class PageChangeNotification {
349
350 /**
351 * Send emails corresponding to the user $editor editing the page $title.
352 * Also updates wl_notificationtimestamp.
353 *
354 * May be deferred via the job queue.
355 *
356 * @param $editor User object
357 * @param $title Title object
358 * @param $timestamp
359 * @param $summary
360 * @param $minorEdit
361 * @param $oldid (default: false)
362 */
363 static function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
364 global $wgEnotifUseJobQ;
365
366 if ( $title->getNamespace() < 0 )
367 return;
368
369 if ( $wgEnotifUseJobQ ) {
370 $params = array(
371 "editor" => $editor->getName(),
372 "editorID" => $editor->getID(),
373 "timestamp" => $timestamp,
374 "summary" => $summary,
375 "minorEdit" => $minorEdit,
376 "oldid" => $oldid);
377 $job = new EnotifNotifyJob( $title, $params );
378 $job->insert();
379 } else {
380 self::actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid );
381 }
382
383 }
384
385 /*
386 * Immediate version of notifyOnPageChange().
387 *
388 * Send emails corresponding to the user $editor editing the page $title.
389 * Also updates wl_notificationtimestamp.
390 *
391 * @param $editor User object
392 * @param $title Title object
393 * @param $timestamp
394 * @param $summary
395 * @param $minorEdit
396 * @param $oldid (default: false)
397 */
398 static function actuallyNotifyOnPageChange( $editor, $title, $timestamp,
399 $summary, $minorEdit, $oldid = false ) {
400 global $wgShowUpdatedMarker, $wgEnotifWatchlist;
401
402 wfProfileIn( __METHOD__ );
403
404 EmailNotification::notify( $editor, $timestamp,
405 array( 'PageChangeNotification::usersList', array( $editor, $title, $minorEdit ) ),
406 array( 'PageChangeNotification::message', array( $oldid, $minorEdit, $summary, $title, $editor ) ) );
407
408 $latestTimestamp = Revision::getTimestampFromId( $title, $title->getLatestRevID() );
409 // Do not update watchlists if something else already did.
410 if ( $timestamp >= $latestTimestamp && ($wgShowUpdatedMarker || $wgEnotifWatchlist) ) {
411 # Mark the changed watch-listed page with a timestamp, so that the page is
412 # listed with an "updated since your last visit" icon in the watch list. Do
413 # not do this to users for their own edits.
414 $dbw = wfGetDB( DB_MASTER );
415 $dbw->update( 'watchlist',
416 array( /* SET */
417 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
418 ), array( /* WHERE */
419 'wl_title' => $title->getDBkey(),
420 'wl_namespace' => $title->getNamespace(),
421 'wl_notificationtimestamp IS NULL',
422 'wl_user != ' . $editor->getID()
423 ), __METHOD__
424 );
425 }
426
427 wfProfileOut( __METHOD__ );
428 }
429
430
431 static function message( $stuff ) {
432 global $wgEnotifImpersonal;
433
434 list( $oldid, $medit, $summary, $title, $user ) = $stuff;
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( $oldid ) {
441 $difflink = $title->getFullUrl( 'diff=0&oldid=' . $oldid );
442 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
443 $keys['$OLDID'] = $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 && $oldid) {
453 # For impersonal mail, show a diff link to the last revision.
454 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
455 $title->getFullURL( "oldid={$oldid}&diff=prev" ) );
456 }
457
458 $keys['$PAGETITLE'] = $title->getPrefixedText();
459 $keys['$PAGETITLE_URL'] = $title->getFullUrl();
460 $keys['$PAGEMINOREDIT'] = $medit ? wfMsg( 'minoredit' ) : '';
461 $keys['$PAGESUMMARY'] = ( $summary == '' ) ? ' - ' : $summary;
462
463 return array( $keys, 'enotif_body', 'enotif_subject' );
464 }
465
466 static function usersList( $stuff ) {
467 global $wgEnotifWatchlist, $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges;
468
469 list( $editor, $title, $minorEdit ) = $stuff;
470 $recipients = array();
471
472 # User talk pages:
473 $userTalkId = false;
474 if( $title->getNamespace() == NS_USER_TALK && ( !$minorEdit || $wgEnotifMinorEdits ) ) {
475 $targetUser = User::newFromName( $title->getText() );
476
477 if ( !$targetUser || $targetUser->isAnon() )
478 $msg = "user talk page edited, but user does not exist";
479
480 else if ( $targetUser->getId() == $editor->getId() )
481 $msg = "user edited their own talk page, no notification sent";
482
483 else if ( !$targetUser->getOption( 'enotifusertalkpages' ) )
484 $msg = "talk page owner doesn't want notifications";
485
486 else if ( !$targetUser->isEmailConfirmed() )
487 $msg = "talk page owner doesn't have validated email";
488
489 else {
490 $msg = "sending talk page update notification";
491 $recipients[] = $targetUser;
492 $userTalkId = $targetUser->getId(); # won't be included in watchlist, below.
493 }
494 wfDebug( __METHOD__ . ': ' . $msg . "\n" );
495 }
496 wfDebug( "Did not send a user-talk notification.\n" );
497
498 if( $wgEnotifWatchlist && ( !$minorEdit || $wgEnotifMinorEdits ) ) {
499 // Send updates to watchers other than the current editor
500 $userCondition = 'wl_user != ' . $editor->getID();
501
502 if ( $userTalkId !== false ) {
503 // Already sent an email to this person
504 $userCondition .= ' AND wl_user != ' . intval( $userTalkId );
505 }
506 $dbr = wfGetDB( DB_SLAVE );
507
508 list( $user ) = $dbr->tableNamesN( 'user' );
509
510 $res = $dbr->select( array( 'watchlist', 'user' ),
511 array( "$user.*" ),
512 array(
513 'wl_user=user_id',
514 'wl_title' => $title->getDBkey(),
515 'wl_namespace' => $title->getNamespace(),
516 $userCondition,
517 'wl_notificationtimestamp IS NULL',
518 ), __METHOD__ );
519 $userArray = UserArray::newFromResult( $res );
520
521 foreach ( $userArray as $watchingUser ) {
522 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
523 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
524 $watchingUser->isEmailConfirmed() ) {
525 $recipients[] = $watchingUser;
526 }
527 }
528 }
529
530 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
531 $recipients[] = User::newFromName( $name );
532 }
533
534 return $recipients;
535 }
536 }
537
538 /**
539 * Backwards compatibility functions
540 */
541 function wfRFC822Phrase( $s ) {
542 return UserMailer::rfc822Phrase( $s );
543 }
544
545 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
546 return UserMailer::send( $to, $from, $subject, $body, $replyto );
547 }