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