MediaWiki master
ApiWatch.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
19
25class ApiWatch extends ApiBase {
27 private $mPageSet = null;
28
30 private $expiryEnabled;
31
33 private $maxDuration;
34
36 private TitleFormatter $titleFormatter;
37
38 public function __construct(
39 ApiMain $mainModule,
40 string $moduleName,
42 TitleFormatter $titleFormatter
43 ) {
44 parent::__construct( $mainModule, $moduleName );
45
46 $this->watchlistManager = $watchlistManager;
47 $this->titleFormatter = $titleFormatter;
48 $this->expiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
49 $this->maxDuration = $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
50 }
51
52 public function execute() {
53 $user = $this->getUser();
54 if ( !$user->isRegistered()
55 || ( $user->isTemp() && !$user->isAllowed( 'editmywatchlist' ) )
56 ) {
57 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
58 }
59
60 $this->checkUserRightsAny( 'editmywatchlist' );
61
62 $params = $this->extractRequestParams();
63
64 $continuationManager = new ApiContinuationManager( $this, [], [] );
65 $this->setContinuationManager( $continuationManager );
66
67 $pageSet = $this->getPageSet();
68 // by default we use pageset to extract the page to work on.
69 // title is still supported for backward compatibility
70 if ( !isset( $params['title'] ) ) {
71 $pageSet->execute();
72 $res = $pageSet->getInvalidTitlesAndRevisions( [
73 'invalidTitles',
74 'special',
75 'missingIds',
76 'missingRevIds',
77 'interwikiTitles'
78 ] );
79
80 foreach ( $pageSet->getMissingPages() as $page ) {
81 $r = $this->watchTitle( $page, $user, $params );
82 $r['missing'] = true;
83 $res[] = $r;
84 }
85
86 foreach ( $pageSet->getGoodPages() as $page ) {
87 $r = $this->watchTitle( $page, $user, $params );
88 $res[] = $r;
89 }
91 } else {
92 // dont allow use of old title parameter with new pageset parameters.
93 $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), static function ( $x ) {
94 return $x !== null && $x !== false;
95 } ) );
96
97 if ( $extraParams ) {
98 $this->dieWithError(
99 [
100 'apierror-invalidparammix-cannotusewith',
101 $this->encodeParamName( 'title' ),
102 $pageSet->encodeParamName( $extraParams[0] )
103 ],
104 'invalidparammix'
105 );
106 }
107
108 $title = Title::newFromText( $params['title'] );
109 if ( !$title || !$this->watchlistManager->isWatchable( $title ) ) {
110 $this->dieWithError( [ 'invalidtitle', $params['title'] ] );
111 }
112 $res = $this->watchTitle( $title, $user, $params, true );
113 }
114 $this->getResult()->addValue( null, $this->getModuleName(), $res );
115
116 $this->setContinuationManager( null );
117 $continuationManager->setContinuationIntoResult( $this->getResult() );
118 }
119
120 private function watchTitle( PageIdentity $page, User $user, array $params,
121 bool $compatibilityMode = false
122 ): array {
123 $res = [ 'title' => $this->titleFormatter->getPrefixedText( $page ), 'ns' => $page->getNamespace() ];
124
125 if ( !$this->watchlistManager->isWatchable( $page ) ) {
126 $res['watchable'] = 0;
127 return $res;
128 }
129
130 if ( $params['unwatch'] ) {
131 $status = $this->watchlistManager->removeWatch( $user, $page );
132 $res['unwatched'] = $status->isOK();
133 } else {
134 $expiry = null;
135
136 // NOTE: If an expiry parameter isn't given, any existing expiries remain unchanged.
137 if ( $this->expiryEnabled && isset( $params['expiry'] ) ) {
138 $expiry = $params['expiry'];
139 $res['expiry'] = ApiResult::formatExpiry( $expiry );
140 }
141
142 $status = $this->watchlistManager->addWatch( $user, $page, $expiry );
143 $res['watched'] = $status->isOK();
144 }
145
146 if ( !$status->isOK() ) {
147 if ( $compatibilityMode ) {
148 $this->dieStatus( $status );
149 }
150 $res['errors'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'error' );
151 $res['warnings'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'warning' );
152 if ( !$res['warnings'] ) {
153 unset( $res['warnings'] );
154 }
155 }
156
157 return $res;
158 }
159
164 private function getPageSet() {
165 $this->mPageSet ??= new ApiPageSet( $this );
166
167 return $this->mPageSet;
168 }
169
171 public function mustBePosted() {
172 return true;
173 }
174
176 public function isWriteMode() {
177 return true;
178 }
179
181 public function needsToken() {
182 return 'watch';
183 }
184
186 public function getAllowedParams( $flags = 0 ) {
187 $result = [
188 'title' => [
189 ParamValidator::PARAM_TYPE => 'string',
190 ParamValidator::PARAM_DEPRECATED => true,
191 ],
192 'expiry' => [
193 ParamValidator::PARAM_TYPE => 'expiry',
194 ExpiryDef::PARAM_MAX => $this->maxDuration,
195 ExpiryDef::PARAM_USE_MAX => true,
196 ],
197 'unwatch' => false,
198 'continue' => [
199 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
200 ],
201 ];
202
203 // If expiry is not enabled, don't accept the parameter.
204 if ( !$this->expiryEnabled ) {
205 unset( $result['expiry'] );
206 }
207
208 if ( $flags ) {
209 $result += $this->getPageSet()->getFinalParams( $flags );
210 }
211
212 return $result;
213 }
214
216 protected function getExamplesMessages() {
217 $title = Title::newMainPage()->getPrefixedText();
218 $mp = rawurlencode( $title );
219
220 // Logically expiry example should go before unwatch examples.
221 $examples = [
222 "action=watch&titles={$mp}&token=123ABC"
223 => 'apihelp-watch-example-watch',
224 ];
225 if ( $this->expiryEnabled ) {
226 $examples["action=watch&titles={$mp}|Foo|Bar&expiry=1%20month&token=123ABC"]
227 = 'apihelp-watch-example-watch-expiry';
228 }
229
230 return array_merge( $examples, [
231 "action=watch&titles={$mp}&unwatch=&token=123ABC"
232 => 'apihelp-watch-example-unwatch',
233 'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
234 => 'apihelp-watch-example-generator',
235 ] );
236 }
237
239 public function getHelpUrls() {
240 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watch';
241 }
242}
243
245class_alias( ApiWatch::class, 'ApiWatch' );
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:61
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1511
checkUserRightsAny( $rights)
Helper function for permission-denied errors.
Definition ApiBase.php:1620
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:543
getResult()
Get the result object.
Definition ApiBase.php:682
setContinuationManager(?ApiContinuationManager $manager=null)
Definition ApiBase.php:729
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:167
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition ApiBase.php:801
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1562
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:823
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:25
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiWatch.php:52
__construct(ApiMain $mainModule, string $moduleName, WatchlistManager $watchlistManager, TitleFormatter $titleFormatter)
Definition ApiWatch.php:38
mustBePosted()
Indicates whether this module must be called with a POST request.Implementations of this method must ...
Definition ApiWatch.php:171
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
Definition ApiWatch.php:239
needsToken()
Returns the token type this module requires in order to execute.Modules are strongly encouraged to us...
Definition ApiWatch.php:181
getAllowedParams( $flags=0)
Definition ApiWatch.php:186
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition ApiWatch.php:216
isWriteMode()
Indicates whether this module requires write access to the wiki.API modules must override this method...
Definition ApiWatch.php:176
WatchlistManager $watchlistManager
Definition ApiWatch.php:35
A class containing constants representing the names of configuration variables.
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()
A title formatter service for MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:69
User class for the MediaWiki software.
Definition User.php:110
isAllowed(string $permission, ?PermissionStatus $status=null)
Checks whether this authority has the given permission in general.
Definition User.php:2130
isTemp()
Is the user an autocreated temporary user?
Definition User.php:3389
isRegistered()
Get whether the user is registered.
Definition User.php:2071
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.