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