MediaWiki  1.28.1
Go to the documentation of this file.
1 <?php
32 class ApiWatch extends ApiBase {
33  private $mPageSet = null;
35  public function execute() {
36  $user = $this->getUser();
37  if ( !$user->isLoggedIn() ) {
38  $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
39  }
41  if ( !$user->isAllowed( 'editmywatchlist' ) ) {
42  $this->dieUsage( 'You don\'t have permission to edit your watchlist', 'permissiondenied' );
43  }
45  $params = $this->extractRequestParams();
47  $continuationManager = new ApiContinuationManager( $this, [], [] );
48  $this->setContinuationManager( $continuationManager );
50  $pageSet = $this->getPageSet();
51  // by default we use pageset to extract the page to work on.
52  // title is still supported for backward compatibility
53  if ( !isset( $params['title'] ) ) {
54  $pageSet->execute();
55  $res = $pageSet->getInvalidTitlesAndRevisions( [
56  'invalidTitles',
57  'special',
58  'missingIds',
59  'missingRevIds',
60  'interwikiTitles'
61  ] );
63  foreach ( $pageSet->getMissingTitles() as $title ) {
64  $r = $this->watchTitle( $title, $user, $params );
65  $r['missing'] = 1;
66  $res[] = $r;
67  }
69  foreach ( $pageSet->getGoodTitles() as $title ) {
70  $r = $this->watchTitle( $title, $user, $params );
71  $res[] = $r;
72  }
74  } else {
75  // dont allow use of old title parameter with new pageset parameters.
76  $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), function ( $x ) {
77  return $x !== null && $x !== false;
78  } ) );
80  if ( $extraParams ) {
81  $p = $this->getModulePrefix();
82  $this->dieUsage(
83  "The parameter {$p}title can not be used with " . implode( ', ', $extraParams ),
84  'invalidparammix'
85  );
86  }
88  $title = Title::newFromText( $params['title'] );
89  if ( !$title || !$title->isWatchable() ) {
90  $this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
91  }
92  $res = $this->watchTitle( $title, $user, $params, true );
93  }
94  $this->getResult()->addValue( null, $this->getModuleName(), $res );
96  $this->setContinuationManager( null );
97  $continuationManager->setContinuationIntoResult( $this->getResult() );
98  }
101  $compatibilityMode = false
102  ) {
103  if ( !$title->isWatchable() ) {
104  return [ 'title' => $title->getPrefixedText(), 'watchable' => 0 ];
105  }
107  $res = [ 'title' => $title->getPrefixedText() ];
109  if ( $params['unwatch'] ) {
110  $status = UnwatchAction::doUnwatch( $title, $user );
111  $res['unwatched'] = $status->isOK();
112  if ( $status->isOK() ) {
113  $msgKey = $title->isTalkPage() ? 'removedwatchtext-talk' : 'removedwatchtext';
114  $res['message'] = $this->msg( $msgKey, $title->getPrefixedText() )
115  ->title( $title )->parseAsBlock();
116  }
117  } else {
118  $status = WatchAction::doWatch( $title, $user );
119  $res['watched'] = $status->isOK();
120  if ( $status->isOK() ) {
121  $msgKey = $title->isTalkPage() ? 'addedwatchtext-talk' : 'addedwatchtext';
122  $res['message'] = $this->msg( $msgKey, $title->getPrefixedText() )
123  ->title( $title )->parseAsBlock();
124  }
125  }
127  if ( !$status->isOK() ) {
128  if ( $compatibilityMode ) {
129  $this->dieStatus( $status );
130  }
131  $res['error'] = $this->getErrorFromStatus( $status );
132  }
134  return $res;
135  }
141  private function getPageSet() {
142  if ( $this->mPageSet === null ) {
143  $this->mPageSet = new ApiPageSet( $this );
144  }
146  return $this->mPageSet;
147  }
149  public function mustBePosted() {
150  return true;
151  }
153  public function isWriteMode() {
154  return true;
155  }
157  public function needsToken() {
158  return 'watch';
159  }
161  public function getAllowedParams( $flags = 0 ) {
162  $result = [
163  'title' => [
164  ApiBase::PARAM_TYPE => 'string',
166  ],
167  'unwatch' => false,
168  'continue' => [
169  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
170  ],
171  ];
172  if ( $flags ) {
173  $result += $this->getPageSet()->getFinalParams( $flags );
174  }
176  return $result;
177  }
179  protected function getExamplesMessages() {
180  return [
181  'action=watch&titles=Main_Page&token=123ABC'
182  => 'apihelp-watch-example-watch',
183  'action=watch&titles=Main_Page&unwatch=&token=123ABC'
184  => 'apihelp-watch-example-unwatch',
185  'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
186  => 'apihelp-watch-example-generator',
187  ];
188  }
190  public function getHelpUrls() {
191  return '';
192  }
193 }
watchTitle(Title $title, User $user, array $params, $compatibilityMode=false)
Definition: ApiWatch.php:100
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
Definition: ApiWatch.php:153
the array() calling protocol came about after MediaWiki 1.4rc1.
Get the result object.
Definition: ApiBase.php:584
Definition: ApiWatch.php:161
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:41
Can this title be added to a user's watchlist?
Definition: Title.php:1042
Is this a talk page of some sort?
Definition: Title.php:1296
This manages continuation state.
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
Get the prefixed title with spaces.
Definition: Title.php:1455
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
Definition: ApiWatch.php:190
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1936
Get a Message object with context set Parameters are the same as wfMessage()
getErrorFromStatus($status, &$extraData=null)
Get error (as code, string) from a Status object.
Definition: ApiBase.php:1630
Definition: database.txt:21
Definition: ApiWatch.php:179
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS)
Watch a page.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
Definition: ApiWatch.php:157
Definition: ApiWatch.php:35
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
API module to allow users to watch a page.
Definition: ApiWatch.php:32
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:472
Get a cached instance of an ApiPageSet object.
Definition: ApiWatch.php:141
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1585
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
Definition: ApiWatch.php:149
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1674
Set the continuation manager.
Definition: ApiBase.php:638
Get the User object.
Output the error message related to a certain array.
Definition: ApiBase.php:2203
static doUnwatch(Title $title, User $user)
Unwatch a page.