MediaWiki REL1_35
ApiProtect.php
Go to the documentation of this file.
1<?php
26class 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 $levels = $this->getPermissionManager()->getNamespaceRestrictionLevels(
71 $titleObj->getNamespace(),
72 $user
73 );
74
75 $protections = [];
76 $expiryarray = [];
77 $resultProtections = [];
78 foreach ( $params['protections'] as $i => $prot ) {
79 $p = explode( '=', $prot );
80 $protections[$p[0]] = ( $p[1] == 'all' ? '' : $p[1] );
81
82 if ( $titleObj->exists() && $p[0] == 'create' ) {
83 $this->dieWithError( 'apierror-create-titleexists' );
84 }
85 if ( !$titleObj->exists() && $p[0] != 'create' ) {
86 $this->dieWithError( 'apierror-missingtitle-createonly' );
87 }
88
89 if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
90 $this->dieWithError( [ 'apierror-protect-invalidaction', wfEscapeWikiText( $p[0] ) ] );
91 }
92 if ( !in_array( $p[1], $levels ) && $p[1] != 'all' ) {
93 $this->dieWithError( [ 'apierror-protect-invalidlevel', wfEscapeWikiText( $p[1] ) ] );
94 }
95
96 if ( wfIsInfinity( $expiry[$i] ) ) {
97 $expiryarray[$p[0]] = 'infinity';
98 } else {
99 $exp = strtotime( $expiry[$i] );
100 if ( $exp < 0 || !$exp ) {
101 $this->dieWithError( [ 'apierror-invalidexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
102 }
103
104 $exp = wfTimestamp( TS_MW, $exp );
105 if ( $exp < wfTimestampNow() ) {
106 $this->dieWithError( [ 'apierror-pastexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
107 }
108 $expiryarray[$p[0]] = $exp;
109 }
110 $resultProtections[] = [
111 $p[0] => $protections[$p[0]],
112 'expiry' => ApiResult::formatExpiry( $expiryarray[$p[0]], 'infinite' ),
113 ];
114 }
115
116 $cascade = $params['cascade'];
117
118 $watch = $params['watch'] ? 'watch' : $params['watchlist'];
119 $watchlistExpiry = $this->getExpiryFromParams( $params );
120 $this->setWatch( $watch, $titleObj, $user, 'watchdefault', $watchlistExpiry );
121
122 $status = $pageObj->doUpdateRestrictions(
123 $protections,
124 $expiryarray,
125 $cascade,
126 $params['reason'],
127 $user,
128 $tags
129 );
130
131 if ( !$status->isOK() ) {
132 $this->dieStatus( $status );
133 }
134 $res = [
135 'title' => $titleObj->getPrefixedText(),
136 'reason' => $params['reason']
137 ];
138 if ( $cascade ) {
139 $res['cascade'] = true;
140 }
141 $res['protections'] = $resultProtections;
142 $result = $this->getResult();
143 ApiResult::setIndexedTagName( $res['protections'], 'protection' );
144 $result->addValue( null, $this->getModuleName(), $res );
145 }
146
147 public function mustBePosted() {
148 return true;
149 }
150
151 public function isWriteMode() {
152 return true;
153 }
154
155 public function getAllowedParams() {
156 return [
157 'title' => [
158 ApiBase::PARAM_TYPE => 'string',
159 ],
160 'pageid' => [
161 ApiBase::PARAM_TYPE => 'integer',
162 ],
163 'protections' => [
166 ],
167 'expiry' => [
170 ApiBase::PARAM_DFLT => 'infinite',
171 ],
172 'reason' => '',
173 'tags' => [
174 ApiBase::PARAM_TYPE => 'tags',
176 ],
177 'cascade' => false,
178 'watch' => [
179 ApiBase::PARAM_DFLT => false,
181 ],
182 ] + $this->getWatchlistParams();
183 }
184
185 public function needsToken() {
186 return 'csrf';
187 }
188
189 protected function getExamplesMessages() {
190 return [
191 'action=protect&title=Main%20Page&token=123ABC&' .
192 'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never'
193 => 'apihelp-protect-example-protect',
194 'action=protect&title=Main%20Page&token=123ABC&' .
195 'protections=edit=all|move=all&reason=Lifting%20restrictions'
196 => 'apihelp-protect-example-unprotect',
197 'action=protect&title=Main%20Page&token=123ABC&' .
198 'protections=&reason=Lifting%20restrictions'
199 => 'apihelp-protect-example-unprotect2',
200 ];
201 }
202
203 public function getHelpUrls() {
204 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Protect';
205 }
206}
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
setWatch(string $watch, Title $title, User $user, ?string $userOption=null, ?string $expiry=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:52
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1437
const PARAM_REQUIRED
Definition ApiBase.php:102
const PARAM_DEPRECATED
Definition ApiBase.php:98
const PARAM_TYPE
Definition ApiBase.php:78
const PARAM_DFLT
Definition ApiBase.php:70
const PARAM_ALLOW_DUPLICATES
Definition ApiBase.php:94
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition ApiBase.php:692
getResult()
Get the result object.
Definition ApiBase.php:620
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:772
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:499
checkTitleUserPermissions(LinkTarget $linkTarget, $actions, array $options=[])
Helper function for permission-denied errors.
Definition ApiBase.php:1564
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition ApiBase.php:1041
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1495
const PARAM_ISMULTI
Definition ApiBase.php:74
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:47
isWriteMode()
Indicates whether this module requires write mode.
getExamplesMessages()
Returns usage examples for this module.
needsToken()
Returns the token type this module requires in order to execute.
mustBePosted()
Indicates whether this module must be called with a POST request Stable to override.
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Stable to call.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getHelpUrls()
Return links to more detailed help pages about the module.
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...
getUser()
Stable to override.
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...