* (bug 23460) Parse action should have a section option
[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 (function_exists('mail')) {
201 if (is_array($to)) {
202 foreach ($to as $recip) {
203 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
204 }
205 } else {
206 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
207 }
208 } else {
209 self::$mErrorString = 'PHP is not configured to send mail';
210 }
211
212 restore_error_handler();
213 ini_set( 'html_errors', $html_errors );
214
215 if ( self::$mErrorString ) {
216 wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
217 return new WikiError( self::$mErrorString );
218 } elseif (! $sent ) {
219 //mail function only tells if there's an error
220 wfDebug( "Error sending mail\n" );
221 return new WikiError( 'mail() failed' );
222 } else {
223 return true;
224 }
225 }
226 }
227
228 /**
229 * Set the mail error message in self::$mErrorString
230 *
231 * @param $code Integer: error number
232 * @param $string String: error message
233 */
234 static function errorHandler( $code, $string ) {
235 self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
236 }
237
238 /**
239 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
240 */
241 static function rfc822Phrase( $phrase ) {
242 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
243 return '"' . $phrase . '"';
244 }
245 }
246
247 /**
248 * This module processes the email notifications when the current page is
249 * changed. It looks up the table watchlist to find out which users are watching
250 * that page.
251 *
252 * The current implementation sends independent emails to each watching user for
253 * the following reason:
254 *
255 * - Each watching user will be notified about the page edit time expressed in
256 * his/her local time (UTC is shown additionally). To achieve this, we need to
257 * find the individual timeoffset of each watching user from the preferences..
258 *
259 * Suggested improvement to slack down the number of sent emails: We could think
260 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
261 * same timeoffset in their preferences.
262 *
263 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
264 *
265 *
266 */
267 class EmailNotification {
268 protected $to, $subject, $body, $replyto, $from;
269 protected $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
270 protected $mailTargets = array();
271
272 /**
273 * Send emails corresponding to the user $editor editing the page $title.
274 * Also updates wl_notificationtimestamp.
275 *
276 * May be deferred via the job queue.
277 *
278 * @param $editor User object
279 * @param $title Title object
280 * @param $timestamp
281 * @param $summary
282 * @param $minorEdit
283 * @param $oldid (default: false)
284 */
285 function notifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid = false) {
286 global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker;
287
288 if ($title->getNamespace() < 0)
289 return;
290
291 // Build a list of users to notfiy
292 $watchers = array();
293 if ($wgEnotifWatchlist || $wgShowUpdatedMarker) {
294 $dbw = wfGetDB( DB_MASTER );
295 $res = $dbw->select( array( 'watchlist' ),
296 array( 'wl_user' ),
297 array(
298 'wl_title' => $title->getDBkey(),
299 'wl_namespace' => $title->getNamespace(),
300 'wl_user != ' . intval( $editor->getID() ),
301 'wl_notificationtimestamp IS NULL',
302 ), __METHOD__
303 );
304 while ($row = $dbw->fetchObject( $res ) ) {
305 $watchers[] = intval( $row->wl_user );
306 }
307 if ($watchers) {
308 // Update wl_notificationtimestamp for all watching users except
309 // the editor
310 $dbw->begin();
311 $dbw->update( 'watchlist',
312 array( /* SET */
313 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
314 ), array( /* WHERE */
315 'wl_title' => $title->getDBkey(),
316 'wl_namespace' => $title->getNamespace(),
317 'wl_user' => $watchers
318 ), __METHOD__
319 );
320 $dbw->commit();
321 }
322 }
323
324 if ($wgEnotifUseJobQ) {
325 $params = array(
326 "editor" => $editor->getName(),
327 "editorID" => $editor->getID(),
328 "timestamp" => $timestamp,
329 "summary" => $summary,
330 "minorEdit" => $minorEdit,
331 "oldid" => $oldid,
332 "watchers" => $watchers);
333 $job = new EnotifNotifyJob( $title, $params );
334 $job->insert();
335 } else {
336 $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
337 }
338
339 }
340
341 /*
342 * Immediate version of notifyOnPageChange().
343 *
344 * Send emails corresponding to the user $editor editing the page $title.
345 * Also updates wl_notificationtimestamp.
346 *
347 * @param $editor User object
348 * @param $title Title object
349 * @param $timestamp string Edit timestamp
350 * @param $summary string Edit summary
351 * @param $minorEdit bool
352 * @param $oldid int Revision ID
353 * @param $watchers array of user IDs
354 */
355 function actuallyNotifyOnPageChange($editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers) {
356 # we use $wgPasswordSender as sender's address
357 global $wgEnotifWatchlist;
358 global $wgEnotifMinorEdits, $wgEnotifUserTalk;
359 global $wgEnotifImpersonal;
360
361 wfProfileIn( __METHOD__ );
362
363 # The following code is only run, if several conditions are met:
364 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
365 # 2. minor edits (changes) are only regarded if the global flag indicates so
366
367 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
368 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
369 $enotifwatchlistpage = $wgEnotifWatchlist;
370
371 $this->title = $title;
372 $this->timestamp = $timestamp;
373 $this->summary = $summary;
374 $this->minorEdit = $minorEdit;
375 $this->oldid = $oldid;
376 $this->editor = $editor;
377 $this->composed_common = false;
378
379 $userTalkId = false;
380
381 if ( !$minorEdit || ($wgEnotifMinorEdits && !$editor->isAllowed('nominornewtalk') ) ) {
382 if ( $wgEnotifUserTalk && $isUserTalkPage ) {
383 $targetUser = User::newFromName( $title->getText() );
384 if ( !$targetUser || $targetUser->isAnon() ) {
385 wfDebug( __METHOD__.": user talk page edited, but user does not exist\n" );
386 } elseif ( $targetUser->getId() == $editor->getId() ) {
387 wfDebug( __METHOD__.": user edited their own talk page, no notification sent\n" );
388 } elseif( $targetUser->getOption( 'enotifusertalkpages' ) ) {
389 if( $targetUser->isEmailConfirmed() ) {
390 wfDebug( __METHOD__.": sending talk page update notification\n" );
391 $this->compose( $targetUser );
392 $userTalkId = $targetUser->getId();
393 } else {
394 wfDebug( __METHOD__.": talk page owner doesn't have validated email\n" );
395 }
396 } else {
397 wfDebug( __METHOD__.": talk page owner doesn't want notifications\n" );
398 }
399 }
400
401 if ( $wgEnotifWatchlist ) {
402 // Send updates to watchers other than the current editor
403 $userArray = UserArray::newFromIDs( $watchers );
404 foreach ( $userArray as $watchingUser ) {
405 if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
406 ( !$minorEdit || $watchingUser->getOption('enotifminoredits') ) &&
407 $watchingUser->isEmailConfirmed() &&
408 $watchingUser->getID() != $userTalkId )
409 {
410 $this->compose( $watchingUser );
411 }
412 }
413 }
414 }
415
416 global $wgUsersNotifiedOnAllChanges;
417 foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
418 $user = User::newFromName( $name );
419 $this->compose( $user );
420 }
421
422 $this->sendMails();
423 wfProfileOut( __METHOD__ );
424 }
425
426 /**
427 * @private
428 */
429 function composeCommonMailtext() {
430 global $wgPasswordSender, $wgNoReplyAddress;
431 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
432 global $wgEnotifImpersonal, $wgEnotifUseRealName;
433
434 $this->composed_common = true;
435
436 $summary = ($this->summary == '') ? ' - ' : $this->summary;
437 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
438
439 # You as the WikiAdmin and Sysops can make use of plenty of
440 # named variables when composing your notification emails while
441 # simply editing the Meta pages
442
443 $subject = wfMsgForContent( 'enotif_subject' );
444 $body = wfMsgForContent( 'enotif_body' );
445 $from = ''; /* fail safe */
446 $replyto = ''; /* fail safe */
447 $keys = array();
448
449 if( $this->oldid ) {
450 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
451 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
452 $keys['$OLDID'] = $this->oldid;
453 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
454 } else {
455 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
456 # clear $OLDID placeholder in the message template
457 $keys['$OLDID'] = '';
458 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
459 }
460
461 if ($wgEnotifImpersonal && $this->oldid)
462 /*
463 * For impersonal mail, show a diff link to the last
464 * revision.
465 */
466 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
467 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
468
469 $body = strtr( $body, $keys );
470 $pagetitle = $this->title->getPrefixedText();
471 $keys['$PAGETITLE'] = $pagetitle;
472 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
473
474 $keys['$PAGEMINOREDIT'] = $medit;
475 $keys['$PAGESUMMARY'] = $summary;
476 $keys['$UNWATCHURL'] = $this->title->getFullUrl( 'action=unwatch' );
477
478 $subject = strtr( $subject, $keys );
479
480 # Reveal the page editor's address as REPLY-TO address only if
481 # the user has not opted-out and the option is enabled at the
482 # global configuration level.
483 $editor = $this->editor;
484 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
485 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
486 $editorAddress = new MailAddress( $editor );
487 if( $wgEnotifRevealEditorAddress
488 && ( $editor->getEmail() != '' )
489 && $editor->getOption( 'enotifrevealaddr' ) ) {
490 if( $wgEnotifFromEditor ) {
491 $from = $editorAddress;
492 } else {
493 $from = $adminAddress;
494 $replyto = $editorAddress;
495 }
496 } else {
497 $from = $adminAddress;
498 $replyto = new MailAddress( $wgNoReplyAddress );
499 }
500
501 if( $editor->isIP( $name ) ) {
502 #real anon (user:xxx.xxx.xxx.xxx)
503 $utext = wfMsgForContent('enotif_anon_editor', $name);
504 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
505 $keys['$PAGEEDITOR'] = $utext;
506 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
507 } else {
508 $subject = str_replace('$PAGEEDITOR', $name, $subject);
509 $keys['$PAGEEDITOR'] = $name;
510 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
511 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
512 }
513 $userPage = $editor->getUserPage();
514 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
515 $body = strtr( $body, $keys );
516 $body = wordwrap( $body, 72 );
517
518 # now save this as the constant user-independent part of the message
519 $this->from = $from;
520 $this->replyto = $replyto;
521 $this->subject = $subject;
522 $this->body = $body;
523 }
524
525 /**
526 * Compose a mail to a given user and either queue it for sending, or send it now,
527 * depending on settings.
528 *
529 * Call sendMails() to send any mails that were queued.
530 */
531 function compose( $user ) {
532 global $wgEnotifImpersonal;
533
534 if ( !$this->composed_common )
535 $this->composeCommonMailtext();
536
537 if ( $wgEnotifImpersonal ) {
538 $this->mailTargets[] = new MailAddress( $user );
539 } else {
540 $this->sendPersonalised( $user );
541 }
542 }
543
544 /**
545 * Send any queued mails
546 */
547 function sendMails() {
548 global $wgEnotifImpersonal;
549 if ( $wgEnotifImpersonal ) {
550 $this->sendImpersonal( $this->mailTargets );
551 }
552 }
553
554 /**
555 * Does the per-user customizations to a notification e-mail (name,
556 * timestamp in proper timezone, etc) and sends it out.
557 * Returns true if the mail was sent successfully.
558 *
559 * @param User $watchingUser
560 * @param object $mail
561 * @return bool
562 * @private
563 */
564 function sendPersonalised( $watchingUser ) {
565 global $wgContLang, $wgEnotifUseRealName;
566 // From the PHP manual:
567 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
568 // The mail command will not parse this properly while talking with the MTA.
569 $to = new MailAddress( $watchingUser );
570 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
571 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
572
573 $timecorrection = $watchingUser->getOption( 'timecorrection' );
574
575 # $PAGEEDITDATE is the time and date of the page change
576 # expressed in terms of individual local time of the notification
577 # recipient, i.e. watching user
578 $body = str_replace(
579 array( '$PAGEEDITDATEANDTIME',
580 '$PAGEEDITDATE',
581 '$PAGEEDITTIME' ),
582 array( $wgContLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
583 $wgContLang->date( $this->timestamp, true, false, $timecorrection ),
584 $wgContLang->time( $this->timestamp, true, false, $timecorrection ) ),
585 $body);
586
587 return UserMailer::send($to, $this->from, $this->subject, $body, $this->replyto);
588 }
589
590 /**
591 * Same as sendPersonalised but does impersonal mail suitable for bulk
592 * mailing. Takes an array of MailAddress objects.
593 */
594 function sendImpersonal( $addresses ) {
595 global $wgContLang;
596
597 if (empty($addresses))
598 return;
599
600 $body = str_replace(
601 array( '$WATCHINGUSERNAME',
602 '$PAGEEDITDATE'),
603 array( wfMsgForContent('enotif_impersonal_salutation'),
604 $wgContLang->timeanddate($this->timestamp, true, false, false)),
605 $this->body);
606
607 return UserMailer::send($addresses, $this->from, $this->subject, $body, $this->replyto);
608 }
609
610 } # end of class EmailNotification
611
612 /**
613 * Backwards compatibility functions
614 */
615 function wfRFC822Phrase( $s ) {
616 return UserMailer::rfc822Phrase( $s );
617 }
618
619 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
620 return UserMailer::send( $to, $from, $subject, $body, $replyto );
621 }