PHPDocumentor [http://en.wikipedia.org/wiki/PhpDocumentor] documentation tweaking...
[lhc/web/wiklou.git] / includes / UserMailer.php
1 <?php
2 /**
3 * UserMailer.php
4 * Copyright (C) 2004 Thomas Gries <mail@tgries.de>
5 * http://www.mediawiki.org/
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @author <brion@pobox.com>
23 * @author <mail@tgries.de>
24 *
25 */
26
27 /**
28 * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
29 */
30 function wfRFC822Phrase( $phrase ) {
31 $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
32 return '"' . $phrase . '"';
33 }
34
35 /**
36 * Stores a single person's name and email address.
37 * These are passed in via the constructor, and will be returned in SMTP
38 * header format when requested.
39 */
40 class MailAddress {
41 /**
42 * @param mixed $address String with an email address, or a User object
43 * @param string $name Human-readable name if a string address is given
44 */
45 function __construct( $address, $name=null ) {
46 if( is_object( $address ) && $address instanceof User ) {
47 $this->address = $address->getEmail();
48 $this->name = $address->getName();
49 } else {
50 $this->address = strval( $address );
51 $this->name = strval( $name );
52 }
53 }
54
55 /**
56 * Return formatted and quoted address to insert into SMTP headers
57 * @return string
58 */
59 function toString() {
60 # PHP's mail() implementation under Windows is somewhat shite, and
61 # can't handle "Joe Bloggs <joe@bloggs.com>" format email addresses,
62 # so don't bother generating them
63 if( $this->name != '' && !wfIsWindows() ) {
64 $quoted = wfQuotedPrintable( $this->name );
65 if( strpos( $quoted, '.' ) !== false ) {
66 $quoted = '"' . $quoted . '"';
67 }
68 return "$quoted <{$this->address}>";
69 } else {
70 return $this->address;
71 }
72 }
73 }
74
75 /**
76 * This function will perform a direct (authenticated) login to
77 * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
78 * array of parameters. It requires PEAR:Mail to do that.
79 * Otherwise it just uses the standard PHP 'mail' function.
80 *
81 * @param $to MailAddress: recipient's email
82 * @param $from MailAddress: sender's email
83 * @param $subject String: email's subject.
84 * @param $body String: email's text.
85 * @param $replyto String: optional reply-to email (default: null).
86 */
87 function userMailer( $to, $from, $subject, $body, $replyto=null ) {
88 global $wgUser, $wgSMTP, $wgOutputEncoding, $wgErrorString;
89
90 if (is_array( $wgSMTP )) {
91 require_once( 'Mail.php' );
92
93 $timestamp = time();
94 $dest = $to->address;
95
96 $headers['From'] = $from->toString();
97 $headers['To'] = $to->toString();
98 if ( $replyto ) {
99 $headers['Reply-To'] = $replyto->toString();
100 }
101 $headers['Subject'] = wfQuotedPrintable( $subject );
102 $headers['Date'] = date( 'r' );
103 $headers['MIME-Version'] = '1.0';
104 $headers['Content-type'] = 'text/plain; charset='.$wgOutputEncoding;
105 $headers['Content-transfer-encoding'] = '8bit';
106 $headers['Message-ID'] = "<{$timestamp}" . $wgUser->getName() . '@' . $wgSMTP['IDHost'] . '>'; // FIXME
107 $headers['X-Mailer'] = 'MediaWiki mailer';
108
109 // Create the mail object using the Mail::factory method
110 $mail_object =& Mail::factory('smtp', $wgSMTP);
111 if( PEAR::isError( $mail_object ) ) {
112 wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
113 return $mail_object->getMessage();
114 }
115
116 wfDebug( "Sending mail via PEAR::Mail to $dest\n" );
117 $mailResult =& $mail_object->send($dest, $headers, $body);
118
119 # Based on the result return an error string,
120 if ($mailResult === true) {
121 return '';
122 } elseif (is_object($mailResult)) {
123 wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
124 return $mailResult->getMessage();
125 } else {
126 wfDebug( "PEAR::Mail failed, unknown error result\n" );
127 return 'Mail object return unknown error.';
128 }
129 } else {
130 # In the following $headers = expression we removed "Reply-To: {$from}\r\n" , because it is treated differently
131 # (fifth parameter of the PHP mail function, see some lines below)
132
133 # Line endings need to be different on Unix and Windows due to
134 # the bug described at http://trac.wordpress.org/ticket/2603
135 if ( wfIsWindows() ) {
136 $body = str_replace( "\n", "\r\n", $body );
137 $endl = "\r\n";
138 } else {
139 $endl = "\n";
140 }
141 $headers =
142 "MIME-Version: 1.0$endl" .
143 "Content-type: text/plain; charset={$wgOutputEncoding}$endl" .
144 "Content-Transfer-Encoding: 8bit$endl" .
145 "X-Mailer: MediaWiki mailer$endl".
146 'From: ' . $from->toString();
147 if ($replyto) {
148 $headers .= "{$endl}Reply-To: " . $replyto->toString();
149 }
150
151 $dest = $to->toString();
152
153 $wgErrorString = '';
154 set_error_handler( 'mailErrorHandler' );
155 wfDebug( "Sending mail via internal mail() function to $dest\n" );
156 mail( $dest, wfQuotedPrintable( $subject ), $body, $headers );
157 restore_error_handler();
158
159 if ( $wgErrorString ) {
160 wfDebug( "Error sending mail: $wgErrorString\n" );
161 }
162 return $wgErrorString;
163 }
164 }
165
166 /**
167 * Get the mail error message in global $wgErrorString
168 *
169 * @param $code Integer: error number
170 * @param $string String: error message
171 */
172 function mailErrorHandler( $code, $string ) {
173 global $wgErrorString;
174 $wgErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
175 }
176
177
178 /**
179 * This module processes the email notifications when the current page is
180 * changed. It looks up the table watchlist to find out which users are watching
181 * that page.
182 *
183 * The current implementation sends independent emails to each watching user for
184 * the following reason:
185 *
186 * - Each watching user will be notified about the page edit time expressed in
187 * his/her local time (UTC is shown additionally). To achieve this, we need to
188 * find the individual timeoffset of each watching user from the preferences..
189 *
190 * Suggested improvement to slack down the number of sent emails: We could think
191 * of sending out bulk mails (bcc:user1,user2...) for all these users having the
192 * same timeoffset in their preferences.
193 *
194 * Visit the documentation pages under http://meta.wikipedia.com/Enotif
195 *
196 *
197 */
198 class EmailNotification {
199 /**
200 * @private member variables:
201 */
202 var $to, $subject, $body, $replyto, $from;
203 var $user, $title, $timestamp, $summary, $minorEdit, $oldid;
204
205 /**
206 * @todo document
207 * @param $title Title object
208 * @param $timestamp
209 * @param $summary
210 * @param $minorEdit
211 * @param $oldid (default: false)
212 */
213 function notifyOnPageChange(&$title, $timestamp, $summary, $minorEdit, $oldid=false) {
214
215 # we use $wgEmergencyContact as sender's address
216 global $wgUser, $wgEnotifWatchlist;
217 global $wgEnotifMinorEdits, $wgEnotifUserTalk, $wgShowUpdatedMarker;
218
219 $fname = 'UserMailer::notifyOnPageChange';
220 wfProfileIn( $fname );
221
222 # The following code is only run, if several conditions are met:
223 # 1. EmailNotification for pages (other than user_talk pages) must be enabled
224 # 2. minor edits (changes) are only regarded if the global flag indicates so
225
226 $isUserTalkPage = ($title->getNamespace() == NS_USER_TALK);
227 $enotifusertalkpage = ($isUserTalkPage && $wgEnotifUserTalk);
228 $enotifwatchlistpage = $wgEnotifWatchlist;
229
230 if ( (!$minorEdit || $wgEnotifMinorEdits) ) {
231 if( $wgEnotifWatchlist ) {
232 // Send updates to watchers other than the current editor
233 $userCondition = 'wl_user <> ' . intval( $wgUser->getId() );
234 } elseif( $wgEnotifUserTalk && $title->getNamespace() == NS_USER_TALK ) {
235 $targetUser = User::newFromName( $title->getText() );
236 if( is_null( $targetUser ) ) {
237 wfDebug( "$fname: user-talk-only mode; no such user\n" );
238 $userCondition = false;
239 } elseif( $targetUser->getId() == $wgUser->getId() ) {
240 wfDebug( "$fname: user-talk-only mode; editor is target user\n" );
241 $userCondition = false;
242 } else {
243 // Don't notify anyone other than the owner of the talk page
244 $userCondition = 'wl_user = ' . intval( $targetUser->getId() );
245 }
246 } else {
247 // Notifications disabled
248 $userCondition = false;
249 }
250 if( $userCondition ) {
251 $dbr = wfGetDB( DB_MASTER );
252
253 $res = $dbr->select( 'watchlist', array( 'wl_user' ),
254 array(
255 'wl_title' => $title->getDBkey(),
256 'wl_namespace' => $title->getNamespace(),
257 $userCondition,
258 'wl_notificationtimestamp IS NULL',
259 ), $fname );
260
261 # if anyone is watching ... set up the email message text which is
262 # common for all receipients ...
263 if ( $dbr->numRows( $res ) > 0 ) {
264 $this->title =& $title;
265 $this->timestamp = $timestamp;
266 $this->summary = $summary;
267 $this->minorEdit = $minorEdit;
268 $this->oldid = $oldid;
269
270 $this->composeCommonMailtext();
271 $watchingUser = new User();
272
273 # ... now do for all watching users ... if the options fit
274 for ($i = 1; $i <= $dbr->numRows( $res ); $i++) {
275
276 $wuser = $dbr->fetchObject( $res );
277 $watchingUser->setID($wuser->wl_user);
278
279 if ( ( $enotifwatchlistpage && $watchingUser->getOption('enotifwatchlistpages') ) ||
280 ( $enotifusertalkpage
281 && $watchingUser->getOption('enotifusertalkpages')
282 && $title->equals( $watchingUser->getTalkPage() ) )
283 && (!$minorEdit || ($wgEnotifMinorEdits && $watchingUser->getOption('enotifminoredits') ) )
284 && ($watchingUser->isEmailConfirmed() ) ) {
285 # ... adjust remaining text and page edit time placeholders
286 # which needs to be personalized for each user
287 $this->composeAndSendPersonalisedMail( $watchingUser );
288
289 } # if the watching user has an email address in the preferences
290 }
291 }
292 } # if anyone is watching
293 } # if $wgEnotifWatchlist = true
294
295 if ( $wgShowUpdatedMarker || $wgEnotifWatchlist ) {
296 # mark the changed watch-listed page with a timestamp, so that the page is
297 # listed with an "updated since your last visit" icon in the watch list, ...
298 $dbw = wfGetDB( DB_MASTER );
299 $success = $dbw->update( 'watchlist',
300 array( /* SET */
301 'wl_notificationtimestamp' => $dbw->timestamp($timestamp)
302 ), array( /* WHERE */
303 'wl_title' => $title->getDBkey(),
304 'wl_namespace' => $title->getNamespace(),
305 ), 'UserMailer::NotifyOnChange'
306 );
307 # FIXME what do we do on failure ?
308 }
309 wfProfileOut( $fname );
310 } # function NotifyOnChange
311
312 /**
313 * @private
314 */
315 function composeCommonMailtext() {
316 global $wgUser, $wgEmergencyContact, $wgNoReplyAddress;
317 global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
318
319 $summary = ($this->summary == '') ? ' - ' : $this->summary;
320 $medit = ($this->minorEdit) ? wfMsg( 'minoredit' ) : '';
321
322 # You as the WikiAdmin and Sysops can make use of plenty of
323 # named variables when composing your notification emails while
324 # simply editing the Meta pages
325
326 $subject = wfMsgForContent( 'enotif_subject' );
327 $body = wfMsgForContent( 'enotif_body' );
328 $from = ''; /* fail safe */
329 $replyto = ''; /* fail safe */
330 $keys = array();
331
332 # regarding the use of oldid as an indicator for the last visited version, see also
333 # http://bugzilla.wikipeda.org/show_bug.cgi?id=603 "Delete + undelete cycle doesn't preserve old_id"
334 # However, in the case of a new page which is already watched, we have no previous version to compare
335 if( $this->oldid ) {
336 $difflink = $this->title->getFullUrl( 'diff=0&oldid=' . $this->oldid );
337 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited', $difflink );
338 $keys['$OLDID'] = $this->oldid;
339 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
340 } else {
341 $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
342 # clear $OLDID placeholder in the message template
343 $keys['$OLDID'] = '';
344 $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
345 }
346
347 $body = strtr( $body, $keys );
348 $pagetitle = $this->title->getPrefixedText();
349 $keys['$PAGETITLE'] = $pagetitle;
350 $keys['$PAGETITLE_URL'] = $this->title->getFullUrl();
351
352 $keys['$PAGEMINOREDIT'] = $medit;
353 $keys['$PAGESUMMARY'] = $summary;
354
355 $subject = strtr( $subject, $keys );
356
357 # Reveal the page editor's address as REPLY-TO address only if
358 # the user has not opted-out and the option is enabled at the
359 # global configuration level.
360 $name = $wgUser->getName();
361 $adminAddress = new MailAddress( $wgEmergencyContact, 'WikiAdmin' );
362 $editorAddress = new MailAddress( $wgUser );
363 if( $wgEnotifRevealEditorAddress
364 && ( $wgUser->getEmail() != '' )
365 && $wgUser->getOption( 'enotifrevealaddr' ) ) {
366 if( $wgEnotifFromEditor ) {
367 $from = $editorAddress;
368 } else {
369 $from = $adminAddress;
370 $replyto = $editorAddress;
371 }
372 } else {
373 $from = $adminAddress;
374 $replyto = new MailAddress( $wgNoReplyAddress );
375 }
376
377 if( $wgUser->isIP( $name ) ) {
378 #real anon (user:xxx.xxx.xxx.xxx)
379 $subject = str_replace('$PAGEEDITOR', 'anonymous user '. $name, $subject);
380 $keys['$PAGEEDITOR'] = 'anonymous user ' . $name;
381 $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
382 } else {
383 $subject = str_replace('$PAGEEDITOR', $name, $subject);
384 $keys['$PAGEEDITOR'] = $name;
385 $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $name );
386 $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getFullUrl();
387 }
388 $userPage = $wgUser->getUserPage();
389 $keys['$PAGEEDITOR_WIKI'] = $userPage->getFullUrl();
390 $body = strtr( $body, $keys );
391 $body = wordwrap( $body, 72 );
392
393 # now save this as the constant user-independent part of the message
394 $this->from = $from;
395 $this->replyto = $replyto;
396 $this->subject = $subject;
397 $this->body = $body;
398 }
399
400
401
402 /**
403 * Does the per-user customizations to a notification e-mail (name,
404 * timestamp in proper timezone, etc) and sends it out.
405 * Returns true if the mail was sent successfully.
406 *
407 * @param User $watchingUser
408 * @param object $mail
409 * @return bool
410 * @private
411 */
412 function composeAndSendPersonalisedMail( $watchingUser ) {
413 global $wgLang;
414 // From the PHP manual:
415 // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
416 // The mail command will not parse this properly while talking with the MTA.
417 $to = new MailAddress( $watchingUser );
418 $body = str_replace( '$WATCHINGUSERNAME', $watchingUser->getName() , $this->body );
419
420 $timecorrection = $watchingUser->getOption( 'timecorrection' );
421
422 # $PAGEEDITDATE is the time and date of the page change
423 # expressed in terms of individual local time of the notification
424 # recipient, i.e. watching user
425 $body = str_replace('$PAGEEDITDATE',
426 $wgLang->timeanddate( $this->timestamp, true, false, $timecorrection ),
427 $body);
428
429 $error = userMailer( $to, $this->from, $this->subject, $body, $this->replyto );
430 return ($error == '');
431 }
432
433 } # end of class EmailNotification
434 ?>