MediaWiki  1.28.1
Go to the documentation of this file.
1 <?php
30 class ApiProtect extends ApiBase {
31  public function execute() {
34  $params = $this->extractRequestParams();
36  $pageObj = $this->getTitleOrPageId( $params, 'fromdbmaster' );
37  $titleObj = $pageObj->getTitle();
39  $errors = $titleObj->getUserPermissionsErrors( 'protect', $this->getUser() );
40  if ( $errors ) {
41  // We don't care about multiple errors, just report one of them
42  $this->dieUsageMsg( reset( $errors ) );
43  }
45  $user = $this->getUser();
46  $tags = $params['tags'];
48  // Check if user can add tags
49  if ( !is_null( $tags ) ) {
50  $ableToTag = ChangeTags::canAddTagsAccompanyingChange( $tags, $user );
51  if ( !$ableToTag->isOK() ) {
52  $this->dieStatus( $ableToTag );
53  }
54  }
56  $expiry = (array)$params['expiry'];
57  if ( count( $expiry ) != count( $params['protections'] ) ) {
58  if ( count( $expiry ) == 1 ) {
59  $expiry = array_fill( 0, count( $params['protections'] ), $expiry[0] );
60  } else {
61  $this->dieUsageMsg( [
62  'toofewexpiries',
63  count( $expiry ),
64  count( $params['protections'] )
65  ] );
66  }
67  }
69  $restrictionTypes = $titleObj->getRestrictionTypes();
71  $protections = [];
72  $expiryarray = [];
73  $resultProtections = [];
74  foreach ( $params['protections'] as $i => $prot ) {
75  $p = explode( '=', $prot );
76  $protections[$p[0]] = ( $p[1] == 'all' ? '' : $p[1] );
78  if ( $titleObj->exists() && $p[0] == 'create' ) {
79  $this->dieUsageMsg( 'create-titleexists' );
80  }
81  if ( !$titleObj->exists() && $p[0] != 'create' ) {
82  $this->dieUsageMsg( 'missingtitle-createonly' );
83  }
85  if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
86  $this->dieUsageMsg( [ 'protect-invalidaction', $p[0] ] );
87  }
88  if ( !in_array( $p[1], $this->getConfig()->get( 'RestrictionLevels' ) ) && $p[1] != 'all' ) {
89  $this->dieUsageMsg( [ 'protect-invalidlevel', $p[1] ] );
90  }
92  if ( wfIsInfinity( $expiry[$i] ) ) {
93  $expiryarray[$p[0]] = 'infinity';
94  } else {
95  $exp = strtotime( $expiry[$i] );
96  if ( $exp < 0 || !$exp ) {
97  $this->dieUsageMsg( [ 'invalidexpiry', $expiry[$i] ] );
98  }
100  $exp = wfTimestamp( TS_MW, $exp );
101  if ( $exp < wfTimestampNow() ) {
102  $this->dieUsageMsg( [ 'pastexpiry', $expiry[$i] ] );
103  }
104  $expiryarray[$p[0]] = $exp;
105  }
106  $resultProtections[] = [
107  $p[0] => $protections[$p[0]],
108  'expiry' => $wgContLang->formatExpiry( $expiryarray[$p[0]], TS_ISO_8601, 'infinite' ),
109  ];
110  }
112  $cascade = $params['cascade'];
114  $watch = $params['watch'] ? 'watch' : $params['watchlist'];
115  $this->setWatch( $watch, $titleObj, 'watchdefault' );
117  $status = $pageObj->doUpdateRestrictions(
118  $protections,
119  $expiryarray,
120  $cascade,
121  $params['reason'],
122  $user,
123  $tags
124  );
126  if ( !$status->isOK() ) {
127  $this->dieStatus( $status );
128  }
129  $res = [
130  'title' => $titleObj->getPrefixedText(),
131  'reason' => $params['reason']
132  ];
133  if ( $cascade ) {
134  $res['cascade'] = true;
135  }
136  $res['protections'] = $resultProtections;
137  $result = $this->getResult();
138  ApiResult::setIndexedTagName( $res['protections'], 'protection' );
139  $result->addValue( null, $this->getModuleName(), $res );
140  }
142  public function mustBePosted() {
143  return true;
144  }
146  public function isWriteMode() {
147  return true;
148  }
150  public function getAllowedParams() {
151  return [
152  'title' => [
153  ApiBase::PARAM_TYPE => 'string',
154  ],
155  'pageid' => [
156  ApiBase::PARAM_TYPE => 'integer',
157  ],
158  'protections' => [
159  ApiBase::PARAM_ISMULTI => true,
160  ApiBase::PARAM_REQUIRED => true,
161  ],
162  'expiry' => [
163  ApiBase::PARAM_ISMULTI => true,
165  ApiBase::PARAM_DFLT => 'infinite',
166  ],
167  'reason' => '',
168  'tags' => [
169  ApiBase::PARAM_TYPE => 'tags',
170  ApiBase::PARAM_ISMULTI => true,
171  ],
172  'cascade' => false,
173  'watch' => [
174  ApiBase::PARAM_DFLT => false,
176  ],
177  'watchlist' => [
178  ApiBase::PARAM_DFLT => 'preferences',
180  'watch',
181  'unwatch',
182  'preferences',
183  'nochange'
184  ],
185  ],
186  ];
187  }
189  public function needsToken() {
190  return 'csrf';
191  }
193  protected function getExamplesMessages() {
194  return [
195  'action=protect&title=Main%20Page&token=123ABC&' .
196  'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never'
197  => 'apihelp-protect-example-protect',
198  'action=protect&title=Main%20Page&token=123ABC&' .
199  'protections=edit=all|move=all&reason=Lifting%20restrictions'
200  => 'apihelp-protect-example-unprotect',
201  'action=protect&title=Main%20Page&token=123ABC&' .
202  'protections=&reason=Lifting%20restrictions'
203  => 'apihelp-protect-example-unprotect2',
204  ];
205  }
207  public function getHelpUrls() {
208  return '';
209  }
210 }
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
the array() calling protocol came about after MediaWiki 1.4rc1.
Get the result object.
Definition: ApiBase.php:584
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
setWatch($watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiBase.php:1434
(boolean) Is the parameter required?
Definition: ApiBase.php:112
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
Definition: defines.php:28
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
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
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getTitleOrPageId($params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:840
Definition: database.txt:21
Get the Config object.
Convenience function; returns MediaWiki timestamp for the present time.
Determine input string is represents as infinity.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: defines.php:11
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
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
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
Definition: ApiProtect.php:193
Definition: ApiProtect.php:150
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
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
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:392
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1674
Get the User object.
Output the error message related to a certain array.
Definition: ApiBase.php:2203
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:103