MediaWiki 1.43.1
ApiProtect.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Api;
24
25use ChangeTags;
32
36class ApiProtect extends ApiBase {
37
39
40 private RestrictionStore $restrictionStore;
41
42 public function __construct(
43 ApiMain $mainModule,
44 string $moduleName,
45 WatchlistManager $watchlistManager,
46 UserOptionsLookup $userOptionsLookup,
47 RestrictionStore $restrictionStore
48 ) {
49 parent::__construct( $mainModule, $moduleName );
50 $this->restrictionStore = $restrictionStore;
51
52 // Variables needed in ApiWatchlistTrait trait
53 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
54 $this->watchlistMaxDuration =
56 $this->watchlistManager = $watchlistManager;
57 $this->userOptionsLookup = $userOptionsLookup;
58 }
59
60 public function execute() {
62
63 $pageObj = $this->getTitleOrPageId( $params, 'fromdbmaster' );
64 $titleObj = $pageObj->getTitle();
65 $this->getErrorFormatter()->setContextTitle( $titleObj );
66
67 $this->checkTitleUserPermissions( $titleObj, 'protect' );
68
69 $user = $this->getUser();
70 $tags = $params['tags'];
71
72 // Check if user can add tags
73 if ( $tags !== null ) {
74 $ableToTag = ChangeTags::canAddTagsAccompanyingChange( $tags, $this->getAuthority() );
75 if ( !$ableToTag->isOK() ) {
76 $this->dieStatus( $ableToTag );
77 }
78 }
79
80 $expiry = (array)$params['expiry'];
81 if ( count( $expiry ) != count( $params['protections'] ) ) {
82 if ( count( $expiry ) == 1 ) {
83 $expiry = array_fill( 0, count( $params['protections'] ), $expiry[0] );
84 } else {
85 $this->dieWithError( [
86 'apierror-toofewexpiries',
87 count( $expiry ),
88 count( $params['protections'] )
89 ] );
90 }
91 }
92
93 $restrictionTypes = $this->restrictionStore->listApplicableRestrictionTypes( $titleObj );
94 $levels = $this->getPermissionManager()->getNamespaceRestrictionLevels(
95 $titleObj->getNamespace(),
96 $user
97 );
98
99 $protections = [];
100 $expiryarray = [];
101 $resultProtections = [];
102 foreach ( $params['protections'] as $i => $prot ) {
103 $p = explode( '=', $prot );
104 $protections[$p[0]] = ( $p[1] == 'all' ? '' : $p[1] );
105
106 if ( $titleObj->exists() && $p[0] == 'create' ) {
107 $this->dieWithError( 'apierror-create-titleexists' );
108 }
109 if ( !$titleObj->exists() && $p[0] != 'create' ) {
110 $this->dieWithError( 'apierror-missingtitle-createonly' );
111 }
112
113 if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
114 $this->dieWithError( [ 'apierror-protect-invalidaction', wfEscapeWikiText( $p[0] ) ] );
115 }
116 if ( !in_array( $p[1], $levels ) && $p[1] != 'all' ) {
117 $this->dieWithError( [ 'apierror-protect-invalidlevel', wfEscapeWikiText( $p[1] ) ] );
118 }
119
120 if ( wfIsInfinity( $expiry[$i] ) ) {
121 $expiryarray[$p[0]] = 'infinity';
122 } else {
123 $exp = strtotime( $expiry[$i] );
124 if ( $exp < 0 || !$exp ) {
125 $this->dieWithError( [ 'apierror-invalidexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
126 }
127
128 $exp = wfTimestamp( TS_MW, $exp );
129 if ( $exp < wfTimestampNow() ) {
130 $this->dieWithError( [ 'apierror-pastexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
131 }
132 $expiryarray[$p[0]] = $exp;
133 }
134 $resultProtections[] = [
135 $p[0] => $protections[$p[0]],
136 'expiry' => ApiResult::formatExpiry( $expiryarray[$p[0]], 'infinite' ),
137 ];
138 }
139
140 $cascade = $params['cascade'];
141
142 $watch = $params['watch'] ? 'watch' : $params['watchlist'];
143 $watchlistExpiry = $this->getExpiryFromParams( $params );
144 $this->setWatch( $watch, $titleObj, $user, 'watchdefault', $watchlistExpiry );
145
146 $status = $pageObj->doUpdateRestrictions(
147 $protections,
148 $expiryarray,
149 $cascade,
150 $params['reason'],
151 $user,
152 $tags ?? []
153 );
154
155 if ( !$status->isOK() ) {
156 $this->dieStatus( $status );
157 }
158 $res = [
159 'title' => $titleObj->getPrefixedText(),
160 'reason' => $params['reason']
161 ];
162 if ( $cascade ) {
163 $res['cascade'] = true;
164 }
165 $res['protections'] = $resultProtections;
166 $result = $this->getResult();
167 ApiResult::setIndexedTagName( $res['protections'], 'protection' );
168 $result->addValue( null, $this->getModuleName(), $res );
169 }
170
171 public function mustBePosted() {
172 return true;
173 }
174
175 public function isWriteMode() {
176 return true;
177 }
178
179 public function getAllowedParams() {
180 return [
181 'title' => [
182 ParamValidator::PARAM_TYPE => 'string',
183 ],
184 'pageid' => [
185 ParamValidator::PARAM_TYPE => 'integer',
186 ],
187 'protections' => [
188 ParamValidator::PARAM_ISMULTI => true,
189 ParamValidator::PARAM_REQUIRED => true,
190 ],
191 'expiry' => [
192 ParamValidator::PARAM_ISMULTI => true,
193 ParamValidator::PARAM_ALLOW_DUPLICATES => true,
194 ParamValidator::PARAM_DEFAULT => 'infinite',
195 ],
196 'reason' => '',
197 'tags' => [
198 ParamValidator::PARAM_TYPE => 'tags',
199 ParamValidator::PARAM_ISMULTI => true,
200 ],
201 'cascade' => false,
202 'watch' => [
203 ParamValidator::PARAM_DEFAULT => false,
204 ParamValidator::PARAM_DEPRECATED => true,
205 ],
206 ] + $this->getWatchlistParams();
207 }
208
209 public function needsToken() {
210 return 'csrf';
211 }
212
213 protected function getExamplesMessages() {
214 $title = Title::newMainPage()->getPrefixedText();
215 $mp = rawurlencode( $title );
216
217 return [
218 "action=protect&title={$mp}&token=123ABC&" .
219 'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never'
220 => 'apihelp-protect-example-protect',
221 "action=protect&title={$mp}&token=123ABC&" .
222 'protections=edit=all|move=all&reason=Lifting%20restrictions'
223 => 'apihelp-protect-example-unprotect',
224 "action=protect&title={$mp}&token=123ABC&" .
225 'protections=&reason=Lifting%20restrictions'
226 => 'apihelp-protect-example-unprotect2',
227 ];
228 }
229
230 public function getHelpUrls() {
231 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Protect';
232 }
233}
234
236class_alias( ApiProtect::class, 'ApiProtect' );
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
array $params
The job parameters.
Recent changes tagging.
static canAddTagsAccompanyingChange(array $tags, ?Authority $performer=null, $checkBlock=true)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:76
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1577
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:571
getResult()
Get the result object.
Definition ApiBase.php:710
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1632
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:851
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition ApiBase.php:770
checkTitleUserPermissions(PageIdentity $pageIdentity, $actions, array $options=[])
Helper function for permission-denied errors.
Definition ApiBase.php:1715
getTitleOrPageId( $params, $load=false)
Attempts to load a WikiPage object from a title or pageid parameter, if possible.
Definition ApiBase.php:1138
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:78
needsToken()
Returns the token type this module requires in order to execute.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
__construct(ApiMain $mainModule, string $moduleName, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup, RestrictionStore $restrictionStore)
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
isWriteMode()
Indicates whether this module requires write access to the wiki.
getHelpUrls()
Return links to more detailed help pages about the module.
getExamplesMessages()
Returns usage examples for this module.
mustBePosted()
Indicates whether this module must be called with a POST request.
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
A class containing constants representing the names of configuration variables.
const WatchlistExpiry
Name constant for the WatchlistExpiry setting, for use with Config::get()
const WatchlistExpiryMaxDuration
Name constant for the WatchlistExpiryMaxDuration setting, for use with Config::get()
Represents a title within MediaWiki.
Definition Title.php:78
Provides access to user options.
Service for formatting and validating API parameters.
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
setWatch(string $watch, PageIdentity $page, 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.