MediaWiki  master
ApiProtect.php
Go to the documentation of this file.
1 <?php
25 
29 class 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' => [
182  ApiBase::PARAM_ISMULTI => true,
183  ApiBase::PARAM_REQUIRED => true,
184  ],
185  'expiry' => [
186  ApiBase::PARAM_ISMULTI => true,
188  ApiBase::PARAM_DFLT => 'infinite',
189  ],
190  'reason' => '',
191  'tags' => [
192  ApiBase::PARAM_TYPE => 'tags',
193  ApiBase::PARAM_ISMULTI => true,
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 }
ApiBase\checkTitleUserPermissions
checkTitleUserPermissions( $pageIdentity, $actions, array $options=[])
Helper function for permission-denied errors.
Definition: ApiBase.php:1514
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:49
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:72
getExpiryFromParams
getExpiryFromParams(array $params)
Get formatted expiry from the given parameters, or null if no expiry was provided.
Definition: ApiWatchlistTrait.php:164
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
Definition: ApiBase.php:78
ApiProtect\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiProtect.php:165
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1379
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1668
ApiBase\getTitleOrPageId
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:976
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:571
ApiProtect\__construct
__construct(ApiMain $mainModule, $moduleName, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup)
Definition: ApiProtect.php:39
ApiBase\PARAM_ALLOW_DUPLICATES
const PARAM_ALLOW_DUPLICATES
Definition: ApiBase.php:76
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
Definition: ApiBase.php:77
MediaWiki\Watchlist\WatchlistManager
WatchlistManager service.
Definition: WatchlistManager.php:52
setWatch
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.
Definition: ApiWatchlistTrait.php:96
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:707
ApiProtect\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiProtect.php:173
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1697
ApiProtect\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiProtect.php:207
ChangeTags\canAddTagsAccompanyingChange
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...
Definition: ChangeTags.php:625
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:603
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:628
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2524
ApiProtect\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiProtect.php:54
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1459
MediaWiki\User\UserOptionsLookup
Provides access to user options.
Definition: UserOptionsLookup.php:29
ApiWatchlistTrait
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Definition: ApiWatchlistTrait.php:21
$watchlistManager
WatchlistManager $watchlistManager
Definition: ApiWatchlistTrait.php:30
$userOptionsLookup
UserOptionsLookup $userOptionsLookup
Definition: ApiWatchlistTrait.php:33
getWatchlistParams
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
Definition: ApiWatchlistTrait.php:59
ApiProtect
Definition: ApiProtect.php:29
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:70
ApiBase\dieStatus
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:1442
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:440
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
Definition: ApiBase.php:71
ApiProtect\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiProtect.php:221
ApiProtect\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiProtect.php:169
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1194
ApiProtect\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiProtect.php:203
ApiBase\getErrorFormatter
getErrorFormatter()
Definition: ApiBase.php:582