MediaWiki  master
ApiWatch.php
Go to the documentation of this file.
1 <?php
25 
31 class ApiWatch extends ApiBase {
32  private $mPageSet = null;
33 
35  private $expiryEnabled;
36 
38  private $maxDuration;
39 
40  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
41  parent::__construct( $mainModule, $moduleName, $modulePrefix );
42 
43  $this->expiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
44  $this->maxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
45  }
46 
47  public function execute() {
48  $user = $this->getUser();
49  if ( !$user->isLoggedIn() ) {
50  $this->dieWithError( 'watchlistanontext', 'notloggedin' );
51  }
52 
53  $this->checkUserRightsAny( 'editmywatchlist' );
54 
55  $params = $this->extractRequestParams();
56 
57  $continuationManager = new ApiContinuationManager( $this, [], [] );
58  $this->setContinuationManager( $continuationManager );
59 
60  $pageSet = $this->getPageSet();
61  // by default we use pageset to extract the page to work on.
62  // title is still supported for backward compatibility
63  if ( !isset( $params['title'] ) ) {
64  $pageSet->execute();
65  $res = $pageSet->getInvalidTitlesAndRevisions( [
66  'invalidTitles',
67  'special',
68  'missingIds',
69  'missingRevIds',
70  'interwikiTitles'
71  ] );
72 
73  foreach ( $pageSet->getMissingTitles() as $title ) {
74  $r = $this->watchTitle( $title, $user, $params );
75  $r['missing'] = true;
76  $res[] = $r;
77  }
78 
79  foreach ( $pageSet->getGoodTitles() as $title ) {
80  $r = $this->watchTitle( $title, $user, $params );
81  $res[] = $r;
82  }
84  } else {
85  // dont allow use of old title parameter with new pageset parameters.
86  $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), function ( $x ) {
87  return $x !== null && $x !== false;
88  } ) );
89 
90  if ( $extraParams ) {
91  $this->dieWithError(
92  [
93  'apierror-invalidparammix-cannotusewith',
94  $this->encodeParamName( 'title' ),
95  $pageSet->encodeParamName( $extraParams[0] )
96  ],
97  'invalidparammix'
98  );
99  }
100 
101  $title = Title::newFromText( $params['title'] );
102  if ( !$title || !$title->isWatchable() ) {
103  $this->dieWithError( [ 'invalidtitle', $params['title'] ] );
104  }
105  $res = $this->watchTitle( $title, $user, $params, true );
106  }
107  $this->getResult()->addValue( null, $this->getModuleName(), $res );
108 
109  $this->setContinuationManager( null );
110  $continuationManager->setContinuationIntoResult( $this->getResult() );
111  }
112 
113  private function watchTitle( Title $title, User $user, array $params,
114  $compatibilityMode = false
115  ) {
116  $res = [ 'title' => $title->getPrefixedText(), 'ns' => $title->getNamespace() ];
117 
118  if ( !$title->isWatchable() ) {
119  $res['watchable'] = 0;
120  return $res;
121  }
122 
123  if ( $params['unwatch'] ) {
124  $status = UnwatchAction::doUnwatch( $title, $user );
125  $res['unwatched'] = $status->isOK();
126  } else {
127  $expiry = null;
128 
129  // NOTE: If an expiry parameter isn't given, any existing expiries remain unchanged.
130  if ( $this->expiryEnabled && isset( $params['expiry'] ) ) {
131  $expiry = $params['expiry'];
132  $res['expiry'] = ApiResult::formatExpiry( $expiry );
133  }
134 
135  $status = WatchAction::doWatch( $title, $user, User::CHECK_USER_RIGHTS, $expiry );
136  $res['watched'] = $status->isOK();
137  }
138 
139  if ( !$status->isOK() ) {
140  if ( $compatibilityMode ) {
141  $this->dieStatus( $status );
142  }
143  $res['errors'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'error' );
144  $res['warnings'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'warning' );
145  if ( !$res['warnings'] ) {
146  unset( $res['warnings'] );
147  }
148  }
149 
150  return $res;
151  }
152 
157  private function getPageSet() {
158  if ( $this->mPageSet === null ) {
159  $this->mPageSet = new ApiPageSet( $this );
160  }
161 
162  return $this->mPageSet;
163  }
164 
165  public function mustBePosted() {
166  return true;
167  }
168 
169  public function isWriteMode() {
170  return true;
171  }
172 
173  public function needsToken() {
174  return 'watch';
175  }
176 
177  public function getAllowedParams( $flags = 0 ) {
178  $result = [
179  'title' => [
180  ParamValidator::PARAM_TYPE => 'string',
181  ParamValidator::PARAM_DEPRECATED => true,
182  ],
183  'expiry' => [
184  ParamValidator::PARAM_TYPE => 'expiry',
185  ExpiryDef::PARAM_MAX => $this->maxDuration,
186  ExpiryDef::PARAM_USE_MAX => true,
187  ],
188  'unwatch' => false,
189  'continue' => [
190  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
191  ],
192  ];
193 
194  // If expiry is not enabled, don't accept the parameter.
195  if ( !$this->expiryEnabled ) {
196  unset( $result['expiry'] );
197  }
198 
199  if ( $flags ) {
200  $result += $this->getPageSet()->getFinalParams( $flags );
201  }
202 
203  return $result;
204  }
205 
206  protected function getExamplesMessages() {
207  // Logically expiry example should go before unwatch examples.
208  $examples = [
209  'action=watch&titles=Main_Page&token=123ABC'
210  => 'apihelp-watch-example-watch',
211  ];
212  if ( $this->expiryEnabled ) {
213  $examples['action=watch&titles=Main_Page|Foo|Bar&expiry=1%20month&token=123ABC']
214  = 'apihelp-watch-example-watch-expiry';
215  }
216 
217  return array_merge( $examples, [
218  'action=watch&titles=Main_Page&unwatch=&token=123ABC'
219  => 'apihelp-watch-example-unwatch',
220  'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
221  => 'apihelp-watch-example-generator',
222  ] );
223  }
224 
225  public function getHelpUrls() {
226  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watch';
227  }
228 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:47
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:67
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:329
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch a page.
Definition: WatchAction.php:207
ApiWatch\getPageSet
getPageSet()
Get a cached instance of an ApiPageSet object.
Definition: ApiWatch.php:157
ApiWatch\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiWatch.php:225
ApiWatch
API module to allow users to watch a page.
Definition: ApiWatch.php:31
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:1382
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:107
WatchAction\doUnwatch
static doUnwatch(Title $title, User $user)
Unwatch a page.
Definition: WatchAction.php:237
ApiWatch\$mPageSet
$mPageSet
Definition: ApiWatch.php:32
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:565
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1484
ApiBase\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiBase.php:621
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:131
ApiWatch\getAllowedParams
getAllowedParams( $flags=0)
Definition: ApiWatch.php:177
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:52
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:16
ApiWatch\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request Stable to override.
Definition: ApiWatch.php:165
ApiWatch\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiWatch.php:47
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:717
$title
$title
Definition: testCompression.php:38
User\CHECK_USER_RIGHTS
const CHECK_USER_RIGHTS
Definition: User.php:88
ApiWatch\watchTitle
watchTitle(Title $title, User $user, array $params, $compatibilityMode=false)
Definition: ApiWatch.php:113
ApiWatch\$expiryEnabled
bool $expiryEnabled
Whether watchlist expiries are enabled.
Definition: ApiWatch.php:35
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:695
ApiWatch\__construct
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Stable to call.
Definition: ApiWatch.php:40
Title
Represents a title within MediaWiki.
Definition: Title.php:42
ApiWatch\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiWatch.php:169
ApiWatch\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiWatch.php:173
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1440
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:444
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1193
ApiWatch\$maxDuration
string $maxDuration
Relative maximum expiry.
Definition: ApiWatch.php:38
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:59
ApiWatch\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiWatch.php:206
ApiBase\getErrorFormatter
getErrorFormatter()
Get the error formatter Stable to override.
Definition: ApiBase.php:580
Wikimedia\ParamValidator\ParamValidator
Service for formatting and validating API parameters.
Definition: ParamValidator.php:42