546f0c747d210ea41085e1cee39b757e0487013d
[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( array( 'watchlist', 'user' ), array( 'user.*' ),
366 array(
367 'wl_user=user_id',
368 'wl_title' => $title->getDBkey(),
369 'wl_namespace' => $title->getNamespace(),
370 $userCondition,
371 'wl_notificationtimestamp IS NULL',
372 ), __METHOD__ );
373 $userArray = UserArray::newFromResult( $res );
374
375 foreach ( $userArray as $watchingUser ) {
376 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
377 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
378 $watchingUser->isEmailConfirmed() )
379 {
380 $this->compose( $watchingUser );
381 }
382 }
383 }
384 }
385
386 global $wgUsersNotifiedOnAllChanges;
387 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
388 $user = User::newFromName( $name );
389 $this->compose( $user );
390 }
391
392 $this->sendMails();
393
394 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
395 # mark the changed watch-listed page with a timestamp, so that the page is
396 # listed with an "updated since your last visit" icon in the watch list, ...
397 $dbw = wfGetDB( DB_MASTER );
398 $dbw->update( 'watchlist',
399 array( /* SET */
400 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
401 ), array( /* WHERE */
402 'wl_title' => $title->getDBkey(),
403 'wl_namespace' => $title->getNamespace(),
404 'wl_notificationtimestamp IS NULL'
405 ), __METHOD__
406 );
407 }
408
409 wfProfileOut( __METHOD__ );
410 } # function NotifyOnChange
411
412 /**
413 * @private
414 */
415 function composeCommonMailtext() {
416 global $wgEmergencyContact, $wgNoReplyAddress;
417 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
418 global $wgEnotifImpersonal;
419
420 $this->composed_common = true;
421
422 $summary = ($this->summary == '') ? ' - ' : $this->summary;
423 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
424
425 # You as the WikiAdmin and Sysops can make use of plenty of
426 # named variables when composing your notification emails while
427 # simply editing the Meta pages
428
429 $subject = wfMsgForContent( 'enotif_subject' );
430 $body = wfMsgForContent( 'enotif_body' );
431 $from = ''; /* fail safe */
432 $replyto = ''; /* fail safe */
433 $keys = array();
434
435 # regarding the use of oldid as an indicator for the last visited version, see also
436 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
437 # However, in the case of a new page which is already watched, we have no previous version to compare
438 if( $this->oldid ) {
439 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
440 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
441 $keys['$OLDID'] = $this->oldid;
442 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
443 } else {
444 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
445 # clear $OLDID placeholder in the message template
446 $keys['$OLDID'] = '';
447 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
448 }
449
450 if ($wgEnotifImpersonal && $this->oldid)
451 /*
452 * For impersonal mail, show a diff link to the last
453 * revision.
454 */
455 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
456 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
457
458 $body = strtr( $body, $keys );
459 $pagetitle = $this->title->getPrefixedText();
460 $keys['$PAGETITLE'] = $pagetitle;
461 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
462
463 $keys['$PAGEMINOREDIT'] = $medit;
464 $keys['$PAGESUMMARY'] = $summary;
465
466 $subject = strtr( $subject, $keys );
467
468 # Reveal the page editor's address as REPLY-TO address only if
469 # the user has not opted-out and the option is enabled at the
470 # global configuration level.
471 $editor = $this->editor;
472 $name = $editor->getName();
473 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
474 $editorAddress = new MailAddress( $editor );
475 if( $wgEnotifRevealEditorAddress
476 && ( $editor->getEmail() != '' )
477 && $editor->getOption( 'enotifrevealaddr' ) ) {
478 if( $wgEnotifFromEditor ) {
479 $from = $editorAddress;
480 } else {
481 $from = $adminAddress;
482 $replyto = $editorAddress;
483 }
484 } else {
485 $from = $adminAddress;
486 $replyto = new MailAddress( $wgNoReplyAddress );
487 }
488
489 if( $editor->isIP( $name ) ) {
490 #real anon (user:xxx.xxx.xxx.xxx)
491 $utext = wfMsgForContent('enotif_anon_editor', $name);
492 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
493 $keys['$PAGEEDITOR'] = $utext;
494 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
495 } else {
496 $subject = str_replace('$PAGEEDITOR', $name, $subject);
497 $keys['$PAGEEDITOR'] = $name;
498 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
499 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
500 }
501 $userPage = $editor->getUserPage();
502 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
503 $body = strtr( $body, $keys );
504 $body = wordwrap( $body, 72 );
505
506 # now save this as the constant user-independent part of the message
507 $this->from = $from;
508 $this->replyto = $replyto;
509 $this->subject = $subject;
510 $this->body = $body;
511 }
512
513 /**
514 * Compose a mail to a given user and either queue it for sending, or send it now,
515 * depending on settings.
516 *
517 * Call sendMails() to send any mails that were queued.
518 */
519 function compose( $user ) {
520 global $wgEnotifImpersonal;
521
522 if ( !$this->composed_common )
523 $this->composeCommonMailtext();
524
525 if ( $wgEnotifImpersonal ) {
526 $this->mailTargets[] = new MailAddress( $user );
527 } else {
528 $this->sendPersonalised( $user );
529 }
530 }
531
532 /**
533 * Send any queued mails
534 */
535 function sendMails() {
536 global $wgEnotifImpersonal;
537 if ( $wgEnotifImpersonal ) {
538 $this->sendImpersonal( $this->mailTargets );
539 }
540 }
541
542 /**
543 * Does the per-user customizations to a notification e-mail (name,
544 * timestamp in proper timezone, etc) and sends it out.
545 * Returns true if the mail was sent successfully.
546 *
547 * @param User $watchingUser
548 * @param object $mail
549 * @return bool
550 * @private
551 */
552 function sendPersonalised( $watchingUser ) {
553 global $wgLang;
554 // From the PHP manual:
555 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
556 // The mail command will not parse this properly while talking with the MTA.
557 $to = new MailAddress( $watchingUser );
558 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
559
560 $timecorrection = $watchingUser->getOption( 'timecorrection' );
561
562 # $PAGEEDITDATE is the time and date of the page change
563 # expressed in terms of individual local time of the notification
564 # recipient, i.e. watching user
565 $body = str_replace('$PAGEEDITDATE',
566 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
567 $body);
568
569 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
570 }
571
572 /**
573 * Same as sendPersonalised but does impersonal mail suitable for bulk
574 * mailing. Takes an array of MailAddress objects.
575 */
576 function sendImpersonal( $addresses ) {
577 global $wgLang;
578
579 if (empty($addresses))
580 return;
581
582 $body = str_replace(
583 array( '$WATCHINGUSERNAME',
584 '$PAGEEDITDATE'),
585 array( wfMsgForContent('enotif_impersonal_salutation'),
586 $wgLang->timeanddate($this->timestamp, true, false, false)),
587 $this->body);
588
589 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
590 }
591
592 } # end of class EmailNotification
593
594 /**
595 * Backwards compatibility functions
596 */
597 function wfRFC822Phrase( $s ) {
598 return UserMailer::rfc822Phrase( $s );
599 }
600
601 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
602 return UserMailer::send( $to, $from, $subject, $body, $replyto );
603 }