MediaWiki master
ApiUndelete.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Api;
24
34
38class ApiUndelete extends ApiBase {
39
41
42 private UndeletePageFactory $undeletePageFactory;
43 private WikiPageFactory $wikiPageFactory;
44
45 public function __construct(
46 ApiMain $mainModule,
47 string $moduleName,
48 WatchlistManager $watchlistManager,
49 UserOptionsLookup $userOptionsLookup,
50 UndeletePageFactory $undeletePageFactory,
51 WikiPageFactory $wikiPageFactory
52 ) {
53 parent::__construct( $mainModule, $moduleName );
54
55 // Variables needed in ApiWatchlistTrait trait
56 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
57 $this->watchlistMaxDuration =
59 $this->watchlistManager = $watchlistManager;
60 $this->userOptionsLookup = $userOptionsLookup;
61 $this->undeletePageFactory = $undeletePageFactory;
62 $this->wikiPageFactory = $wikiPageFactory;
63 }
64
65 public function execute() {
67
68 $params = $this->extractRequestParams();
69
70 $user = $this->getUser();
71 $block = $user->getBlock( IDBAccessObject::READ_LATEST );
72 if ( $block && $block->isSitewide() ) {
73 $this->dieBlocked( $block );
74 }
75
76 $titleObj = Title::newFromText( $params['title'] );
77 if ( !$titleObj || $titleObj->isExternal() ) {
78 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
79 }
80 if ( !$titleObj->canExist() ) {
81 $this->dieWithError( 'apierror-pagecannotexist' );
82 }
83
84 // Convert timestamps
85 if ( !isset( $params['timestamps'] ) ) {
86 $params['timestamps'] = [];
87 }
88 if ( !is_array( $params['timestamps'] ) ) {
89 $params['timestamps'] = [ $params['timestamps'] ];
90 }
91 foreach ( $params['timestamps'] as $i => $ts ) {
92 $params['timestamps'][$i] = wfTimestamp( TS_MW, $ts );
93 }
94
95 $undeletePage = $this->undeletePageFactory->newUndeletePage(
96 $this->wikiPageFactory->newFromTitle( $titleObj ),
97 $this->getAuthority()
98 )
99 ->setUndeleteOnlyTimestamps( $params['timestamps'] ?? [] )
100 ->setUndeleteOnlyFileVersions( $params['fileids'] ?: [] )
101 ->setTags( $params['tags'] ?: [] );
102
103 if ( $params['undeletetalk'] ) {
104 $undeletePage->setUndeleteAssociatedTalk( true );
105 }
106
107 $status = $undeletePage->undeleteIfAllowed( $params['reason'] );
108 if ( $status->isOK() ) {
109 // in case there are warnings
110 $this->addMessagesFromStatus( $status );
111 } else {
112 $this->dieStatus( $status );
113 }
114
115 $restoredRevs = $status->getValue()[UndeletePage::REVISIONS_RESTORED];
116 $restoredFiles = $status->getValue()[UndeletePage::FILES_RESTORED];
117
118 if ( $restoredRevs === 0 && $restoredFiles === 0 ) {
119 // BC for code that predates UndeletePage
120 $this->dieWithError( 'apierror-cantundelete' );
121 }
122
123 if ( $restoredFiles ) {
124 $this->getHookRunner()->onFileUndeleteComplete(
125 $titleObj, $params['fileids'],
126 $this->getUser(), $params['reason'] );
127 }
128
129 $watchlistExpiry = $this->getExpiryFromParams( $params );
130 $this->setWatch( $params['watchlist'], $titleObj, $user, null, $watchlistExpiry );
131
132 $info = [
133 'title' => $titleObj->getPrefixedText(),
134 'revisions' => $restoredRevs,
135 'fileversions' => $restoredFiles,
136 'reason' => $params['reason']
137 ];
138 $this->getResult()->addValue( null, $this->getModuleName(), $info );
139 }
140
141 public function mustBePosted() {
142 return true;
143 }
144
145 public function isWriteMode() {
146 return true;
147 }
148
149 public function getAllowedParams() {
150 return [
151 'title' => [
152 ParamValidator::PARAM_TYPE => 'string',
153 ParamValidator::PARAM_REQUIRED => true
154 ],
155 'reason' => '',
156 'tags' => [
157 ParamValidator::PARAM_TYPE => 'tags',
158 ParamValidator::PARAM_ISMULTI => true,
159 ],
160 'timestamps' => [
161 ParamValidator::PARAM_TYPE => 'timestamp',
162 ParamValidator::PARAM_ISMULTI => true,
163 ],
164 'fileids' => [
165 ParamValidator::PARAM_TYPE => 'integer',
166 ParamValidator::PARAM_ISMULTI => true,
167 ],
168 'undeletetalk' => false,
169 ] + $this->getWatchlistParams();
170 }
171
172 public function needsToken() {
173 return 'csrf';
174 }
175
176 protected function getExamplesMessages() {
177 $title = Title::newMainPage()->getPrefixedText();
178 $mp = rawurlencode( $title );
179
180 return [
181 "action=undelete&title={$mp}&token=123ABC&reason=Restoring%20{$mp}"
182 => 'apihelp-undelete-example-page',
183 "action=undelete&title={$mp}&token=123ABC" .
184 '&timestamps=2007-07-03T22:00:45Z|2007-07-02T19:48:56Z'
185 => 'apihelp-undelete-example-revisions',
186 ];
187 }
188
189 public function getHelpUrls() {
190 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete';
191 }
192}
193
195class_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:75
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:557
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:781
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition ApiBase.php:1370
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'], array $filter=[])
Add warnings and/or errors from a Status.
Definition ApiBase.php:1500
getResult()
Get the result object.
Definition ApiBase.php:696
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition ApiBase.php:1550
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1573
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:78
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
__construct(ApiMain $mainModule, string $moduleName, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup, UndeletePageFactory $undeletePageFactory, WikiPageFactory $wikiPageFactory)
getHelpUrls()
Return links to more detailed help pages about the module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getExamplesMessages()
Returns usage examples for this module.
needsToken()
Returns the token type this module requires in order to execute.
isWriteMode()
Indicates whether this module requires write access to the wiki.
mustBePosted()
Indicates whether this module must be called with a POST request.
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()
Backend logic for performing a page undelete action.
Service for creating WikiPage objects.
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...
Service for page undelete actions.
Interface for database access objects.
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.