Refactored UserMailer.php. Please let me know if this breaks anything.
[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 function notify($editor, $timestamp, $userListFunction, $messageCompositionFunction) {
266 global $wgEnotifUseRealName, $wgEnotifImpersonal;
267 global $wgLang;
268
269 $common_keys = self::commonMessageKeys($editor);
270 $users = wfInvoke($userListFunction);
271 foreach($users as $u) {
272 list($user_keys, $body_msg_name, $subj_msg_name) =
273 wfInvoke($messageCompositionFunction, array($u));
274 $keys = array_merge($common_keys, $user_keys);
275
276 if( $wgEnotifImpersonal ) {
277 $keys['$WATCHINGUSERNAME'] = wfMsgForContent('enotif_impersonal_salutation');
278 $keys['$PAGEEDITDATE'] = $wgLang->timeanddate($timestamp, true, false, false);
279 } else {
280 $keys['$WATCHINGUSERNAME'] = $wgEnotifUseRealName ? $u->getRealName() : $u->getName();
281 $keys['$PAGEEDITDATE'] = $wgLang->timeAndDate($timestamp, true, false,
282 $u->getOption('timecorrection'));
283 }
284
285 $subject = strtr(wfMsgForContent( $subj_msg_name ), $keys);
286 $body = wordwrap( strtr( wfMsgForContent( $body_msg_name ), $keys ), 72 );
287
288 $to = new MailAddress($u);
289 $from = $keys['$FROM_HEADER'];
290 $replyto = $keys['$REPLYTO_HEADER'];
291 UserMailer::send($to, $from, $subject, $body, $replyto);
292 }
293 }
294
295
296 static function commonMessageKeys($editor) {
297 global $wgEnotifUseRealName, $wgEnotifRevealEditorAddress;
298 global $wgNoReplyAddress, $wgPasswordSender;
299
300 $keys = array();
301
302 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
303
304 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
305 $editorAddress = new MailAddress( $editor );
306 if( $wgEnotifRevealEditorAddress
307 && $editor->getEmail() != ''
308 && $editor->getOption( 'enotifrevealaddr' ) ) {
309 if( $wgEnotifFromEditor ) {
310 $from = $editorAddress;
311 } else {
312 $from = $adminAddress;
313 $replyto = $editorAddress;
314 }
315 } else {
316 $from = $adminAddress;
317 $replyto = new MailAddress( $wgNoReplyAddress );
318 }
319 $keys['$FROM_HEADER'] = $from;
320 $keys['$REPLYTO_HEADER'] = $replyto;
321
322 if( $editor->isAnon() ) {
323 $keys['$PAGEEDITOR'] = wfMsgForContent('enotif_anon_editor', $name);
324 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
325 } else{
326 $keys['$PAGEEDITOR'] = $name;
327 $keys['$PAGEEDITOR_EMAIL'] = SpecialPage::getSafeTitleFor('Emailuser', $name)->getFullUrl();
328 }
329 $keys['$PAGEEDITOR_WIKI'] = $editor->getUserPage()->getFullUrl();
330
331 return $keys;
332 }
333
334
335
336 /*
337 * @deprecated
338 * Use PageChangeNotification::notifyOnPageChange instead.
339 */
340 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
341 PageChangeNotification::notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
342 }
343 }
344
345 class PageChangeNotification {
346
347 /**
348 * Send emails corresponding to the user $editor editing the page $title.
349 * Also updates wl_notificationtimestamp.
350 *
351 * May be deferred via the job queue.
352 *
353 * @param $editor User object
354 * @param $title Title object
355 * @param $timestamp
356 * @param $summary
357 * @param $minorEdit
358 * @param $oldid (default: false)
359 */
360 static function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
361 global $wgEnotifUseJobQ;
362
363 if( $title->getNamespace() < 0 )
364 return;
365
366 if ($wgEnotifUseJobQ) {
367 $params = array(
368 "editor" => $editor->getName(),
369 "editorID" => $editor->getID(),
370 "timestamp" => $timestamp,
371 "summary" => $summary,
372 "minorEdit" => $minorEdit,
373 "oldid" => $oldid);
374 $job = new EnotifNotifyJob( $title, $params );
375 $job->insert();
376 } else {
377 self::actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
378 }
379
380 }
381
382 /*
383 * Immediate version of notifyOnPageChange().
384 *
385 * Send emails corresponding to the user $editor editing the page $title.
386 * Also updates wl_notificationtimestamp.
387 *
388 * @param $editor User object
389 * @param $title Title object
390 * @param $timestamp
391 * @param $summary
392 * @param $minorEdit
393 * @param $oldid (default: false)
394 */
395 static function actuallyNotifyOnPageChange($editor, $title, $timestamp,
396 $summary, $minorEdit, $oldid=false) {
397 global $wgShowUpdatedMarker, $wgEnotifWatchlist;
398
399 wfProfileIn( __METHOD__ );
400
401 EmailNotification::notify($editor, $timestamp,
402 array('PageChangeNotification::usersList', array($editor, $title, $minorEdit)),
403 array('PageChangeNotification::message', array($oldid, $minorEdit, $summary, $title, $editor) ) );
404
405 $latestTimestamp = Revision::getTimestampFromId( $title, $title->getLatestRevID() );
406 // Do not update watchlists if something else already did.
407 if ( $timestamp >= $latestTimestamp && ($wgShowUpdatedMarker || $wgEnotifWatchlist) ) {
408 # Mark the changed watch-listed page with a timestamp, so that the page is
409 # listed with an "updated since your last visit" icon in the watch list. Do
410 # not do this to users for their own edits.
411 $dbw = wfGetDB( DB_MASTER );
412 $dbw->update( 'watchlist',
413 array( /* SET */
414 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
415 ), array( /* WHERE */
416 'wl_title' => $title->getDBkey(),
417 'wl_namespace' => $title->getNamespace(),
418 'wl_notificationtimestamp IS NULL',
419 'wl_user != ' . $editor->getID()
420 ), __METHOD__
421 );
422 }
423
424 wfProfileOut( __METHOD__ );
425 }
426
427
428 static function message( $stuff ) {
429 global $wgEnotifImpersonal;
430
431 list($oldid, $medit, $summary, $title, $user) = $stuff;
432 $keys = array();
433
434 # regarding the use of oldid as an indicator for the last visited version, see also
435 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
436 # However, in the case of a new page which is already watched, we have no previous version to compare
437 if( $oldid ) {
438 $difflink = $title->getFullUrl( 'diff=0&oldid=' . $oldid );
439 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
440 $keys['$OLDID'] = $oldid;
441 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
442 } else {
443 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
444 # clear $OLDID placeholder in the message template
445 $keys['$OLDID'] = '';
446 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
447 }
448
449 if ($wgEnotifImpersonal && $oldid) {
450 # For impersonal mail, show a diff link to the last revision.
451 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
452 $title->getFullURL("oldid={$oldid}&diff=prev"));
453 }
454
455 $keys['$PAGETITLE'] = $title->getPrefixedText();
456 $keys['$PAGETITLE_URL'] = $title->getFullUrl();
457 $keys['$PAGEMINOREDIT'] = $medit ? wfMsg( 'minoredit' ) : '';
458 $keys['$PAGESUMMARY'] = ($summary == '') ? ' - ' : $summary;
459
460 return array($keys, 'enotif_body', 'enotif_subject');
461 }
462
463 static function usersList($stuff) {
464 global $wgEnotifWatchlist, $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges;
465
466 list($editor, $title, $minorEdit) = $stuff;
467 $recipients = array();
468
469 # User talk pages:
470 $userTalkId = false;
471 if( $title->getNamespace() == NS_USER_TALK && (!$minorEdit || $wgEnotifMinorEdits) ) {
472 $targetUser = User::newFromName($title->getText());
473
474 if ( !$targetUser || $targetUser->isAnon() )
475 $msg = "user talk page edited, but user does not exist";
476
477 else if ( $targetUser->getId() == $editor->getId() )
478 $msg = "user edited their own talk page, no notification sent";
479
480 else if ( !$targetUser->getOption('enotifusertalkpages') )
481 $msg = "talk page owner doesn't want notifications";
482
483 else if ( !$targetUser->isEmailConfirmed() )
484 $msg = "talk page owner doesn't have validated email";
485
486 else {
487 $msg = "sending talk page update notification";
488 $recipients[] = $targetUser;
489 $userTalkId = $targetUser->getId(); # won't be included in watchlist, below.
490 }
491 wfDebug( __METHOD__ .": ". $msg . "\n" );
492 }
493 wfDebug("Did not send a user-talk notification.\n");
494
495 if( $wgEnotifWatchlist && (!$minorEdit || $wgEnotifMinorEdits) ) {
496 // Send updates to watchers other than the current editor
497 $userCondition = 'wl_user != ' . $editor->getID();
498
499 if ( $userTalkId !== false ) {
500 // Already sent an email to this person
501 $userCondition .= ' AND wl_user != ' . intval( $userTalkId );
502 }
503 $dbr = wfGetDB( DB_SLAVE );
504
505 list( $user ) = $dbr->tableNamesN( 'user' );
506
507 $res = $dbr->select( array( 'watchlist', 'user' ),
508 array( "$user.*" ),
509 array(
510 'wl_user=user_id',
511 'wl_title' => $title->getDBkey(),
512 'wl_namespace' => $title->getNamespace(),
513 $userCondition,
514 'wl_notificationtimestamp IS NULL',
515 ), __METHOD__ );
516 $userArray = UserArray::newFromResult( $res );
517
518 foreach ( $userArray as $watchingUser ) {
519 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
520 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
521 $watchingUser->isEmailConfirmed() ) {
522 $recipients[] = $watchingUser;
523 }
524 }
525 }
526
527 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
528 $recipients[] = User::newFromName($name);
529 }
530
531 return $recipients;
532 }
533 }
534
535 /**
536 * Backwards compatibility functions
537 */
538 function wfRFC822Phrase( $s ) {
539 return UserMailer::rfc822Phrase( $s );
540 }
541
542 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
543 return UserMailer::send( $to, $from, $subject, $body, $replyto );
544 }