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