MediaWiki master
ApiWatch.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
24
30class ApiWatch extends ApiBase {
32 private $mPageSet = null;
33
35 private $expiryEnabled;
36
38 private $maxDuration;
39
41 private $labelsEnabled;
42
43 public function __construct(
44 ApiMain $mainModule,
45 string $moduleName,
46 private readonly WatchlistManager $watchlistManager,
47 private readonly TitleFormatter $titleFormatter,
48 private readonly WatchlistLabelStore $watchlistLabelStore,
49 private readonly WatchedItemStoreInterface $watchedItemStore,
50 private readonly NamespaceInfo $namespaceInfo,
51 ) {
52 parent::__construct( $mainModule, $moduleName );
53
54 $this->expiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
55 $this->maxDuration = $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
56 $this->labelsEnabled = $this->getConfig()->get( MainConfigNames::EnableWatchlistLabels );
57 }
58
59 public function execute() {
60 $user = $this->getUser();
61 if ( !$user->isRegistered()
62 || ( $user->isTemp() && !$user->isAllowed( 'editmywatchlist' ) )
63 ) {
64 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
65 }
66
67 $this->checkUserRightsAny( 'editmywatchlist' );
68
69 $params = $this->extractRequestParams();
70
71 $continuationManager = new ApiContinuationManager( $this, [], [] );
72 $this->setContinuationManager( $continuationManager );
73
74 // Validate labels
75 $validLabels = [];
76 $labelError = null;
77 if ( isset( $params['labels'] ) && $params['labels'] ) {
78 $validationResult = $this->validateLabels( $user, $params['labels'] );
79 $validLabels = $validationResult['labels'];
80 $labelError = $validationResult['error'];
81 }
82
83 $pageSet = $this->getPageSet();
84 // by default we use pageset to extract the page to work on.
85 // title is still supported for backward compatibility
86 if ( !isset( $params['title'] ) ) {
87 $pageSet->execute();
88 $res = $pageSet->getInvalidTitlesAndRevisions( [
89 'invalidTitles',
90 'special',
91 'missingIds',
92 'missingRevIds',
93 'interwikiTitles'
94 ] );
95
96 foreach ( $pageSet->getMissingPages() as $page ) {
97 $r = $this->watchTitle( $page, $user, $params, false, $validLabels, $labelError );
98 $r['missing'] = true;
99 $res[] = $r;
100 }
101
102 foreach ( $pageSet->getGoodPages() as $page ) {
103 $r = $this->watchTitle( $page, $user, $params, false, $validLabels, $labelError );
104 $res[] = $r;
105 }
106 ApiResult::setIndexedTagName( $res, 'w' );
107 } else {
108 // dont allow use of old title parameter with new pageset parameters.
109 $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), static function ( $x ) {
110 return $x !== null && $x !== false;
111 } ) );
112
113 if ( $extraParams ) {
114 $this->dieWithError(
115 [
116 'apierror-invalidparammix-cannotusewith',
117 $this->encodeParamName( 'title' ),
118 $pageSet->encodeParamName( $extraParams[0] )
119 ],
120 'invalidparammix'
121 );
122 }
123
124 $title = Title::newFromText( $params['title'] );
125 if ( !$title || !$this->watchlistManager->isWatchable( $title ) ) {
126 $this->dieWithError( [ 'invalidtitle', $params['title'] ] );
127 }
128 $res = $this->watchTitle( $title, $user, $params, true, $validLabels, $labelError );
129 }
130 $this->getResult()->addValue( null, $this->getModuleName(), $res );
131
132 $this->setContinuationManager( null );
133 $continuationManager->setContinuationIntoResult( $this->getResult() );
134 }
135
136 private function watchTitle( PageIdentity $page, User $user, array $params,
137 bool $compatibilityMode = false,
138 array $validLabels = [],
139 ?array $labelError = null
140 ): array {
141 $res = [ 'title' => $this->titleFormatter->getPrefixedText( $page ), 'ns' => $page->getNamespace() ];
142
143 if ( !$this->watchlistManager->isWatchable( $page ) ) {
144 $res['watchable'] = 0;
145 return $res;
146 }
147
148 if ( $params['unwatch'] ) {
149 $status = $this->watchlistManager->removeWatch( $user, $page );
150 $res['unwatched'] = $status->isOK();
151 } else {
152 $expiry = null;
153
154 // NOTE: If an expiry parameter isn't given, any existing expiries remain unchanged.
155 if ( $this->expiryEnabled && isset( $params['expiry'] ) ) {
156 $expiry = $params['expiry'];
157 $res['expiry'] = ApiResult::formatExpiry( $expiry );
158 }
159
160 $status = $this->watchlistManager->addWatch( $user, $page, $expiry );
161 $res['watched'] = $status->isOK();
162
163 // Apply labels if provided and watching was successful
164 if ( $status->isOK() && $validLabels ) {
165 $this->applyLabelsToWatchedPage( $user, $page, $validLabels, $compatibilityMode, $res );
166 // Add error to response if there were invalid labels but we applied the valid ones
167 if ( $labelError ) {
168 if ( !isset( $res['errors'] ) ) {
169 $res['errors'] = [];
170 }
171 $res['errors'][] = $labelError;
172 }
173 } elseif ( $status->isOK() && $labelError ) {
174 // Add label error to response if labels were requested but had an error
175 $res['errors'] = [ $labelError ];
176 }
177 }
178
179 if ( !$status->isOK() ) {
180 if ( $compatibilityMode ) {
181 $this->dieStatus( $status );
182 }
183 $res['errors'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'error' );
184 $res['warnings'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'warning' );
185 if ( !$res['warnings'] ) {
186 unset( $res['warnings'] );
187 }
188 }
189
190 return $res;
191 }
192
204 private function applyLabelsToWatchedPage(
205 User $user,
206 PageIdentity $page,
207 array $validLabels,
208 bool $compatibilityMode,
209 array &$res
210 ): void {
211 if ( !$this->labelsEnabled ) {
212 $res['errors'] = [ $this->getErrorFormatter()->formatMessage(
213 [ 'apierror-labels-disabled', 'labels-disabled' ]
214 ) ];
215 if ( $compatibilityMode ) {
216 $this->dieWithError( 'apierror-labels-disabled', 'labels-disabled' );
217 }
218 return;
219 }
220
221 $title = Title::newFromPageIdentity( $page );
222 $pagesToWatch = [ $page ];
223
224 // Also watch the talk page if this page can have one
225 if ( $this->namespaceInfo->canHaveTalkPage( $title ) ) {
226 $talkPageTarget = $this->namespaceInfo->getTalkPage( $title );
227 // Convert LinkTarget to PageReferenceValue for consistency
228 $talkPage = PageReferenceValue::localReference(
229 $talkPageTarget->getNamespace(),
230 $talkPageTarget->getDBkey()
231 );
232 $pagesToWatch[] = $talkPage;
233 }
234
235 // Get existing labels to remove
236 foreach ( $pagesToWatch as $pageToWatch ) {
237 $watchedItem = $this->watchedItemStore->loadWatchedItem( $user, $pageToWatch );
238 if ( $watchedItem ) {
239 $existingLabels = $watchedItem->getLabels();
240 // Remove all existing labels before adding new ones
241 if ( $existingLabels ) {
242 $this->watchedItemStore->removeLabels( $user, [ $pageToWatch ], $existingLabels );
243 }
244 }
245 }
246
247 // Add the new labels
248 if ( $validLabels ) {
249 $this->watchedItemStore->addLabels( $user, $pagesToWatch, $validLabels );
250 // Return the labels that we just saved
251 $res['labels'] = array_map( static function ( WatchlistLabel $label ) {
252 return [
253 'id' => $label->getId(),
254 'name' => $label->getName(),
255 ];
256 }, $validLabels );
257 }
258 }
259
267 private function validateLabels( User $user, array $labelIds ): array {
268 // Check if labels are enabled
269 if ( !$this->labelsEnabled ) {
270 return [
271 'labels' => [],
272 'error' => $this->getErrorFormatter()->formatMessage(
273 [ 'apierror-labels-disabled', 'labels-disabled' ]
274 )
275 ];
276 }
277
278 $validLabels = $this->watchlistLabelStore->loadByIds( $user, $labelIds );
279 $hasError = count( $labelIds ) !== count( $validLabels );
280
281 return [
282 'labels' => $validLabels,
283 'error' => $hasError ? $this->getErrorFormatter()->formatMessage(
284 [ 'apierror-invalid-label-id', 'invalid-label-id' ]
285 ) : null
286 ];
287 }
288
293 private function getPageSet() {
294 $this->mPageSet ??= new ApiPageSet( $this );
295
296 return $this->mPageSet;
297 }
298
300 public function mustBePosted() {
301 return true;
302 }
303
305 public function isWriteMode() {
306 return true;
307 }
308
310 public function needsToken() {
311 return 'watch';
312 }
313
315 public function getAllowedParams( $flags = 0 ) {
316 $result = [
317 'title' => [
318 ParamValidator::PARAM_TYPE => 'string',
319 ParamValidator::PARAM_DEPRECATED => true,
320 ],
321 'expiry' => [
322 ParamValidator::PARAM_TYPE => 'expiry',
323 ExpiryDef::PARAM_MAX => $this->maxDuration,
324 ExpiryDef::PARAM_USE_MAX => true,
325 ],
326 'labels' => [
327 ParamValidator::PARAM_TYPE => 'integer',
328 ParamValidator::PARAM_ISMULTI => true,
329 ApiBase::PARAM_HELP_MSG => 'apihelp-watch-param-labels',
330 ],
331 'unwatch' => false,
332 'continue' => [
333 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
334 ],
335 ];
336
337 // If expiry is not enabled, don't accept the parameter.
338 if ( !$this->expiryEnabled ) {
339 unset( $result['expiry'] );
340 }
341
342 if ( $flags ) {
343 $result += $this->getPageSet()->getFinalParams( $flags );
344 }
345
346 return $result;
347 }
348
350 protected function getExamplesMessages() {
351 $title = Title::newMainPage()->getPrefixedText();
352 $mp = rawurlencode( $title );
353
354 // Logically expiry example should go before unwatch examples.
355 $examples = [
356 "action=watch&titles={$mp}&token=123ABC"
357 => 'apihelp-watch-example-watch',
358 ];
359 if ( $this->expiryEnabled ) {
360 $examples["action=watch&titles={$mp}|Foo|Bar&expiry=1%20month&token=123ABC"]
361 = 'apihelp-watch-example-watch-expiry';
362 }
363
364 // Add example with labels
365 $examples["action=watch&titles={$mp}&labels=1%7C2&token=123ABC"]
366 = 'apihelp-watch-example-watch-labels';
367
368 return array_merge( $examples, [
369 "action=watch&titles={$mp}&unwatch=&token=123ABC"
370 => 'apihelp-watch-example-unwatch',
371 'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
372 => 'apihelp-watch-example-generator',
373 ] );
374 }
375
377 public function getHelpUrls() {
378 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watch';
379 }
380}
381
383class_alias( ApiWatch::class, 'ApiWatch' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:60
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
checkUserRightsAny( $rights)
Helper function for permission-denied errors.
Definition ApiBase.php:1631
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:557
getResult()
Get the result object.
Definition ApiBase.php:696
setContinuationManager(?ApiContinuationManager $manager=null)
Definition ApiBase.php:743
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition ApiBase.php:815
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1573
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:66
This class contains a list of pages that the client has requested.
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
API module to allow users to watch a page.
Definition ApiWatch.php:30
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiWatch.php:59
__construct(ApiMain $mainModule, string $moduleName, private readonly WatchlistManager $watchlistManager, private readonly TitleFormatter $titleFormatter, private readonly WatchlistLabelStore $watchlistLabelStore, private readonly WatchedItemStoreInterface $watchedItemStore, private readonly NamespaceInfo $namespaceInfo,)
Definition ApiWatch.php:43
mustBePosted()
Indicates whether this module must be called with a POST request.Implementations of this method must ...
Definition ApiWatch.php:300
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
Definition ApiWatch.php:377
needsToken()
Returns the token type this module requires in order to execute.Modules are strongly encouraged to us...
Definition ApiWatch.php:310
getAllowedParams( $flags=0)
Definition ApiWatch.php:315
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition ApiWatch.php:350
isWriteMode()
Indicates whether this module requires write access to the wiki.API modules must override this method...
Definition ApiWatch.php:305
A class containing constants representing the names of configuration variables.
const EnableWatchlistLabels
Name constant for the EnableWatchlistLabels setting, for use with Config::get()
const WatchlistExpiry
Name constant for the WatchlistExpiry setting, for use with Config::get()
const WatchlistExpiryMaxDuration
Name constant for the WatchlistExpiryMaxDuration setting, for use with Config::get()
Immutable value object representing a page reference.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
A title formatter service for MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:69
User class for the MediaWiki software.
Definition User.php:130
Service class for storage of watchlist labels.
Service for formatting and validating API parameters.
Type definition for expiry timestamps.
Definition ExpiryDef.php:18
Interface for objects (potentially) representing an editable wiki page.