EmailNotification.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. * @author Luke Welling lwelling@wikimedia.org
  25. */
  26. use MediaWiki\Linker\LinkTarget;
  27. use MediaWiki\MediaWikiServices;
  28. /**
  29. * This module processes the email notifications when the current page is
  30. * changed. It looks up the table watchlist to find out which users are watching
  31. * that page.
  32. *
  33. * The current implementation sends independent emails to each watching user for
  34. * the following reason:
  35. *
  36. * - Each watching user will be notified about the page edit time expressed in
  37. * his/her local time (UTC is shown additionally). To achieve this, we need to
  38. * find the individual timeoffset of each watching user from the preferences..
  39. *
  40. * Suggested improvement to slack down the number of sent emails: We could think
  41. * of sending out bulk mails (bcc:user1,user2...) for all these users having the
  42. * same timeoffset in their preferences.
  43. *
  44. * Visit the documentation pages under
  45. * https://www.mediawiki.org/wiki/Help:Watching_pages
  46. */
  47. class EmailNotification {
  48. /**
  49. * Notification is due to user's user talk being edited
  50. */
  51. const USER_TALK = 'user_talk';
  52. /**
  53. * Notification is due to a watchlisted page being edited
  54. */
  55. const WATCHLIST = 'watchlist';
  56. /**
  57. * Notification because user is notified for all changes
  58. */
  59. const ALL_CHANGES = 'all_changes';
  60. protected $subject, $body, $replyto, $from;
  61. protected $timestamp, $summary, $minorEdit, $oldid, $composed_common, $pageStatus;
  62. protected $mailTargets = [];
  63. /**
  64. * @var Title
  65. */
  66. protected $title;
  67. /**
  68. * @var User
  69. */
  70. protected $editor;
  71. /**
  72. * @deprecated since 1.27 use WatchedItemStore::updateNotificationTimestamp directly
  73. *
  74. * @param User $editor The editor that triggered the update. Their notification
  75. * timestamp will not be updated(they have already seen it)
  76. * @param LinkTarget $linkTarget The link target of the title to update timestamps for
  77. * @param string $timestamp Set the update timestamp to this value
  78. *
  79. * @return int[] Array of user IDs
  80. */
  81. public static function updateWatchlistTimestamp(
  82. User $editor,
  83. LinkTarget $linkTarget,
  84. $timestamp
  85. ) {
  86. wfDeprecated( __METHOD__, '1.27' );
  87. $config = RequestContext::getMain()->getConfig();
  88. if ( !$config->get( 'EnotifWatchlist' ) && !$config->get( 'ShowUpdatedMarker' ) ) {
  89. return [];
  90. }
  91. return MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
  92. $editor,
  93. $linkTarget,
  94. $timestamp
  95. );
  96. }
  97. /**
  98. * Send emails corresponding to the user $editor editing the page $title.
  99. *
  100. * May be deferred via the job queue.
  101. *
  102. * @param User $editor
  103. * @param Title $title
  104. * @param string $timestamp
  105. * @param string $summary
  106. * @param bool $minorEdit
  107. * @param bool $oldid (default: false)
  108. * @param string $pageStatus (default: 'changed')
  109. */
  110. public function notifyOnPageChange( $editor, $title, $timestamp, $summary,
  111. $minorEdit, $oldid = false, $pageStatus = 'changed'
  112. ) {
  113. global $wgEnotifMinorEdits, $wgUsersNotifiedOnAllChanges, $wgEnotifUserTalk;
  114. if ( $title->getNamespace() < 0 ) {
  115. return;
  116. }
  117. // update wl_notificationtimestamp for watchers
  118. $config = RequestContext::getMain()->getConfig();
  119. $watchers = [];
  120. if ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) ) {
  121. $watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
  122. $editor,
  123. $title,
  124. $timestamp
  125. );
  126. }
  127. $sendEmail = true;
  128. // $watchers deals with $wgEnotifWatchlist.
  129. // If nobody is watching the page, and there are no users notified on all changes
  130. // don't bother creating a job/trying to send emails, unless it's a
  131. // talk page with an applicable notification.
  132. if ( !count( $watchers ) && !count( $wgUsersNotifiedOnAllChanges ) ) {
  133. $sendEmail = false;
  134. // Only send notification for non minor edits, unless $wgEnotifMinorEdits
  135. if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
  136. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  137. if ( $wgEnotifUserTalk
  138. && $isUserTalkPage
  139. && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
  140. ) {
  141. $sendEmail = true;
  142. }
  143. }
  144. }
  145. if ( $sendEmail ) {
  146. JobQueueGroup::singleton()->lazyPush( new EnotifNotifyJob(
  147. $title,
  148. [
  149. 'editor' => $editor->getName(),
  150. 'editorID' => $editor->getId(),
  151. 'timestamp' => $timestamp,
  152. 'summary' => $summary,
  153. 'minorEdit' => $minorEdit,
  154. 'oldid' => $oldid,
  155. 'watchers' => $watchers,
  156. 'pageStatus' => $pageStatus
  157. ]
  158. ) );
  159. }
  160. }
  161. /**
  162. * Immediate version of notifyOnPageChange().
  163. *
  164. * Send emails corresponding to the user $editor editing the page $title.
  165. *
  166. * @note Do not call directly. Use notifyOnPageChange so that wl_notificationtimestamp is updated.
  167. * @param User $editor
  168. * @param Title $title
  169. * @param string $timestamp Edit timestamp
  170. * @param string $summary Edit summary
  171. * @param bool $minorEdit
  172. * @param int $oldid Revision ID
  173. * @param array $watchers Array of user IDs
  174. * @param string $pageStatus
  175. * @throws MWException
  176. */
  177. public function actuallyNotifyOnPageChange( $editor, $title, $timestamp, $summary, $minorEdit,
  178. $oldid, $watchers, $pageStatus = 'changed' ) {
  179. # we use $wgPasswordSender as sender's address
  180. global $wgUsersNotifiedOnAllChanges;
  181. global $wgEnotifWatchlist, $wgBlockDisablesLogin;
  182. global $wgEnotifMinorEdits, $wgEnotifUserTalk;
  183. # The following code is only run, if several conditions are met:
  184. # 1. EmailNotification for pages (other than user_talk pages) must be enabled
  185. # 2. minor edits (changes) are only regarded if the global flag indicates so
  186. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  187. $this->title = $title;
  188. $this->timestamp = $timestamp;
  189. $this->summary = $summary;
  190. $this->minorEdit = $minorEdit;
  191. $this->oldid = $oldid;
  192. $this->editor = $editor;
  193. $this->composed_common = false;
  194. $this->pageStatus = $pageStatus;
  195. $formattedPageStatus = [ 'deleted', 'created', 'moved', 'restored', 'changed' ];
  196. Hooks::run( 'UpdateUserMailerFormattedPageStatus', [ &$formattedPageStatus ] );
  197. if ( !in_array( $this->pageStatus, $formattedPageStatus ) ) {
  198. throw new MWException( 'Not a valid page status!' );
  199. }
  200. $userTalkId = false;
  201. if ( !$minorEdit || ( $wgEnotifMinorEdits && !$editor->isAllowed( 'nominornewtalk' ) ) ) {
  202. if ( $wgEnotifUserTalk
  203. && $isUserTalkPage
  204. && $this->canSendUserTalkEmail( $editor, $title, $minorEdit )
  205. ) {
  206. $targetUser = User::newFromName( $title->getText() );
  207. $this->compose( $targetUser, self::USER_TALK );
  208. $userTalkId = $targetUser->getId();
  209. }
  210. if ( $wgEnotifWatchlist ) {
  211. // Send updates to watchers other than the current editor
  212. // and don't send to watchers who are blocked and cannot login
  213. $userArray = UserArray::newFromIDs( $watchers );
  214. foreach ( $userArray as $watchingUser ) {
  215. if ( $watchingUser->getOption( 'enotifwatchlistpages' )
  216. && ( !$minorEdit || $watchingUser->getOption( 'enotifminoredits' ) )
  217. && $watchingUser->isEmailConfirmed()
  218. && $watchingUser->getId() != $userTalkId
  219. && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
  220. && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
  221. ) {
  222. if ( Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) {
  223. $this->compose( $watchingUser, self::WATCHLIST );
  224. }
  225. }
  226. }
  227. }
  228. }
  229. foreach ( $wgUsersNotifiedOnAllChanges as $name ) {
  230. if ( $editor->getName() == $name ) {
  231. // No point notifying the user that actually made the change!
  232. continue;
  233. }
  234. $user = User::newFromName( $name );
  235. $this->compose( $user, self::ALL_CHANGES );
  236. }
  237. $this->sendMails();
  238. }
  239. /**
  240. * @param User $editor
  241. * @param Title $title
  242. * @param bool $minorEdit
  243. * @return bool
  244. */
  245. private function canSendUserTalkEmail( $editor, $title, $minorEdit ) {
  246. global $wgEnotifUserTalk, $wgBlockDisablesLogin;
  247. $isUserTalkPage = ( $title->getNamespace() == NS_USER_TALK );
  248. if ( $wgEnotifUserTalk && $isUserTalkPage ) {
  249. $targetUser = User::newFromName( $title->getText() );
  250. if ( !$targetUser || $targetUser->isAnon() ) {
  251. wfDebug( __METHOD__ . ": user talk page edited, but user does not exist\n" );
  252. } elseif ( $targetUser->getId() == $editor->getId() ) {
  253. wfDebug( __METHOD__ . ": user edited their own talk page, no notification sent\n" );
  254. } elseif ( $wgBlockDisablesLogin && $targetUser->isBlocked() ) {
  255. wfDebug( __METHOD__ . ": talk page owner is blocked and cannot login, no notification sent\n" );
  256. } elseif ( $targetUser->getOption( 'enotifusertalkpages' )
  257. && ( !$minorEdit || $targetUser->getOption( 'enotifminoredits' ) )
  258. ) {
  259. if ( !$targetUser->isEmailConfirmed() ) {
  260. wfDebug( __METHOD__ . ": talk page owner doesn't have validated email\n" );
  261. } elseif ( !Hooks::run( 'AbortTalkPageEmailNotification', [ $targetUser, $title ] ) ) {
  262. wfDebug( __METHOD__ . ": talk page update notification is aborted for this user\n" );
  263. } else {
  264. wfDebug( __METHOD__ . ": sending talk page update notification\n" );
  265. return true;
  266. }
  267. } else {
  268. wfDebug( __METHOD__ . ": talk page owner doesn't want notifications\n" );
  269. }
  270. }
  271. return false;
  272. }
  273. /**
  274. * Generate the generic "this page has been changed" e-mail text.
  275. */
  276. private function composeCommonMailtext() {
  277. global $wgPasswordSender, $wgNoReplyAddress;
  278. global $wgEnotifFromEditor, $wgEnotifRevealEditorAddress;
  279. global $wgEnotifImpersonal, $wgEnotifUseRealName;
  280. $this->composed_common = true;
  281. # You as the WikiAdmin and Sysops can make use of plenty of
  282. # named variables when composing your notification emails while
  283. # simply editing the Meta pages
  284. $keys = [];
  285. $postTransformKeys = [];
  286. $pageTitleUrl = $this->title->getCanonicalURL();
  287. $pageTitle = $this->title->getPrefixedText();
  288. if ( $this->oldid ) {
  289. // Always show a link to the diff which triggered the mail. See T34210.
  290. $keys['$NEWPAGE'] = "\n\n" . wfMessage( 'enotif_lastdiff',
  291. $this->title->getCanonicalURL( [ 'diff' => 'next', 'oldid' => $this->oldid ] ) )
  292. ->inContentLanguage()->text();
  293. if ( !$wgEnotifImpersonal ) {
  294. // For personal mail, also show a link to the diff of all changes
  295. // since last visited.
  296. $keys['$NEWPAGE'] .= "\n\n" . wfMessage( 'enotif_lastvisited',
  297. $this->title->getCanonicalURL( [ 'diff' => '0', 'oldid' => $this->oldid ] ) )
  298. ->inContentLanguage()->text();
  299. }
  300. $keys['$OLDID'] = $this->oldid;
  301. // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
  302. $keys['$CHANGEDORCREATED'] = wfMessage( 'changed' )->inContentLanguage()->text();
  303. } else {
  304. # clear $OLDID placeholder in the message template
  305. $keys['$OLDID'] = '';
  306. $keys['$NEWPAGE'] = '';
  307. // Deprecated since MediaWiki 1.21, not used by default. Kept for backwards-compatibility.
  308. $keys['$CHANGEDORCREATED'] = wfMessage( 'created' )->inContentLanguage()->text();
  309. }
  310. $keys['$PAGETITLE'] = $this->title->getPrefixedText();
  311. $keys['$PAGETITLE_URL'] = $this->title->getCanonicalURL();
  312. $keys['$PAGEMINOREDIT'] = $this->minorEdit ?
  313. wfMessage( 'enotif_minoredit' )->inContentLanguage()->text() : '';
  314. $keys['$UNWATCHURL'] = $this->title->getCanonicalURL( 'action=unwatch' );
  315. if ( $this->editor->isAnon() ) {
  316. # real anon (user:xxx.xxx.xxx.xxx)
  317. $keys['$PAGEEDITOR'] = wfMessage( 'enotif_anon_editor', $this->editor->getName() )
  318. ->inContentLanguage()->text();
  319. $keys['$PAGEEDITOR_EMAIL'] = wfMessage( 'noemailtitle' )->inContentLanguage()->text();
  320. } else {
  321. $keys['$PAGEEDITOR'] = $wgEnotifUseRealName && $this->editor->getRealName() !== ''
  322. ? $this->editor->getRealName() : $this->editor->getName();
  323. $emailPage = SpecialPage::getSafeTitleFor( 'Emailuser', $this->editor->getName() );
  324. $keys['$PAGEEDITOR_EMAIL'] = $emailPage->getCanonicalURL();
  325. }
  326. $keys['$PAGEEDITOR_WIKI'] = $this->editor->getUserPage()->getCanonicalURL();
  327. $keys['$HELPPAGE'] = wfExpandUrl(
  328. Skin::makeInternalOrExternalUrl( wfMessage( 'helppage' )->inContentLanguage()->text() )
  329. );
  330. # Replace this after transforming the message, T37019
  331. $postTransformKeys['$PAGESUMMARY'] = $this->summary == '' ? ' - ' : $this->summary;
  332. // Now build message's subject and body
  333. // Messages:
  334. // enotif_subject_deleted, enotif_subject_created, enotif_subject_moved,
  335. // enotif_subject_restored, enotif_subject_changed
  336. $this->subject = wfMessage( 'enotif_subject_' . $this->pageStatus )->inContentLanguage()
  337. ->params( $pageTitle, $keys['$PAGEEDITOR'] )->text();
  338. // Messages:
  339. // enotif_body_intro_deleted, enotif_body_intro_created, enotif_body_intro_moved,
  340. // enotif_body_intro_restored, enotif_body_intro_changed
  341. $keys['$PAGEINTRO'] = wfMessage( 'enotif_body_intro_' . $this->pageStatus )
  342. ->inContentLanguage()->params( $pageTitle, $keys['$PAGEEDITOR'], $pageTitleUrl )
  343. ->text();
  344. $body = wfMessage( 'enotif_body' )->inContentLanguage()->plain();
  345. $body = strtr( $body, $keys );
  346. $body = MessageCache::singleton()->transform( $body, false, null, $this->title );
  347. $this->body = wordwrap( strtr( $body, $postTransformKeys ), 72 );
  348. # Reveal the page editor's address as REPLY-TO address only if
  349. # the user has not opted-out and the option is enabled at the
  350. # global configuration level.
  351. $adminAddress = new MailAddress( $wgPasswordSender,
  352. wfMessage( 'emailsender' )->inContentLanguage()->text() );
  353. if ( $wgEnotifRevealEditorAddress
  354. && ( $this->editor->getEmail() != '' )
  355. && $this->editor->getOption( 'enotifrevealaddr' )
  356. ) {
  357. $editorAddress = MailAddress::newFromUser( $this->editor );
  358. if ( $wgEnotifFromEditor ) {
  359. $this->from = $editorAddress;
  360. } else {
  361. $this->from = $adminAddress;
  362. $this->replyto = $editorAddress;
  363. }
  364. } else {
  365. $this->from = $adminAddress;
  366. $this->replyto = new MailAddress( $wgNoReplyAddress );
  367. }
  368. }
  369. /**
  370. * Compose a mail to a given user and either queue it for sending, or send it now,
  371. * depending on settings.
  372. *
  373. * Call sendMails() to send any mails that were queued.
  374. * @param User $user
  375. * @param string $source
  376. */
  377. function compose( $user, $source ) {
  378. global $wgEnotifImpersonal;
  379. if ( !$this->composed_common ) {
  380. $this->composeCommonMailtext();
  381. }
  382. if ( $wgEnotifImpersonal ) {
  383. $this->mailTargets[] = MailAddress::newFromUser( $user );
  384. } else {
  385. $this->sendPersonalised( $user, $source );
  386. }
  387. }
  388. /**
  389. * Send any queued mails
  390. */
  391. function sendMails() {
  392. global $wgEnotifImpersonal;
  393. if ( $wgEnotifImpersonal ) {
  394. $this->sendImpersonal( $this->mailTargets );
  395. }
  396. }
  397. /**
  398. * Does the per-user customizations to a notification e-mail (name,
  399. * timestamp in proper timezone, etc) and sends it out.
  400. * Returns true if the mail was sent successfully.
  401. *
  402. * @param User $watchingUser
  403. * @param string $source
  404. * @return bool
  405. * @private
  406. */
  407. function sendPersonalised( $watchingUser, $source ) {
  408. global $wgEnotifUseRealName;
  409. // From the PHP manual:
  410. // Note: The to parameter cannot be an address in the form of
  411. // "Something <someone@example.com>". The mail command will not parse
  412. // this properly while talking with the MTA.
  413. $to = MailAddress::newFromUser( $watchingUser );
  414. # $PAGEEDITDATE is the time and date of the page change
  415. # expressed in terms of individual local time of the notification
  416. # recipient, i.e. watching user
  417. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  418. $body = str_replace(
  419. [ '$WATCHINGUSERNAME',
  420. '$PAGEEDITDATE',
  421. '$PAGEEDITTIME' ],
  422. [ $wgEnotifUseRealName && $watchingUser->getRealName() !== ''
  423. ? $watchingUser->getRealName() : $watchingUser->getName(),
  424. $contLang->userDate( $this->timestamp, $watchingUser ),
  425. $contLang->userTime( $this->timestamp, $watchingUser ) ],
  426. $this->body );
  427. $headers = [];
  428. if ( $source === self::WATCHLIST ) {
  429. $headers['List-Help'] = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Watchlist';
  430. }
  431. return UserMailer::send( $to, $this->from, $this->subject, $body, [
  432. 'replyTo' => $this->replyto,
  433. 'headers' => $headers,
  434. ] );
  435. }
  436. /**
  437. * Same as sendPersonalised but does impersonal mail suitable for bulk
  438. * mailing. Takes an array of MailAddress objects.
  439. * @param MailAddress[] $addresses
  440. * @return Status|null
  441. */
  442. function sendImpersonal( $addresses ) {
  443. if ( empty( $addresses ) ) {
  444. return null;
  445. }
  446. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  447. $body = str_replace(
  448. [ '$WATCHINGUSERNAME',
  449. '$PAGEEDITDATE',
  450. '$PAGEEDITTIME' ],
  451. [ wfMessage( 'enotif_impersonal_salutation' )->inContentLanguage()->text(),
  452. $contLang->date( $this->timestamp, false, false ),
  453. $contLang->time( $this->timestamp, false, false ) ],
  454. $this->body );
  455. return UserMailer::send( $addresses, $this->from, $this->subject, $body, [
  456. 'replyTo' => $this->replyto,
  457. ] );
  458. }
  459. }