ApiFeedWatchlist.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. /**
  3. * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  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. */
  22. use MediaWiki\MediaWikiServices;
  23. /**
  24. * This action allows users to get their watchlist items in RSS/Atom formats.
  25. * When executed, it performs a nested call to the API to get the needed data,
  26. * and formats it in a proper format.
  27. *
  28. * @ingroup API
  29. */
  30. class ApiFeedWatchlist extends ApiBase {
  31. private $watchlistModule = null;
  32. private $linkToSections = false;
  33. /**
  34. * This module uses a custom feed wrapper printer.
  35. *
  36. * @return ApiFormatFeedWrapper
  37. */
  38. public function getCustomPrinter() {
  39. return new ApiFormatFeedWrapper( $this->getMain() );
  40. }
  41. /**
  42. * Make a nested call to the API to request watchlist items in the last $hours.
  43. * Wrap the result as an RSS/Atom feed.
  44. */
  45. public function execute() {
  46. $config = $this->getConfig();
  47. $feedClasses = $config->get( 'FeedClasses' );
  48. $params = [];
  49. try {
  50. $params = $this->extractRequestParams();
  51. if ( !$config->get( 'Feed' ) ) {
  52. $this->dieWithError( 'feed-unavailable' );
  53. }
  54. if ( !isset( $feedClasses[$params['feedformat']] ) ) {
  55. $this->dieWithError( 'feed-invalid' );
  56. }
  57. // limit to the number of hours going from now back
  58. $endTime = wfTimestamp( TS_MW, time() - (int)$params['hours'] * 60 * 60 );
  59. // Prepare parameters for nested request
  60. $fauxReqArr = [
  61. 'action' => 'query',
  62. 'meta' => 'siteinfo',
  63. 'siprop' => 'general',
  64. 'list' => 'watchlist',
  65. 'wlprop' => 'title|user|comment|timestamp|ids|loginfo',
  66. 'wldir' => 'older', // reverse order - from newest to oldest
  67. 'wlend' => $endTime, // stop at this time
  68. 'wllimit' => min( 50, $this->getConfig()->get( 'FeedLimit' ) )
  69. ];
  70. if ( $params['wlowner'] !== null ) {
  71. $fauxReqArr['wlowner'] = $params['wlowner'];
  72. }
  73. if ( $params['wltoken'] !== null ) {
  74. $fauxReqArr['wltoken'] = $params['wltoken'];
  75. }
  76. if ( $params['wlexcludeuser'] !== null ) {
  77. $fauxReqArr['wlexcludeuser'] = $params['wlexcludeuser'];
  78. }
  79. if ( $params['wlshow'] !== null ) {
  80. $fauxReqArr['wlshow'] = $params['wlshow'];
  81. }
  82. if ( $params['wltype'] !== null ) {
  83. $fauxReqArr['wltype'] = $params['wltype'];
  84. }
  85. // Support linking directly to sections when possible
  86. // (possible only if section name is present in comment)
  87. if ( $params['linktosections'] ) {
  88. $this->linkToSections = true;
  89. }
  90. // Check for 'allrev' parameter, and if found, show all revisions to each page on wl.
  91. if ( $params['allrev'] ) {
  92. $fauxReqArr['wlallrev'] = '';
  93. }
  94. $fauxReq = new FauxRequest( $fauxReqArr );
  95. $module = new ApiMain( $fauxReq );
  96. $module->execute();
  97. $data = $module->getResult()->getResultData( [ 'query', 'watchlist' ] );
  98. $feedItems = [];
  99. foreach ( (array)$data as $key => $info ) {
  100. if ( ApiResult::isMetadataKey( $key ) ) {
  101. continue;
  102. }
  103. $feedItem = $this->createFeedItem( $info );
  104. if ( $feedItem ) {
  105. $feedItems[] = $feedItem;
  106. }
  107. }
  108. $msg = wfMessage( 'watchlist' )->inContentLanguage()->text();
  109. $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - ' . $msg .
  110. ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
  111. $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
  112. $feed = new $feedClasses[$params['feedformat']] (
  113. $feedTitle,
  114. htmlspecialchars( $msg ),
  115. $feedUrl
  116. );
  117. ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
  118. } catch ( Exception $e ) {
  119. // Error results should not be cached
  120. $this->getMain()->setCacheMaxAge( 0 );
  121. // @todo FIXME: Localise brackets
  122. $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - Error - ' .
  123. wfMessage( 'watchlist' )->inContentLanguage()->text() .
  124. ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
  125. $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
  126. $feedFormat = $params['feedformat'] ?? 'rss';
  127. $msg = wfMessage( 'watchlist' )->inContentLanguage()->escaped();
  128. $feed = new $feedClasses[$feedFormat] ( $feedTitle, $msg, $feedUrl );
  129. if ( $e instanceof ApiUsageException ) {
  130. foreach ( $e->getStatusValue()->getErrors() as $error ) {
  131. // @phan-suppress-next-line PhanUndeclaredMethod
  132. $msg = ApiMessage::create( $error )
  133. ->inLanguage( $this->getLanguage() );
  134. $errorTitle = $this->msg( 'api-feed-error-title', $msg->getApiCode() );
  135. $errorText = $msg->text();
  136. $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
  137. }
  138. } else {
  139. // Something is seriously wrong
  140. $errorCode = 'internal_api_error';
  141. $errorTitle = $this->msg( 'api-feed-error-title', $errorCode );
  142. $errorText = $e->getMessage();
  143. $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
  144. }
  145. ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
  146. }
  147. }
  148. /**
  149. * @param array $info
  150. * @return FeedItem
  151. */
  152. private function createFeedItem( $info ) {
  153. if ( !isset( $info['title'] ) ) {
  154. // Probably a revdeled log entry, skip it.
  155. return null;
  156. }
  157. $titleStr = $info['title'];
  158. $title = Title::newFromText( $titleStr );
  159. $curidParam = [];
  160. if ( !$title || $title->isExternal() ) {
  161. // Probably a formerly-valid title that's now conflicting with an
  162. // interwiki prefix or the like.
  163. if ( isset( $info['pageid'] ) ) {
  164. $title = Title::newFromID( $info['pageid'] );
  165. $curidParam = [ 'curid' => $info['pageid'] ];
  166. }
  167. if ( !$title || $title->isExternal() ) {
  168. return null;
  169. }
  170. }
  171. if ( isset( $info['revid'] ) ) {
  172. if ( $info['revid'] === 0 && isset( $info['logid'] ) ) {
  173. $logTitle = Title::makeTitle( NS_SPECIAL, 'Log' );
  174. $titleUrl = $logTitle->getFullURL( [ 'logid' => $info['logid'] ] );
  175. } else {
  176. $titleUrl = $title->getFullURL( [ 'diff' => $info['revid'] ] );
  177. }
  178. } else {
  179. $titleUrl = $title->getFullURL( $curidParam );
  180. }
  181. $comment = $info['comment'] ?? null;
  182. // Create an anchor to section.
  183. // The anchor won't work for sections that have dupes on page
  184. // as there's no way to strip that info from ApiWatchlist (apparently?).
  185. // RegExp in the line below is equal to Linker::formatAutocomments().
  186. if ( $this->linkToSections && $comment !== null &&
  187. preg_match( '!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment, $matches )
  188. ) {
  189. $titleUrl .= MediaWikiServices::getInstance()->getParser()
  190. ->guessSectionNameFromWikiText( $matches[ 2 ] );
  191. }
  192. $timestamp = $info['timestamp'];
  193. if ( isset( $info['user'] ) ) {
  194. $user = $info['user'];
  195. $completeText = "$comment ($user)";
  196. } else {
  197. $user = '';
  198. $completeText = (string)$comment;
  199. }
  200. return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
  201. }
  202. private function getWatchlistModule() {
  203. if ( $this->watchlistModule === null ) {
  204. $this->watchlistModule = $this->getMain()->getModuleManager()->getModule( 'query' )
  205. ->getModuleManager()->getModule( 'watchlist' );
  206. }
  207. return $this->watchlistModule;
  208. }
  209. public function getAllowedParams( $flags = 0 ) {
  210. $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
  211. $ret = [
  212. 'feedformat' => [
  213. ApiBase::PARAM_DFLT => 'rss',
  214. ApiBase::PARAM_TYPE => $feedFormatNames
  215. ],
  216. 'hours' => [
  217. ApiBase::PARAM_DFLT => 24,
  218. ApiBase::PARAM_TYPE => 'integer',
  219. ApiBase::PARAM_MIN => 1,
  220. ApiBase::PARAM_MAX => 72,
  221. ],
  222. 'linktosections' => false,
  223. ];
  224. $copyParams = [
  225. 'allrev' => 'allrev',
  226. 'owner' => 'wlowner',
  227. 'token' => 'wltoken',
  228. 'show' => 'wlshow',
  229. 'type' => 'wltype',
  230. 'excludeuser' => 'wlexcludeuser',
  231. ];
  232. if ( $flags ) {
  233. $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
  234. foreach ( $copyParams as $from => $to ) {
  235. $p = $wlparams[$from];
  236. if ( !is_array( $p ) ) {
  237. $p = [ ApiBase::PARAM_DFLT => $p ];
  238. }
  239. if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
  240. $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
  241. }
  242. if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
  243. isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE] )
  244. ) {
  245. foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
  246. if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
  247. $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
  248. }
  249. }
  250. }
  251. $ret[$to] = $p;
  252. }
  253. } else {
  254. foreach ( $copyParams as $from => $to ) {
  255. $ret[$to] = null;
  256. }
  257. }
  258. return $ret;
  259. }
  260. protected function getExamplesMessages() {
  261. return [
  262. 'action=feedwatchlist'
  263. => 'apihelp-feedwatchlist-example-default',
  264. 'action=feedwatchlist&allrev=&hours=6'
  265. => 'apihelp-feedwatchlist-example-all6hrs',
  266. ];
  267. }
  268. public function getHelpUrls() {
  269. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
  270. }
  271. }