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
53 public function __construct(
54 ApiMain $mainModule,
55 $moduleName,
56 WatchlistManager $watchlistManager,
57 UserOptionsLookup $userOptionsLookup,
58 UndeletePageFactory $undeletePageFactory,
59 WikiPageFactory $wikiPageFactory
60 ) {
61 parent::__construct( $mainModule, $moduleName );
62
63 // Variables needed in ApiWatchlistTrait trait
64 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
65 $this->watchlistMaxDuration =
67 $this->watchlistManager = $watchlistManager;
68 $this->userOptionsLookup = $userOptionsLookup;
69 $this->undeletePageFactory = $undeletePageFactory;
70 $this->wikiPageFactory = $wikiPageFactory;
71 }
72
73 public function execute() {
75
77
78 $user = $this->getUser();
79 $block = $user->getBlock( IDBAccessObject::READ_LATEST );
80 if ( $block && $block->isSitewide() ) {
81 $this->dieBlocked( $block );
82 }
83
84 $titleObj = Title::newFromText( $params['title'] );
85 if ( !$titleObj || $titleObj->isExternal() ) {
86 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
87 }
88 if ( !$titleObj->canExist() ) {
89 $this->dieWithError( 'apierror-pagecannotexist' );
90 }
91
92 // Convert timestamps
93 if ( !isset( $params['timestamps'] ) ) {
94 $params['timestamps'] = [];
95 }
96 if ( !is_array( $params['timestamps'] ) ) {
97 $params['timestamps'] = [ $params['timestamps'] ];
98 }
99 foreach ( $params['timestamps'] as $i => $ts ) {
100 $params['timestamps'][$i] = wfTimestamp( TS_MW, $ts );
101 }
102
103 $undeletePage = $this->undeletePageFactory->newUndeletePage(
104 $this->wikiPageFactory->newFromTitle( $titleObj ),
105 $this->getAuthority()
106 )
107 ->setUndeleteOnlyTimestamps( $params['timestamps'] ?? [] )
108 ->setUndeleteOnlyFileVersions( $params['fileids'] ?: [] )
109 ->setTags( $params['tags'] ?: [] );
110
111 if ( $params['undeletetalk'] ) {
112 $undeletePage->setUndeleteAssociatedTalk( true );
113 }
114
115 $status = $undeletePage->undeleteIfAllowed( $params['reason'] );
116 if ( $status->isOK() ) {
117 // in case there are warnings
118 $this->addMessagesFromStatus( $status );
119 } else {
120 $this->dieStatus( $status );
121 }
122
123 $restoredRevs = $status->getValue()[UndeletePage::REVISIONS_RESTORED];
124 $restoredFiles = $status->getValue()[UndeletePage::FILES_RESTORED];
125
126 if ( $restoredRevs === 0 && $restoredFiles === 0 ) {
127 // BC for code that predates UndeletePage
128 $this->dieWithError( 'apierror-cantundelete' );
129 }
130
131 if ( $restoredFiles ) {
132 $this->getHookRunner()->onFileUndeleteComplete(
133 $titleObj, $params['fileids'],
134 $this->getUser(), $params['reason'] );
135 }
136
137 $watchlistExpiry = $this->getExpiryFromParams( $params );
138 $this->setWatch( $params['watchlist'], $titleObj, $user, null, $watchlistExpiry );
139
140 $info = [
141 'title' => $titleObj->getPrefixedText(),
142 'revisions' => $restoredRevs,
143 'fileversions' => $restoredFiles,
144 'reason' => $params['reason']
145 ];
146 $this->getResult()->addValue( null, $this->getModuleName(), $info );
147 }
148
149 public function mustBePosted() {
150 return true;
151 }
152
153 public function isWriteMode() {
154 return true;
155 }
156
157 public function getAllowedParams() {
158 return [
159 'title' => [
160 ParamValidator::PARAM_TYPE => 'string',
161 ParamValidator::PARAM_REQUIRED => true
162 ],
163 'reason' => '',
164 'tags' => [
165 ParamValidator::PARAM_TYPE => 'tags',
166 ParamValidator::PARAM_ISMULTI => true,
167 ],
168 'timestamps' => [
169 ParamValidator::PARAM_TYPE => 'timestamp',
170 ParamValidator::PARAM_ISMULTI => true,
171 ],
172 'fileids' => [
173 ParamValidator::PARAM_TYPE => 'integer',
174 ParamValidator::PARAM_ISMULTI => true,
175 ],
176 'undeletetalk' => false,
177 ] + $this->getWatchlistParams();
178 }
179
180 public function needsToken() {
181 return 'csrf';
182 }
183
184 protected function getExamplesMessages() {
185 $title = Title::newMainPage()->getPrefixedText();
186 $mp = rawurlencode( $title );
187
188 return [
189 "action=undelete&title={$mp}&token=123ABC&reason=Restoring%20{$mp}"
190 => 'apihelp-undelete-example-page',
191 "action=undelete&title={$mp}&token=123ABC" .
192 '&timestamps=2007-07-03T22:00:45Z|2007-07-02T19:48:56Z'
193 => 'apihelp-undelete-example-revisions',
194 ];
195 }
196
197 public function getHelpUrls() {
198 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete';
199 }
200}
201
203class_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.
array $params
The job parameters.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:76
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1577
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:571
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition ApiBase.php:795
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition ApiBase.php:1425
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'], array $filter=[])
Add warnings and/or errors from a Status.
Definition ApiBase.php:1555
getResult()
Get the result object.
Definition ApiBase.php:710
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition ApiBase.php:1605
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1632
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:851
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.
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.
__construct(ApiMain $mainModule, $moduleName, WatchlistManager $watchlistManager, UserOptionsLookup $userOptionsLookup, UndeletePageFactory $undeletePageFactory, WikiPageFactory $wikiPageFactory)
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.