MediaWiki  1.23.2
ApiProtect.php
Go to the documentation of this file.
1 <?php
30 class ApiProtect extends ApiBase {
31  public function execute() {
32  global $wgRestrictionLevels;
33  $params = $this->extractRequestParams();
34 
35  $pageObj = $this->getTitleOrPageId( $params, 'fromdbmaster' );
36  $titleObj = $pageObj->getTitle();
37 
38  $errors = $titleObj->getUserPermissionsErrors( 'protect', $this->getUser() );
39  if ( $errors ) {
40  // We don't care about multiple errors, just report one of them
41  $this->dieUsageMsg( reset( $errors ) );
42  }
43 
44  $expiry = (array)$params['expiry'];
45  if ( count( $expiry ) != count( $params['protections'] ) ) {
46  if ( count( $expiry ) == 1 ) {
47  $expiry = array_fill( 0, count( $params['protections'] ), $expiry[0] );
48  } else {
49  $this->dieUsageMsg( array(
50  'toofewexpiries',
51  count( $expiry ),
52  count( $params['protections'] )
53  ) );
54  }
55  }
56 
57  $restrictionTypes = $titleObj->getRestrictionTypes();
58  $db = $this->getDB();
59 
60  $protections = array();
61  $expiryarray = array();
62  $resultProtections = array();
63  foreach ( $params['protections'] as $i => $prot ) {
64  $p = explode( '=', $prot );
65  $protections[$p[0]] = ( $p[1] == 'all' ? '' : $p[1] );
66 
67  if ( $titleObj->exists() && $p[0] == 'create' ) {
68  $this->dieUsageMsg( 'create-titleexists' );
69  }
70  if ( !$titleObj->exists() && $p[0] != 'create' ) {
71  $this->dieUsageMsg( 'missingtitle-createonly' );
72  }
73 
74  if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
75  $this->dieUsageMsg( array( 'protect-invalidaction', $p[0] ) );
76  }
77  if ( !in_array( $p[1], $wgRestrictionLevels ) && $p[1] != 'all' ) {
78  $this->dieUsageMsg( array( 'protect-invalidlevel', $p[1] ) );
79  }
80 
81  if ( in_array( $expiry[$i], array( 'infinite', 'indefinite', 'never' ) ) ) {
82  $expiryarray[$p[0]] = $db->getInfinity();
83  } else {
84  $exp = strtotime( $expiry[$i] );
85  if ( $exp < 0 || !$exp ) {
86  $this->dieUsageMsg( array( 'invalidexpiry', $expiry[$i] ) );
87  }
88 
89  $exp = wfTimestamp( TS_MW, $exp );
90  if ( $exp < wfTimestampNow() ) {
91  $this->dieUsageMsg( array( 'pastexpiry', $expiry[$i] ) );
92  }
93  $expiryarray[$p[0]] = $exp;
94  }
95  $resultProtections[] = array(
96  $p[0] => $protections[$p[0]],
97  'expiry' => ( $expiryarray[$p[0]] == $db->getInfinity()
98  ? 'infinite'
99  : wfTimestamp( TS_ISO_8601, $expiryarray[$p[0]] )
100  )
101  );
102  }
103 
104  $cascade = $params['cascade'];
105 
106  $watch = $params['watch'] ? 'watch' : $params['watchlist'];
107  $this->setWatch( $watch, $titleObj, 'watchdefault' );
108 
109  $status = $pageObj->doUpdateRestrictions(
110  $protections,
111  $expiryarray,
112  $cascade,
113  $params['reason'],
114  $this->getUser()
115  );
116 
117  if ( !$status->isOK() ) {
118  $this->dieStatus( $status );
119  }
120  $res = array(
121  'title' => $titleObj->getPrefixedText(),
122  'reason' => $params['reason']
123  );
124  if ( $cascade ) {
125  $res['cascade'] = '';
126  }
127  $res['protections'] = $resultProtections;
128  $result = $this->getResult();
129  $result->setIndexedTagName( $res['protections'], 'protection' );
130  $result->addValue( null, $this->getModuleName(), $res );
131  }
132 
133  public function mustBePosted() {
134  return true;
135  }
136 
137  public function isWriteMode() {
138  return true;
139  }
140 
141  public function getAllowedParams() {
142  return array(
143  'title' => array(
144  ApiBase::PARAM_TYPE => 'string',
145  ),
146  'pageid' => array(
147  ApiBase::PARAM_TYPE => 'integer',
148  ),
149  'token' => array(
150  ApiBase::PARAM_TYPE => 'string',
152  ),
153  'protections' => array(
154  ApiBase::PARAM_ISMULTI => true,
155  ApiBase::PARAM_REQUIRED => true,
156  ),
157  'expiry' => array(
158  ApiBase::PARAM_ISMULTI => true,
160  ApiBase::PARAM_DFLT => 'infinite',
161  ),
162  'reason' => '',
163  'cascade' => false,
164  'watch' => array(
165  ApiBase::PARAM_DFLT => false,
167  ),
168  'watchlist' => array(
169  ApiBase::PARAM_DFLT => 'preferences',
171  'watch',
172  'unwatch',
173  'preferences',
174  'nochange'
175  ),
176  ),
177  );
178  }
179 
180  public function getParamDescription() {
181  $p = $this->getModulePrefix();
182 
183  return array(
184  'title' => "Title of the page you want to (un)protect. Cannot be used together with {$p}pageid",
185  'pageid' => "ID of the page you want to (un)protect. Cannot be used together with {$p}title",
186  'token' => 'A protect token previously retrieved through prop=info',
187  'protections' => 'List of protection levels, formatted action=group (e.g. edit=sysop)',
188  'expiry' => array(
189  'Expiry timestamps. If only one timestamp is ' .
190  'set, it\'ll be used for all protections.',
191  'Use \'infinite\', \'indefinite\' or \'never\', for a never-expiring protection.'
192  ),
193  'reason' => 'Reason for (un)protecting',
194  'cascade' => array(
195  'Enable cascading protection (i.e. protect pages included in this page)',
196  'Ignored if not all protection levels are \'sysop\' or \'protect\''
197  ),
198  'watch' => 'If set, add the page being (un)protected to your watchlist',
199  'watchlist' => 'Unconditionally add or remove the page from your ' .
200  'watchlist, use preferences or do not change watch',
201  );
202  }
203 
204  public function getResultProperties() {
205  return array(
206  '' => array(
207  'title' => 'string',
208  'reason' => 'string',
209  'cascade' => 'boolean'
210  )
211  );
212  }
213 
214  public function getDescription() {
215  return 'Change the protection level of a page.';
216  }
217 
218  public function getPossibleErrors() {
219  return array_merge( parent::getPossibleErrors(),
221  array(
222  array( 'toofewexpiries', 'noofexpiries', 'noofprotections' ),
223  array( 'create-titleexists' ),
224  array( 'missingtitle-createonly' ),
225  array( 'protect-invalidaction', 'action' ),
226  array( 'protect-invalidlevel', 'level' ),
227  array( 'invalidexpiry', 'expiry' ),
228  array( 'pastexpiry', 'expiry' ),
229  )
230  );
231  }
232 
233  public function needsToken() {
234  return true;
235  }
236 
237  public function getTokenSalt() {
238  return '';
239  }
240 
241  public function getExamples() {
242  return array(
243  'api.php?action=protect&title=Main%20Page&token=123ABC&' .
244  'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never',
245  'api.php?action=protect&title=Main%20Page&token=123ABC&' .
246  'protections=edit=all|move=all&reason=Lifting%20restrictions'
247  );
248  }
249 
250  public function getHelpUrls() {
251  return 'https://www.mediawiki.org/wiki/API:Protect';
252  }
253 }
ApiBase\dieStatus
dieStatus( $status)
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1419
ApiProtect\getPossibleErrors
getPossibleErrors()
Returns a list of all possible errors returned by the module.
Definition: ApiProtect.php:218
$result
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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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. '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 '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) '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. 'LinkBegin':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:1528
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
Definition: ApiBase.php:62
ApiProtect\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiProtect.php:133
ApiProtect\getExamples
getExamples()
Returns usage examples for this module.
Definition: ApiProtect.php:241
ApiBase\dieUsageMsg
dieUsageMsg( $error)
Output the error message related to a certain array.
Definition: ApiBase.php:1929
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2483
ApiProtect\getParamDescription
getParamDescription()
Returns an array of parameter descriptions.
Definition: ApiProtect.php:180
ApiBase\getTitleOrPageId
getTitleOrPageId( $params, $load=false)
Definition: ApiBase.php:853
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:50
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:205
$params
$params
Definition: styleTest.css.php:40
ApiBase\getDB
getDB()
Gets a default slave database connection object.
Definition: ApiBase.php:2312
ApiProtect\getTokenSalt
getTokenSalt()
Returns the token salt if there is one, '' if the module doesn't require a salt, else false if the mo...
Definition: ApiProtect.php:237
ApiBase\PARAM_ALLOW_DUPLICATES
const PARAM_ALLOW_DUPLICATES
Definition: ApiBase.php:58
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:132
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:42
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
Definition: ApiBase.php:60
TS_ISO_8601
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
Definition: GlobalFunctions.php:2448
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
ApiProtect\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiProtect.php:141
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2514
ApiBase\getModulePrefix
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:165
ApiBase\setWatch
setWatch( $watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiBase.php:952
TS_MW
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: GlobalFunctions.php:2431
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:687
ApiProtect\getResultProperties
getResultProperties()
Returns possible properties in the result, grouped by the value of the prop parameter that shows them...
Definition: ApiProtect.php:204
ApiProtect\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiProtect.php:31
ApiProtect
Definition: ApiProtect.php:30
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:46
as
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
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:148
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
Definition: ApiBase.php:48
ApiProtect\getHelpUrls
getHelpUrls()
Definition: ApiProtect.php:250
ApiProtect\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiProtect.php:137
$res
$res
Definition: database.txt:21
ApiProtect\needsToken
needsToken()
Returns whether this module requires a token to execute It is used to show possible errors in action=...
Definition: ApiProtect.php:233
ApiProtect\getDescription
getDescription()
Returns the description string for this module.
Definition: ApiProtect.php:214
ApiBase\getTitleOrPageIdErrorMessage
getTitleOrPageIdErrorMessage()
Definition: ApiBase.php:885