* remove end of line whitespace
[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 "timestamp" => $timestamp,
288 "summary" => $summary,
289 "minorEdit" => $minorEdit,
290 "oldid" => $oldid);
291 $job = new EnotifNotifyJob( $title, $params );
292 $job->insert();
293 } else {
294 $this->actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
295 }
296
297 }
298
299 /*
300 * Immediate version of notifyOnPageChange().
301 *
302 * Send emails corresponding to the user $editor editing the page $title.
303 * Also updates wl_notificationtimestamp.
304 *
305 * @param $editor User object
306 * @param $title Title object
307 * @param $timestamp
308 * @param $summary
309 * @param $minorEdit
310 * @param $oldid (default: false)
311 */
312 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid=false) {
313
314 # we use $wgEmergencyContact as sender's address
315 global $wgEnotifWatchlist;
316 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
317 global $wgEnotifImpersonal;
318
319 wfProfileIn( __METHOD__ );
320
321 # The following code is only run, if several conditions are met:
322 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
323 # 2. minor edits (changes) are only regarded if the global flag indicates so
324
325 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
326 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
327 $enotifwatchlistpage = $wgEnotifWatchlist;
328
329 $this->title = $title;
330 $this->timestamp = $timestamp;
331 $this->summary = $summary;
332 $this->minorEdit = $minorEdit;
333 $this->oldid = $oldid;
334 $this->editor = $editor;
335 $this->composed_common = false;
336
337 $userTalkId = false;
338
339 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
340 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
341 $targetUser = User::newFromName( $title->getText() );
342 if ( !$targetUser || $targetUser->isAnon() ) {
343 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
344 } elseif ( $targetUser->getId() == $editor->getId() ) {
345 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
346 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
347 wfDebug( __METHOD__.": sending talk page update notification\n" );
348 $this->compose( $targetUser );
349 $userTalkId = $targetUser->getId();
350 } else {
351 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
352 }
353 }
354
355
356 if ( $wgEnotifWatchlist ) {
357 // Send updates to watchers other than the current editor
358 $userCondition = 'wl_user <> ' . intval( $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 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
366 array(
367 'wl_title' => $title->getDBkey(),
368 'wl_namespace' => $title->getNamespace(),
369 $userCondition,
370 'wl_notificationtimestamp IS NULL',
371 ), __METHOD__ );
372
373 foreach ( $res as $row ) {
374 $watchingUser = User::newFromId( $row->wl_user );
375 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
376 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
377 $watchingUser->isEmailConfirmed() )
378 {
379 $this->compose( $watchingUser );
380 }
381 }
382 }
383 }
384
385 global $wgUsersNotifiedOnAllChanges;
386 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
387 $user = User::newFromName( $name );
388 $this->compose( $user );
389 }
390
391 $this->sendMails();
392
393 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
394 # mark the changed watch-listed page with a timestamp, so that the page is
395 # listed with an "updated since your last visit" icon in the watch list, ...
396 $dbw = wfGetDB( DB_MASTER );
397 $dbw->update( 'watchlist',
398 array( /* SET */
399 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
400 ), array( /* WHERE */
401 'wl_title' => $title->getDBkey(),
402 'wl_namespace' => $title->getNamespace(),
403 'wl_notificationtimestamp IS NULL'
404 ), __METHOD__
405 );
406 }
407
408 wfProfileOut( __METHOD__ );
409 } # function NotifyOnChange
410
411 /**
412 * @private
413 */
414 function composeCommonMailtext() {
415 global $wgEmergencyContact, $wgNoReplyAddress;
416 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
417 global $wgEnotifImpersonal;
418
419 $this->composed_common = true;
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 $editor = $this->editor;
471 $name = $editor->getName();
472 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
473 $editorAddress = new MailAddress( $editor );
474 if( $wgEnotifRevealEditorAddress
475 && ( $editor->getEmail() != '' )
476 && $editor->getOption( 'enotifrevealaddr' ) ) {
477 if( $wgEnotifFromEditor ) {
478 $from = $editorAddress;
479 } else {
480 $from = $adminAddress;
481 $replyto = $editorAddress;
482 }
483 } else {
484 $from = $adminAddress;
485 $replyto = new MailAddress( $wgNoReplyAddress );
486 }
487
488 if( $editor->isIP( $name ) ) {
489 #real anon (user:xxx.xxx.xxx.xxx)
490 $utext = wfMsgForContent('enotif_anon_editor', $name);
491 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
492 $keys['$PAGEEDITOR'] = $utext;
493 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
494 } else {
495 $subject = str_replace('$PAGEEDITOR', $name, $subject);
496 $keys['$PAGEEDITOR'] = $name;
497 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
498 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
499 }
500 $userPage = $editor->getUserPage();
501 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
502 $body = strtr( $body, $keys );
503 $body = wordwrap( $body, 72 );
504
505 # now save this as the constant user-independent part of the message
506 $this->from = $from;
507 $this->replyto = $replyto;
508 $this->subject = $subject;
509 $this->body = $body;
510 }
511
512 /**
513 * Compose a mail to a given user and either queue it for sending, or send it now,
514 * depending on settings.
515 *
516 * Call sendMails() to send any mails that were queued.
517 */
518 function compose( $user ) {
519 global $wgEnotifImpersonal;
520
521 if ( !$this->composed_common )
522 $this->composeCommonMailtext();
523
524 if ( $wgEnotifImpersonal ) {
525 $this->mailTargets[] = new MailAddress( $user );
526 } else {
527 $this->sendPersonalised( $user );
528 }
529 }
530
531 /**
532 * Send any queued mails
533 */
534 function sendMails() {
535 global $wgEnotifImpersonal;
536 if ( $wgEnotifImpersonal ) {
537 $this->sendImpersonal( $this->mailTargets );
538 }
539 }
540
541 /**
542 * Does the per-user customizations to a notification e-mail (name,
543 * timestamp in proper timezone, etc) and sends it out.
544 * Returns true if the mail was sent successfully.
545 *
546 * @param User $watchingUser
547 * @param object $mail
548 * @return bool
549 * @private
550 */
551 function sendPersonalised( $watchingUser ) {
552 global $wgLang;
553 // From the PHP manual:
554 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
555 // The mail command will not parse this properly while talking with the MTA.
556 $to = new MailAddress( $watchingUser );
557 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
558
559 $timecorrection = $watchingUser->getOption( 'timecorrection' );
560
561 # $PAGEEDITDATE is the time and date of the page change
562 # expressed in terms of individual local time of the notification
563 # recipient, i.e. watching user
564 $body = str_replace('$PAGEEDITDATE',
565 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
566 $body);
567
568 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
569 }
570
571 /**
572 * Same as sendPersonalised but does impersonal mail suitable for bulk
573 * mailing. Takes an array of MailAddress objects.
574 */
575 function sendImpersonal( $addresses ) {
576 global $wgLang;
577
578 if (empty($addresses))
579 return;
580
581 $body = str_replace(
582 array( '$WATCHINGUSERNAME',
583 '$PAGEEDITDATE'),
584 array( wfMsgForContent('enotif_impersonal_salutation'),
585 $wgLang->timeanddate($this->timestamp, true, false, false)),
586 $this->body);
587
588 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
589 }
590
591 } # end of class EmailNotification
592
593 /**
594 * Backwards compatibility functions
595 */
596 function wfRFC822Phrase( $s ) {
597 return UserMailer::rfc822Phrase( $s );
598 }
599
600 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
601 return UserMailer::send( $to, $from, $subject, $body, $replyto );
602 }