MediaWiki  master
ApiFeedWatchlist.php
Go to the documentation of this file.
1 <?php
24 
32 class ApiFeedWatchlist extends ApiBase {
33 
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  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  $msg = ApiMessage::create( $error )
154  ->inLanguage( $this->getLanguage() );
155  $errorTitle = $this->msg( 'api-feed-error-title', $msg->getApiCode() );
156  $errorText = $msg->text();
157  $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
158  }
159  } else {
160  // Something is seriously wrong
161  $errorCode = 'internal_api_error';
162  $errorTitle = $this->msg( 'api-feed-error-title', $errorCode );
163  $errorText = $e->getMessage();
164  $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
165  }
166 
167  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
168  }
169  }
170 
175  private function createFeedItem( $info ) {
176  if ( !isset( $info['title'] ) ) {
177  // Probably a revdeled log entry, skip it.
178  return null;
179  }
180 
181  $titleStr = $info['title'];
182  $title = Title::newFromText( $titleStr );
183  $curidParam = [];
184  if ( !$title || $title->isExternal() ) {
185  // Probably a formerly-valid title that's now conflicting with an
186  // interwiki prefix or the like.
187  if ( isset( $info['pageid'] ) ) {
188  $title = Title::newFromID( $info['pageid'] );
189  $curidParam = [ 'curid' => $info['pageid'] ];
190  }
191  if ( !$title || $title->isExternal() ) {
192  return null;
193  }
194  }
195  if ( isset( $info['revid'] ) ) {
196  if ( $info['revid'] === 0 && isset( $info['logid'] ) ) {
197  $logTitle = Title::makeTitle( NS_SPECIAL, 'Log' );
198  $titleUrl = $logTitle->getFullURL( [ 'logid' => $info['logid'] ] );
199  } else {
200  $titleUrl = $title->getFullURL( [ 'diff' => $info['revid'] ] );
201  }
202  } else {
203  $titleUrl = $title->getFullURL( $curidParam );
204  }
205  $comment = $info['comment'] ?? null;
206 
207  // Create an anchor to section.
208  // The anchor won't work for sections that have dupes on page
209  // as there's no way to strip that info from ApiWatchlist (apparently?).
210  // RegExp in the line below is equal to Linker::formatAutocomments().
211  if ( $this->linkToSections && $comment !== null &&
212  preg_match( '!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment, $matches )
213  ) {
214  $titleUrl .= MediaWikiServices::getInstance()->getParser()
215  ->guessSectionNameFromWikiText( $matches[ 2 ] );
216  }
217 
218  $timestamp = $info['timestamp'];
219 
220  if ( isset( $info['user'] ) ) {
221  $user = $info['user'];
222  $completeText = "$comment ($user)";
223  } else {
224  $user = '';
225  $completeText = (string)$comment;
226  }
227 
228  return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
229  }
230 
231  private function getWatchlistModule() {
232  if ( $this->watchlistModule === null ) {
233  $this->watchlistModule = $this->getMain()->getModuleManager()->getModule( 'query' )
234  ->getModuleManager()->getModule( 'watchlist' );
235  }
236 
237  return $this->watchlistModule;
238  }
239 
240  public function getAllowedParams( $flags = 0 ) {
241  $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
242  $ret = [
243  'feedformat' => [
244  ApiBase::PARAM_DFLT => 'rss',
245  ApiBase::PARAM_TYPE => $feedFormatNames
246  ],
247  'hours' => [
248  ApiBase::PARAM_DFLT => 24,
249  ApiBase::PARAM_TYPE => 'integer',
250  ApiBase::PARAM_MIN => 1,
251  ApiBase::PARAM_MAX => 72,
252  ],
253  'linktosections' => false,
254  ];
255 
256  $copyParams = [
257  'allrev' => 'allrev',
258  'owner' => 'wlowner',
259  'token' => 'wltoken',
260  'show' => 'wlshow',
261  'type' => 'wltype',
262  'excludeuser' => 'wlexcludeuser',
263  ];
264  if ( $flags ) {
265  $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
266  foreach ( $copyParams as $from => $to ) {
267  $p = $wlparams[$from];
268  if ( !is_array( $p ) ) {
269  $p = [ ApiBase::PARAM_DFLT => $p ];
270  }
271  if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
272  $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
273  }
274  if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
276  ) {
277  foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
278  if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
279  $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
280  }
281  }
282  }
283  $ret[$to] = $p;
284  }
285  } else {
286  foreach ( $copyParams as $from => $to ) {
287  $ret[$to] = null;
288  }
289  }
290 
291  return $ret;
292  }
293 
294  protected function getExamplesMessages() {
295  return [
296  'action=feedwatchlist'
297  => 'apihelp-feedwatchlist-example-default',
298  'action=feedwatchlist&allrev=&hours=6'
299  => 'apihelp-feedwatchlist-example-all6hrs',
300  ];
301  }
302 
303  public function getHelpUrls() {
304  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
305  }
306 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getAllowedParams( $flags=0)
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
getResult()
Get the result object.
Definition: ApiBase.php:633
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:470
execute()
Make a nested call to the API to request watchlist items in the last $hours.
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:49
getMain()
Get the main module.
Definition: ApiBase.php:529
Exception used to abort API execution with an error.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:91
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
const NS_SPECIAL
Definition: Defines.php:53
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1991
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:744
static isMetadataKey( $key)
Test whether a key should be considered metadata.
Definition: ApiResult.php:793
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
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:158
getCustomPrinter()
This module uses a custom feed wrapper printer.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:82
A base class for outputting syndication feeds (e.g.
Definition: FeedItem.php:33
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
This action allows users to get their watchlist items in RSS/Atom formats.
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:38
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:100
This printer is used to wrap an instance of the Feed class.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
$matches
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319