MediaWiki  1.28.1
Go to the documentation of this file.
1 <?php
32 class ApiRevisionDelete extends ApiBase {
34  public function execute() {
37  $params = $this->extractRequestParams();
38  $user = $this->getUser();
39  if ( !$user->isAllowed( RevisionDeleter::getRestriction( $params['type'] ) ) ) {
40  $this->dieUsageMsg( 'badaccess-group0' );
41  }
43  if ( $user->isBlocked() ) {
44  $this->dieBlocked( $user->getBlock() );
45  }
47  if ( !$params['ids'] ) {
48  $this->dieUsage( "At least one value is required for 'ids'", 'badparams' );
49  }
51  $hide = $params['hide'] ?: [];
52  $show = $params['show'] ?: [];
53  if ( array_intersect( $hide, $show ) ) {
54  $this->dieUsage( "Mutually exclusive values for 'hide' and 'show'", 'badparams' );
55  } elseif ( !$hide && !$show ) {
56  $this->dieUsage( "At least one value is required for 'hide' or 'show'", 'badparams' );
57  }
58  $bits = [
59  'content' => RevisionDeleter::getRevdelConstant( $params['type'] ),
60  'comment' => Revision::DELETED_COMMENT,
61  'user' => Revision::DELETED_USER,
62  ];
63  $bitfield = [];
64  foreach ( $bits as $key => $bit ) {
65  if ( in_array( $key, $hide ) ) {
66  $bitfield[$bit] = 1;
67  } elseif ( in_array( $key, $show ) ) {
68  $bitfield[$bit] = 0;
69  } else {
70  $bitfield[$bit] = -1;
71  }
72  }
74  if ( $params['suppress'] === 'yes' ) {
75  if ( !$user->isAllowed( 'suppressrevision' ) ) {
76  $this->dieUsageMsg( 'badaccess-group0' );
77  }
78  $bitfield[Revision::DELETED_RESTRICTED] = 1;
79  } elseif ( $params['suppress'] === 'no' ) {
80  $bitfield[Revision::DELETED_RESTRICTED] = 0;
81  } else {
82  $bitfield[Revision::DELETED_RESTRICTED] = -1;
83  }
85  $targetObj = null;
86  if ( $params['target'] ) {
87  $targetObj = Title::newFromText( $params['target'] );
88  }
89  $targetObj = RevisionDeleter::suggestTarget( $params['type'], $targetObj, $params['ids'] );
90  if ( $targetObj === null ) {
91  $this->dieUsage( 'A target title is required for this RevDel type', 'needtarget' );
92  }
95  $params['type'], $this->getContext(), $targetObj, $params['ids']
96  );
97  $status = $list->setVisibility(
98  [ 'value' => $bitfield, 'comment' => $params['reason'], 'perItemStatus' => true ]
99  );
101  $result = $this->getResult();
102  $data = $this->extractStatusInfo( $status );
103  $data['target'] = $targetObj->getFullText();
104  $data['items'] = [];
106  foreach ( $status->itemStatuses as $id => $s ) {
107  $data['items'][$id] = $this->extractStatusInfo( $s );
108  $data['items'][$id]['id'] = $id;
109  }
111  $list->reloadFromMaster();
112  // @codingStandardsIgnoreStart Avoid function calls in a FOR loop test part
113  for ( $item = $list->reset(); $list->current(); $item = $list->next() ) {
114  $data['items'][$item->getId()] += $item->getApiData( $this->getResult() );
115  }
116  // @codingStandardsIgnoreEnd
118  $data['items'] = array_values( $data['items'] );
119  ApiResult::setIndexedTagName( $data['items'], 'i' );
120  $result->addValue( null, $this->getModuleName(), $data );
121  }
123  private function extractStatusInfo( $status ) {
124  $ret = [
125  'status' => $status->isOK() ? 'Success' : 'Fail',
126  ];
127  $errors = $this->formatStatusMessages( $status->getErrorsByType( 'error' ) );
128  if ( $errors ) {
129  ApiResult::setIndexedTagName( $errors, 'e' );
130  $ret['errors'] = $errors;
131  }
132  $warnings = $this->formatStatusMessages( $status->getErrorsByType( 'warning' ) );
133  if ( $warnings ) {
134  ApiResult::setIndexedTagName( $warnings, 'w' );
135  $ret['warnings'] = $warnings;
136  }
138  return $ret;
139  }
141  private function formatStatusMessages( $messages ) {
142  if ( !$messages ) {
143  return [];
144  }
145  $ret = [];
146  foreach ( $messages as $m ) {
147  if ( $m['message'] instanceof Message ) {
148  $msg = $m['message'];
149  $message = [ 'message' => $msg->getKey() ];
150  if ( $msg->getParams() ) {
151  $message['params'] = $msg->getParams();
152  ApiResult::setIndexedTagName( $message['params'], 'p' );
153  }
154  } else {
155  $message = [ 'message' => $m['message'] ];
156  $msg = wfMessage( $m['message'] );
157  if ( isset( $m['params'] ) ) {
158  $message['params'] = $m['params'];
159  ApiResult::setIndexedTagName( $message['params'], 'p' );
160  $msg->params( $m['params'] );
161  }
162  }
163  $message['rendered'] = $msg->useDatabase( false )->inLanguage( 'en' )->plain();
164  $ret[] = $message;
165  }
167  return $ret;
168  }
170  public function mustBePosted() {
171  return true;
172  }
174  public function isWriteMode() {
175  return true;
176  }
178  public function getAllowedParams() {
179  return [
180  'type' => [
183  ],
184  'target' => null,
185  'ids' => [
186  ApiBase::PARAM_ISMULTI => true,
188  ],
189  'hide' => [
190  ApiBase::PARAM_TYPE => [ 'content', 'comment', 'user' ],
191  ApiBase::PARAM_ISMULTI => true,
192  ],
193  'show' => [
194  ApiBase::PARAM_TYPE => [ 'content', 'comment', 'user' ],
195  ApiBase::PARAM_ISMULTI => true,
196  ],
197  'suppress' => [
198  ApiBase::PARAM_TYPE => [ 'yes', 'no', 'nochange' ],
199  ApiBase::PARAM_DFLT => 'nochange',
200  ],
201  'reason' => null,
202  ];
203  }
205  public function needsToken() {
206  return 'csrf';
207  }
209  protected function getExamplesMessages() {
210  return [
211  'action=revisiondelete&target=Main%20Page&type=revision&ids=12345&' .
212  'hide=content&token=123ABC'
213  => 'apihelp-revisiondelete-example-revision',
214  'action=revisiondelete&type=logging&ids=67890&hide=content|comment|user&' .
215  'reason=BLP%20violation&token=123ABC'
216  => 'apihelp-revisiondelete-example-log',
217  ];
218  }
220  public function getHelpUrls() {
221  return '';
222  }
223 }
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
API interface to RevDel.
Get the result object.
Definition: ApiBase.php:584
static getRevdelConstant($typeName)
Get the revision deletion constant for the RevDel type.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1936
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:2764
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
(boolean) Is the parameter required?
Definition: ApiBase.php:112
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
static suggestTarget($typeName, $target, array $ids)
Suggest a target for the revision deletion.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1936
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
Get the base IContextSource object.
Definition: Revision.php:88
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Definition: Revision.php:87
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1585
dieBlocked(Block $block)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1602
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
static createList($typeName, IContextSource $context, Title $title, array $ids)
Instantiate the appropriate list class for a given list of IDs.
Definition: Revision.php:86
static static static getTypes()
Lists the valid possible types for revision deletion.
static getRestriction($typeName)
Get the user right required for the RevDel type.
Get the User object.
Output the error message related to a certain array.
Definition: ApiBase.php:2203