MediaWiki  master
ApiWatch.php
Go to the documentation of this file.
1 <?php
24 
30 class ApiWatch extends ApiBase {
31  private $mPageSet = null;
32 
34  private $expiryEnabled;
35 
36  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
37  parent::__construct( $mainModule, $moduleName, $modulePrefix );
38 
39  $this->expiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
40  }
41 
42  public function execute() {
43  $user = $this->getUser();
44  if ( !$user->isLoggedIn() ) {
45  $this->dieWithError( 'watchlistanontext', 'notloggedin' );
46  }
47 
48  $this->checkUserRightsAny( 'editmywatchlist' );
49 
50  $params = $this->extractRequestParams();
51 
52  $continuationManager = new ApiContinuationManager( $this, [], [] );
53  $this->setContinuationManager( $continuationManager );
54 
55  $pageSet = $this->getPageSet();
56  // by default we use pageset to extract the page to work on.
57  // title is still supported for backward compatibility
58  if ( !isset( $params['title'] ) ) {
59  $pageSet->execute();
60  $res = $pageSet->getInvalidTitlesAndRevisions( [
61  'invalidTitles',
62  'special',
63  'missingIds',
64  'missingRevIds',
65  'interwikiTitles'
66  ] );
67 
68  foreach ( $pageSet->getMissingTitles() as $title ) {
69  $r = $this->watchTitle( $title, $user, $params );
70  $r['missing'] = true;
71  $res[] = $r;
72  }
73 
74  foreach ( $pageSet->getGoodTitles() as $title ) {
75  $r = $this->watchTitle( $title, $user, $params );
76  $res[] = $r;
77  }
79  } else {
80  // dont allow use of old title parameter with new pageset parameters.
81  $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), function ( $x ) {
82  return $x !== null && $x !== false;
83  } ) );
84 
85  if ( $extraParams ) {
86  $this->dieWithError(
87  [
88  'apierror-invalidparammix-cannotusewith',
89  $this->encodeParamName( 'title' ),
90  $pageSet->encodeParamName( $extraParams[0] )
91  ],
92  'invalidparammix'
93  );
94  }
95 
96  $title = Title::newFromText( $params['title'] );
97  if ( !$title || !$title->isWatchable() ) {
98  $this->dieWithError( [ 'invalidtitle', $params['title'] ] );
99  }
100  $res = $this->watchTitle( $title, $user, $params, true );
101  }
102  $this->getResult()->addValue( null, $this->getModuleName(), $res );
103 
104  $this->setContinuationManager( null );
105  $continuationManager->setContinuationIntoResult( $this->getResult() );
106  }
107 
113  private function normalizeAndValidateExpiry( string $expiryParam ): string {
114  $expiry = WatchedItem::normalizeExpiry( $expiryParam );
115 
116  if ( $expiry === false ) {
117  $this->dieWithError( [
118  'apierror-invalidexpiry',
119  Message::plaintextParam( $expiryParam )
120  ] );
121  }
122  if ( $expiry < wfTimestampNow() ) {
123  $this->dieWithError( [
124  'apierror-pastexpiry',
125  Message::plaintextParam( $expiryParam )
126  ] );
127  }
128 
129  return $expiry;
130  }
131 
132  private function watchTitle( Title $title, User $user, array $params,
133  $compatibilityMode = false
134  ) {
135  $res = [ 'title' => $title->getPrefixedText(), 'ns' => $title->getNamespace() ];
136 
137  if ( !$title->isWatchable() ) {
138  $res['watchable'] = 0;
139  return $res;
140  }
141 
142  if ( $params['unwatch'] ) {
143  $status = UnwatchAction::doUnwatch( $title, $user );
144  $res['unwatched'] = $status->isOK();
145  } else {
146  $expiry = null;
147 
148  // NOTE: If an expiry parameter isn't given, any existing expiries remain unchanged.
149  if ( $this->expiryEnabled && isset( $params['expiry'] ) ) {
150  $expiry = $this->normalizeAndValidateExpiry( $params['expiry'] );
151  $res['expiry'] = ApiResult::formatExpiry( $expiry );
152  }
153 
154  $status = WatchAction::doWatch( $title, $user, User::CHECK_USER_RIGHTS, $expiry );
155  $res['watched'] = $status->isOK();
156  }
157 
158  if ( !$status->isOK() ) {
159  if ( $compatibilityMode ) {
160  $this->dieStatus( $status );
161  }
162  $res['errors'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'error' );
163  $res['warnings'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'warning' );
164  if ( !$res['warnings'] ) {
165  unset( $res['warnings'] );
166  }
167  }
168 
169  return $res;
170  }
171 
176  private function getPageSet() {
177  if ( $this->mPageSet === null ) {
178  $this->mPageSet = new ApiPageSet( $this );
179  }
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 => 'string',
204  ],
205  'unwatch' => false,
206  'continue' => [
207  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
208  ],
209  ];
210 
211  // If expiry is not enabled, don't accept the parameter.
212  if ( !$this->expiryEnabled ) {
213  unset( $result['expiry'] );
214  }
215 
216  if ( $flags ) {
217  $result += $this->getPageSet()->getFinalParams( $flags );
218  }
219 
220  return $result;
221  }
222 
223  protected function getExamplesMessages() {
224  // Logically expiry example should go before unwatch examples.
225  $examples = [
226  'action=watch&titles=Main_Page&token=123ABC'
227  => 'apihelp-watch-example-watch',
228  ];
229  if ( $this->expiryEnabled ) {
230  $examples['action=watch&titles=Main_Page|Foo|Bar&expiry=1%20month&token=123ABC']
231  = 'apihelp-watch-example-watch-expiry';
232  }
233 
234  return array_merge( $examples, [
235  'action=watch&titles=Main_Page&unwatch=&token=123ABC'
236  => 'apihelp-watch-example-unwatch',
237  'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
238  => 'apihelp-watch-example-generator',
239  ] );
240  }
241 
242  public function getHelpUrls() {
243  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watch';
244  }
245 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:44
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:63
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:332
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch a page.
Definition: WatchAction.php:118
ApiWatch\getPageSet
getPageSet()
Get a cached instance of an ApiPageSet object.
Definition: ApiWatch.php:176
ApiWatch\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiWatch.php:242
ApiWatch
API module to allow users to watch a page.
Definition: ApiWatch.php:30
ApiContinuationManager
This manages continuation state.
Definition: ApiContinuationManager.php:26
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1379
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:96
WatchAction\doUnwatch
static doUnwatch(Title $title, User $user)
Unwatch a page.
Definition: WatchAction.php:148
ApiWatch\$mPageSet
$mPageSet
Definition: ApiWatch.php:31
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:538
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1481
ApiBase\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiBase.php:592
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
ApiWatch\getAllowedParams
getAllowedParams( $flags=0)
Definition: ApiWatch.php:196
ApiPageSet
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:42
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:48
WatchedItem\normalizeExpiry
static normalizeExpiry(?string $expiry)
Normalize a user-inputted expiry.
Definition: WatchedItem.php:139
ApiWatch\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiWatch.php:184
ApiWatch\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiWatch.php:42
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:659
$title
$title
Definition: testCompression.php:38
User\CHECK_USER_RIGHTS
const CHECK_USER_RIGHTS
Definition: User.php:81
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1835
ApiWatch\watchTitle
watchTitle(Title $title, User $user, array $params, $compatibilityMode=false)
Definition: ApiWatch.php:132
ApiWatch\normalizeAndValidateExpiry
normalizeAndValidateExpiry(string $expiryParam)
Normalize the expiry into TS_MW format, or throw errors if it is invalid.
Definition: ApiWatch.php:113
ApiWatch\$expiryEnabled
bool $expiryEnabled
Whether watchlist expiries are enabled.
Definition: ApiWatch.php:34
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
ApiBase\encodeParamName
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:637
ApiWatch\__construct
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Definition: ApiWatch.php:36
Title
Represents a title within MediaWiki.
Definition: Title.php:42
ApiWatch\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiWatch.php:188
ApiWatch\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiWatch.php:192
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1437
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:418
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1193
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:54
ApiWatch\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiWatch.php:223
ApiBase\getErrorFormatter
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:552
Wikimedia\ParamValidator\ParamValidator
Service for formatting and validating API parameters.
Definition: ParamValidator.php:42