MediaWiki REL1_33
ApiFeedWatchlist.php
Go to the documentation of this file.
1<?php
31
32 private $watchlistModule = null;
33 private $linkToSections = false;
34
40 public function getCustomPrinter() {
41 return new ApiFormatFeedWrapper( $this->getMain() );
42 }
43
48 public function execute() {
49 $config = $this->getConfig();
50 $feedClasses = $config->get( 'FeedClasses' );
51 $params = [];
52 try {
54
55 if ( !$config->get( 'Feed' ) ) {
56 $this->dieWithError( 'feed-unavailable' );
57 }
58
59 if ( !isset( $feedClasses[$params['feedformat']] ) ) {
60 $this->dieWithError( 'feed-invalid' );
61 }
62
63 // limit to the number of hours going from now back
64 $endTime = wfTimestamp( TS_MW, time() - (int)$params['hours'] * 60 * 60 );
65
66 // Prepare parameters for nested request
67 $fauxReqArr = [
68 'action' => 'query',
69 'meta' => 'siteinfo',
70 'siprop' => 'general',
71 'list' => 'watchlist',
72 'wlprop' => 'title|user|comment|timestamp|ids|loginfo',
73 'wldir' => 'older', // reverse order - from newest to oldest
74 'wlend' => $endTime, // stop at this time
75 'wllimit' => min( 50, $this->getConfig()->get( 'FeedLimit' ) )
76 ];
77
78 if ( $params['wlowner'] !== null ) {
79 $fauxReqArr['wlowner'] = $params['wlowner'];
80 }
81 if ( $params['wltoken'] !== null ) {
82 $fauxReqArr['wltoken'] = $params['wltoken'];
83 }
84 if ( $params['wlexcludeuser'] !== null ) {
85 $fauxReqArr['wlexcludeuser'] = $params['wlexcludeuser'];
86 }
87 if ( $params['wlshow'] !== null ) {
88 $fauxReqArr['wlshow'] = $params['wlshow'];
89 }
90 if ( $params['wltype'] !== null ) {
91 $fauxReqArr['wltype'] = $params['wltype'];
92 }
93
94 // Support linking directly to sections when possible
95 // (possible only if section name is present in comment)
96 if ( $params['linktosections'] ) {
97 $this->linkToSections = true;
98 }
99
100 // Check for 'allrev' parameter, and if found, show all revisions to each page on wl.
101 if ( $params['allrev'] ) {
102 $fauxReqArr['wlallrev'] = '';
103 }
104
105 $fauxReq = new FauxRequest( $fauxReqArr );
106
107 $module = new ApiMain( $fauxReq );
108 $module->execute();
109
110 $data = $module->getResult()->getResultData( [ 'query', 'watchlist' ] );
111 $feedItems = [];
112 foreach ( (array)$data as $key => $info ) {
113 if ( ApiResult::isMetadataKey( $key ) ) {
114 continue;
115 }
116 $feedItem = $this->createFeedItem( $info );
117 if ( $feedItem ) {
118 $feedItems[] = $feedItem;
119 }
120 }
121
122 $msg = wfMessage( 'watchlist' )->inContentLanguage()->text();
123
124 $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - ' . $msg .
125 ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
126 $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
127
128 $feed = new $feedClasses[$params['feedformat']] (
129 $feedTitle,
130 htmlspecialchars( $msg ),
131 $feedUrl
132 );
133
134 ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
135 } catch ( Exception $e ) {
136 // Error results should not be cached
137 $this->getMain()->setCacheMaxAge( 0 );
138
139 // @todo FIXME: Localise brackets
140 $feedTitle = $this->getConfig()->get( 'Sitename' ) . ' - Error - ' .
141 wfMessage( 'watchlist' )->inContentLanguage()->text() .
142 ' [' . $this->getConfig()->get( 'LanguageCode' ) . ']';
143 $feedUrl = SpecialPage::getTitleFor( 'Watchlist' )->getFullURL();
144
145 $feedFormat = $params['feedformat'] ?? 'rss';
146 $msg = wfMessage( 'watchlist' )->inContentLanguage()->escaped();
147 $feed = new $feedClasses[$feedFormat] ( $feedTitle, $msg, $feedUrl );
148
149 if ( $e instanceof ApiUsageException ) {
150 foreach ( $e->getStatusValue()->getErrors() as $error ) {
151 $msg = ApiMessage::create( $error )
152 ->inLanguage( $this->getLanguage() );
153 $errorTitle = $this->msg( 'api-feed-error-title', $msg->getApiCode() );
154 $errorText = $msg->text();
155 $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
156 }
157 } else {
158 // Something is seriously wrong
159 $errorCode = 'internal_api_error';
160 $errorTitle = $this->msg( 'api-feed-error-title', $errorCode );
161 $errorText = $e->getMessage();
162 $feedItems[] = new FeedItem( $errorTitle, $errorText, '', '', '' );
163 }
164
165 ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
166 }
167 }
168
173 private function createFeedItem( $info ) {
174 if ( !isset( $info['title'] ) ) {
175 // Probably a revdeled log entry, skip it.
176 return null;
177 }
178
179 $titleStr = $info['title'];
180 $title = Title::newFromText( $titleStr );
181 $curidParam = [];
182 if ( !$title || $title->isExternal() ) {
183 // Probably a formerly-valid title that's now conflicting with an
184 // interwiki prefix or the like.
185 if ( isset( $info['pageid'] ) ) {
186 $title = Title::newFromID( $info['pageid'] );
187 $curidParam = [ 'curid' => $info['pageid'] ];
188 }
189 if ( !$title || $title->isExternal() ) {
190 return null;
191 }
192 }
193 if ( isset( $info['revid'] ) ) {
194 if ( $info['revid'] === 0 && isset( $info['logid'] ) ) {
195 $logTitle = Title::makeTitle( NS_SPECIAL, 'Log' );
196 $titleUrl = $logTitle->getFullURL( [ 'logid' => $info['logid'] ] );
197 } else {
198 $titleUrl = $title->getFullURL( [ 'diff' => $info['revid'] ] );
199 }
200 } else {
201 $titleUrl = $title->getFullURL( $curidParam );
202 }
203 $comment = $info['comment'] ?? null;
204
205 // Create an anchor to section.
206 // The anchor won't work for sections that have dupes on page
207 // as there's no way to strip that info from ApiWatchlist (apparently?).
208 // RegExp in the line below is equal to Linker::formatAutocomments().
209 if ( $this->linkToSections && $comment !== null &&
210 preg_match( '!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment, $matches )
211 ) {
212 global $wgParser;
213 $titleUrl .= $wgParser->guessSectionNameFromWikiText( $matches[ 2 ] );
214 }
215
216 $timestamp = $info['timestamp'];
217
218 if ( isset( $info['user'] ) ) {
219 $user = $info['user'];
220 $completeText = "$comment ($user)";
221 } else {
222 $user = '';
223 $completeText = (string)$comment;
224 }
225
226 return new FeedItem( $titleStr, $completeText, $titleUrl, $timestamp, $user );
227 }
228
229 private function getWatchlistModule() {
230 if ( $this->watchlistModule === null ) {
231 $this->watchlistModule = $this->getMain()->getModuleManager()->getModule( 'query' )
232 ->getModuleManager()->getModule( 'watchlist' );
233 }
234
236 }
237
238 public function getAllowedParams( $flags = 0 ) {
239 $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
240 $ret = [
241 'feedformat' => [
242 ApiBase::PARAM_DFLT => 'rss',
243 ApiBase::PARAM_TYPE => $feedFormatNames
244 ],
245 'hours' => [
247 ApiBase::PARAM_TYPE => 'integer',
249 ApiBase::PARAM_MAX => 72,
250 ],
251 'linktosections' => false,
252 ];
253
254 $copyParams = [
255 'allrev' => 'allrev',
256 'owner' => 'wlowner',
257 'token' => 'wltoken',
258 'show' => 'wlshow',
259 'type' => 'wltype',
260 'excludeuser' => 'wlexcludeuser',
261 ];
262 if ( $flags ) {
263 $wlparams = $this->getWatchlistModule()->getAllowedParams( $flags );
264 foreach ( $copyParams as $from => $to ) {
265 $p = $wlparams[$from];
266 if ( !is_array( $p ) ) {
267 $p = [ ApiBase::PARAM_DFLT => $p ];
268 }
269 if ( !isset( $p[ApiBase::PARAM_HELP_MSG] ) ) {
270 $p[ApiBase::PARAM_HELP_MSG] = "apihelp-query+watchlist-param-$from";
271 }
272 if ( isset( $p[ApiBase::PARAM_TYPE] ) && is_array( $p[ApiBase::PARAM_TYPE] ) &&
274 ) {
275 foreach ( $p[ApiBase::PARAM_TYPE] as $v ) {
276 if ( !isset( $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] ) ) {
277 $p[ApiBase::PARAM_HELP_MSG_PER_VALUE][$v] = "apihelp-query+watchlist-paramvalue-$from-$v";
278 }
279 }
280 }
281 $ret[$to] = $p;
282 }
283 } else {
284 foreach ( $copyParams as $from => $to ) {
285 $ret[$to] = null;
286 }
287 }
288
289 return $ret;
290 }
291
292 protected function getExamplesMessages() {
293 return [
294 'action=feedwatchlist'
295 => 'apihelp-feedwatchlist-example-default',
296 'action=feedwatchlist&allrev=&hours=6'
297 => 'apihelp-feedwatchlist-example-all6hrs',
298 ];
299 }
300
301 public function getHelpUrls() {
302 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watchlist_feed';
303 }
304}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgParser
Definition Setup.php:886
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:90
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1990
getMain()
Get the main module.
Definition ApiBase.php:528
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
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
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:99
getResult()
Get the result object.
Definition ApiBase.php:632
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:743
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:124
This action allows users to get their watchlist items in RSS/Atom formats.
getAllowedParams( $flags=0)
getExamplesMessages()
Returns usage examples for this module.
getHelpUrls()
Return links to more detailed help pages about the module.
getCustomPrinter()
This module uses a custom feed wrapper printer.
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:41
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)
Get a Message object with context set Parameters are the same as wfMessage()
WebRequest clone which takes values from a provided array.
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
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
const NS_SPECIAL
Definition Defines.php:62
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:181
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:955
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:2003
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;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
return true to allow those checks to and false if checking is done & $user
Definition hooks.txt:1510
returning false will NOT prevent logging $e
Definition hooks.txt:2175
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:37
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))
$params