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