MediaWiki  1.28.0
ApiFeedWatchlist.php
Go to the documentation of this file.
1 <?php
34 class ApiFeedWatchlist extends ApiBase {
35 
36  private $watchlistModule = null;
37  private $linkToSections = false;
38 
44  public function getCustomPrinter() {
45  return new ApiFormatFeedWrapper( $this->getMain() );
46  }
47 
52  public function execute() {
53  $config = $this->getConfig();
54  $feedClasses = $config->get( 'FeedClasses' );
55  try {
56  $params = $this->extractRequestParams();
57 
58  if ( !$config->get( 'Feed' ) ) {
59  $this->dieUsage( 'Syndication feeds are not available', 'feed-unavailable' );
60  }
61 
62  if ( !isset( $feedClasses[$params['feedformat']] ) ) {
63  $this->dieUsage( 'Invalid subscription feed type', 'feed-invalid' );
64  }
65 
66  // limit to the number of hours going from now back
67  $endTime = wfTimestamp( TS_MW, time() - intval( $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',
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  // Create the request
109  $fauxReq = new FauxRequest( $fauxReqArr );
110 
111  // Execute
112  $module = new ApiMain( $fauxReq );
113  $module->execute();
114 
115  $data = $module->getResult()->getResultData( [ 'query', 'watchlist' ] );
116  $feedItems = [];
117  foreach ( (array)$data as $key => $info ) {
118  if ( ApiResult::isMetadataKey( $key ) ) {
119  continue;
120  }
121  $feedItem = $this->createFeedItem( $info );
122  if ( $feedItem ) {
123  $feedItems[] = $feedItem;
124  }
125  }
126 
127  $msg = wfMessage( 'watchlist' )->inContentLanguage()->text();
128 
129  $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - ' . $msg .
130  ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
131  $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
132 
133  $feed = new $feedClasses[$params['feedformat']] (
134  $feedTitle,
135  htmlspecialchars( $msg ),
136  $feedUrl
137  );
138 
139  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
140  } catch ( Exception $e ) {
141  // Error results should not be cached
142  $this->getMain()->setCacheMaxAge( 0 );
143 
144  // @todo FIXME: Localise brackets
145  $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - Error - ' .
146  wfMessage( 'watchlist' )->inContentLanguage()->text() .
147  ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
148  $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
149 
150  $feedFormat = isset( $params['feedformat'] ) ? $params['feedformat'] : 'rss';
151  $msg = wfMessage( 'watchlist' )->inContentLanguage()->escaped();
152  $feed = new $feedClasses[$feedFormat] ( $feedTitle, $msg, $feedUrl );
153 
154  if ( $e instanceof UsageException ) {
155  $errorCode = $e->getCodeString();
156  } else {
157  // Something is seriously wrong
158  $errorCode = 'internal_api_error';
159  }
160 
161  $errorText = $e->getMessage();
162  $feedItems[] = new FeedItem( "Error ($errorCode)", $errorText, '', '', '' );
163  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
164  }
165  }
166 
171  private function createFeedItem( $info ) {
172  if ( !isset( $info['title'] ) ) {
173  // Probably a revdeled log entry, skip it.
174  return null;
175  }
176 
177  $titleStr = $info['title'];
178  $title = Title::newFromText( $titleStr );
179  $curidParam = [];
180  if ( !$title || $title->isExternal() ) {
181  // Probably a formerly-valid title that's now conflicting with an
182  // interwiki prefix or the like.
183  if ( isset( $info['pageid'] ) ) {
184  $title = Title::newFromID( $info['pageid'] );
185  $curidParam = [ 'curid' => $info['pageid'] ];
186  }
187  if ( !$title || $title->isExternal() ) {
188  return null;
189  }
190  }
191  if ( isset( $info['revid'] ) ) {
192  $titleUrl = $title->getFullURL( [ 'diff' => $info['revid'] ] );
193  } else {
194  $titleUrl = $title->getFullURL( $curidParam );
195  }
196  $comment = isset( $info['comment'] ) ? $info['comment'] : null;
197 
198  // Create an anchor to section.
199  // The anchor won't work for sections that have dupes on page
200  // as there's no way to strip that info from ApiWatchlist (apparently?).
201  // RegExp in the line below is equal to Linker::formatAutocomments().
202  if ( $this->linkToSections && $comment !== null &&
203  preg_match( '!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment, $matches )
204  ) {
206 
207  $sectionTitle = $wgParser->stripSectionName( $matches[2] );
208  $sectionTitle = Sanitizer::normalizeSectionNameWhitespace( $sectionTitle );
209  $titleUrl .= Title::newFromText( '#' . $sectionTitle )->getFragmentForURL();
210  }
211 
212  $timestamp = $info['timestamp'];
213 
214  if ( isset( $info['user'] ) ) {
215  $user = $info['user'];
216  $completeText = "$comment ($user)";
217  } else {
218  $user = '';
219  $completeText = (string)$comment;
220  }
221 
222  return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
223  }
224 
225  private function getWatchlistModule() {
226  if ( $this->watchlistModule === null ) {
227  $this->watchlistModule = $this->getMain()->getModuleManager()->getModule( 'query' )
228  ->getModuleManager()->getModule( 'watchlist' );
229  }
230 
231  return $this->watchlistModule;
232  }
233 
234  public function getAllowedParams( $flags = 0 ) {
235  $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
236  $ret = [
237  'feedformat' => [
238  ApiBase::PARAM_DFLT => 'rss',
239  ApiBase::PARAM_TYPE => $feedFormatNames
240  ],
241  'hours' => [
242  ApiBase::PARAM_DFLT => 24,
243  ApiBase::PARAM_TYPE => 'integer',
244  ApiBase::PARAM_MIN => 1,
245  ApiBase::PARAM_MAX => 72,
246  ],
247  'linktosections' => false,
248  ];
249 
250  $copyParams = [
251  'allrev' => 'allrev',
252  'owner' => 'wlowner',
253  'token' => 'wltoken',
254  'show' => 'wlshow',
255  'type' => 'wltype',
256  'excludeuser' => 'wlexcludeuser',
257  ];
258  if ( $flags ) {
259  $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
260  foreach ( $copyParams as $from => $to ) {
261  $p = $wlparams[$from];
262  if ( !is_array( $p ) ) {
263  $p = [ ApiBase::PARAM_DFLT => $p ];
264  }
265  if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
266  $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
267  }
268  if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
270  ) {
271  foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
272  if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
273  $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
274  }
275  }
276  }
277  $ret[$to] = $p;
278  }
279  } else {
280  foreach ( $copyParams as $from => $to ) {
281  $ret[$to] = null;
282  }
283  }
284 
285  return $ret;
286  }
287 
288  protected function getExamplesMessages() {
289  return [
290  'action=feedwatchlist'
291  => 'apihelp-feedwatchlist-example-default',
292  'action=feedwatchlist&allrev=&hours=6'
293  => 'apihelp-feedwatchlist-example-all6hrs',
294  ];
295  }
296 
297  public function getHelpUrls() {
298  return 'https://www.mediawiki.org/wiki/API:Watchlist_feed';
299  }
300 }
static newFromID($id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:402
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
the array() calling protocol came about after MediaWiki 1.4rc1.
getResult()
Get the result object.
Definition: ApiBase.php:577
getAllowedParams($flags=0)
execute()
Make a nested call to the API to request watchlist items in the last $hours.
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:1936
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:82
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
getMain()
Get the main module.
Definition: ApiBase.php:473
$wgParser
Definition: Setup.php:821
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:91
$comment
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
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:177
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
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:157
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getCustomPrinter()
This module uses a custom feed wrapper printer.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static normalizeSectionNameWhitespace($section)
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(), for use in the id's that are used for section links.
Definition: Sanitizer.php:1381
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 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
if($limit) $timestamp
getConfig()
Get the Config object.
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:43
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: defines.php:11
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
A base class for basic support for outputting syndication feeds in RSS and other formats.
Definition: Feed.php:38
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
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
$from
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
static setResult($result, $feed, $feedItems)
Call this method to initialize output data.
This action allows users to get their watchlist items in RSS/Atom formats.
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1574
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:100
This printer is used to wrap an instance of the Feed class.
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1837
$matches
static isMetadataKey($key)
Test whether a key should be considered metadata.
Definition: ApiResult.php:795