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