MediaWiki master
ApiUndelete.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
12use MediaWiki\Page\UndeletePage;
21use Wikimedia\Timestamp\TimestampFormat as TS;
22
26class ApiUndelete extends ApiBase {
27
29
30 private UndeletePageFactory $undeletePageFactory;
31 private WikiPageFactory $wikiPageFactory;
32
33 public function __construct(
34 ApiMain $mainModule,
35 string $moduleName,
36 WatchlistManager $watchlistManager,
37 WatchedItemStoreInterface $watchedItemStore,
38 UserOptionsLookup $userOptionsLookup,
39 UndeletePageFactory $undeletePageFactory,
40 WikiPageFactory $wikiPageFactory
41 ) {
42 parent::__construct( $mainModule, $moduleName );
43
44 // Variables needed in ApiWatchlistTrait trait
45 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
46 $this->watchlistMaxDuration =
48 $this->watchlistManager = $watchlistManager;
49 $this->watchedItemStore = $watchedItemStore;
50 $this->userOptionsLookup = $userOptionsLookup;
51 $this->undeletePageFactory = $undeletePageFactory;
52 $this->wikiPageFactory = $wikiPageFactory;
53 }
54
55 public function execute() {
57
58 $params = $this->extractRequestParams();
59
60 $user = $this->getUser();
61 $block = $user->getBlock( IDBAccessObject::READ_LATEST );
62 if ( $block && $block->isSitewide() ) {
63 $this->dieBlocked( $block );
64 }
65
66 $titleObj = Title::newFromText( $params['title'] );
67 if ( !$titleObj || $titleObj->isExternal() ) {
68 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
69 }
70 if ( !$titleObj->canExist() ) {
71 $this->dieWithError( 'apierror-pagecannotexist' );
72 }
73
74 // Convert timestamps
75 if ( !isset( $params['timestamps'] ) ) {
76 $params['timestamps'] = [];
77 }
78 if ( !is_array( $params['timestamps'] ) ) {
79 $params['timestamps'] = [ $params['timestamps'] ];
80 }
81 foreach ( $params['timestamps'] as $i => $ts ) {
82 $params['timestamps'][$i] = wfTimestamp( TS::MW, $ts );
83 }
84
85 $undeletePage = $this->undeletePageFactory->newUndeletePage(
86 $this->wikiPageFactory->newFromTitle( $titleObj ),
87 $this->getAuthority()
88 )
89 ->setUndeleteOnlyTimestamps( $params['timestamps'] ?? [] )
90 ->setUndeleteOnlyFileVersions( $params['fileids'] ?: [] )
91 ->setTags( $params['tags'] ?: [] );
92
93 if ( $params['undeletetalk'] ) {
94 $undeletePage->setUndeleteAssociatedTalk( true );
95 }
96
97 $status = $undeletePage->undeleteIfAllowed( $params['reason'] );
98 if ( $status->isOK() ) {
99 // in case there are warnings
100 $this->addMessagesFromStatus( $status );
101 } else {
102 $this->dieStatus( $status );
103 }
104
105 $restoredRevs = $status->getValue()[UndeletePage::REVISIONS_RESTORED];
106 $restoredFiles = $status->getValue()[UndeletePage::FILES_RESTORED];
107
108 if ( $restoredRevs === 0 && $restoredFiles === 0 ) {
109 // BC for code that predates UndeletePage
110 $this->dieWithError( 'apierror-cantundelete' );
111 }
112
113 if ( $restoredFiles ) {
114 $this->getHookRunner()->onFileUndeleteComplete(
115 $titleObj, $params['fileids'],
116 $this->getUser(), $params['reason'] );
117 }
118
119 $watchlistExpiry = $this->getExpiryFromParams( $params, $titleObj, $user );
120 $this->setWatch( $params['watchlist'], $titleObj, $user, null, $watchlistExpiry );
121
122 $info = [
123 'title' => $titleObj->getPrefixedText(),
124 'revisions' => $restoredRevs,
125 'fileversions' => $restoredFiles,
126 'reason' => $params['reason']
127 ];
128 $this->getResult()->addValue( null, $this->getModuleName(), $info );
129 }
130
132 public function mustBePosted() {
133 return true;
134 }
135
137 public function isWriteMode() {
138 return true;
139 }
140
142 public function getAllowedParams() {
143 return [
144 'title' => [
145 ParamValidator::PARAM_TYPE => 'string',
146 ParamValidator::PARAM_REQUIRED => true
147 ],
148 'reason' => '',
149 'tags' => [
150 ParamValidator::PARAM_TYPE => 'tags',
151 ParamValidator::PARAM_ISMULTI => true,
152 ],
153 'timestamps' => [
154 ParamValidator::PARAM_TYPE => 'timestamp',
155 ParamValidator::PARAM_ISMULTI => true,
156 ],
157 'fileids' => [
158 ParamValidator::PARAM_TYPE => 'integer',
159 ParamValidator::PARAM_ISMULTI => true,
160 ],
161 'undeletetalk' => false,
162 ] + $this->getWatchlistParams();
163 }
164
166 public function needsToken() {
167 return 'csrf';
168 }
169
171 protected function getExamplesMessages() {
172 $title = Title::newMainPage()->getPrefixedText();
173 $mp = rawurlencode( $title );
174
175 return [
176 "action=undelete&title={$mp}&token=123ABC&reason=Restoring%20{$mp}"
177 => 'apihelp-undelete-example-page',
178 "action=undelete&title={$mp}&token=123ABC" .
179 '&timestamps=2007-07-03T22:00:45Z|2007-07-02T19:48:56Z'
180 => 'apihelp-undelete-example-revisions',
181 ];
182 }
183
185 public function getHelpUrls() {
186 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete';
187 }
188}
189
191class_alias( ApiUndelete::class, 'ApiUndelete' );
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:61
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1507
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:543
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:767
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition ApiBase.php:1355
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'], array $filter=[])
Add warnings and/or errors from a Status.
Definition ApiBase.php:1485
getResult()
Get the result object.
Definition ApiBase.php:682
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition ApiBase.php:1535
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1558
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:823
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:67
__construct(ApiMain $mainModule, string $moduleName, WatchlistManager $watchlistManager, WatchedItemStoreInterface $watchedItemStore, UserOptionsLookup $userOptionsLookup, UndeletePageFactory $undeletePageFactory, WikiPageFactory $wikiPageFactory)
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
needsToken()
Returns the token type this module requires in order to execute.Modules are strongly encouraged to us...
isWriteMode()
Indicates whether this module requires write access to the wiki.API modules must override this method...
mustBePosted()
Indicates whether this module must be called with a POST request.Implementations of this method must ...
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()
Service for creating WikiPage objects.
Represents a title within MediaWiki.
Definition Title.php:69
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...
Service for page undelete actions.
Interface for database access objects.
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.
getExpiryFromParams(array $params, ?PageIdentity $page=null, ?UserIdentity $user=null, string $userOption='watchdefault-expiry')
Get formatted expiry from the given parameters.