PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/UserMailer.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 776 lines | 435 code | 88 blank | 253 comment | 97 complexity | e4fe58106464f2f91805292150a86fc8 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Classes used to send e-mails
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @author <brion@pobox.com>
  22. * @author <mail@tgries.de>
  23. * @author Tim Starling
  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 string|User string with an email address, or a User object
  33. * @param $name String: human-readable name if a string address is given
  34. * @param $realName String: human-readable real name if a string address is given
  35. */
  36. function __construct( $address, $name = null, $realName = null ) {
  37. if ( is_object( $address ) && $address instanceof User ) {
  38. $this->address = $address->getEmail();
  39. $this->name = $address->getName();
  40. $this->realName = $address->getRealName();
  41. } else {
  42. $this->address = strval( $address );
  43. $this->name = strval( $name );
  44. $this->realName = strval( $realName );
  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->address ) {
  56. if ( $this->name != '' && !wfIsWindows() ) {
  57. global $wgEnotifUseRealName;
  58. $name = ( $wgEnotifUseRealName && $this->realName ) ? $this->realName : $this->name;
  59. $quoted = UserMailer::quotedPrintable( $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. } else {
  68. return "";
  69. }
  70. }
  71. function __toString() {
  72. return $this->toString();
  73. }
  74. }
  75. /**
  76. * Collection of static functions for sending mail
  77. */
  78. class UserMailer {
  79. static $mErrorString;
  80. /**
  81. * Send mail using a PEAR mailer
  82. *
  83. * @param $mailer
  84. * @param $dest
  85. * @param $headers
  86. * @param $body
  87. *
  88. * @return Status
  89. */
  90. protected static function sendWithPear( $mailer, $dest, $headers, $body ) {
  91. $mailResult = $mailer->send( $dest, $headers, $body );
  92. # Based on the result return an error string,
  93. if ( PEAR::isError( $mailResult ) ) {
  94. wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" );
  95. return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() );
  96. } else {
  97. return Status::newGood();
  98. }
  99. }
  100. /**
  101. * Creates a single string from an associative array
  102. *
  103. * @param $headers Associative Array: keys are header field names,
  104. * values are ... values.
  105. * @param $endl String: The end of line character. Defaults to "\n"
  106. * @return String
  107. */
  108. static function arrayToHeaderString( $headers, $endl = "\n" ) {
  109. foreach( $headers as $name => $value ) {
  110. $string[] = "$name: $value";
  111. }
  112. return implode( $endl, $string );
  113. }
  114. /**
  115. * Create a value suitable for the MessageId Header
  116. *
  117. * @return String
  118. */
  119. static function makeMsgId() {
  120. global $wgSMTP, $wgServer;
  121. $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */
  122. if ( is_array($wgSMTP) && isset($wgSMTP['IDHost']) && $wgSMTP['IDHost'] ) {
  123. $domain = $wgSMTP['IDHost'];
  124. } else {
  125. $url = wfParseUrl($wgServer);
  126. $domain = $url['host'];
  127. }
  128. return "<$msgid@$domain>";
  129. }
  130. /**
  131. * This function will perform a direct (authenticated) login to
  132. * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
  133. * array of parameters. It requires PEAR:Mail to do that.
  134. * Otherwise it just uses the standard PHP 'mail' function.
  135. *
  136. * @param $to MailAddress: recipient's email (or an array of them)
  137. * @param $from MailAddress: sender's email
  138. * @param $subject String: email's subject.
  139. * @param $body String: email's text.
  140. * @param $replyto MailAddress: optional reply-to email (default: null).
  141. * @param $contentType String: optional custom Content-Type (default: text/plain; charset=UTF-8)
  142. * @return Status object
  143. */
  144. public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) {
  145. global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
  146. if ( !is_array( $to ) ) {
  147. $to = array( $to );
  148. }
  149. wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" );
  150. # Make sure we have at least one address
  151. $has_address = false;
  152. foreach ( $to as $u ) {
  153. if ( $u->address ) {
  154. $has_address = true;
  155. break;
  156. }
  157. }
  158. if ( !$has_address ) {
  159. return Status::newFatal( 'user-mail-no-addy' );
  160. }
  161. # Forge email headers
  162. # -------------------
  163. #
  164. # WARNING
  165. #
  166. # DO NOT add To: or Subject: headers at this step. They need to be
  167. # handled differently depending upon the mailer we are going to use.
  168. #
  169. # To:
  170. # PHP mail() first argument is the mail receiver. The argument is
  171. # used as a recipient destination and as a To header.
  172. #
  173. # PEAR mailer has a recipient argument which is only used to
  174. # send the mail. If no To header is given, PEAR will set it to
  175. # to 'undisclosed-recipients:'.
  176. #
  177. # NOTE: To: is for presentation, the actual recipient is specified
  178. # by the mailer using the Rcpt-To: header.
  179. #
  180. # Subject:
  181. # PHP mail() second argument to pass the subject, passing a Subject
  182. # as an additional header will result in a duplicate header.
  183. #
  184. # PEAR mailer should be passed a Subject header.
  185. #
  186. # -- hashar 20120218
  187. $headers['From'] = $from->toString();
  188. $headers['Return-Path'] = $from->address;
  189. if ( $replyto ) {
  190. $headers['Reply-To'] = $replyto->toString();
  191. }
  192. $headers['Date'] = date( 'r' );
  193. $headers['MIME-Version'] = '1.0';
  194. $headers['Content-type'] = ( is_null( $contentType ) ?
  195. 'text/plain; charset=UTF-8' : $contentType );
  196. $headers['Content-transfer-encoding'] = '8bit';
  197. $headers['Message-ID'] = self::makeMsgId();
  198. $headers['X-Mailer'] = 'MediaWiki mailer';
  199. $ret = wfRunHooks( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) );
  200. if ( $ret === false ) {
  201. return Status::newGood();
  202. } elseif ( $ret !== true ) {
  203. return Status::newFatal( 'php-mail-error', $ret );
  204. }
  205. if ( is_array( $wgSMTP ) ) {
  206. #
  207. # PEAR MAILER
  208. #
  209. if ( function_exists( 'stream_resolve_include_path' ) ) {
  210. $found = stream_resolve_include_path( 'Mail.php' );
  211. } else {
  212. $found = Fallback::stream_resolve_include_path( 'Mail.php' );
  213. }
  214. if ( !$found ) {
  215. throw new MWException( 'PEAR mail package is not installed' );
  216. }
  217. require_once( 'Mail.php' );
  218. wfSuppressWarnings();
  219. // Create the mail object using the Mail::factory method
  220. $mail_object =& Mail::factory( 'smtp', $wgSMTP );
  221. if ( PEAR::isError( $mail_object ) ) {
  222. wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" );
  223. wfRestoreWarnings();
  224. return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() );
  225. }
  226. wfDebug( "Sending mail via PEAR::Mail\n" );
  227. $headers['Subject'] = self::quotedPrintable( $subject );
  228. # When sending only to one recipient, shows it its email using To:
  229. if ( count( $to ) == 1 ) {
  230. $headers['To'] = $to[0]->toString();
  231. }
  232. # Split jobs since SMTP servers tends to limit the maximum
  233. # number of possible recipients.
  234. $chunks = array_chunk( $to, $wgEnotifMaxRecips );
  235. foreach ( $chunks as $chunk ) {
  236. $status = self::sendWithPear( $mail_object, $chunk, $headers, $body );
  237. # FIXME : some chunks might be sent while others are not!
  238. if ( !$status->isOK() ) {
  239. wfRestoreWarnings();
  240. return $status;
  241. }
  242. }
  243. wfRestoreWarnings();
  244. return Status::newGood();
  245. } else {
  246. #
  247. # PHP mail()
  248. #
  249. # Line endings need to be different on Unix and Windows due to
  250. # the bug described at http://trac.wordpress.org/ticket/2603
  251. if ( wfIsWindows() ) {
  252. $body = str_replace( "\n", "\r\n", $body );
  253. $endl = "\r\n";
  254. } else {
  255. $endl = "\n";
  256. }
  257. if( count($to) > 1 ) {
  258. $headers['To'] = 'undisclosed-recipients:;';
  259. }
  260. $headers = self::arrayToHeaderString( $headers, $endl );
  261. wfDebug( "Sending mail via internal mail() function\n" );
  262. self::$mErrorString = '';
  263. $html_errors = ini_get( 'html_errors' );
  264. ini_set( 'html_errors', '0' );
  265. set_error_handler( 'UserMailer::errorHandler' );
  266. $safeMode = wfIniGetBool( 'safe_mode' );
  267. foreach ( $to as $recip ) {
  268. if ( $safeMode ) {
  269. $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers );
  270. } else {
  271. $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $wgAdditionalMailParams );
  272. }
  273. }
  274. restore_error_handler();
  275. ini_set( 'html_errors', $html_errors );
  276. if ( self::$mErrorString ) {
  277. wfDebug( "Error sending mail: " . self::$mErrorString . "\n" );
  278. return Status::newFatal( 'php-mail-error', self::$mErrorString );
  279. } elseif ( ! $sent ) {
  280. // mail function only tells if there's an error
  281. wfDebug( "Unknown error sending mail\n" );
  282. return Status::newFatal( 'php-mail-error-unknown' );
  283. } else {
  284. return Status::newGood();
  285. }
  286. }
  287. }
  288. /**
  289. * Set the mail error message in self::$mErrorString
  290. *
  291. * @param $code Integer: error number
  292. * @param $string String: error message
  293. */
  294. static function errorHandler( $code, $string ) {
  295. self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string );
  296. }
  297. /**
  298. * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name
  299. * @param $phrase string
  300. * @return string
  301. */
  302. public static function rfc822Phrase( $phrase ) {
  303. $phrase = strtr( $phrase, array( "\r" => '', "\n" => '', '"' => '' ) );
  304. return '"' . $phrase . '"';
  305. }
  306. /**
  307. * Converts a string into quoted-printable format
  308. * @since 1.17
  309. */
  310. public static function quotedPrintable( $string, $charset = '' ) {
  311. # Probably incomplete; see RFC 2045
  312. if( empty( $charset ) ) {
  313. $charset = 'UTF-8';
  314. }
  315. $charset = strtoupper( $charset );
  316. $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
  317. $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
  318. $replace = $illegal . '\t ?_';
  319. if( !preg_match( "/[$illegal]/", $string ) ) {
  320. return $string;
  321. }
  322. $out = "=?$charset?Q?";
  323. $out .= preg_replace_callback( "/([$replace])/",
  324. array( __CLASS__, 'quotedPrintableCallback' ), $string );
  325. $out .= '?=';
  326. return $out;
  327. }
  328. protected static function quotedPrintableCallback( $matches ) {
  329. return sprintf( "=%02X", ord( $matches[1] ) );
  330. }
  331. }
  332. /**
  333. * This module processes the email notifications when the current page is
  334. * changed. It looks up the table watchlist to find out which users are watching
  335. * that page.
  336. *
  337. * The current implementation sends independent emails to each watching user for
  338. * the following reason:
  339. *
  340. * - Each watching user will be notified about the page edit time expressed in
  341. * his/her local time (UTC is shown additionally). To achieve this, we need to
  342. * find the individual timeoffset of each watching user from the preferences..
  343. *
  344. * Suggested improvement to slack down the number of sent emails: We could think
  345. * of sending out bulk mails (bcc:user1,user2...) for all these users having the
  346. * same timeoffset in their preferences.
  347. *
  348. * Visit the documentation pages under http://meta.wikipedia.com/Enotif
  349. *
  350. *
  351. */
  352. class EmailNotification {
  353. protected $subject, $body, $replyto, $from;
  354. protected $timestamp, $summary, $minorEdit, $oldid, $composed_common;
  355. protected $mailTargets = array();
  356. /**
  357. * @var Title
  358. */
  359. protected $title;
  360. /**
  361. * @var User
  362. */
  363. protected $editor;
  364. /**
  365. * Send emails corresponding to the user $editor editing the page $title.
  366. * Also updates wl_notificationtimestamp.
  367. *
  368. * May be deferred via the job queue.
  369. *
  370. * @param $editor User object
  371. * @param $title Title object
  372. * @param $timestamp
  373. * @param $summary
  374. * @param $minorEdit
  375. * @param $oldid (default: false)
  376. */
  377. public function notifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid = false ) {
  378. global $wgEnotifUseJobQ, $wgEnotifWatchlist, $wgShowUpdatedMarker, $wgEnotifMinorEdits,
  379. $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
  380. if ( $title->getNamespace() < 0 ) {
  381. return;
  382. }
  383. // Build a list of users to notfiy
  384. $watchers = array();
  385. if ( $wgEnotifWatchlist || $wgShowUpdatedMarker ) {
  386. $dbw = wfGetDB( DB_MASTER );
  387. $res = $dbw->select( array( 'watchlist' ),
  388. array( 'wl_user' ),
  389. array(
  390. 'wl_title' => $title->getDBkey(),
  391. 'wl_namespace' => $title->getNamespace(),
  392. 'wl_user != ' . intval( $editor->getID() ),
  393. 'wl_notificationtimestamp IS NULL',
  394. ), __METHOD__
  395. );
  396. foreach ( $res as $row ) {
  397. $watchers[] = intval( $row->wl_user );
  398. }
  399. if ( $watchers ) {
  400. // Update wl_notificationtimestamp for all watching users except
  401. // the editor
  402. $dbw->begin();
  403. $dbw->update( 'watchlist',
  404. array( /* SET */
  405. 'wl_notificationtimestamp' => $dbw->timestamp( $timestamp )
  406. ), array( /* WHERE */
  407. 'wl_title' => $title->getDBkey(),
  408. 'wl_namespace' => $title->getNamespace(),
  409. 'wl_user' => $watchers
  410. ), __METHOD__
  411. );
  412. $dbw->commit();
  413. }
  414. }
  415. $sendEmail = true;
  416. // If nobody is watching the page, and there are no users notified on all changes
  417. // don't bother creating a job/trying to send emails
  418. // $watchers deals with $wgEnotifWatchlist
  419. if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
  420. $sendEmail = false;
  421. // Only send notification for non minor edits, unless $wgEnotifMinorEdits
  422. if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
  423. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  424. if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
  425. $sendEmail = true;
  426. }
  427. }
  428. }
  429. if ( !$sendEmail ) {
  430. return;
  431. }
  432. if ( $wgEnotifUseJobQ ) {
  433. $params = array(
  434. 'editor' => $editor->getName(),
  435. 'editorID' => $editor->getID(),
  436. 'timestamp' => $timestamp,
  437. 'summary' => $summary,
  438. 'minorEdit' => $minorEdit,
  439. 'oldid' => $oldid,
  440. 'watchers' => $watchers
  441. );
  442. $job = new EnotifNotifyJob( $title, $params );
  443. $job->insert();
  444. } else {
  445. $this->actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers );
  446. }
  447. }
  448. /**
  449. * Immediate version of notifyOnPageChange().
  450. *
  451. * Send emails corresponding to the user $editor editing the page $title.
  452. * Also updates wl_notificationtimestamp.
  453. *
  454. * @param $editor User object
  455. * @param $title Title object
  456. * @param $timestamp string Edit timestamp
  457. * @param $summary string Edit summary
  458. * @param $minorEdit bool
  459. * @param $oldid int Revision ID
  460. * @param $watchers array of user IDs
  461. */
  462. public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit, $oldid, $watchers ) {
  463. # we use $wgPasswordSender as sender's address
  464. global $wgEnotifWatchlist;
  465. global $wgEnotifMinorEdits, $wgEnotifUserTalk;
  466. wfProfileIn( __METHOD__ );
  467. # The following code is only run, if several conditions are met:
  468. # 1. EmailNotification for pages (other than user_talk pages) must be enabled
  469. # 2. minor edits (changes) are only regarded if the global flag indicates so
  470. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  471. $this->title = $title;
  472. $this->timestamp = $timestamp;
  473. $this->summary = $summary;
  474. $this->minorEdit = $minorEdit;
  475. $this->oldid = $oldid;
  476. $this->editor = $editor;
  477. $this->composed_common = false;
  478. $userTalkId = false;
  479. if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
  480. if ( $wgEnotifUserTalk && $isUserTalkPage && $this->canSendUserTalkEmail( $editor, $title, $minorEdit ) ) {
  481. $targetUser = User::newFromName( $title->getText() );
  482. $this->compose( $targetUser );
  483. $userTalkId = $targetUser->getId();
  484. }
  485. if ( $wgEnotifWatchlist ) {
  486. // Send updates to watchers other than the current editor
  487. $userArray = UserArray::newFromIDs( $watchers );
  488. foreach ( $userArray as $watchingUser ) {
  489. if ( $watchingUser->getOption( 'enotifwatchlistpages' ) &&
  490. ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) ) &&
  491. $watchingUser->isEmailConfirmed() &&
  492. $watchingUser->getID() != $userTalkId )
  493. {
  494. $this->compose( $watchingUser );
  495. }
  496. }
  497. }
  498. }
  499. global $wgUsersNotifiedOnAllChanges;
  500. foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
  501. if ( $editor->getName() == $name ) {
  502. // No point notifying the user that actually made the change!
  503. continue;
  504. }
  505. $user = User::newFromName( $name );
  506. $this->compose( $user );
  507. }
  508. $this->sendMails();
  509. wfProfileOut( __METHOD__ );
  510. }
  511. /**
  512. * @param $editor User
  513. * @param $title Title bool
  514. * @param $minorEdit
  515. * @return bool
  516. */
  517. private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
  518. global $wgEnotifUserTalk;
  519. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  520. if ( $wgEnotifUserTalk && $isUserTalkPage ) {
  521. $targetUser = User::newFromName( $title->getText() );
  522. if ( !$targetUser || $targetUser->isAnon() ) {
  523. wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
  524. } elseif ( $targetUser->getId() == $editor->getId() ) {
  525. wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
  526. } elseif ( $targetUser->getOption( 'enotifusertalkpages' ) &&
  527. ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) ) )
  528. {
  529. if ( $targetUser->isEmailConfirmed() ) {
  530. wfDebug( __METHOD__ . ": sending talk page update notification\n" );
  531. return true;
  532. } else {
  533. wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
  534. }
  535. } else {
  536. wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
  537. }
  538. }
  539. return false;
  540. }
  541. /**
  542. * Generate the generic "this page has been changed" e-mail text.
  543. */
  544. private function composeCommonMailtext() {
  545. global $wgPasswordSender, $wgPasswordSenderName, $wgNoReplyAddress;
  546. global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
  547. global $wgEnotifImpersonal, $wgEnotifUseRealName;
  548. $this->composed_common = true;
  549. # You as the WikiAdmin and Sysops can make use of plenty of
  550. # named variables when composing your notification emails while
  551. # simply editing the Meta pages
  552. $keys = array();
  553. $postTransformKeys = array();
  554. if ( $this->oldid ) {
  555. if ( $wgEnotifImpersonal ) {
  556. // For impersonal mail, show a diff link to the last revision.
  557. $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastdiff',
  558. $this->title->getCanonicalUrl( 'diff=next&oldid=' . $this->oldid ) );
  559. } else {
  560. $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_lastvisited',
  561. $this->title->getCanonicalUrl( 'diff=0&oldid=' . $this->oldid ) );
  562. }
  563. $keys['$OLDID'] = $this->oldid;
  564. $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'changed' );
  565. } else {
  566. $keys['$NEWPAGE'] = wfMsgForContent( 'enotif_newpagetext' );
  567. # clear $OLDID placeholder in the message template
  568. $keys['$OLDID'] = '';
  569. $keys['$CHANGEDORCREATED'] = wfMsgForContent( 'created' );
  570. }
  571. $keys['$PAGETITLE'] = $this->title->getPrefixedText();
  572. $keys['$PAGETITLE_URL'] = $this->title->getCanonicalUrl();
  573. $keys['$PAGEMINOREDIT'] = $this->minorEdit ? wfMsgForContent( 'minoredit' ) : '';
  574. $keys['$UNWATCHURL'] = $this->title->getCanonicalUrl( 'action=unwatch' );
  575. if ( $this->editor->isAnon() ) {
  576. # real anon (user:xxx.xxx.xxx.xxx)
  577. $keys['$PAGEEDITOR'] = wfMsgForContent( 'enotif_anon_editor', $this->editor->getName() );
  578. $keys['$PAGEEDITOR_EMAIL'] = wfMsgForContent( 'noemailtitle' );
  579. } else {
  580. $keys['$PAGEEDITOR'] = $wgEnotifUseRealName ? $this->editor->getRealName() : $this->editor->getName();
  581. $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
  582. $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalUrl();
  583. }
  584. $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalUrl();
  585. # Replace this after transforming the message, bug 35019
  586. $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
  587. # Now build message's subject and body
  588. $subject = wfMsgExt( 'enotif_subject', 'content' );
  589. $subject = strtr( $subject, $keys );
  590. $subject = MessageCache::singleton()->transform( $subject, false, null, $this->title );
  591. $this->subject = strtr( $subject, $postTransformKeys );
  592. $body = wfMsgExt( 'enotif_body', 'content' );
  593. $body = strtr( $body, $keys );
  594. $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
  595. $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
  596. # Reveal the page editor's address as REPLY-TO address only if
  597. # the user has not opted-out and the option is enabled at the
  598. # global configuration level.
  599. $adminAddress = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
  600. if ( $wgEnotifRevealEditorAddress
  601. && ( $this->editor->getEmail() != '' )
  602. && $this->editor->getOption( 'enotifrevealaddr' ) )
  603. {
  604. $editorAddress = new MailAddress( $this->editor );
  605. if ( $wgEnotifFromEditor ) {
  606. $this->from = $editorAddress;
  607. } else {
  608. $this->from = $adminAddress;
  609. $this->replyto = $editorAddress;
  610. }
  611. } else {
  612. $this->from = $adminAddress;
  613. $this->replyto = new MailAddress( $wgNoReplyAddress );
  614. }
  615. }
  616. /**
  617. * Compose a mail to a given user and either queue it for sending, or send it now,
  618. * depending on settings.
  619. *
  620. * Call sendMails() to send any mails that were queued.
  621. * @param $user User
  622. */
  623. function compose( $user ) {
  624. global $wgEnotifImpersonal;
  625. if ( !$this->composed_common )
  626. $this->composeCommonMailtext();
  627. if ( $wgEnotifImpersonal ) {
  628. $this->mailTargets[] = new MailAddress( $user );
  629. } else {
  630. $this->sendPersonalised( $user );
  631. }
  632. }
  633. /**
  634. * Send any queued mails
  635. */
  636. function sendMails() {
  637. global $wgEnotifImpersonal;
  638. if ( $wgEnotifImpersonal ) {
  639. $this->sendImpersonal( $this->mailTargets );
  640. }
  641. }
  642. /**
  643. * Does the per-user customizations to a notification e-mail (name,
  644. * timestamp in proper timezone, etc) and sends it out.
  645. * Returns true if the mail was sent successfully.
  646. *
  647. * @param $watchingUser User object
  648. * @return Boolean
  649. * @private
  650. */
  651. function sendPersonalised( $watchingUser ) {
  652. global $wgContLang, $wgEnotifUseRealName;
  653. // From the PHP manual:
  654. // Note: The to parameter cannot be an address in the form of "Something <someone@example.com>".
  655. // The mail command will not parse this properly while talking with the MTA.
  656. $to = new MailAddress( $watchingUser );
  657. # $PAGEEDITDATE is the time and date of the page change
  658. # expressed in terms of individual local time of the notification
  659. # recipient, i.e. watching user
  660. $body = str_replace(
  661. array( '$WATCHINGUSERNAME',
  662. '$PAGEEDITDATE',
  663. '$PAGEEDITTIME' ),
  664. array( $wgEnotifUseRealName ? $watchingUser->getRealName() : $watchingUser->getName(),
  665. $wgContLang->userDate( $this->timestamp, $watchingUser ),
  666. $wgContLang->userTime( $this->timestamp, $watchingUser ) ),
  667. $this->body );
  668. return UserMailer::send( $to, $this->from, $this->subject, $body, $this->replyto );
  669. }
  670. /**
  671. * Same as sendPersonalised but does impersonal mail suitable for bulk
  672. * mailing. Takes an array of MailAddress objects.
  673. */
  674. function sendImpersonal( $addresses ) {
  675. global $wgContLang;
  676. if ( empty( $addresses ) )
  677. return;
  678. $body = str_replace(
  679. array( '$WATCHINGUSERNAME',
  680. '$PAGEEDITDATE',
  681. '$PAGEEDITTIME' ),
  682. array( wfMsgForContent( 'enotif_impersonal_salutation' ),
  683. $wgContLang->date( $this->timestamp, false, false ),
  684. $wgContLang->time( $this->timestamp, false, false ) ),
  685. $this->body );
  686. return UserMailer::send( $addresses, $this->from, $this->subject, $body, $this->replyto );
  687. }
  688. } # end of class EmailNotification