Added DatabaseUpdater::addExtensionUpdate() to let extensions add their own updates...
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 */
25
26
27 /**
28 * Stores a single person's name and email address.
29 * These are passed in via the constructor, and will be returned in SMTP
30 * header format when requested.
31 */
32 class MailAddress {
33 /**
34 * @param $address Mixed: string with an email address, or a User object
35 * @param $name String: human-readable name if a string address is given
36 * @param $realName String: human-readable real name if a string address is given
37 */
38 function __construct( $address, $name = null, $realName = null ) {
39 if( is_object( $address ) && $address instanceof User ) {
40 $this->address = $address->getEmail();
41 $this->name = $address->getName();
42 $this->realName = $address->getRealName();
43 } else {
44 $this->address = strval( $address );
45 $this->name = strval( $name );
46 $this->realName = strval( $realName );
47 }
48 }
49
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
53 */
54 function toString() {
55 # PHP's mail() implementation under Windows is somewhat shite, and
56 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
57 # so don't bother generating them
58 if( $this->name != '' && !wfIsWindows() ) {
59 global $wgEnotifUseRealName;
60 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
61 $quoted = wfQuotedPrintable( $name );
62 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
63 $quoted = '"' . $quoted . '"';
64 }
65 return "$quoted <{$this->address}>";
66 } else {
67 return $this->address;
68 }
69 }
70
71 function __toString() {
72 return $this->toString();
73 }
74 }
75
76
77 /**
78 * Collection of static functions for sending mail
79 */
80 class UserMailer {
81 static $mErrorString;
82
83 /**
84 * Send mail using a PEAR mailer
85 */
86 protected static function sendWithPear($mailer, $dest, $headers, $body)
87 {
88 $mailResult = $mailer->send($dest, $headers, $body);
89
90 # Based on the result return an error string,
91 if( PEAR::isError( $mailResult ) ) {
92 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
93 return new WikiError( $mailResult->getMessage() );
94 } else {
95 return true;
96 }
97 }
98
99 /**
100 * This function will perform a direct (authenticated) login to
101 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
102 * array of parameters. It requires PEAR:Mail to do that.
103 * Otherwise it just uses the standard PHP 'mail' function.
104 *
105 * @param $to MailAddress: recipient's email (or an array of them)
106 * @param $from MailAddress: sender's email
107 * @param $subject String: email's subject.
108 * @param $body String: email's text.
109 * @param $replyto MailAddress: optional reply-to email (default: null).
110 * @param $contentType String: optional custom Content-Type
111 * @return mixed True on success, a WikiError object on failure.
112 */
113 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
114 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
115 global $wgEnotifMaxRecips;
116
117 if ( is_array( $to ) ) {
118 // This wouldn't be necessary if implode() worked on arrays of
119 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
120 foreach( $to as $t ) {
121 $emails .= $t->toString() . ",";
122 }
123 $emails = rtrim( $emails, ',' );
124 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
125 } else {
126 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
127 }
128
129 if (is_array( $wgSMTP )) {
130 require_once( 'Mail.php' );
131
132 $msgid = str_replace(" ", "_", microtime());
133 if (function_exists('posix_getpid'))
134 $msgid .= '.' . posix_getpid();
135
136 if (is_array($to)) {
137 $dest = array();
138 foreach ($to as $u)
139 $dest[] = $u->address;
140 } else
141 $dest = $to->address;
142
143 $headers['From'] = $from->toString();
144
145 if ($wgEnotifImpersonal) {
146 $headers['To'] = 'undisclosed-recipients:;';
147 }
148 else {
149 $headers['To'] = implode( ", ", (array )$dest );
150 }
151
152 if ( $replyto ) {
153 $headers['Reply-To'] = $replyto->toString();
154 }
155 $headers['Subject'] = wfQuotedPrintable( $subject );
156 $headers['Date'] = date( 'r' );
157 $headers['MIME-Version'] = '1.0';
158 $headers['Content-type'] = (is_null($contentType) ?
159 'text/plain; charset='.$wgOutputEncoding : $contentType);
160 $headers['Content-transfer-encoding'] = '8bit';
161 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
162 $headers['X-Mailer'] = 'MediaWiki mailer';
163
164 // Create the mail object using the Mail::factory method
165 $mail_object =& Mail::factory('smtp', $wgSMTP);
166 if( PEAR::isError( $mail_object ) ) {
167 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
168 return new WikiError( $mail_object->getMessage() );
169 }
170
171 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
172 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
173 foreach ($chunks as $chunk) {
174 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
175 if( WikiError::isError( $e ) )
176 return $e;
177 }
178 } else {
179 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
180 # (fifth parameter of the PHP mail function, see some lines below)
181
182 # Line endings need to be different on Unix and Windows due to
183 # the bug described at http://trac.wordpress.org/ticket/2603
184 if ( wfIsWindows() ) {
185 $body = str_replace( "\n", "\r\n", $body );
186 $endl = "\r\n";
187 } else {
188 $endl = "\n";
189 }
190 $ctype = (is_null($contentType) ?
191 'text/plain; charset='.$wgOutputEncoding : $contentType);
192 $headers =
193 "MIME-Version: 1.0$endl" .
194 "Content-type: $ctype$endl" .
195 "Content-Transfer-Encoding: 8bit$endl" .
196 "X-Mailer: MediaWiki mailer$endl".
197 'From: ' . $from->toString();
198 if ($replyto) {
199 $headers .= "{$endl}Reply-To: " . $replyto->toString();
200 }
201
202 wfDebug( "Sending mail via internal mail() function\n" );
203
204 self::$mErrorString = '';
205 $html_errors = ini_get( 'html_errors' );
206 ini_set( 'html_errors', '0' );
207 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
208
209 if (is_array($to)) {
210 foreach ($to as $recip) {
211 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
212 }
213 } else {
214 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
215 }
216
217 restore_error_handler();
218 ini_set( 'html_errors', $html_errors );
219
220 if ( self::$mErrorString ) {
221 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
222 return new WikiError( self::$mErrorString );
223 } elseif (! $sent ) {
224 //mail function only tells if there's an error
225 wfDebug( "Error sending mail\n" );
226 return new WikiError( 'mail() failed' );
227 } else {
228 return true;
229 }
230 }
231 }
232
233 /**
234 * Set the mail error message in self::$mErrorString
235 *
236 * @param $code Integer: error number
237 * @param $string String: error message
238 */
239 static function errorHandler( $code, $string ) {
240 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
241 }
242
243 /**
244 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
245 */
246 static function rfc822Phrase( $phrase ) {
247 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
248 return '"' . $phrase . '"';
249 }
250 }
251
252 /**
253 * This module processes the email notifications when the current page is
254 * changed. It looks up the table watchlist to find out which users are watching
255 * that page.
256 *
257 * The current implementation sends independent emails to each watching user for
258 * the following reason:
259 *
260 * - Each watching user will be notified about the page edit time expressed in
261 * his/her local time (UTC is shown additionally). To achieve this, we need to
262 * find the individual timeoffset of each watching user from the preferences..
263 *
264 * Suggested improvement to slack down the number of sent emails: We could think
265 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
266 * same timeoffset in their preferences.
267 *
268 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
269 *
270 *
271 */
272 class EmailNotification {
273 protected $to, $subject, $body, $replyto, $from;
274 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
275 protected $mailTargets = array();
276
277 /**
278 * Send emails corresponding to the user $editor editing the page $title.
279 * Also updates wl_notificationtimestamp.
280 *
281 * May be deferred via the job queue.
282 *
283 * @param $editor User object
284 * @param $title Title object
285 * @param $timestamp
286 * @param $summary
287 * @param $minorEdit
288 * @param $oldid (default: false)
289 */
290 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
291 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
292
293 if ($title->getNamespace() < 0)
294 return;
295
296 // Build a list of users to notfiy
297 $watchers = array();
298 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
299 $dbw = wfGetDB( DB_MASTER );
300 $res = $dbw->select( array( 'watchlist' ),
301 array( 'wl_user' ),
302 array(
303 'wl_title' => $title->getDBkey(),
304 'wl_namespace' => $title->getNamespace(),
305 'wl_user != ' . intval( $editor->getID() ),
306 'wl_notificationtimestamp IS NULL',
307 ), __METHOD__
308 );
309 while ($row = $dbw->fetchObject( $res ) ) {
310 $watchers[] = intval( $row->wl_user );
311 }
312 if ($watchers) {
313 // Update wl_notificationtimestamp for all watching users except
314 // the editor
315 $dbw->begin();
316 $dbw->update( 'watchlist',
317 array( /* SET */
318 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
319 ), array( /* WHERE */
320 'wl_title' => $title->getDBkey(),
321 'wl_namespace' => $title->getNamespace(),
322 'wl_user' => $watchers
323 ), __METHOD__
324 );
325 $dbw->commit();
326 }
327 }
328
329 if ($wgEnotifUseJobQ) {
330 $params = array(
331 "editor" => $editor->getName(),
332 "editorID" => $editor->getID(),
333 "timestamp" => $timestamp,
334 "summary" => $summary,
335 "minorEdit" => $minorEdit,
336 "oldid" => $oldid,
337 "watchers" => $watchers);
338 $job = new EnotifNotifyJob( $title, $params );
339 $job->insert();
340 } else {
341 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
342 }
343
344 }
345
346 /*
347 * Immediate version of notifyOnPageChange().
348 *
349 * Send emails corresponding to the user $editor editing the page $title.
350 * Also updates wl_notificationtimestamp.
351 *
352 * @param $editor User object
353 * @param $title Title object
354 * @param $timestamp string Edit timestamp
355 * @param $summary string Edit summary
356 * @param $minorEdit bool
357 * @param $oldid int Revision ID
358 * @param $watchers array of user IDs
359 */
360 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
361 # we use $wgPasswordSender as sender's address
362 global $wgEnotifWatchlist;
363 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
364
365 wfProfileIn( __METHOD__ );
366
367 # The following code is only run, if several conditions are met:
368 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
369 # 2. minor edits (changes) are only regarded if the global flag indicates so
370
371 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
372
373 $this->title = $title;
374 $this->timestamp = $timestamp;
375 $this->summary = $summary;
376 $this->minorEdit = $minorEdit;
377 $this->oldid = $oldid;
378 $this->editor = $editor;
379 $this->composed_common = false;
380
381 $userTalkId = false;
382
383 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
384 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
385 $targetUser = User::newFromName( $title->getText() );
386 if ( !$targetUser || $targetUser->isAnon() ) {
387 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
388 } elseif ( $targetUser->getId() == $editor->getId() ) {
389 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
390 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
391 if( $targetUser->isEmailConfirmed() ) {
392 wfDebug( __METHOD__.": sending talk page update notification\n" );
393 $this->compose( $targetUser );
394 $userTalkId = $targetUser->getId();
395 } else {
396 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
397 }
398 } else {
399 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
400 }
401 }
402
403 if ( $wgEnotifWatchlist ) {
404 // Send updates to watchers other than the current editor
405 $userArray = UserArray::newFromIDs( $watchers );
406 foreach ( $userArray as $watchingUser ) {
407 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
408 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
409 $watchingUser->isEmailConfirmed() &&
410 $watchingUser->getID() != $userTalkId )
411 {
412 $this->compose( $watchingUser );
413 }
414 }
415 }
416 }
417
418 global $wgUsersNotifiedOnAllChanges;
419 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
420 $user = User::newFromName( $name );
421 $this->compose( $user );
422 }
423
424 $this->sendMails();
425 wfProfileOut( __METHOD__ );
426 }
427
428 /**
429 * @private
430 */
431 function composeCommonMailtext() {
432 global $wgPasswordSender, $wgNoReplyAddress;
433 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
434 global $wgEnotifImpersonal, $wgEnotifUseRealName;
435
436 $this->composed_common = true;
437
438 $summary = ($this->summary == '') ? ' - ' : $this->summary;
439 $medit = ($this->minorEdit) ? wfMsgForContent( 'minoredit' ) : '';
440
441 # You as the WikiAdmin and Sysops can make use of plenty of
442 # named variables when composing your notification emails while
443 # simply editing the Meta pages
444
445 $subject = wfMsgForContent( 'enotif_subject' );
446 $body = wfMsgForContent( 'enotif_body' );
447 $from = ''; /* fail safe */
448 $replyto = ''; /* fail safe */
449 $keys = array();
450
451 if( $this->oldid ) {
452 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
453 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
454 $keys['$OLDID'] = $this->oldid;
455 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
456 } else {
457 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
458 # clear $OLDID placeholder in the message template
459 $keys['$OLDID'] = '';
460 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
461 }
462
463 if ($wgEnotifImpersonal && $this->oldid)
464 /*
465 * For impersonal mail, show a diff link to the last
466 * revision.
467 */
468 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
469 $this->title->getFullURL("oldid={$this->oldid}&diff=next"));
470
471 $body = strtr( $body, $keys );
472 $pagetitle = $this->title->getPrefixedText();
473 $keys['$PAGETITLE'] = $pagetitle;
474 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
475
476 $keys['$PAGEMINOREDIT'] = $medit;
477 $keys['$PAGESUMMARY'] = $summary;
478 $keys['$UNWATCHURL'] = $this->title->getFullUrl( 'action=unwatch' );
479
480 $subject = strtr( $subject, $keys );
481
482 # Reveal the page editor's address as REPLY-TO address only if
483 # the user has not opted-out and the option is enabled at the
484 # global configuration level.
485 $editor = $this->editor;
486 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
487 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
488 $editorAddress = new MailAddress( $editor );
489 if( $wgEnotifRevealEditorAddress
490 && ( $editor->getEmail() != '' )
491 && $editor->getOption( 'enotifrevealaddr' ) ) {
492 if( $wgEnotifFromEditor ) {
493 $from = $editorAddress;
494 } else {
495 $from = $adminAddress;
496 $replyto = $editorAddress;
497 }
498 } else {
499 $from = $adminAddress;
500 $replyto = new MailAddress( $wgNoReplyAddress );
501 }
502
503 if( $editor->isIP( $name ) ) {
504 #real anon (user:xxx.xxx.xxx.xxx)
505 $utext = wfMsgForContent('enotif_anon_editor', $name);
506 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
507 $keys['$PAGEEDITOR'] = $utext;
508 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
509 } else {
510 $subject = str_replace('$PAGEEDITOR', $name, $subject);
511 $keys['$PAGEEDITOR'] = $name;
512 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
513 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
514 }
515 $userPage = $editor->getUserPage();
516 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
517 $body = strtr( $body, $keys );
518 $body = wordwrap( $body, 72 );
519
520 # now save this as the constant user-independent part of the message
521 $this->from = $from;
522 $this->replyto = $replyto;
523 $this->subject = $subject;
524 $this->body = $body;
525 }
526
527 /**
528 * Compose a mail to a given user and either queue it for sending, or send it now,
529 * depending on settings.
530 *
531 * Call sendMails() to send any mails that were queued.
532 */
533 function compose( $user ) {
534 global $wgEnotifImpersonal;
535
536 if ( !$this->composed_common )
537 $this->composeCommonMailtext();
538
539 if ( $wgEnotifImpersonal ) {
540 $this->mailTargets[] = new MailAddress( $user );
541 } else {
542 $this->sendPersonalised( $user );
543 }
544 }
545
546 /**
547 * Send any queued mails
548 */
549 function sendMails() {
550 global $wgEnotifImpersonal;
551 if ( $wgEnotifImpersonal ) {
552 $this->sendImpersonal( $this->mailTargets );
553 }
554 }
555
556 /**
557 * Does the per-user customizations to a notification e-mail (name,
558 * timestamp in proper timezone, etc) and sends it out.
559 * Returns true if the mail was sent successfully.
560 *
561 * @param $watchingUser User object
562 * @return Boolean
563 * @private
564 */
565 function sendPersonalised( $watchingUser ) {
566 global $wgContLang, $wgEnotifUseRealName;
567 // From the PHP manual:
568 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
569 // The mail command will not parse this properly while talking with the MTA.
570 $to = new MailAddress( $watchingUser );
571 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
572 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
573
574 $timecorrection = $watchingUser->getOption( 'timecorrection' );
575
576 # $PAGEEDITDATE is the time and date of the page change
577 # expressed in terms of individual local time of the notification
578 # recipient, i.e. watching user
579 $body = str_replace(
580 array( '$PAGEEDITDATEANDTIME',
581 '$PAGEEDITDATE',
582 '$PAGEEDITTIME' ),
583 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
584 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
585 $wgContLang->time( $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 $wgContLang;
597
598 if (empty($addresses))
599 return;
600
601 $body = str_replace(
602 array( '$WATCHINGUSERNAME',
603 '$PAGEEDITDATE'),
604 array( wfMsgForContent('enotif_impersonal_salutation'),
605 $wgContLang->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 }