Duplicate code
[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 /**@{{
263 * @private
264 */
265 var $to, $subject, $body, $replyto, $from;
266 var $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
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 "editorID" => $editor->getID(),
294 "timestamp" => $timestamp,
295 "summary" => $summary,
296 "minorEdit" => $minorEdit,
297 "oldid" => $oldid);
298 $job = new EnotifNotifyJob( $title, $params );
299 $job->insert();
300 } else {
301 $this->actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid);
302 }
303
304 }
305
306 /*
307 * Immediate version of notifyOnPageChange().
308 *
309 * Send emails corresponding to the user $editor editing the page $title.
310 * Also updates wl_notificationtimestamp.
311 *
312 * @param $editor User object
313 * @param $title Title object
314 * @param $timestamp
315 * @param $summary
316 * @param $minorEdit
317 * @param $oldid (default: false)
318 */
319 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid=false) {
320
321 # we use $wgPasswordSender as sender's address
322 global $wgEnotifWatchlist;
323 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
324 global $wgEnotifImpersonal;
325
326 wfProfileIn( __METHOD__ );
327
328 # The following code is only run, if several conditions are met:
329 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
330 # 2. minor edits (changes) are only regarded if the global flag indicates so
331
332 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
333 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
334 $enotifwatchlistpage = $wgEnotifWatchlist;
335
336 $this->title = $title;
337 $this->timestamp = $timestamp;
338 $this->summary = $summary;
339 $this->minorEdit = $minorEdit;
340 $this->oldid = $oldid;
341 $this->editor = $editor;
342 $this->composed_common = false;
343
344 $userTalkId = false;
345
346 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
347 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
348 $targetUser = User::newFromName( $title->getText() );
349 if ( !$targetUser || $targetUser->isAnon() ) {
350 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
351 } elseif ( $targetUser->getId() == $editor->getId() ) {
352 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
353 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
354 if( $targetUser->isEmailConfirmed() ) {
355 wfDebug( __METHOD__.": sending talk page update notification\n" );
356 $this->compose( $targetUser );
357 $userTalkId = $targetUser->getId();
358 } else {
359 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
360 }
361 } else {
362 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
363 }
364 }
365
366 if ( $wgEnotifWatchlist ) {
367 // Send updates to watchers other than the current editor
368 $userCondition = 'wl_user != ' . $editor->getID();
369 if ( $userTalkId !== false ) {
370 // Already sent an email to this person
371 $userCondition .= ' AND wl_user != ' . intval( $userTalkId );
372 }
373 $dbr = wfGetDB( DB_SLAVE );
374
375 list( $user ) = $dbr->tableNamesN( 'user' );
376
377 $res = $dbr->select( array( 'watchlist', 'user' ),
378 array( "$user.*" ),
379 array(
380 'wl_user=user_id',
381 'wl_title' => $title->getDBkey(),
382 'wl_namespace' => $title->getNamespace(),
383 $userCondition,
384 'wl_notificationtimestamp IS NULL',
385 ), __METHOD__ );
386 $userArray = UserArray::newFromResult( $res );
387
388 foreach ( $userArray as $watchingUser ) {
389 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
390 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
391 $watchingUser->isEmailConfirmed() )
392 {
393 $this->compose( $watchingUser );
394 }
395 }
396 }
397 }
398
399 global $wgUsersNotifiedOnAllChanges;
400 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
401 $user = User::newFromName( $name );
402 $this->compose( $user );
403 }
404
405 $this->sendMails();
406
407 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
408 # Mark the changed watch-listed page with a timestamp, so that the page is
409 # listed with an "updated since your last visit" icon in the watch list. Do
410 # not do this to users for their own edits.
411 $dbw = wfGetDB( DB_MASTER );
412 $dbw->update( 'watchlist',
413 array( /* SET */
414 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
415 ), array( /* WHERE */
416 'wl_title' => $title->getDBkey(),
417 'wl_namespace' => $title->getNamespace(),
418 'wl_notificationtimestamp IS NULL',
419 'wl_user != ' . $editor->getID()
420 ), __METHOD__
421 );
422 }
423
424 wfProfileOut( __METHOD__ );
425 } # function NotifyOnChange
426
427 /**
428 * @private
429 */
430 function composeCommonMailtext() {
431 global $wgPasswordSender, $wgNoReplyAddress;
432 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
433 global $wgEnotifImpersonal;
434
435 $this->composed_common = true;
436
437 $summary = ($this->summary == '') ? ' - ' : $this->summary;
438 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
439
440 # You as the WikiAdmin and Sysops can make use of plenty of
441 # named variables when composing your notification emails while
442 # simply editing the Meta pages
443
444 $subject = wfMsgForContent( 'enotif_subject' );
445 $body = wfMsgForContent( 'enotif_body' );
446 $from = ''; /* fail safe */
447 $replyto = ''; /* fail safe */
448 $keys = array();
449
450 # regarding the use of oldid as an indicator for the last visited version, see also
451 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
452 # However, in the case of a new page which is already watched, we have no previous version to compare
453 if( $this->oldid ) {
454 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
455 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
456 $keys['$OLDID'] = $this->oldid;
457 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
458 } else {
459 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
460 # clear $OLDID placeholder in the message template
461 $keys['$OLDID'] = '';
462 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
463 }
464
465 if ($wgEnotifImpersonal && $this->oldid)
466 /*
467 * For impersonal mail, show a diff link to the last
468 * revision.
469 */
470 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
471 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
472
473 $body = strtr( $body, $keys );
474 $pagetitle = $this->title->getPrefixedText();
475 $keys['$PAGETITLE'] = $pagetitle;
476 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
477
478 $keys['$PAGEMINOREDIT'] = $medit;
479 $keys['$PAGESUMMARY'] = $summary;
480
481 $subject = strtr( $subject, $keys );
482
483 # Reveal the page editor's address as REPLY-TO address only if
484 # the user has not opted-out and the option is enabled at the
485 # global configuration level.
486 $editor = $this->editor;
487 $name = $editor->getName();
488 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
489 $editorAddress = new MailAddress( $editor );
490 if( $wgEnotifRevealEditorAddress
491 && ( $editor->getEmail() != '' )
492 && $editor->getOption( 'enotifrevealaddr' ) ) {
493 if( $wgEnotifFromEditor ) {
494 $from = $editorAddress;
495 } else {
496 $from = $adminAddress;
497 $replyto = $editorAddress;
498 }
499 } else {
500 $from = $adminAddress;
501 $replyto = new MailAddress( $wgNoReplyAddress );
502 }
503
504 if( $editor->isIP( $name ) ) {
505 #real anon (user:xxx.xxx.xxx.xxx)
506 $utext = wfMsgForContent('enotif_anon_editor', $name);
507 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
508 $keys['$PAGEEDITOR'] = $utext;
509 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
510 } else {
511 $subject = str_replace('$PAGEEDITOR', $name, $subject);
512 $keys['$PAGEEDITOR'] = $name;
513 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
514 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
515 }
516 $userPage = $editor->getUserPage();
517 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
518 $body = strtr( $body, $keys );
519 $body = wordwrap( $body, 72 );
520
521 # now save this as the constant user-independent part of the message
522 $this->from = $from;
523 $this->replyto = $replyto;
524 $this->subject = $subject;
525 $this->body = $body;
526 }
527
528 /**
529 * Compose a mail to a given user and either queue it for sending, or send it now,
530 * depending on settings.
531 *
532 * Call sendMails() to send any mails that were queued.
533 */
534 function compose( $user ) {
535 global $wgEnotifImpersonal;
536
537 if ( !$this->composed_common )
538 $this->composeCommonMailtext();
539
540 if ( $wgEnotifImpersonal ) {
541 $this->mailTargets[] = new MailAddress( $user );
542 } else {
543 $this->sendPersonalised( $user );
544 }
545 }
546
547 /**
548 * Send any queued mails
549 */
550 function sendMails() {
551 global $wgEnotifImpersonal;
552 if ( $wgEnotifImpersonal ) {
553 $this->sendImpersonal( $this->mailTargets );
554 }
555 }
556
557 /**
558 * Does the per-user customizations to a notification e-mail (name,
559 * timestamp in proper timezone, etc) and sends it out.
560 * Returns true if the mail was sent successfully.
561 *
562 * @param User $watchingUser
563 * @param object $mail
564 * @return bool
565 * @private
566 */
567 function sendPersonalised( $watchingUser ) {
568 global $wgLang;
569 // From the PHP manual:
570 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
571 // The mail command will not parse this properly while talking with the MTA.
572 $to = new MailAddress( $watchingUser );
573 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $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('$PAGEEDITDATE',
581 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
582 $body);
583
584 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
585 }
586
587 /**
588 * Same as sendPersonalised but does impersonal mail suitable for bulk
589 * mailing. Takes an array of MailAddress objects.
590 */
591 function sendImpersonal( $addresses ) {
592 global $wgLang;
593
594 if (empty($addresses))
595 return;
596
597 $body = str_replace(
598 array( '$WATCHINGUSERNAME',
599 '$PAGEEDITDATE'),
600 array( wfMsgForContent('enotif_impersonal_salutation'),
601 $wgLang->timeanddate($this->timestamp, true, false, false)),
602 $this->body);
603
604 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
605 }
606
607 } # end of class EmailNotification
608
609 /**
610 * Backwards compatibility functions
611 */
612 function wfRFC822Phrase( $s ) {
613 return UserMailer::rfc822Phrase( $s );
614 }
615
616 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
617 return UserMailer::send( $to, $from, $subject, $body, $replyto );
618 }