MediaWiki  master
ApiFeedWatchlist.php
Go to the documentation of this file.
1 <?php
24 
32 class ApiFeedWatchlist extends ApiBase {
33 
34  private $watchlistModule = null;
35  private $linkToSections = false;
36 
42  public function getCustomPrinter() {
43  return new ApiFormatFeedWrapper( $this->getMain() );
44  }
45 
50  public function execute() {
51  $config = $this->getConfig();
52  $feedClasses = $config->get( 'FeedClasses' );
53  $params = [];
54  $feedItems = [];
55  try {
56  $params = $this->extractRequestParams();
57 
58  if ( !$config->get( 'Feed' ) ) {
59  $this->dieWithError( 'feed-unavailable' );
60  }
61 
62  if ( !isset( $feedClasses[$params['feedformat']] ) ) {
63  $this->dieWithError( 'feed-invalid' );
64  }
65 
66  // limit to the number of hours going from now back
67  $endTime = wfTimestamp( TS_MW, time() - (int)$params['hours'] * 60 * 60 );
68 
69  // Prepare parameters for nested request
70  $fauxReqArr = [
71  'action' => 'query',
72  'meta' => 'siteinfo',
73  'siprop' => 'general',
74  'list' => 'watchlist',
75  'wlprop' => 'title|user|comment|timestamp|ids|loginfo',
76  'wldir' => 'older', // reverse order - from newest to oldest
77  'wlend' => $endTime, // stop at this time
78  'wllimit' => min( 50, $this->getConfig()->get( 'FeedLimit' ) )
79  ];
80 
81  if ( $params['wlowner'] !== null ) {
82  $fauxReqArr['wlowner'] = $params['wlowner'];
83  }
84  if ( $params['wltoken'] !== null ) {
85  $fauxReqArr['wltoken'] = $params['wltoken'];
86  }
87  if ( $params['wlexcludeuser'] !== null ) {
88  $fauxReqArr['wlexcludeuser'] = $params['wlexcludeuser'];
89  }
90  if ( $params['wlshow'] !== null ) {
91  $fauxReqArr['wlshow'] = $params['wlshow'];
92  }
93  if ( $params['wltype'] !== null ) {
94  $fauxReqArr['wltype'] = $params['wltype'];
95  }
96 
97  // Support linking directly to sections when possible
98  // (possible only if section name is present in comment)
99  if ( $params['linktosections'] ) {
100  $this->linkToSections = true;
101  }
102 
103  // Check for 'allrev' parameter, and if found, show all revisions to each page on wl.
104  if ( $params['allrev'] ) {
105  $fauxReqArr['wlallrev'] = '';
106  }
107 
108  $fauxReq = new FauxRequest( $fauxReqArr );
109 
110  $module = new ApiMain( $fauxReq );
111  $module->execute();
112 
113  $data = $module->getResult()->getResultData( [ 'query', 'watchlist' ] );
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 
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  // @phan-suppress-next-line PhanParamTooMany
267  $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
268  foreach ( $copyParams as $from => $to ) {
269  $p = $wlparams[$from];
270  if ( !is_array( $p ) ) {
271  $p = [ ApiBase::PARAM_DFLT => $p ];
272  }
273  if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
274  $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
275  }
276  if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
278  ) {
279  foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
280  if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
281  $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
282  }
283  }
284  }
285  $ret[$to] = $p;
286  }
287  } else {
288  foreach ( $copyParams as $from => $to ) {
289  $ret[$to] = null;
290  }
291  }
292 
293  return $ret;
294  }
295 
296  protected function getExamplesMessages() {
297  return [
298  'action=feedwatchlist'
299  => 'apihelp-feedwatchlist-example-default',
300  'action=feedwatchlist&allrev=&hours=6'
301  => 'apihelp-feedwatchlist-example-all6hrs',
302  ];
303  }
304 
305  public function getHelpUrls() {
306  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
307  }
308 }
ApiFeedWatchlist\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiFeedWatchlist.php:296
ApiFeedWatchlist\getAllowedParams
getAllowedParams( $flags=0)
Definition: ApiFeedWatchlist.php:241
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:48
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:67
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:35
ApiFeedWatchlist
This action allows users to get their watchlist items in RSS/Atom formats.
Definition: ApiFeedWatchlist.php:32
FeedItem
A base class for outputting syndication feeds (e.g.
Definition: FeedItem.php:33
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:328
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:29
ApiFeedWatchlist\getCustomPrinter
getCustomPrinter()
This module uses a custom feed wrapper printer.
Definition: ApiFeedWatchlist.php:42
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:158
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1381
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:106
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:564
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
SpecialPage\getTitleFor
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,...
Definition: SpecialPage.php:92
ApiFeedWatchlist\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiFeedWatchlist.php:305
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:140
ApiFeedWatchlist\$linkToSections
$linkToSections
Definition: ApiFeedWatchlist.php:35
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:58
ApiBase\PARAM_MIN
const PARAM_MIN
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:73
ApiFeedWatchlist\$watchlistModule
$watchlistModule
Definition: ApiFeedWatchlist.php:34
ApiFormatFeedWrapper
This printer is used to wrap an instance of the Feed class.
Definition: ApiFormatFeedWrapper.php:27
$matches
$matches
Definition: NoLocalSettings.php:24
ApiFeedWatchlist\execute
execute()
Make a nested call to the API to request watchlist items in the last $hours.
Definition: ApiFeedWatchlist.php:50
ApiBase\PARAM_MAX
const PARAM_MAX
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:71
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:716
$title
$title
Definition: testCompression.php:38
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:591
ApiFeedWatchlist\createFeedItem
createFeedItem( $info)
Definition: ApiFeedWatchlist.php:176
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:42
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:184
ApiResult\isMetadataKey
static isMetadataKey( $key)
Test whether a key should be considered metadata.
Definition: ApiResult.php:781
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:68
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:459
ApiFeedWatchlist\getWatchlistModule
getWatchlistModule()
Definition: ApiFeedWatchlist.php:232
ApiBase\PARAM_HELP_MSG_PER_VALUE
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:139
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:472
ApiFormatFeedWrapper\setResult
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
Definition: ApiFormatFeedWrapper.php:39