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