* Allow $wgDiff3=false
[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 * @param $contentType String: optional custom Content-Type
102 * @return mixed True on success, a WikiError object on failure.
103 */
104 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
105 global $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
106 global $wgEnotifMaxRecips;
107
108 if ( is_array( $to ) ) {
109 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
110 } else {
111 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
112 }
113
114 if (is_array( $wgSMTP )) {
115 require_once( 'Mail.php' );
116
117 $msgid = str_replace(" ", "_", microtime());
118 if (function_exists('posix_getpid'))
119 $msgid .= '.' . posix_getpid();
120
121 if (is_array($to)) {
122 $dest = array();
123 foreach ($to as $u)
124 $dest[] = $u->address;
125 } else
126 $dest = $to->address;
127
128 $headers['From'] = $from->toString();
129
130 if ($wgEnotifImpersonal) {
131 $headers['To'] = 'undisclosed-recipients:;';
132 }
133 else {
134 $headers['To'] = implode( ", ", (array )$dest );
135 }
136
137 if ( $replyto ) {
138 $headers['Reply-To'] = $replyto->toString();
139 }
140 $headers['Subject'] = wfQuotedPrintable( $subject );
141 $headers['Date'] = date( 'r' );
142 $headers['MIME-Version'] = '1.0';
143 $headers['Content-type'] = (is_null($contentType) ?
144 'text/plain; charset='.$wgOutputEncoding : $contentType);
145 $headers['Content-transfer-encoding'] = '8bit';
146 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
147 $headers['X-Mailer'] = 'MediaWiki mailer';
148
149 // Create the mail object using the Mail::factory method
150 $mail_object =& Mail::factory('smtp', $wgSMTP);
151 if( PEAR::isError( $mail_object ) ) {
152 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
153 return new WikiError( $mail_object->getMessage() );
154 }
155
156 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
157 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
158 foreach ($chunks as $chunk) {
159 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
160 if( WikiError::isError( $e ) )
161 return $e;
162 }
163 } else {
164 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
165 # (fifth parameter of the PHP mail function, see some lines below)
166
167 # Line endings need to be different on Unix and Windows due to
168 # the bug described at http://trac.wordpress.org/ticket/2603
169 if ( wfIsWindows() ) {
170 $body = str_replace( "\n", "\r\n", $body );
171 $endl = "\r\n";
172 } else {
173 $endl = "\n";
174 }
175 $ctype = (is_null($contentType) ?
176 'text/plain; charset='.$wgOutputEncoding : $contentType);
177 $headers =
178 "MIME-Version: 1.0$endl" .
179 "Content-type: $ctype$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 new WikiError( $wgErrorString );
211 } elseif (! $sent) {
212 //mail function only tells if there's an error
213 wfDebug( "Error sending mail\n" );
214 return new WikiError( 'mailer error' );
215 } else {
216 return true;
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 private $to, $subject, $body, $replyto, $from;
263 private $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
264 private $mailTargets = array();
265
266 /**
267 * Send emails corresponding to the user $editor editing the page $title.
268 * Also updates wl_notificationtimestamp.
269 *
270 * May be deferred via the job queue.
271 *
272 * @param $editor User object
273 * @param $title Title object
274 * @param $timestamp
275 * @param $summary
276 * @param $minorEdit
277 * @param $oldid (default: false)
278 */
279 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
280 global $wgEnotifUseJobQ;
281
282 if( $title->getNamespace() < 0 )
283 return;
284
285 if ($wgEnotifUseJobQ) {
286 $params = array(
287 "editor" => $editor->getName(),
288 "editorID" => $editor->getID(),
289 "timestamp" => $timestamp,
290 "summary" => $summary,
291 "minorEdit" => $minorEdit,
292 "oldid" => $oldid);
293 $job = new EnotifNotifyJob( $title, $params );
294 $job->insert();
295 } else {
296 $this->actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
297 }
298
299 }
300
301 /*
302 * Immediate version of notifyOnPageChange().
303 *
304 * Send emails corresponding to the user $editor editing the page $title.
305 * Also updates wl_notificationtimestamp.
306 *
307 * @param $editor User object
308 * @param $title Title object
309 * @param $timestamp
310 * @param $summary
311 * @param $minorEdit
312 * @param $oldid (default: false)
313 */
314 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid=false) {
315
316 # we use $wgPasswordSender as sender's address
317 global $wgEnotifWatchlist;
318 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
319 global $wgEnotifImpersonal;
320
321 wfProfileIn( __METHOD__ );
322
323 # The following code is only run, if several conditions are met:
324 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
325 # 2. minor edits (changes) are only regarded if the global flag indicates so
326
327 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
328 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
329 $enotifwatchlistpage = $wgEnotifWatchlist;
330
331 $this->title = $title;
332 $this->timestamp = $timestamp;
333 $this->summary = $summary;
334 $this->minorEdit = $minorEdit;
335 $this->oldid = $oldid;
336 $this->editor = $editor;
337 $this->composed_common = false;
338
339 $userTalkId = false;
340
341 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
342 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
343 $targetUser = User::newFromName( $title->getText() );
344 if ( !$targetUser || $targetUser->isAnon() ) {
345 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
346 } elseif ( $targetUser->getId() == $editor->getId() ) {
347 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
348 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
349 if( $targetUser->isEmailConfirmed() ) {
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 have validated email\n" );
355 }
356 } else {
357 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
358 }
359 }
360
361 if ( $wgEnotifWatchlist ) {
362 // Send updates to watchers other than the current editor
363 $userCondition = 'wl_user != ' . $editor->getID();
364 if ( $userTalkId !== false ) {
365 // Already sent an email to this person
366 $userCondition .= ' AND wl_user != ' . intval( $userTalkId );
367 }
368 $dbr = wfGetDB( DB_SLAVE );
369
370 list( $user ) = $dbr->tableNamesN( 'user' );
371
372 $res = $dbr->select( array( 'watchlist', 'user' ),
373 array( "$user.*" ),
374 array(
375 'wl_user=user_id',
376 'wl_title' => $title->getDBkey(),
377 'wl_namespace' => $title->getNamespace(),
378 $userCondition,
379 'wl_notificationtimestamp IS NULL',
380 ), __METHOD__ );
381 $userArray = UserArray::newFromResult( $res );
382
383 foreach ( $userArray as $watchingUser ) {
384 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
385 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
386 $watchingUser->isEmailConfirmed() )
387 {
388 $this->compose( $watchingUser );
389 }
390 }
391 }
392 }
393
394 global $wgUsersNotifiedOnAllChanges;
395 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
396 $user = User::newFromName( $name );
397 $this->compose( $user );
398 }
399
400 $this->sendMails();
401
402 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
403 # Mark the changed watch-listed page with a timestamp, so that the page is
404 # listed with an "updated since your last visit" icon in the watch list. Do
405 # not do this to users for their own edits.
406 $dbw = wfGetDB( DB_MASTER );
407 $dbw->update( 'watchlist',
408 array( /* SET */
409 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
410 ), array( /* WHERE */
411 'wl_title' => $title->getDBkey(),
412 'wl_namespace' => $title->getNamespace(),
413 'wl_notificationtimestamp IS NULL',
414 'wl_user != ' . $editor->getID()
415 ), __METHOD__
416 );
417 }
418
419 wfProfileOut( __METHOD__ );
420 } # function NotifyOnChange
421
422 /**
423 * @private
424 */
425 function composeCommonMailtext() {
426 global $wgPasswordSender, $wgNoReplyAddress;
427 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
428 global $wgEnotifImpersonal;
429
430 $this->composed_common = true;
431
432 $summary = ($this->summary == '') ? ' - ' : $this->summary;
433 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
434
435 # You as the WikiAdmin and Sysops can make use of plenty of
436 # named variables when composing your notification emails while
437 # simply editing the Meta pages
438
439 $subject = wfMsgForContent( 'enotif_subject' );
440 $body = wfMsgForContent( 'enotif_body' );
441 $from = ''; /* fail safe */
442 $replyto = ''; /* fail safe */
443 $keys = array();
444
445 # regarding the use of oldid as an indicator for the last visited version, see also
446 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
447 # However, in the case of a new page which is already watched, we have no previous version to compare
448 if( $this->oldid ) {
449 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
450 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
451 $keys['$OLDID'] = $this->oldid;
452 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
453 } else {
454 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
455 # clear $OLDID placeholder in the message template
456 $keys['$OLDID'] = '';
457 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
458 }
459
460 if ($wgEnotifImpersonal && $this->oldid)
461 /*
462 * For impersonal mail, show a diff link to the last
463 * revision.
464 */
465 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
466 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
467
468 $body = strtr( $body, $keys );
469 $pagetitle = $this->title->getPrefixedText();
470 $keys['$PAGETITLE'] = $pagetitle;
471 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
472
473 $keys['$PAGEMINOREDIT'] = $medit;
474 $keys['$PAGESUMMARY'] = $summary;
475
476 $subject = strtr( $subject, $keys );
477
478 # Reveal the page editor's address as REPLY-TO address only if
479 # the user has not opted-out and the option is enabled at the
480 # global configuration level.
481 $editor = $this->editor;
482 $name = $editor->getName();
483 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
484 $editorAddress = new MailAddress( $editor );
485 if( $wgEnotifRevealEditorAddress
486 && ( $editor->getEmail() != '' )
487 && $editor->getOption( 'enotifrevealaddr' ) ) {
488 if( $wgEnotifFromEditor ) {
489 $from = $editorAddress;
490 } else {
491 $from = $adminAddress;
492 $replyto = $editorAddress;
493 }
494 } else {
495 $from = $adminAddress;
496 $replyto = new MailAddress( $wgNoReplyAddress );
497 }
498
499 if( $editor->isIP( $name ) ) {
500 #real anon (user:xxx.xxx.xxx.xxx)
501 $utext = wfMsgForContent('enotif_anon_editor', $name);
502 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
503 $keys['$PAGEEDITOR'] = $utext;
504 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
505 } else {
506 $subject = str_replace('$PAGEEDITOR', $name, $subject);
507 $keys['$PAGEEDITOR'] = $name;
508 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
509 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
510 }
511 $userPage = $editor->getUserPage();
512 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
513 $body = strtr( $body, $keys );
514 $body = wordwrap( $body, 72 );
515
516 # now save this as the constant user-independent part of the message
517 $this->from = $from;
518 $this->replyto = $replyto;
519 $this->subject = $subject;
520 $this->body = $body;
521 }
522
523 /**
524 * Compose a mail to a given user and either queue it for sending, or send it now,
525 * depending on settings.
526 *
527 * Call sendMails() to send any mails that were queued.
528 */
529 function compose( $user ) {
530 global $wgEnotifImpersonal;
531
532 if ( !$this->composed_common )
533 $this->composeCommonMailtext();
534
535 if ( $wgEnotifImpersonal ) {
536 $this->mailTargets[] = new MailAddress( $user );
537 } else {
538 $this->sendPersonalised( $user );
539 }
540 }
541
542 /**
543 * Send any queued mails
544 */
545 function sendMails() {
546 global $wgEnotifImpersonal;
547 if ( $wgEnotifImpersonal ) {
548 $this->sendImpersonal( $this->mailTargets );
549 }
550 }
551
552 /**
553 * Does the per-user customizations to a notification e-mail (name,
554 * timestamp in proper timezone, etc) and sends it out.
555 * Returns true if the mail was sent successfully.
556 *
557 * @param User $watchingUser
558 * @param object $mail
559 * @return bool
560 * @private
561 */
562 function sendPersonalised( $watchingUser ) {
563 global $wgLang;
564 // From the PHP manual:
565 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
566 // The mail command will not parse this properly while talking with the MTA.
567 $to = new MailAddress( $watchingUser );
568 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
569
570 $timecorrection = $watchingUser->getOption( 'timecorrection' );
571
572 # $PAGEEDITDATE is the time and date of the page change
573 # expressed in terms of individual local time of the notification
574 # recipient, i.e. watching user
575 $body = str_replace('$PAGEEDITDATE',
576 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
577 $body);
578
579 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
580 }
581
582 /**
583 * Same as sendPersonalised but does impersonal mail suitable for bulk
584 * mailing. Takes an array of MailAddress objects.
585 */
586 function sendImpersonal( $addresses ) {
587 global $wgLang;
588
589 if (empty($addresses))
590 return;
591
592 $body = str_replace(
593 array( '$WATCHINGUSERNAME',
594 '$PAGEEDITDATE'),
595 array( wfMsgForContent('enotif_impersonal_salutation'),
596 $wgLang->timeanddate($this->timestamp, true, false, false)),
597 $this->body);
598
599 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
600 }
601
602 } # end of class EmailNotification
603
604 /**
605 * Backwards compatibility functions
606 */
607 function wfRFC822Phrase( $s ) {
608 return UserMailer::rfc822Phrase( $s );
609 }
610
611 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
612 return UserMailer::send( $to, $from, $subject, $body, $replyto );
613 }