MediaWiki  master
ApiProtect.php
Go to the documentation of this file.
1 <?php
26 class ApiProtect extends ApiBase {
27 
29 
30  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
31  parent::__construct( $mainModule, $moduleName, $modulePrefix );
32 
33  $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
34  $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
35  }
36 
37  public function execute() {
38  $params = $this->extractRequestParams();
39 
40  $pageObj = $this->getTitleOrPageId( $params, 'fromdbmaster' );
41  $titleObj = $pageObj->getTitle();
42 
43  $this->checkTitleUserPermissions( $titleObj, 'protect' );
44 
45  $user = $this->getUser();
46  $tags = $params['tags'];
47 
48  // Check if user can add tags
49  if ( $tags !== null ) {
50  $ableToTag = ChangeTags::canAddTagsAccompanyingChange( $tags, $user );
51  if ( !$ableToTag->isOK() ) {
52  $this->dieStatus( $ableToTag );
53  }
54  }
55 
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->dieWithError( [
62  'apierror-toofewexpiries',
63  count( $expiry ),
64  count( $params['protections'] )
65  ] );
66  }
67  }
68 
69  $restrictionTypes = $titleObj->getRestrictionTypes();
70 
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] );
77 
78  if ( $titleObj->exists() && $p[0] == 'create' ) {
79  $this->dieWithError( 'apierror-create-titleexists' );
80  }
81  if ( !$titleObj->exists() && $p[0] != 'create' ) {
82  $this->dieWithError( 'apierror-missingtitle-createonly' );
83  }
84 
85  if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
86  $this->dieWithError( [ 'apierror-protect-invalidaction', wfEscapeWikiText( $p[0] ) ] );
87  }
88  if ( !in_array( $p[1], $this->getConfig()->get( 'RestrictionLevels' ) ) && $p[1] != 'all' ) {
89  $this->dieWithError( [ 'apierror-protect-invalidlevel', wfEscapeWikiText( $p[1] ) ] );
90  }
91 
92  if ( wfIsInfinity( $expiry[$i] ) ) {
93  $expiryarray[$p[0]] = 'infinity';
94  } else {
95  $exp = strtotime( $expiry[$i] );
96  if ( $exp < 0 || !$exp ) {
97  $this->dieWithError( [ 'apierror-invalidexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
98  }
99 
100  $exp = wfTimestamp( TS_MW, $exp );
101  if ( $exp < wfTimestampNow() ) {
102  $this->dieWithError( [ 'apierror-pastexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
103  }
104  $expiryarray[$p[0]] = $exp;
105  }
106  $resultProtections[] = [
107  $p[0] => $protections[$p[0]],
108  'expiry' => ApiResult::formatExpiry( $expiryarray[$p[0]], 'infinite' ),
109  ];
110  }
111 
112  $cascade = $params['cascade'];
113 
114  $watch = $params['watch'] ? 'watch' : $params['watchlist'];
115  $watchlistExpiry = $this->getExpiryFromParams( $params );
116  $this->setWatch( $watch, $titleObj, 'watchdefault', $watchlistExpiry );
117 
118  $status = $pageObj->doUpdateRestrictions(
119  $protections,
120  $expiryarray,
121  $cascade,
122  $params['reason'],
123  $user,
124  $tags
125  );
126 
127  if ( !$status->isOK() ) {
128  $this->dieStatus( $status );
129  }
130  $res = [
131  'title' => $titleObj->getPrefixedText(),
132  'reason' => $params['reason']
133  ];
134  if ( $cascade ) {
135  $res['cascade'] = true;
136  }
137  $res['protections'] = $resultProtections;
138  $result = $this->getResult();
139  ApiResult::setIndexedTagName( $res['protections'], 'protection' );
140  $result->addValue( null, $this->getModuleName(), $res );
141  }
142 
143  public function mustBePosted() {
144  return true;
145  }
146 
147  public function isWriteMode() {
148  return true;
149  }
150 
151  public function getAllowedParams() {
152  return [
153  'title' => [
154  ApiBase::PARAM_TYPE => 'string',
155  ],
156  'pageid' => [
157  ApiBase::PARAM_TYPE => 'integer',
158  ],
159  'protections' => [
160  ApiBase::PARAM_ISMULTI => true,
161  ApiBase::PARAM_REQUIRED => true,
162  ],
163  'expiry' => [
164  ApiBase::PARAM_ISMULTI => true,
166  ApiBase::PARAM_DFLT => 'infinite',
167  ],
168  'reason' => '',
169  'tags' => [
170  ApiBase::PARAM_TYPE => 'tags',
171  ApiBase::PARAM_ISMULTI => true,
172  ],
173  'cascade' => false,
174  'watch' => [
175  ApiBase::PARAM_DFLT => false,
177  ],
178  ] + $this->getWatchlistParams();
179  }
180 
181  public function needsToken() {
182  return 'csrf';
183  }
184 
185  protected function getExamplesMessages() {
186  return [
187  'action=protect&title=Main%20Page&token=123ABC&' .
188  'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never'
189  => 'apihelp-protect-example-protect',
190  'action=protect&title=Main%20Page&token=123ABC&' .
191  'protections=edit=all|move=all&reason=Lifting%20restrictions'
192  => 'apihelp-protect-example-unprotect',
193  'action=protect&title=Main%20Page&token=123ABC&' .
194  'protections=&reason=Lifting%20restrictions'
195  => 'apihelp-protect-example-unprotect2',
196  ];
197  }
198 
199  public function getHelpUrls() {
200  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Protect';
201  }
202 }
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
getExpiryFromParams
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
Definition: ApiWatchlistTrait.php:132
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:77
ApiProtect\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request Stable to override.
Definition: ApiProtect.php:143
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1382
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1808
ApiBase\getTitleOrPageId
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:986
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:71
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:565
ApiBase\PARAM_ALLOW_DUPLICATES
const PARAM_ALLOW_DUPLICATES
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:75
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:131
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:76
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:717
ApiProtect\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiProtect.php:151
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1837
ApiProtect\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiProtect.php:185
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2785
ApiProtect\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiProtect.php:37
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1487
ApiProtect\__construct
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Stable to call.
Definition: ApiProtect.php:30
ApiWatchlistTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Definition: ApiWatchlistTrait.php:17
ChangeTags\canAddTagsAccompanyingChange
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:544
getWatchlistParams
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
Definition: ApiWatchlistTrait.php:35
ApiProtect
Definition: ApiProtect.php:26
setWatch
setWatch(string $watch, Title $titleObj, ?string $userOption=null, ?string $expiry=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiWatchlistTrait.php:71
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:69
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
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
ApiProtect\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiProtect.php:199
ApiProtect\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiProtect.php:147
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1193
ApiBase\checkTitleUserPermissions
checkTitleUserPermissions(LinkTarget $linkTarget, $actions, array $options=[])
Helper function for permission-denied errors.
Definition: ApiBase.php:1509
ApiProtect\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiProtect.php:181