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