MediaWiki  1.29.1
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  $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', $msg->getApiCode() );
171  $errorText = $e->getMessage();
172  $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
173  }
174 
175  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
176  }
177  }
178 
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  ) {
218 
219  $sectionTitle = $wgParser->stripSectionName( $matches[2] );
220  $sectionTitle = Sanitizer::normalizeSectionNameWhitespace( $sectionTitle );
221  $titleUrl .= Title::newFromText( '#' . $sectionTitle )->getFragmentForURL();
222  }
223 
224  $timestamp = $info['timestamp'];
225 
226  if ( isset( $info['user'] ) ) {
227  $user = $info['user'];
228  $completeText = "$comment ($user)";
229  } else {
230  $user = '';
231  $completeText = (string)$comment;
232  }
233 
234  return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
235  }
236 
237  private function getWatchlistModule() {
238  if ( $this->watchlistModule === null ) {
239  $this->watchlistModule = $this->getMain()->getModuleManager()->getModule( 'query' )
240  ->getModuleManager()->getModule( 'watchlist' );
241  }
242 
243  return $this->watchlistModule;
244  }
245 
246  public function getAllowedParams( $flags = 0 ) {
247  $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
248  $ret = [
249  'feedformat' => [
250  ApiBase::PARAM_DFLT => 'rss',
251  ApiBase::PARAM_TYPE => $feedFormatNames
252  ],
253  'hours' => [
254  ApiBase::PARAM_DFLT => 24,
255  ApiBase::PARAM_TYPE => 'integer',
256  ApiBase::PARAM_MIN => 1,
257  ApiBase::PARAM_MAX => 72,
258  ],
259  'linktosections' => false,
260  ];
261 
262  $copyParams = [
263  'allrev' => 'allrev',
264  'owner' => 'wlowner',
265  'token' => 'wltoken',
266  'show' => 'wlshow',
267  'type' => 'wltype',
268  'excludeuser' => 'wlexcludeuser',
269  ];
270  if ( $flags ) {
271  $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
272  foreach ( $copyParams as $from => $to ) {
273  $p = $wlparams[$from];
274  if ( !is_array( $p ) ) {
275  $p = [ ApiBase::PARAM_DFLT => $p ];
276  }
277  if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
278  $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
279  }
280  if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
282  ) {
283  foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
284  if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
285  $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
286  }
287  }
288  }
289  $ret[$to] = $p;
290  }
291  } else {
292  foreach ( $copyParams as $from => $to ) {
293  $ret[$to] = null;
294  }
295  }
296 
297  return $ret;
298  }
299 
300  protected function getExamplesMessages() {
301  return [
302  'action=feedwatchlist'
303  => 'apihelp-feedwatchlist-example-default',
304  'action=feedwatchlist&allrev=&hours=6'
305  => 'apihelp-feedwatchlist-example-all6hrs',
306  ];
307  }
308 
309  public function getHelpUrls() {
310  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
311  }
312 }
ApiFeedWatchlist\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiFeedWatchlist.php:300
ApiFeedWatchlist\getAllowedParams
getAllowedParams( $flags=0)
Definition: ApiFeedWatchlist.php:246
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:45
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ApiFeedWatchlist
This action allows users to get their watchlist items in RSS/Atom formats.
Definition: ApiFeedWatchlist.php:34
FeedItem
A base class for basic support for outputting syndication feeds in RSS and other formats.
Definition: Feed.php:38
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:265
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:98
$wgParser
$wgParser
Definition: Setup.php:796
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
ApiFeedWatchlist\getCustomPrinter
getCustomPrinter()
This module uses a custom feed wrapper printer.
Definition: ApiFeedWatchlist.php:44
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:128
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
$user
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 account $user
Definition: hooks.txt:246
$params
$params
Definition: styleTest.css.php:40
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:82
ApiFeedWatchlist\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiFeedWatchlist.php:309
php
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
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
ApiFeedWatchlist\$linkToSections
$linkToSections
Definition: ApiFeedWatchlist.php:37
ApiBase\PARAM_MIN
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:103
ApiFeedWatchlist\$watchlistModule
$watchlistModule
Definition: ApiFeedWatchlist.php:36
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
ApiFormatFeedWrapper
This printer is used to wrap an instance of the Feed class.
Definition: ApiFormatFeedWrapper.php:31
UsageException
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiUsageException.php:28
$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:52
ApiBase\PARAM_MAX
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:94
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ApiFeedWatchlist\createFeedItem
createFeedItem( $info)
Definition: ApiFeedWatchlist.php:183
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:212
string
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
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
$ret
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:1956
ApiResult\isMetadataKey
static isMetadataKey( $key)
Test whether a key should be considered metadata.
Definition: ApiResult.php:793
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
as
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
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:506
wfMessage
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 unset offset - wrap String Wrap the message in html(usually something like "&lt
ApiFeedWatchlist\getWatchlistModule
getWatchlistModule()
Definition: ApiFeedWatchlist.php:237
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:160
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:405
ApiFormatFeedWrapper\setResult
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
Definition: ApiFormatFeedWrapper.php:43
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
array
the array() calling protocol came about after MediaWiki 1.4rc1.