MediaWiki REL1_37
ApiProtect.php
Go to the documentation of this file.
1<?php
25
29class ApiProtect extends ApiBase {
30
32
39 public function __construct(
40 ApiMain $mainModule,
41 $moduleName,
44 ) {
45 parent::__construct( $mainModule, $moduleName );
46
47 // Variables needed in ApiWatchlistTrait trait
48 $this->watchlistExpiryEnabled = $this->getConfig()->get( 'WatchlistExpiry' );
49 $this->watchlistMaxDuration = $this->getConfig()->get( 'WatchlistExpiryMaxDuration' );
50 $this->watchlistManager = $watchlistManager;
51 $this->userOptionsLookup = $userOptionsLookup;
52 }
53
54 public function execute() {
55 $params = $this->extractRequestParams();
56
57 $pageObj = $this->getTitleOrPageId( $params, 'fromdbmaster' );
58 $titleObj = $pageObj->getTitle();
59 $this->getErrorFormatter()->setContextTitle( $titleObj );
60
61 $this->checkTitleUserPermissions( $titleObj, 'protect' );
62
63 $user = $this->getUser();
64 $tags = $params['tags'];
65
66 // Check if user can add tags
67 if ( $tags !== null ) {
68 $ableToTag = ChangeTags::canAddTagsAccompanyingChange( $tags, $this->getAuthority() );
69 if ( !$ableToTag->isOK() ) {
70 $this->dieStatus( $ableToTag );
71 }
72 }
73
74 $expiry = (array)$params['expiry'];
75 if ( count( $expiry ) != count( $params['protections'] ) ) {
76 if ( count( $expiry ) == 1 ) {
77 $expiry = array_fill( 0, count( $params['protections'] ), $expiry[0] );
78 } else {
79 $this->dieWithError( [
80 'apierror-toofewexpiries',
81 count( $expiry ),
82 count( $params['protections'] )
83 ] );
84 }
85 }
86
87 $restrictionTypes = $titleObj->getRestrictionTypes();
88 $levels = $this->getPermissionManager()->getNamespaceRestrictionLevels(
89 $titleObj->getNamespace(),
90 $user
91 );
92
93 $protections = [];
94 $expiryarray = [];
95 $resultProtections = [];
96 foreach ( $params['protections'] as $i => $prot ) {
97 $p = explode( '=', $prot );
98 $protections[$p[0]] = ( $p[1] == 'all' ? '' : $p[1] );
99
100 if ( $titleObj->exists() && $p[0] == 'create' ) {
101 $this->dieWithError( 'apierror-create-titleexists' );
102 }
103 if ( !$titleObj->exists() && $p[0] != 'create' ) {
104 $this->dieWithError( 'apierror-missingtitle-createonly' );
105 }
106
107 if ( !in_array( $p[0], $restrictionTypes ) && $p[0] != 'create' ) {
108 $this->dieWithError( [ 'apierror-protect-invalidaction', wfEscapeWikiText( $p[0] ) ] );
109 }
110 if ( !in_array( $p[1], $levels ) && $p[1] != 'all' ) {
111 $this->dieWithError( [ 'apierror-protect-invalidlevel', wfEscapeWikiText( $p[1] ) ] );
112 }
113
114 if ( wfIsInfinity( $expiry[$i] ) ) {
115 $expiryarray[$p[0]] = 'infinity';
116 } else {
117 $exp = strtotime( $expiry[$i] );
118 if ( $exp < 0 || !$exp ) {
119 $this->dieWithError( [ 'apierror-invalidexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
120 }
121
122 $exp = wfTimestamp( TS_MW, $exp );
123 if ( $exp < wfTimestampNow() ) {
124 $this->dieWithError( [ 'apierror-pastexpiry', wfEscapeWikiText( $expiry[$i] ) ] );
125 }
126 $expiryarray[$p[0]] = $exp;
127 }
128 $resultProtections[] = [
129 $p[0] => $protections[$p[0]],
130 'expiry' => ApiResult::formatExpiry( $expiryarray[$p[0]], 'infinite' ),
131 ];
132 }
133
134 $cascade = $params['cascade'];
135
136 $watch = $params['watch'] ? 'watch' : $params['watchlist'];
137 $watchlistExpiry = $this->getExpiryFromParams( $params );
138 $this->setWatch( $watch, $titleObj, $user, 'watchdefault', $watchlistExpiry );
139
140 $status = $pageObj->doUpdateRestrictions(
141 $protections,
142 $expiryarray,
143 $cascade,
144 $params['reason'],
145 $user,
146 $tags
147 );
148
149 if ( !$status->isOK() ) {
150 $this->dieStatus( $status );
151 }
152 $res = [
153 'title' => $titleObj->getPrefixedText(),
154 'reason' => $params['reason']
155 ];
156 if ( $cascade ) {
157 $res['cascade'] = true;
158 }
159 $res['protections'] = $resultProtections;
160 $result = $this->getResult();
161 ApiResult::setIndexedTagName( $res['protections'], 'protection' );
162 $result->addValue( null, $this->getModuleName(), $res );
163 }
164
165 public function mustBePosted() {
166 return true;
167 }
168
169 public function isWriteMode() {
170 return true;
171 }
172
173 public function getAllowedParams() {
174 return [
175 'title' => [
176 ApiBase::PARAM_TYPE => 'string',
177 ],
178 'pageid' => [
179 ApiBase::PARAM_TYPE => 'integer',
180 ],
181 'protections' => [
184 ],
185 'expiry' => [
188 ApiBase::PARAM_DFLT => 'infinite',
189 ],
190 'reason' => '',
191 'tags' => [
192 ApiBase::PARAM_TYPE => 'tags',
194 ],
195 'cascade' => false,
196 'watch' => [
197 ApiBase::PARAM_DFLT => false,
199 ],
200 ] + $this->getWatchlistParams();
201 }
202
203 public function needsToken() {
204 return 'csrf';
205 }
206
207 protected function getExamplesMessages() {
208 return [
209 'action=protect&title=Main%20Page&token=123ABC&' .
210 'protections=edit=sysop|move=sysop&cascade=&expiry=20070901163000|never'
211 => 'apihelp-protect-example-protect',
212 'action=protect&title=Main%20Page&token=123ABC&' .
213 'protections=edit=all|move=all&reason=Lifting%20restrictions'
214 => 'apihelp-protect-example-unprotect',
215 'action=protect&title=Main%20Page&token=123ABC&' .
216 'protections=&reason=Lifting%20restrictions'
217 => 'apihelp-protect-example-unprotect2',
218 ];
219 }
220
221 public function getHelpUrls() {
222 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Protect';
223 }
224}
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.
WatchlistManager $watchlistManager
UserOptionsLookup $userOptionsLookup
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:55
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1436
const PARAM_REQUIRED
Definition ApiBase.php:105
const PARAM_DEPRECATED
Definition ApiBase.php:101
const PARAM_TYPE
Definition ApiBase.php:81
getErrorFormatter()
Definition ApiBase.php:639
const PARAM_DFLT
Definition ApiBase.php:73
const PARAM_ALLOW_DUPLICATES
Definition ApiBase.php:97
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition ApiBase.php:685
getResult()
Get the result object.
Definition ApiBase.php:628
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:764
checkTitleUserPermissions( $pageIdentity, $actions, array $options=[])
Helper function for permission-denied errors.
Definition ApiBase.php:1565
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:497
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition ApiBase.php:1033
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1495
const PARAM_ISMULTI
Definition ApiBase.php:77
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:49
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.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
__construct(ApiMain $mainModule, $moduleName, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup)
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, Authority $performer=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Provides access to user options.
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...