ApiFileRevert::validateParameters()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 8
nop 0
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
1
<?php
2
/**
3
 *
4
 *
5
 * Created on March 5, 2011
6
 *
7
 * Copyright © 2011 Bryan Tong Minh <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License along
20
 * with this program; if not, write to the Free Software Foundation, Inc.,
21
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
 * http://www.gnu.org/copyleft/gpl.html
23
 *
24
 * @file
25
 */
26
27
/**
28
 * @ingroup API
29
 */
30
class ApiFileRevert extends ApiBase {
31
	/** @var LocalFile */
32
	protected $file;
33
34
	/** @var string */
35
	protected $archiveName;
36
37
	/** @var array */
38
	protected $params;
39
40
	public function execute() {
41
		$this->useTransactionalTimeLimit();
42
43
		$this->params = $this->extractRequestParams();
44
		// Extract the file and archiveName from the request parameters
45
		$this->validateParameters();
46
47
		// Check whether we're allowed to revert this file
48
		$this->checkPermissions( $this->getUser() );
49
50
		$sourceUrl = $this->file->getArchiveVirtualUrl( $this->archiveName );
51
		$status = $this->file->upload(
52
			$sourceUrl,
53
			$this->params['comment'],
54
			$this->params['comment'],
55
			0,
56
			false,
57
			false,
58
			$this->getUser()
59
		);
60
61
		if ( $status->isGood() ) {
62
			$result = [ 'result' => 'Success' ];
63
		} else {
64
			$result = [
65
				'result' => 'Failure',
66
				'errors' => $this->getErrorFormatter()->arrayFromStatus( $status ),
67
			];
68
		}
69
70
		$this->getResult()->addValue( null, $this->getModuleName(), $result );
71
	}
72
73
	/**
74
	 * Checks that the user has permissions to perform this revert.
75
	 * Dies with usage message on inadequate permissions.
76
	 * @param User $user The user to check.
77
	 */
78
	protected function checkPermissions( $user ) {
79
		$title = $this->file->getTitle();
80
		$permissionErrors = array_merge(
81
			$title->getUserPermissionsErrors( 'edit', $user ),
82
			$title->getUserPermissionsErrors( 'upload', $user )
83
		);
84
85
		if ( $permissionErrors ) {
86
			$this->dieUsageMsg( $permissionErrors[0] );
87
		}
88
	}
89
90
	/**
91
	 * Validate the user parameters and set $this->archiveName and $this->file.
92
	 * Throws an error if validation fails
93
	 */
94
	protected function validateParameters() {
95
		// Validate the input title
96
		$title = Title::makeTitleSafe( NS_FILE, $this->params['filename'] );
97
		if ( is_null( $title ) ) {
98
			$this->dieUsageMsg( [ 'invalidtitle', $this->params['filename'] ] );
99
		}
100
		$localRepo = RepoGroup::singleton()->getLocalRepo();
101
102
		// Check if the file really exists
103
		$this->file = $localRepo->newFile( $title );
0 ignored issues
show
Documentation Bug introduced by
It seems like $localRepo->newFile($title) can also be of type object<File>. However, the property $file is declared as type object<LocalFile>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
Bug introduced by
It seems like $title defined by \Title::makeTitleSafe(NS...is->params['filename']) on line 96 can be null; however, FileRepo::newFile() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
104
		if ( !$this->file->exists() ) {
105
			$this->dieUsageMsg( 'notanarticle' );
106
		}
107
108
		// Check if the archivename is valid for this file
109
		$this->archiveName = $this->params['archivename'];
110
		$oldFile = $localRepo->newFromArchiveName( $title, $this->archiveName );
0 ignored issues
show
Bug introduced by
It seems like $title defined by \Title::makeTitleSafe(NS...is->params['filename']) on line 96 can be null; however, LocalRepo::newFromArchiveName() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
111
		if ( !$oldFile->exists() ) {
112
			$this->dieUsageMsg( 'filerevert-badversion' );
113
		}
114
	}
115
116
	public function mustBePosted() {
117
		return true;
118
	}
119
120
	public function isWriteMode() {
121
		return true;
122
	}
123
124 View Code Duplication
	public function getAllowedParams() {
125
		return [
126
			'filename' => [
127
				ApiBase::PARAM_TYPE => 'string',
128
				ApiBase::PARAM_REQUIRED => true,
129
			],
130
			'comment' => [
131
				ApiBase::PARAM_DFLT => '',
132
			],
133
			'archivename' => [
134
				ApiBase::PARAM_TYPE => 'string',
135
				ApiBase::PARAM_REQUIRED => true,
136
			],
137
		];
138
	}
139
140
	public function needsToken() {
141
		return 'csrf';
142
	}
143
144
	protected function getExamplesMessages() {
145
		return [
146
			'action=filerevert&filename=Wiki.png&comment=Revert&' .
147
				'archivename=20110305152740!Wiki.png&token=123ABC'
148
				=> 'apihelp-filerevert-example-revert',
149
		];
150
	}
151
}
152