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