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