* (bug 23524) Api Modules as followup to bug 14473 (Add iwlinks table to track inline...
[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->realName = 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 static $mErrorString;
79
80 /**
81 * Send mail using a PEAR mailer
82 */
83 protected static function sendWithPear($mailer, $dest, $headers, $body)
84 {
85 $mailResult = $mailer->send($dest, $headers, $body);
86
87 # Based on the result return an error string,
88 if( PEAR::isError( $mailResult ) ) {
89 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
90 return new WikiError( $mailResult->getMessage() );
91 } else {
92 return true;
93 }
94 }
95
96 /**
97 * This function will perform a direct (authenticated) login to
98 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
99 * array of parameters. It requires PEAR:Mail to do that.
100 * Otherwise it just uses the standard PHP 'mail' function.
101 *
102 * @param $to MailAddress: recipient's email (or an array of them)
103 * @param $from MailAddress: sender's email
104 * @param $subject String: email's subject.
105 * @param $body String: email's text.
106 * @param $replyto MailAddress: optional reply-to email (default: null).
107 * @param $contentType String: optional custom Content-Type
108 * @return mixed True on success, a WikiError object on failure.
109 */
110 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
111 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
112 global $wgEnotifMaxRecips;
113
114 if ( is_array( $to ) ) {
115 // This wouldn't be necessary if implode() worked on arrays of
116 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
117 foreach( $to as $t ) {
118 $emails .= $t->toString() . ",";
119 }
120 $emails = rtrim( $emails, ',' );
121 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
122 } else {
123 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
124 }
125
126 if (is_array( $wgSMTP )) {
127 require_once( 'Mail.php' );
128
129 $msgid = str_replace(" ", "_", microtime());
130 if (function_exists('posix_getpid'))
131 $msgid .= '.' . posix_getpid();
132
133 if (is_array($to)) {
134 $dest = array();
135 foreach ($to as $u)
136 $dest[] = $u->address;
137 } else
138 $dest = $to->address;
139
140 $headers['From'] = $from->toString();
141
142 if ($wgEnotifImpersonal) {
143 $headers['To'] = 'undisclosed-recipients:;';
144 }
145 else {
146 $headers['To'] = implode( ", ", (array )$dest );
147 }
148
149 if ( $replyto ) {
150 $headers['Reply-To'] = $replyto->toString();
151 }
152 $headers['Subject'] = wfQuotedPrintable( $subject );
153 $headers['Date'] = date( 'r' );
154 $headers['MIME-Version'] = '1.0';
155 $headers['Content-type'] = (is_null($contentType) ?
156 'text/plain; charset='.$wgOutputEncoding : $contentType);
157 $headers['Content-transfer-encoding'] = '8bit';
158 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
159 $headers['X-Mailer'] = 'MediaWiki mailer';
160
161 // Create the mail object using the Mail::factory method
162 $mail_object =& Mail::factory('smtp', $wgSMTP);
163 if( PEAR::isError( $mail_object ) ) {
164 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
165 return new WikiError( $mail_object->getMessage() );
166 }
167
168 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
169 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
170 foreach ($chunks as $chunk) {
171 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
172 if( WikiError::isError( $e ) )
173 return $e;
174 }
175 } else {
176 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
177 # (fifth parameter of the PHP mail function, see some lines below)
178
179 # Line endings need to be different on Unix and Windows due to
180 # the bug described at http://trac.wordpress.org/ticket/2603
181 if ( wfIsWindows() ) {
182 $body = str_replace( "\n", "\r\n", $body );
183 $endl = "\r\n";
184 } else {
185 $endl = "\n";
186 }
187 $ctype = (is_null($contentType) ?
188 'text/plain; charset='.$wgOutputEncoding : $contentType);
189 $headers =
190 "MIME-Version: 1.0$endl" .
191 "Content-type: $ctype$endl" .
192 "Content-Transfer-Encoding: 8bit$endl" .
193 "X-Mailer: MediaWiki mailer$endl".
194 'From: ' . $from->toString();
195 if ($replyto) {
196 $headers .= "{$endl}Reply-To: " . $replyto->toString();
197 }
198
199 wfDebug( "Sending mail via internal mail() function\n" );
200
201 self::$mErrorString = '';
202 $html_errors = ini_get( 'html_errors' );
203 ini_set( 'html_errors', '0' );
204 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
205
206 if (is_array($to)) {
207 foreach ($to as $recip) {
208 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
209 }
210 } else {
211 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
212 }
213
214 restore_error_handler();
215 ini_set( 'html_errors', $html_errors );
216
217 if ( self::$mErrorString ) {
218 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
219 return new WikiError( self::$mErrorString );
220 } elseif (! $sent ) {
221 //mail function only tells if there's an error
222 wfDebug( "Error sending mail\n" );
223 return new WikiError( 'mail() failed' );
224 } else {
225 return true;
226 }
227 }
228 }
229
230 /**
231 * Set the mail error message in self::$mErrorString
232 *
233 * @param $code Integer: error number
234 * @param $string String: error message
235 */
236 static function errorHandler( $code, $string ) {
237 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
238 }
239
240 /**
241 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
242 */
243 static function rfc822Phrase( $phrase ) {
244 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
245 return '"' . $phrase . '"';
246 }
247 }
248
249 /**
250 * This module processes the email notifications when the current page is
251 * changed. It looks up the table watchlist to find out which users are watching
252 * that page.
253 *
254 * The current implementation sends independent emails to each watching user for
255 * the following reason:
256 *
257 * - Each watching user will be notified about the page edit time expressed in
258 * his/her local time (UTC is shown additionally). To achieve this, we need to
259 * find the individual timeoffset of each watching user from the preferences..
260 *
261 * Suggested improvement to slack down the number of sent emails: We could think
262 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
263 * same timeoffset in their preferences.
264 *
265 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
266 *
267 *
268 */
269 class EmailNotification {
270 protected $to, $subject, $body, $replyto, $from;
271 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
272 protected $mailTargets = array();
273
274 /**
275 * Send emails corresponding to the user $editor editing the page $title.
276 * Also updates wl_notificationtimestamp.
277 *
278 * May be deferred via the job queue.
279 *
280 * @param $editor User object
281 * @param $title Title object
282 * @param $timestamp
283 * @param $summary
284 * @param $minorEdit
285 * @param $oldid (default: false)
286 */
287 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
288 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
289
290 if ($title->getNamespace() < 0)
291 return;
292
293 // Build a list of users to notfiy
294 $watchers = array();
295 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
296 $dbw = wfGetDB( DB_MASTER );
297 $res = $dbw->select( array( 'watchlist' ),
298 array( 'wl_user' ),
299 array(
300 'wl_title' => $title->getDBkey(),
301 'wl_namespace' => $title->getNamespace(),
302 'wl_user != ' . intval( $editor->getID() ),
303 'wl_notificationtimestamp IS NULL',
304 ), __METHOD__
305 );
306 while ($row = $dbw->fetchObject( $res ) ) {
307 $watchers[] = intval( $row->wl_user );
308 }
309 if ($watchers) {
310 // Update wl_notificationtimestamp for all watching users except
311 // the editor
312 $dbw->begin();
313 $dbw->update( 'watchlist',
314 array( /* SET */
315 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
316 ), array( /* WHERE */
317 'wl_title' => $title->getDBkey(),
318 'wl_namespace' => $title->getNamespace(),
319 'wl_user' => $watchers
320 ), __METHOD__
321 );
322 $dbw->commit();
323 }
324 }
325
326 if ($wgEnotifUseJobQ) {
327 $params = array(
328 "editor" => $editor->getName(),
329 "editorID" => $editor->getID(),
330 "timestamp" => $timestamp,
331 "summary" => $summary,
332 "minorEdit" => $minorEdit,
333 "oldid" => $oldid,
334 "watchers" => $watchers);
335 $job = new EnotifNotifyJob( $title, $params );
336 $job->insert();
337 } else {
338 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
339 }
340
341 }
342
343 /*
344 * Immediate version of notifyOnPageChange().
345 *
346 * Send emails corresponding to the user $editor editing the page $title.
347 * Also updates wl_notificationtimestamp.
348 *
349 * @param $editor User object
350 * @param $title Title object
351 * @param $timestamp string Edit timestamp
352 * @param $summary string Edit summary
353 * @param $minorEdit bool
354 * @param $oldid int Revision ID
355 * @param $watchers array of user IDs
356 */
357 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
358 # we use $wgPasswordSender as sender's address
359 global $wgEnotifWatchlist;
360 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
361 global $wgEnotifImpersonal;
362
363 wfProfileIn( __METHOD__ );
364
365 # The following code is only run, if several conditions are met:
366 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
367 # 2. minor edits (changes) are only regarded if the global flag indicates so
368
369 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
370 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
371 $enotifwatchlistpage = $wgEnotifWatchlist;
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) ? wfMsg( '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=prev"));
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 User $watchingUser
562 * @param object $mail
563 * @return bool
564 * @private
565 */
566 function sendPersonalised( $watchingUser ) {
567 global $wgContLang, $wgEnotifUseRealName;
568 // From the PHP manual:
569 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
570 // The mail command will not parse this properly while talking with the MTA.
571 $to = new MailAddress( $watchingUser );
572 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
573 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
574
575 $timecorrection = $watchingUser->getOption( 'timecorrection' );
576
577 # $PAGEEDITDATE is the time and date of the page change
578 # expressed in terms of individual local time of the notification
579 # recipient, i.e. watching user
580 $body = str_replace(
581 array( '$PAGEEDITDATEANDTIME',
582 '$PAGEEDITDATE',
583 '$PAGEEDITTIME' ),
584 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
585 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
586 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
587 $body);
588
589 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
590 }
591
592 /**
593 * Same as sendPersonalised but does impersonal mail suitable for bulk
594 * mailing. Takes an array of MailAddress objects.
595 */
596 function sendImpersonal( $addresses ) {
597 global $wgContLang;
598
599 if (empty($addresses))
600 return;
601
602 $body = str_replace(
603 array( '$WATCHINGUSERNAME',
604 '$PAGEEDITDATE'),
605 array( wfMsgForContent('enotif_impersonal_salutation'),
606 $wgContLang->timeanddate($this->timestamp, true, false, false)),
607 $this->body);
608
609 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
610 }
611
612 } # end of class EmailNotification
613
614 /**
615 * Backwards compatibility functions
616 */
617 function wfRFC822Phrase( $s ) {
618 return UserMailer::rfc822Phrase( $s );
619 }
620
621 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
622 return UserMailer::send( $to, $from, $subject, $body, $replyto );
623 }