Kill E_STRICTs from Mail package
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * Classes used to send e-mails
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author <brion@pobox.com>
22 * @author <mail@tgries.de>
23 * @author Tim Starling
24 */
25
26
27 /**
28 * Stores a single person's name and email address.
29 * These are passed in via the constructor, and will be returned in SMTP
30 * header format when requested.
31 */
32 class MailAddress {
33 /**
34 * @param $address Mixed: string with an email address, or a User object
35 * @param $name String: human-readable name if a string address is given
36 * @param $realName String: human-readable real name if a string address is given
37 */
38 function __construct( $address, $name = null, $realName = null ) {
39 if( is_object( $address ) && $address instanceof User ) {
40 $this->address = $address->getEmail();
41 $this->name = $address->getName();
42 $this->realName = $address->getRealName();
43 } else {
44 $this->address = strval( $address );
45 $this->name = strval( $name );
46 $this->realName = strval( $realName );
47 }
48 }
49
50 /**
51 * Return formatted and quoted address to insert into SMTP headers
52 * @return string
53 */
54 function toString() {
55 # PHP's mail() implementation under Windows is somewhat shite, and
56 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
57 # so don't bother generating them
58 if( $this->name != '' && !wfIsWindows() ) {
59 global $wgEnotifUseRealName;
60 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
61 $quoted = wfQuotedPrintable( $name );
62 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
63 $quoted = '"' . $quoted . '"';
64 }
65 return "$quoted <{$this->address}>";
66 } else {
67 return $this->address;
68 }
69 }
70
71 function __toString() {
72 return $this->toString();
73 }
74 }
75
76
77 /**
78 * Collection of static functions for sending mail
79 */
80 class UserMailer {
81 static $mErrorString;
82
83 /**
84 * Send mail using a PEAR mailer
85 */
86 protected static function sendWithPear($mailer, $dest, $headers, $body)
87 {
88 $mailResult = $mailer->send($dest, $headers, $body);
89
90 # Based on the result return an error string,
91 if( PEAR::isError( $mailResult ) ) {
92 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
93 return new WikiError( $mailResult->getMessage() );
94 } else {
95 return true;
96 }
97 }
98
99 /**
100 * This function will perform a direct (authenticated) login to
101 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
102 * array of parameters. It requires PEAR:Mail to do that.
103 * Otherwise it just uses the standard PHP 'mail' function.
104 *
105 * @param $to MailAddress: recipient's email (or an array of them)
106 * @param $from MailAddress: sender's email
107 * @param $subject String: email's subject.
108 * @param $body String: email's text.
109 * @param $replyto MailAddress: optional reply-to email (default: null).
110 * @param $contentType String: optional custom Content-Type
111 * @return mixed True on success, a WikiError object on failure.
112 */
113 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
114 global $wgSMTP, $wgOutputEncoding, $wgEnotifImpersonal;
115 global $wgEnotifMaxRecips, $wgAdditionalMailParams;
116
117 if ( is_array( $to ) ) {
118 // This wouldn't be necessary if implode() worked on arrays of
119 // objects using __toString(). http://bugs.php.net/bug.php?id=36612
120 foreach( $to as $t ) {
121 $emails .= $t->toString() . ",";
122 }
123 $emails = rtrim( $emails, ',' );
124 wfDebug( __METHOD__.': sending mail to ' . $emails . "\n" );
125 } else {
126 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
127 }
128
129 if (is_array( $wgSMTP )) {
130 $found = false;
131 $pathArray = explode( PATH_SEPARATOR, get_include_path() );
132 foreach ( $pathArray as $path ) {
133 if ( file_exists( $path . DIRECTORY_SEPARATOR . 'Mail.php' ) ) {
134 $found = true;
135 break;
136 }
137 }
138 if ( !$found ) {
139 throw new MWException( 'PEAR mail package is not installed' );
140 }
141 require_once( 'Mail.php' );
142
143 $msgid = str_replace(" ", "_", microtime());
144 if (function_exists('posix_getpid'))
145 $msgid .= '.' . posix_getpid();
146
147 if (is_array($to)) {
148 $dest = array();
149 foreach ($to as $u)
150 $dest[] = $u->address;
151 } else
152 $dest = $to->address;
153
154 $headers['From'] = $from->toString();
155
156 if ($wgEnotifImpersonal) {
157 $headers['To'] = 'undisclosed-recipients:;';
158 }
159 else {
160 $headers['To'] = implode( ", ", (array )$dest );
161 }
162
163 if ( $replyto ) {
164 $headers['Reply-To'] = $replyto->toString();
165 }
166 $headers['Subject'] = wfQuotedPrintable( $subject );
167 $headers['Date'] = date( 'r' );
168 $headers['MIME-Version'] = '1.0';
169 $headers['Content-type'] = (is_null($contentType) ?
170 'text/plain; charset='.$wgOutputEncoding : $contentType);
171 $headers['Content-transfer-encoding'] = '8bit';
172 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
173 $headers['X-Mailer'] = 'MediaWiki mailer';
174
175 wfSuppressWarnings();
176
177 // Create the mail object using the Mail::factory method
178 $mail_object =& Mail::factory('smtp', $wgSMTP);
179 if( PEAR::isError( $mail_object ) ) {
180 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
181 wfRestoreWarnings();
182 return new WikiError( $mail_object->getMessage() );
183 }
184
185 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
186 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
187 foreach ($chunks as $chunk) {
188 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
189 if( WikiError::isError( $e ) ) {
190 wfRestoreWarnings();
191 return $e;
192 }
193 }
194 wfRestoreWarnings();
195 } else {
196 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
197 # (fifth parameter of the PHP mail function, see some lines below)
198
199 # Line endings need to be different on Unix and Windows due to
200 # the bug described at http://trac.wordpress.org/ticket/2603
201 if ( wfIsWindows() ) {
202 $body = str_replace( "\n", "\r\n", $body );
203 $endl = "\r\n";
204 } else {
205 $endl = "\n";
206 }
207 $ctype = (is_null($contentType) ?
208 'text/plain; charset='.$wgOutputEncoding : $contentType);
209 $headers =
210 "MIME-Version: 1.0$endl" .
211 "Content-type: $ctype$endl" .
212 "Content-Transfer-Encoding: 8bit$endl" .
213 "X-Mailer: MediaWiki mailer$endl".
214 'From: ' . $from->toString();
215 if ($replyto) {
216 $headers .= "{$endl}Reply-To: " . $replyto->toString();
217 }
218
219 wfDebug( "Sending mail via internal mail() function\n" );
220
221 self::$mErrorString = '';
222 $html_errors = ini_get( 'html_errors' );
223 ini_set( 'html_errors', '0' );
224 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
225
226 if (is_array($to)) {
227 foreach ($to as $recip) {
228 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
229 }
230 } else {
231 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
232 }
233
234 restore_error_handler();
235 ini_set( 'html_errors', $html_errors );
236
237 if ( self::$mErrorString ) {
238 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
239 return new WikiError( self::$mErrorString );
240 } elseif (! $sent ) {
241 //mail function only tells if there's an error
242 wfDebug( "Error sending mail\n" );
243 return new WikiError( 'mail() failed' );
244 } else {
245 return true;
246 }
247 }
248 }
249
250 /**
251 * Set the mail error message in self::$mErrorString
252 *
253 * @param $code Integer: error number
254 * @param $string String: error message
255 */
256 static function errorHandler( $code, $string ) {
257 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
258 }
259
260 /**
261 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
262 */
263 static function rfc822Phrase( $phrase ) {
264 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
265 return '"' . $phrase . '"';
266 }
267 }
268
269 /**
270 * This module processes the email notifications when the current page is
271 * changed. It looks up the table watchlist to find out which users are watching
272 * that page.
273 *
274 * The current implementation sends independent emails to each watching user for
275 * the following reason:
276 *
277 * - Each watching user will be notified about the page edit time expressed in
278 * his/her local time (UTC is shown additionally). To achieve this, we need to
279 * find the individual timeoffset of each watching user from the preferences..
280 *
281 * Suggested improvement to slack down the number of sent emails: We could think
282 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
283 * same timeoffset in their preferences.
284 *
285 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
286 *
287 *
288 */
289 class EmailNotification {
290 protected $to, $subject, $body, $replyto, $from;
291 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
292 protected $mailTargets = array();
293
294 /**
295 * Send emails corresponding to the user $editor editing the page $title.
296 * Also updates wl_notificationtimestamp.
297 *
298 * May be deferred via the job queue.
299 *
300 * @param $editor User object
301 * @param $title Title object
302 * @param $timestamp
303 * @param $summary
304 * @param $minorEdit
305 * @param $oldid (default: false)
306 */
307 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
308 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
309
310 if ($title->getNamespace() < 0)
311 return;
312
313 // Build a list of users to notfiy
314 $watchers = array();
315 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
316 $dbw = wfGetDB( DB_MASTER );
317 $res = $dbw->select( array( 'watchlist' ),
318 array( 'wl_user' ),
319 array(
320 'wl_title' => $title->getDBkey(),
321 'wl_namespace' => $title->getNamespace(),
322 'wl_user != ' . intval( $editor->getID() ),
323 'wl_notificationtimestamp IS NULL',
324 ), __METHOD__
325 );
326 foreach ( $res as $row ) {
327 $watchers[] = intval( $row->wl_user );
328 }
329 if ($watchers) {
330 // Update wl_notificationtimestamp for all watching users except
331 // the editor
332 $dbw->begin();
333 $dbw->update( 'watchlist',
334 array( /* SET */
335 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
336 ), array( /* WHERE */
337 'wl_title' => $title->getDBkey(),
338 'wl_namespace' => $title->getNamespace(),
339 'wl_user' => $watchers
340 ), __METHOD__
341 );
342 $dbw->commit();
343 }
344 }
345
346 if ($wgEnotifUseJobQ) {
347 $params = array(
348 "editor" => $editor->getName(),
349 "editorID" => $editor->getID(),
350 "timestamp" => $timestamp,
351 "summary" => $summary,
352 "minorEdit" => $minorEdit,
353 "oldid" => $oldid,
354 "watchers" => $watchers);
355 $job = new EnotifNotifyJob( $title, $params );
356 $job->insert();
357 } else {
358 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
359 }
360
361 }
362
363 /*
364 * Immediate version of notifyOnPageChange().
365 *
366 * Send emails corresponding to the user $editor editing the page $title.
367 * Also updates wl_notificationtimestamp.
368 *
369 * @param $editor User object
370 * @param $title Title object
371 * @param $timestamp string Edit timestamp
372 * @param $summary string Edit summary
373 * @param $minorEdit bool
374 * @param $oldid int Revision ID
375 * @param $watchers array of user IDs
376 */
377 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
378 # we use $wgPasswordSender as sender's address
379 global $wgEnotifWatchlist;
380 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
381
382 wfProfileIn( __METHOD__ );
383
384 # The following code is only run, if several conditions are met:
385 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
386 # 2. minor edits (changes) are only regarded if the global flag indicates so
387
388 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
389
390 $this->title = $title;
391 $this->timestamp = $timestamp;
392 $this->summary = $summary;
393 $this->minorEdit = $minorEdit;
394 $this->oldid = $oldid;
395 $this->editor = $editor;
396 $this->composed_common = false;
397
398 $userTalkId = false;
399
400 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
401 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
402 $targetUser = User::newFromName( $title->getText() );
403 if ( !$targetUser || $targetUser->isAnon() ) {
404 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
405 } elseif ( $targetUser->getId() == $editor->getId() ) {
406 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
407 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
408 if( $targetUser->isEmailConfirmed() ) {
409 wfDebug( __METHOD__.": sending talk page update notification\n" );
410 $this->compose( $targetUser );
411 $userTalkId = $targetUser->getId();
412 } else {
413 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
414 }
415 } else {
416 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
417 }
418 }
419
420 if ( $wgEnotifWatchlist ) {
421 // Send updates to watchers other than the current editor
422 $userArray = UserArray::newFromIDs( $watchers );
423 foreach ( $userArray as $watchingUser ) {
424 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
425 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
426 $watchingUser->isEmailConfirmed() &&
427 $watchingUser->getID() != $userTalkId )
428 {
429 $this->compose( $watchingUser );
430 }
431 }
432 }
433 }
434
435 global $wgUsersNotifiedOnAllChanges;
436 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
437 $user = User::newFromName( $name );
438 $this->compose( $user );
439 }
440
441 $this->sendMails();
442 wfProfileOut( __METHOD__ );
443 }
444
445 /**
446 * @private
447 */
448 function composeCommonMailtext() {
449 global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
450 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
451 global $wgEnotifImpersonal, $wgEnotifUseRealName;
452
453 $this->composed_common = true;
454
455 $summary = ($this->summary == '') ? ' - ' : $this->summary;
456 $medit = ($this->minorEdit) ? wfMsgForContent( 'minoredit' ) : '';
457
458 # You as the WikiAdmin and Sysops can make use of plenty of
459 # named variables when composing your notification emails while
460 # simply editing the Meta pages
461
462 $subject = wfMsgForContent( 'enotif_subject' );
463 $body = wfMsgForContent( 'enotif_body' );
464 $from = ''; /* fail safe */
465 $replyto = ''; /* fail safe */
466 $keys = array();
467
468 if( $this->oldid ) {
469 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
470 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
471 $keys['$OLDID'] = $this->oldid;
472 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
473 } else {
474 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
475 # clear $OLDID placeholder in the message template
476 $keys['$OLDID'] = '';
477 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
478 }
479
480 if ($wgEnotifImpersonal && $this->oldid) {
481 /*
482 * For impersonal mail, show a diff link to the last
483 * revision.
484 */
485 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
486 $this->title->getFullURL("oldid={$this->oldid}&diff=next"));
487 }
488
489 $body = strtr( $body, $keys );
490 $pagetitle = $this->title->getPrefixedText();
491 $keys['$PAGETITLE'] = $pagetitle;
492 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
493
494 $keys['$PAGEMINOREDIT'] = $medit;
495 $keys['$PAGESUMMARY'] = $summary;
496 $keys['$UNWATCHURL'] = $this->title->getFullUrl( 'action=unwatch' );
497
498 $subject = strtr( $subject, $keys );
499
500 # Reveal the page editor's address as REPLY-TO address only if
501 # the user has not opted-out and the option is enabled at the
502 # global configuration level.
503 $editor = $this->editor;
504 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
505 $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
506 $editorAddress = new MailAddress( $editor );
507 if( $wgEnotifRevealEditorAddress
508 && ( $editor->getEmail() != '' )
509 && $editor->getOption( 'enotifrevealaddr' ) ) {
510 if( $wgEnotifFromEditor ) {
511 $from = $editorAddress;
512 } else {
513 $from = $adminAddress;
514 $replyto = $editorAddress;
515 }
516 } else {
517 $from = $adminAddress;
518 $replyto = new MailAddress( $wgNoReplyAddress );
519 }
520
521 if( $editor->isIP( $name ) ) {
522 #real anon (user:xxx.xxx.xxx.xxx)
523 $utext = wfMsgForContent('enotif_anon_editor', $name);
524 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
525 $keys['$PAGEEDITOR'] = $utext;
526 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
527 } else {
528 $subject = str_replace('$PAGEEDITOR', $name, $subject);
529 $keys['$PAGEEDITOR'] = $name;
530 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
531 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
532 }
533 $userPage = $editor->getUserPage();
534 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
535 $body = strtr( $body, $keys );
536 $body = wordwrap( $body, 72 );
537
538 # now save this as the constant user-independent part of the message
539 $this->from = $from;
540 $this->replyto = $replyto;
541 $this->subject = $subject;
542 $this->body = $body;
543 }
544
545 /**
546 * Compose a mail to a given user and either queue it for sending, or send it now,
547 * depending on settings.
548 *
549 * Call sendMails() to send any mails that were queued.
550 */
551 function compose( $user ) {
552 global $wgEnotifImpersonal;
553
554 if ( !$this->composed_common )
555 $this->composeCommonMailtext();
556
557 if ( $wgEnotifImpersonal ) {
558 $this->mailTargets[] = new MailAddress( $user );
559 } else {
560 $this->sendPersonalised( $user );
561 }
562 }
563
564 /**
565 * Send any queued mails
566 */
567 function sendMails() {
568 global $wgEnotifImpersonal;
569 if ( $wgEnotifImpersonal ) {
570 $this->sendImpersonal( $this->mailTargets );
571 }
572 }
573
574 /**
575 * Does the per-user customizations to a notification e-mail (name,
576 * timestamp in proper timezone, etc) and sends it out.
577 * Returns true if the mail was sent successfully.
578 *
579 * @param $watchingUser User object
580 * @return Boolean
581 * @private
582 */
583 function sendPersonalised( $watchingUser ) {
584 global $wgContLang, $wgEnotifUseRealName;
585 // From the PHP manual:
586 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
587 // The mail command will not parse this properly while talking with the MTA.
588 $to = new MailAddress( $watchingUser );
589 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
590 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
591
592 $timecorrection = $watchingUser->getOption( 'timecorrection' );
593
594 # $PAGEEDITDATE is the time and date of the page change
595 # expressed in terms of individual local time of the notification
596 # recipient, i.e. watching user
597 $body = str_replace(
598 array( '$PAGEEDITDATEANDTIME',
599 '$PAGEEDITDATE',
600 '$PAGEEDITTIME' ),
601 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
602 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
603 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
604 $body);
605
606 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
607 }
608
609 /**
610 * Same as sendPersonalised but does impersonal mail suitable for bulk
611 * mailing. Takes an array of MailAddress objects.
612 */
613 function sendImpersonal( $addresses ) {
614 global $wgContLang;
615
616 if (empty($addresses))
617 return;
618
619 $body = str_replace(
620 array( '$WATCHINGUSERNAME',
621 '$PAGEEDITDATE'),
622 array( wfMsgForContent('enotif_impersonal_salutation'),
623 $wgContLang->timeanddate($this->timestamp, true, false, false)),
624 $this->body);
625
626 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
627 }
628
629 } # end of class EmailNotification
630
631 /**@{
632 * Backwards compatibility functions
633 *
634 * @deprecated Use UserMailer methods; will be removed in 1.19
635 */
636 function wfRFC822Phrase( $s ) {
637 wfDeprecated( __FUNCTION__ );
638 return UserMailer::rfc822Phrase( $s );
639 }
640
641 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
642 wfDeprecated( __FUNCTION__ );
643 return UserMailer::send( $to, $from, $subject, $body, $replyto );
644 }
645 /**@}*/