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 public function __construct(
31 ApiMain $mainModule,
32 string $moduleName,
33 WatchlistManager $watchlistManager,
34 WatchedItemStoreInterface $watchedItemStore,
35 UserOptionsLookup $userOptionsLookup,
36 private readonly UndeletePageFactory $undeletePageFactory,
37 private readonly WikiPageFactory $wikiPageFactory,
38 ) {
39 parent::__construct( $mainModule, $moduleName );
40
41 // Variables needed in ApiWatchlistTrait trait
42 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
43 $this->watchlistMaxDuration =
45 $this->watchlistManager = $watchlistManager;
46 $this->watchedItemStore = $watchedItemStore;
47 $this->userOptionsLookup = $userOptionsLookup;
48 }
49
50 public function execute() {
52
53 $params = $this->extractRequestParams();
54
55 $user = $this->getUser();
56 $block = $user->getBlock( IDBAccessObject::READ_LATEST );
57 if ( $block && $block->isSitewide() ) {
58 $this->dieBlocked( $block );
59 }
60
61 $titleObj = Title::newFromText( $params['title'] );
62 if ( !$titleObj || $titleObj->isExternal() ) {
63 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
64 }
65 if ( !$titleObj->canExist() ) {
66 $this->dieWithError( 'apierror-pagecannotexist' );
67 }
68
69 // Convert timestamps
70 if ( !isset( $params['timestamps'] ) ) {
71 $params['timestamps'] = [];
72 }
73 if ( !is_array( $params['timestamps'] ) ) {
74 $params['timestamps'] = [ $params['timestamps'] ];
75 }
76 foreach ( $params['timestamps'] as $i => $ts ) {
77 $params['timestamps'][$i] = wfTimestamp( TS::MW, $ts );
78 }
79
80 $undeletePage = $this->undeletePageFactory->newUndeletePage(
81 $this->wikiPageFactory->newFromTitle( $titleObj ),
82 $this->getAuthority()
83 )
84 ->setUndeleteOnlyTimestamps( $params['timestamps'] ?? [] )
85 ->setUndeleteOnlyFileVersions( $params['fileids'] ?: [] )
86 ->setTags( $params['tags'] ?: [] );
87
88 if ( $params['undeletetalk'] ) {
89 $undeletePage->setUndeleteAssociatedTalk( true );
90 }
91
92 $status = $undeletePage->undeleteIfAllowed( $params['reason'] );
93 if ( $status->isOK() ) {
94 // in case there are warnings
95 $this->addMessagesFromStatus( $status );
96 } else {
97 $this->dieStatus( $status );
98 }
99
100 $restoredRevs = $status->getValue()[UndeletePage::REVISIONS_RESTORED];
101 $restoredFiles = $status->getValue()[UndeletePage::FILES_RESTORED];
102
103 if ( $restoredRevs === 0 && $restoredFiles === 0 ) {
104 // BC for code that predates UndeletePage
105 $this->dieWithError( 'apierror-cantundelete' );
106 }
107
108 if ( $restoredFiles ) {
109 $this->getHookRunner()->onFileUndeleteComplete(
110 $titleObj, $params['fileids'],
111 $this->getUser(), $params['reason'] );
112 }
113
114 $watchlistExpiry = $this->getExpiryFromParams( $params, $titleObj, $user );
115 $this->setWatch( $params['watchlist'], $titleObj, $user, null, $watchlistExpiry );
116
117 $info = [
118 'title' => $titleObj->getPrefixedText(),
119 'revisions' => $restoredRevs,
120 'fileversions' => $restoredFiles,
121 'reason' => $params['reason']
122 ];
123 $this->getResult()->addValue( null, $this->getModuleName(), $info );
124 }
125
127 public function mustBePosted() {
128 return true;
129 }
130
132 public function isWriteMode() {
133 return true;
134 }
135
137 public function getAllowedParams() {
138 return [
139 'title' => [
140 ParamValidator::PARAM_TYPE => 'string',
141 ParamValidator::PARAM_REQUIRED => true
142 ],
143 'reason' => '',
144 'tags' => [
145 ParamValidator::PARAM_TYPE => 'tags',
146 ParamValidator::PARAM_ISMULTI => true,
147 ],
148 'timestamps' => [
149 ParamValidator::PARAM_TYPE => 'timestamp',
150 ParamValidator::PARAM_ISMULTI => true,
151 ],
152 'fileids' => [
153 ParamValidator::PARAM_TYPE => 'integer',
154 ParamValidator::PARAM_ISMULTI => true,
155 ],
156 'undeletetalk' => false,
157 ] + $this->getWatchlistParams();
158 }
159
161 public function needsToken() {
162 return 'csrf';
163 }
164
166 protected function getExamplesMessages() {
167 $title = Title::newMainPage()->getPrefixedText();
168 $mp = rawurlencode( $title );
169
170 return [
171 "action=undelete&title={$mp}&token=123ABC&reason=Restoring%20{$mp}"
172 => 'apihelp-undelete-example-page',
173 "action=undelete&title={$mp}&token=123ABC" .
174 '&timestamps=2007-07-03T22:00:45Z|2007-07-02T19:48:56Z'
175 => 'apihelp-undelete-example-revisions',
176 ];
177 }
178
180 public function getHelpUrls() {
181 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete';
182 }
183}
184
186class_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:60
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:1369
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:66
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...
__construct(ApiMain $mainModule, string $moduleName, WatchlistManager $watchlistManager, WatchedItemStoreInterface $watchedItemStore, UserOptionsLookup $userOptionsLookup, private readonly UndeletePageFactory $undeletePageFactory, private readonly WikiPageFactory $wikiPageFactory,)
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.