MediaWiki master
ApiFeedWatchlist.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Api;
24
25use Exception;
34
43
45 private $watchlistModule = null;
47 private $linkToSections = false;
48
49 private ParserFactory $parserFactory;
50
51 public function __construct(
52 ApiMain $main,
53 string $action,
54 ParserFactory $parserFactory
55 ) {
56 parent::__construct( $main, $action );
57 $this->parserFactory = $parserFactory;
58 }
59
65 public function getCustomPrinter() {
66 return new ApiFormatFeedWrapper( $this->getMain() );
67 }
68
73 public function execute() {
74 $config = $this->getConfig();
75 $feedClasses = $config->get( MainConfigNames::FeedClasses );
76 $params = [];
77 $feedItems = [];
78 try {
79 $params = $this->extractRequestParams();
80
81 if ( !$config->get( MainConfigNames::Feed ) ) {
82 $this->dieWithError( 'feed-unavailable' );
83 }
84
85 if ( !isset( $feedClasses[$params['feedformat']] ) ) {
86 $this->dieWithError( 'feed-invalid' );
87 }
88
89 // limit to the number of hours going from now back
90 $endTime = wfTimestamp( TS_MW, time() - (int)$params['hours'] * 60 * 60 );
91
92 // Prepare parameters for nested request
93 $fauxReqArr = [
94 'action' => 'query',
95 'meta' => 'siteinfo',
96 'siprop' => 'general',
97 'list' => 'watchlist',
98 'wlprop' => 'title|user|comment|timestamp|ids|loginfo',
99 'wldir' => 'older', // reverse order - from newest to oldest
100 'wlend' => $endTime, // stop at this time
101 'wllimit' => min( 50, $this->getConfig()->get( MainConfigNames::FeedLimit ) )
102 ];
103
104 if ( $params['wlowner'] !== null ) {
105 $fauxReqArr['wlowner'] = $params['wlowner'];
106 }
107 if ( $params['wltoken'] !== null ) {
108 $fauxReqArr['wltoken'] = $params['wltoken'];
109 }
110 if ( $params['wlexcludeuser'] !== null ) {
111 $fauxReqArr['wlexcludeuser'] = $params['wlexcludeuser'];
112 }
113 if ( $params['wlshow'] !== null ) {
114 $fauxReqArr['wlshow'] = ParamValidator::implodeMultiValue( $params['wlshow'] );
115 }
116 if ( $params['wltype'] !== null ) {
117 $fauxReqArr['wltype'] = ParamValidator::implodeMultiValue( $params['wltype'] );
118 }
119
120 // Support linking directly to sections when possible
121 // (possible only if section name is present in comment)
122 if ( $params['linktosections'] ) {
123 $this->linkToSections = true;
124 }
125
126 // Check for 'allrev' parameter, and if found, show all revisions to each page on wl.
127 if ( $params['allrev'] ) {
128 $fauxReqArr['wlallrev'] = '';
129 }
130
131 $fauxReq = new FauxRequest( $fauxReqArr );
132
133 $module = new ApiMain( $fauxReq );
134 $module->execute();
135
136 $data = $module->getResult()->getResultData( [ 'query', 'watchlist' ] );
137 foreach ( (array)$data as $key => $info ) {
138 if ( ApiResult::isMetadataKey( $key ) ) {
139 continue;
140 }
141 $feedItem = $this->createFeedItem( $info );
142 if ( $feedItem ) {
143 $feedItems[] = $feedItem;
144 }
145 }
146
147 $msg = $this->msg( 'watchlist' )->inContentLanguage()->text();
148
149 $feedTitle = $this->getConfig()->get( MainConfigNames::Sitename ) . ' - ' . $msg .
150 ' [' . $this->getConfig()->get( MainConfigNames::LanguageCode ) . ']';
151 $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
152
153 $feed = new $feedClasses[$params['feedformat']] (
154 $feedTitle,
155 htmlspecialchars( $msg ),
156 $feedUrl
157 );
158
159 ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
160 } catch ( Exception $e ) {
161 // Error results should not be cached
162 $this->getMain()->setCacheMaxAge( 0 );
163
164 // @todo FIXME: Localise brackets
165 $feedTitle = $this->getConfig()->get( MainConfigNames::Sitename ) . ' - Error - ' .
166 $this->msg( 'watchlist' )->inContentLanguage()->text() .
167 ' [' . $this->getConfig()->get( MainConfigNames::LanguageCode ) . ']';
168 $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
169
170 $feedFormat = $params['feedformat'] ?? 'rss';
171 $msg = $this->msg( 'watchlist' )->inContentLanguage()->escaped();
172 $feed = new $feedClasses[$feedFormat] ( $feedTitle, $msg, $feedUrl );
173
174 if ( $e instanceof ApiUsageException ) {
175 foreach ( $e->getStatusValue()->getMessages() as $msg ) {
176 // @phan-suppress-next-line PhanUndeclaredMethod
177 $msg = ApiMessage::create( $msg )
178 ->inLanguage( $this->getLanguage() );
179 $errorTitle = $this->msg( 'api-feed-error-title', $msg->getApiCode() );
180 $errorText = $msg->text();
181 $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
182 }
183 } else {
184 // Something is seriously wrong
185 $errorCode = 'internal_api_error';
186 $errorTitle = $this->msg( 'api-feed-error-title', $errorCode );
187 $errorText = $e->getMessage();
188 $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
189 }
190
191 ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
192 }
193 }
194
199 private function createFeedItem( $info ) {
200 if ( !isset( $info['title'] ) ) {
201 // Probably a revdeled log entry, skip it.
202 return null;
203 }
204
205 $titleStr = $info['title'];
206 $title = Title::newFromText( $titleStr );
207 $curidParam = [];
208 if ( !$title || $title->isExternal() ) {
209 // Probably a formerly-valid title that's now conflicting with an
210 // interwiki prefix or the like.
211 if ( isset( $info['pageid'] ) ) {
212 $title = Title::newFromID( $info['pageid'] );
213 $curidParam = [ 'curid' => $info['pageid'] ];
214 }
215 if ( !$title || $title->isExternal() ) {
216 return null;
217 }
218 }
219 if ( isset( $info['revid'] ) ) {
220 if ( $info['revid'] === 0 && isset( $info['logid'] ) ) {
221 $logTitle = Title::makeTitle( NS_SPECIAL, 'Log' );
222 $titleUrl = $logTitle->getFullURL( [ 'logid' => $info['logid'] ] );
223 } else {
224 $titleUrl = $title->getFullURL( [ 'diff' => $info['revid'] ] );
225 }
226 } else {
227 $titleUrl = $title->getFullURL( $curidParam );
228 }
229 $comment = $info['comment'] ?? null;
230
231 // Create an anchor to section.
232 // The anchor won't work for sections that have dupes on page
233 // as there's no way to strip that info from ApiWatchlist (apparently?).
234 // RegExp in the line below is equal to MediaWiki\CommentFormatter\CommentParser::doSectionLinks().
235 if ( $this->linkToSections && $comment !== null &&
236 preg_match( '!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment, $matches )
237 ) {
238 $titleUrl .= $this->parserFactory->getMainInstance()->guessSectionNameFromWikiText( $matches[ 2 ] );
239 }
240
241 $timestamp = $info['timestamp'];
242
243 if ( isset( $info['user'] ) ) {
244 $user = $info['user'];
245 $completeText = "$comment ($user)";
246 } else {
247 $user = '';
248 $completeText = (string)$comment;
249 }
250
251 return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
252 }
253
254 private function getWatchlistModule() {
255 $this->watchlistModule ??= $this->getMain()->getModuleManager()->getModule( 'query' )
256 ->getModuleManager()->getModule( 'watchlist' );
257
258 return $this->watchlistModule;
259 }
260
261 public function getAllowedParams( $flags = 0 ) {
262 $feedFormatNames = array_keys( $this->getConfig()->get( MainConfigNames::FeedClasses ) );
263 $ret = [
264 'feedformat' => [
265 ParamValidator::PARAM_DEFAULT => 'rss',
266 ParamValidator::PARAM_TYPE => $feedFormatNames
267 ],
268 'hours' => [
269 ParamValidator::PARAM_DEFAULT => 24,
270 ParamValidator::PARAM_TYPE => 'integer',
271 IntegerDef::PARAM_MIN => 1,
272 IntegerDef::PARAM_MAX => 72,
273 ],
274 'linktosections' => false,
275 ];
276
277 $copyParams = [
278 'allrev' => 'allrev',
279 'owner' => 'wlowner',
280 'token' => 'wltoken',
281 'show' => 'wlshow',
282 'type' => 'wltype',
283 'excludeuser' => 'wlexcludeuser',
284 ];
285 // @phan-suppress-next-line PhanParamTooMany
286 $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
287 foreach ( $copyParams as $from => $to ) {
288 $p = $wlparams[$from];
289 if ( !is_array( $p ) ) {
290 $p = [ ParamValidator::PARAM_DEFAULT => $p ];
291 }
292 if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
293 $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
294 }
295 if ( isset( $p[ParamValidator::PARAM_TYPE] ) && is_array( $p[ParamValidator::PARAM_TYPE] ) &&
297 ) {
298 foreach ( $p[ParamValidator::PARAM_TYPE] as $v ) {
299 if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
300 $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
301 }
302 }
303 }
304 $ret[$to] = $p;
305 }
306
307 return $ret;
308 }
309
310 protected function getExamplesMessages() {
311 return [
312 'action=feedwatchlist'
313 => 'apihelp-feedwatchlist-example-default',
314 'action=feedwatchlist&allrev=&hours=6'
315 => 'apihelp-feedwatchlist-example-all6hrs',
316 ];
317 }
318
319 public function getHelpUrls() {
320 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
321 }
322}
323
325class_alias( ApiFeedWatchlist::class, 'ApiFeedWatchlist' );
const NS_SPECIAL
Definition Defines.php:54
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:75
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
getMain()
Get the main module.
Definition ApiBase.php:575
getResult()
Get the result object.
Definition ApiBase.php:696
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, or 'string' with PARAM_ISMULTI,...
Definition ApiBase.php:221
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:181
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
This action allows users to get their watchlist items in RSS/Atom formats.
getCustomPrinter()
This module uses a custom feed wrapper printer.
__construct(ApiMain $main, string $action, ParserFactory $parserFactory)
getHelpUrls()
Return links to more detailed help pages about the module.
getExamplesMessages()
Returns usage examples for this module.
execute()
Make a nested call to the API to request watchlist items in the last $hours.
This printer is used to wrap an instance of the Feed class.
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:78
static create( $msg, $code=null, ?array $data=null)
Create an IApiMessage for the message.
static isMetadataKey( $key)
Test whether a key should be considered metadata.
Exception used to abort API execution with an error.
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
A base class for outputting syndication feeds (e.g.
Definition FeedItem.php:40
A class containing constants representing the names of configuration variables.
const FeedClasses
Name constant for the FeedClasses setting, for use with Config::get()
const Feed
Name constant for the Feed setting, for use with Config::get()
const Sitename
Name constant for the Sitename setting, for use with Config::get()
const LanguageCode
Name constant for the LanguageCode setting, for use with Config::get()
const FeedLimit
Name constant for the FeedLimit setting, for use with Config::get()
WebRequest clone which takes values from a provided array.
Parent class for all special pages.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Represents a title within MediaWiki.
Definition Title.php:78
Service for formatting and validating API parameters.
Type definition for integer types.