Add missing global $wgEnotifUseRealName. Fix for undefined variable notice in r43155.
[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->reaName = strval( $realName );
44 }
45 }
46
47 /**
48 * Return formatted and quoted address to insert into SMTP headers
49 * @param bool $useRealName True will use real name instead of username
50 * @return string
51 */
52 function toString() {
53 # PHP's mail() implementation under Windows is somewhat shite, and
54 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
55 # so don't bother generating them
56 if( $this->name != '' && !wfIsWindows() ) {
57 global $wgEnotifUseRealName;
58 $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
59 $quoted = wfQuotedPrintable( $name );
60 if( strpos( $quoted, '.' ) !== false || strpos( $quoted, ',' ) !== false ) {
61 $quoted = '"' . $quoted . '"';
62 }
63 return "$quoted <{$this->address}>";
64 } else {
65 return $this->address;
66 }
67 }
68
69 function __toString() {
70 return $this->toString();
71 }
72 }
73
74
75 /**
76 * Collection of static functions for sending mail
77 */
78 class UserMailer {
79 /**
80 * Send mail using a PEAR mailer
81 */
82 protected static function sendWithPear($mailer, $dest, $headers, $body)
83 {
84 $mailResult = $mailer->send($dest, $headers, $body);
85
86 # Based on the result return an error string,
87 if( PEAR::isError( $mailResult ) ) {
88 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
89 return new WikiError( $mailResult->getMessage() );
90 } else {
91 return true;
92 }
93 }
94
95 /**
96 * This function will perform a direct (authenticated) login to
97 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
98 * array of parameters. It requires PEAR:Mail to do that.
99 * Otherwise it just uses the standard PHP 'mail' function.
100 *
101 * @param $to MailAddress: recipient's email
102 * @param $from MailAddress: sender's email
103 * @param $subject String: email's subject.
104 * @param $body String: email's text.
105 * @param $replyto String: optional reply-to email (default: null).
106 * @param $contentType String: optional custom Content-Type
107 * @return mixed True on success, a WikiError object on failure.
108 */
109 static function send( $to, $from, $subject, $body, $replyto=null, $contentType=null ) {
110 global $wgSMTP, $wgOutputEncoding, $wgErrorString, $wgEnotifImpersonal;
111 global $wgEnotifMaxRecips;
112
113 if ( is_array( $to ) ) {
114 wfDebug( __METHOD__.': sending mail to ' . implode( ',', $to ) . "\n" );
115 } else {
116 wfDebug( __METHOD__.': sending mail to ' . implode( ',', array( $to->toString() ) ) . "\n" );
117 }
118
119 if (is_array( $wgSMTP )) {
120 require_once( 'Mail.php' );
121
122 $msgid = str_replace(" ", "_", microtime());
123 if (function_exists('posix_getpid'))
124 $msgid .= '.' . posix_getpid();
125
126 if (is_array($to)) {
127 $dest = array();
128 foreach ($to as $u)
129 $dest[] = $u->address;
130 } else
131 $dest = $to->address;
132
133 $headers['From'] = $from->toString();
134
135 if ($wgEnotifImpersonal) {
136 $headers['To'] = 'undisclosed-recipients:;';
137 }
138 else {
139 $headers['To'] = implode( ", ", (array )$dest );
140 }
141
142 if ( $replyto ) {
143 $headers['Reply-To'] = $replyto->toString();
144 }
145 $headers['Subject'] = wfQuotedPrintable( $subject );
146 $headers['Date'] = date( 'r' );
147 $headers['MIME-Version'] = '1.0';
148 $headers['Content-type'] = (is_null($contentType) ?
149 'text/plain; charset='.$wgOutputEncoding : $contentType);
150 $headers['Content-transfer-encoding'] = '8bit';
151 $headers['Message-ID'] = "<$msgid@" . $wgSMTP['IDHost'] . '>'; // FIXME
152 $headers['X-Mailer'] = 'MediaWiki mailer';
153
154 // Create the mail object using the Mail::factory method
155 $mail_object =& Mail::factory('smtp', $wgSMTP);
156 if( PEAR::isError( $mail_object ) ) {
157 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
158 return new WikiError( $mail_object->getMessage() );
159 }
160
161 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
162 $chunks = array_chunk( (array)$dest, $wgEnotifMaxRecips );
163 foreach ($chunks as $chunk) {
164 $e = self::sendWithPear($mail_object, $chunk, $headers, $body);
165 if( WikiError::isError( $e ) )
166 return $e;
167 }
168 } else {
169 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
170 # (fifth parameter of the PHP mail function, see some lines below)
171
172 # Line endings need to be different on Unix and Windows due to
173 # the bug described at http://trac.wordpress.org/ticket/2603
174 if ( wfIsWindows() ) {
175 $body = str_replace( "\n", "\r\n", $body );
176 $endl = "\r\n";
177 } else {
178 $endl = "\n";
179 }
180 $ctype = (is_null($contentType) ?
181 'text/plain; charset='.$wgOutputEncoding : $contentType);
182 $headers =
183 "MIME-Version: 1.0$endl" .
184 "Content-type: $ctype$endl" .
185 "Content-Transfer-Encoding: 8bit$endl" .
186 "X-Mailer: MediaWiki mailer$endl".
187 'From: ' . $from->toString();
188 if ($replyto) {
189 $headers .= "{$endl}Reply-To: " . $replyto->toString();
190 }
191
192 $wgErrorString = '';
193 $html_errors = ini_get( 'html_errors' );
194 ini_set( 'html_errors', '0' );
195 set_error_handler( array( 'UserMailer', 'errorHandler' ) );
196 wfDebug( "Sending mail via internal mail() function\n" );
197
198 if (function_exists('mail')) {
199 if (is_array($to)) {
200 foreach ($to as $recip) {
201 $sent = mail( $recip->toString(), wfQuotedPrintable( $subject ), $body, $headers );
202 }
203 } else {
204 $sent = mail( $to->toString(), wfQuotedPrintable( $subject ), $body, $headers );
205 }
206 } else {
207 $wgErrorString = 'PHP is not configured to send mail';
208 }
209
210 restore_error_handler();
211 ini_set( 'html_errors', $html_errors );
212
213 if ( $wgErrorString ) {
214 wfDebug( "Error sending mail: $wgErrorString\n" );
215 return new WikiError( $wgErrorString );
216 } elseif (! $sent) {
217 //mail function only tells if there's an error
218 wfDebug( "Error sending mail\n" );
219 return new WikiError( 'mailer error' );
220 } else {
221 return true;
222 }
223 }
224 }
225
226 /**
227 * Get the mail error message in global $wgErrorString
228 *
229 * @param $code Integer: error number
230 * @param $string String: error message
231 */
232 static function errorHandler( $code, $string ) {
233 global $wgErrorString;
234 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
235 }
236
237 /**
238 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
239 */
240 static function rfc822Phrase( $phrase ) {
241 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
242 return '"' . $phrase . '"';
243 }
244 }
245
246 /**
247 * This module processes the email notifications when the current page is
248 * changed. It looks up the table watchlist to find out which users are watching
249 * that page.
250 *
251 * The current implementation sends independent emails to each watching user for
252 * the following reason:
253 *
254 * - Each watching user will be notified about the page edit time expressed in
255 * his/her local time (UTC is shown additionally). To achieve this, we need to
256 * find the individual timeoffset of each watching user from the preferences..
257 *
258 * Suggested improvement to slack down the number of sent emails: We could think
259 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
260 * same timeoffset in their preferences.
261 *
262 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
263 *
264 *
265 */
266 class EmailNotification {
267 private $to, $subject, $body, $replyto, $from;
268 private $user, $title, $timestamp, $summary, $minorEdit, $oldid, $composed_common, $editor;
269 private $mailTargets = array();
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 $latestTimestamp = Revision::getTimestampFromId( $title, $title->getLatestRevID() );
408 // Do not update watchlists if something else already did.
409 if ( $timestamp >= $latestTimestamp && ($wgShowUpdatedMarker || $wgEnotifWatchlist) ) {
410 # Mark the changed watch-listed page with a timestamp, so that the page is
411 # listed with an "updated since your last visit" icon in the watch list. Do
412 # not do this to users for their own edits.
413 $dbw = wfGetDB( DB_MASTER );
414 $dbw->update( 'watchlist',
415 array( /* SET */
416 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
417 ), array( /* WHERE */
418 'wl_title' => $title->getDBkey(),
419 'wl_namespace' => $title->getNamespace(),
420 'wl_notificationtimestamp IS NULL',
421 'wl_user != ' . $editor->getID()
422 ), __METHOD__
423 );
424 }
425
426 wfProfileOut( __METHOD__ );
427 } # function NotifyOnChange
428
429 /**
430 * @private
431 */
432 function composeCommonMailtext() {
433 global $wgPasswordSender, $wgNoReplyAddress;
434 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
435 global $wgEnotifImpersonal, $wgEnotifUseRealName;
436
437 $this->composed_common = true;
438
439 $summary = ($this->summary == '') ? ' - ' : $this->summary;
440 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
441
442 # You as the WikiAdmin and Sysops can make use of plenty of
443 # named variables when composing your notification emails while
444 # simply editing the Meta pages
445
446 $subject = wfMsgForContent( 'enotif_subject' );
447 $body = wfMsgForContent( 'enotif_body' );
448 $from = ''; /* fail safe */
449 $replyto = ''; /* fail safe */
450 $keys = array();
451
452 # regarding the use of oldid as an indicator for the last visited version, see also
453 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
454 # However, in the case of a new page which is already watched, we have no previous version to compare
455 if( $this->oldid ) {
456 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
457 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
458 $keys['$OLDID'] = $this->oldid;
459 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
460 } else {
461 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
462 # clear $OLDID placeholder in the message template
463 $keys['$OLDID'] = '';
464 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
465 }
466
467 if ($wgEnotifImpersonal && $this->oldid)
468 /*
469 * For impersonal mail, show a diff link to the last
470 * revision.
471 */
472 $keys['$NEWPAGE'] = wfMsgForContent('enotif_lastdiff',
473 $this->title->getFullURL("oldid={$this->oldid}&diff=prev"));
474
475 $body = strtr( $body, $keys );
476 $pagetitle = $this->title->getPrefixedText();
477 $keys['$PAGETITLE'] = $pagetitle;
478 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
479
480 $keys['$PAGEMINOREDIT'] = $medit;
481 $keys['$PAGESUMMARY'] = $summary;
482
483 $subject = strtr( $subject, $keys );
484
485 # Reveal the page editor's address as REPLY-TO address only if
486 # the user has not opted-out and the option is enabled at the
487 # global configuration level.
488 $editor = $this->editor;
489 $name = $wgEnotifUseRealName ? $editor->getRealName() : $editor->getName();
490 $adminAddress = new MailAddress( $wgPasswordSender, 'WikiAdmin' );
491 $editorAddress = new MailAddress( $editor );
492 if( $wgEnotifRevealEditorAddress
493 && ( $editor->getEmail() != '' )
494 && $editor->getOption( 'enotifrevealaddr' ) ) {
495 if( $wgEnotifFromEditor ) {
496 $from = $editorAddress;
497 } else {
498 $from = $adminAddress;
499 $replyto = $editorAddress;
500 }
501 } else {
502 $from = $adminAddress;
503 $replyto = new MailAddress( $wgNoReplyAddress );
504 }
505
506 if( $editor->isIP( $name ) ) {
507 #real anon (user:xxx.xxx.xxx.xxx)
508 $utext = wfMsgForContent('enotif_anon_editor', $name);
509 $subject = str_replace('$PAGEEDITOR', $utext, $subject);
510 $keys['$PAGEEDITOR'] = $utext;
511 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
512 } else {
513 $subject = str_replace('$PAGEEDITOR', $name, $subject);
514 $keys['$PAGEEDITOR'] = $name;
515 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
516 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
517 }
518 $userPage = $editor->getUserPage();
519 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
520 $body = strtr( $body, $keys );
521 $body = wordwrap( $body, 72 );
522
523 # now save this as the constant user-independent part of the message
524 $this->from = $from;
525 $this->replyto = $replyto;
526 $this->subject = $subject;
527 $this->body = $body;
528 }
529
530 /**
531 * Compose a mail to a given user and either queue it for sending, or send it now,
532 * depending on settings.
533 *
534 * Call sendMails() to send any mails that were queued.
535 */
536 function compose( $user ) {
537 global $wgEnotifImpersonal;
538
539 if ( !$this->composed_common )
540 $this->composeCommonMailtext();
541
542 if ( $wgEnotifImpersonal ) {
543 $this->mailTargets[] = new MailAddress( $user );
544 } else {
545 $this->sendPersonalised( $user );
546 }
547 }
548
549 /**
550 * Send any queued mails
551 */
552 function sendMails() {
553 global $wgEnotifImpersonal;
554 if ( $wgEnotifImpersonal ) {
555 $this->sendImpersonal( $this->mailTargets );
556 }
557 }
558
559 /**
560 * Does the per-user customizations to a notification e-mail (name,
561 * timestamp in proper timezone, etc) and sends it out.
562 * Returns true if the mail was sent successfully.
563 *
564 * @param User $watchingUser
565 * @param object $mail
566 * @return bool
567 * @private
568 */
569 function sendPersonalised( $watchingUser ) {
570 global $wgLang, $wgEnotifUseRealName;
571 // From the PHP manual:
572 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
573 // The mail command will not parse this properly while talking with the MTA.
574 $to = new MailAddress( $watchingUser );
575 $name = $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName();
576 $body = str_replace( '$WATCHINGUSERNAME', $name , $this->body );
577
578 $timecorrection = $watchingUser->getOption( 'timecorrection' );
579
580 # $PAGEEDITDATE is the time and date of the page change
581 # expressed in terms of individual local time of the notification
582 # recipient, i.e. watching user
583 $body = str_replace('$PAGEEDITDATE',
584 $wgLang->timeanddate( $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 $wgLang;
596
597 if (empty($addresses))
598 return;
599
600 $body = str_replace(
601 array( '$WATCHINGUSERNAME',
602 '$PAGEEDITDATE'),
603 array( wfMsgForContent('enotif_impersonal_salutation'),
604 $wgLang->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 }