ApiRevisionDelete::extractStatusInfo()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 8
nop 1
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created on Jun 25, 2013
4
 *
5
 * Copyright © 2013 Brad Jorsch <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License along
18
 * with this program; if not, write to the Free Software Foundation, Inc.,
19
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
 * http://www.gnu.org/copyleft/gpl.html
21
 *
22
 * @file
23
 * @since 1.23
24
 */
25
26
/**
27
 * API interface to RevDel. The API equivalent of Special:RevisionDelete.
28
 * Requires API write mode to be enabled.
29
 *
30
 * @ingroup API
31
 */
32
class ApiRevisionDelete extends ApiBase {
33
34
	public function execute() {
35
		$this->useTransactionalTimeLimit();
36
37
		$params = $this->extractRequestParams();
38
		$user = $this->getUser();
39
		if ( !$user->isAllowed( RevisionDeleter::getRestriction( $params['type'] ) ) ) {
40
			$this->dieUsageMsg( 'badaccess-group0' );
41
		}
42
43
		if ( $user->isBlocked() ) {
44
			$this->dieBlocked( $user->getBlock() );
0 ignored issues
show
Bug introduced by
It seems like $user->getBlock() can be null; however, dieBlocked() 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...
45
		}
46
47
		if ( !$params['ids'] ) {
48
			$this->dieUsage( "At least one value is required for 'ids'", 'badparams' );
49
		}
50
51
		$hide = $params['hide'] ?: [];
52
		$show = $params['show'] ?: [];
53
		if ( array_intersect( $hide, $show ) ) {
54
			$this->dieUsage( "Mutually exclusive values for 'hide' and 'show'", 'badparams' );
55
		} elseif ( !$hide && !$show ) {
56
			$this->dieUsage( "At least one value is required for 'hide' or 'show'", 'badparams' );
57
		}
58
		$bits = [
59
			'content' => RevisionDeleter::getRevdelConstant( $params['type'] ),
60
			'comment' => Revision::DELETED_COMMENT,
61
			'user' => Revision::DELETED_USER,
62
		];
63
		$bitfield = [];
64
		foreach ( $bits as $key => $bit ) {
65
			if ( in_array( $key, $hide ) ) {
66
				$bitfield[$bit] = 1;
67
			} elseif ( in_array( $key, $show ) ) {
68
				$bitfield[$bit] = 0;
69
			} else {
70
				$bitfield[$bit] = -1;
71
			}
72
		}
73
74
		if ( $params['suppress'] === 'yes' ) {
75
			if ( !$user->isAllowed( 'suppressrevision' ) ) {
76
				$this->dieUsageMsg( 'badaccess-group0' );
77
			}
78
			$bitfield[Revision::DELETED_RESTRICTED] = 1;
79
		} elseif ( $params['suppress'] === 'no' ) {
80
			$bitfield[Revision::DELETED_RESTRICTED] = 0;
81
		} else {
82
			$bitfield[Revision::DELETED_RESTRICTED] = -1;
83
		}
84
85
		$targetObj = null;
86
		if ( $params['target'] ) {
87
			$targetObj = Title::newFromText( $params['target'] );
88
		}
89
		$targetObj = RevisionDeleter::suggestTarget( $params['type'], $targetObj, $params['ids'] );
90
		if ( $targetObj === null ) {
91
			$this->dieUsage( 'A target title is required for this RevDel type', 'needtarget' );
92
		}
93
94
		$list = RevisionDeleter::createList(
95
			$params['type'], $this->getContext(), $targetObj, $params['ids']
0 ignored issues
show
Bug introduced by
It seems like $targetObj defined by \RevisionDeleter::sugges...getObj, $params['ids']) on line 89 can be null; however, RevisionDeleter::createList() 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...
96
		);
97
		$status = $list->setVisibility(
98
			[ 'value' => $bitfield, 'comment' => $params['reason'], 'perItemStatus' => true ]
99
		);
100
101
		$result = $this->getResult();
102
		$data = $this->extractStatusInfo( $status );
103
		$data['target'] = $targetObj->getFullText();
104
		$data['items'] = [];
105
106
		foreach ( $status->itemStatuses as $id => $s ) {
0 ignored issues
show
Documentation introduced by
The property itemStatuses does not exist on object<Status>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
107
			$data['items'][$id] = $this->extractStatusInfo( $s );
108
			$data['items'][$id]['id'] = $id;
109
		}
110
111
		$list->reloadFromMaster();
112
		// @codingStandardsIgnoreStart Avoid function calls in a FOR loop test part
113
		for ( $item = $list->reset(); $list->current(); $item = $list->next() ) {
114
			$data['items'][$item->getId()] += $item->getApiData( $this->getResult() );
0 ignored issues
show
Bug introduced by
The method getApiData() does not seem to exist on object<Revision>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
		}
116
		// @codingStandardsIgnoreEnd
117
118
		$data['items'] = array_values( $data['items'] );
119
		ApiResult::setIndexedTagName( $data['items'], 'i' );
120
		$result->addValue( null, $this->getModuleName(), $data );
121
	}
122
123
	private function extractStatusInfo( $status ) {
124
		$ret = [
125
			'status' => $status->isOK() ? 'Success' : 'Fail',
126
		];
127
		$errors = $this->formatStatusMessages( $status->getErrorsByType( 'error' ) );
128
		if ( $errors ) {
129
			ApiResult::setIndexedTagName( $errors, 'e' );
130
			$ret['errors'] = $errors;
131
		}
132
		$warnings = $this->formatStatusMessages( $status->getErrorsByType( 'warning' ) );
133
		if ( $warnings ) {
134
			ApiResult::setIndexedTagName( $warnings, 'w' );
135
			$ret['warnings'] = $warnings;
136
		}
137
138
		return $ret;
139
	}
140
141
	private function formatStatusMessages( $messages ) {
142
		if ( !$messages ) {
143
			return [];
144
		}
145
		$ret = [];
146
		foreach ( $messages as $m ) {
147
			if ( $m['message'] instanceof Message ) {
148
				$msg = $m['message'];
149
				$message = [ 'message' => $msg->getKey() ];
150
				if ( $msg->getParams() ) {
151
					$message['params'] = $msg->getParams();
152
					ApiResult::setIndexedTagName( $message['params'], 'p' );
153
				}
154
			} else {
155
				$message = [ 'message' => $m['message'] ];
156
				$msg = wfMessage( $m['message'] );
157 View Code Duplication
				if ( isset( $m['params'] ) ) {
158
					$message['params'] = $m['params'];
159
					ApiResult::setIndexedTagName( $message['params'], 'p' );
160
					$msg->params( $m['params'] );
161
				}
162
			}
163
			$message['rendered'] = $msg->useDatabase( false )->inLanguage( 'en' )->plain();
164
			$ret[] = $message;
165
		}
166
167
		return $ret;
168
	}
169
170
	public function mustBePosted() {
171
		return true;
172
	}
173
174
	public function isWriteMode() {
175
		return true;
176
	}
177
178
	public function getAllowedParams() {
179
		return [
180
			'type' => [
181
				ApiBase::PARAM_TYPE => RevisionDeleter::getTypes(),
182
				ApiBase::PARAM_REQUIRED => true
183
			],
184
			'target' => null,
185
			'ids' => [
186
				ApiBase::PARAM_ISMULTI => true,
187
				ApiBase::PARAM_REQUIRED => true
188
			],
189
			'hide' => [
190
				ApiBase::PARAM_TYPE => [ 'content', 'comment', 'user' ],
191
				ApiBase::PARAM_ISMULTI => true,
192
			],
193
			'show' => [
194
				ApiBase::PARAM_TYPE => [ 'content', 'comment', 'user' ],
195
				ApiBase::PARAM_ISMULTI => true,
196
			],
197
			'suppress' => [
198
				ApiBase::PARAM_TYPE => [ 'yes', 'no', 'nochange' ],
199
				ApiBase::PARAM_DFLT => 'nochange',
200
			],
201
			'reason' => null,
202
		];
203
	}
204
205
	public function needsToken() {
206
		return 'csrf';
207
	}
208
209
	protected function getExamplesMessages() {
210
		return [
211
			'action=revisiondelete&target=Main%20Page&type=revision&ids=12345&' .
212
				'hide=content&token=123ABC'
213
				=> 'apihelp-revisiondelete-example-revision',
214
			'action=revisiondelete&type=logging&ids=67890&hide=content|comment|user&' .
215
				'reason=BLP%20violation&token=123ABC'
216
				=> 'apihelp-revisiondelete-example-log',
217
		];
218
	}
219
220
	public function getHelpUrls() {
221
		return 'https://www.mediawiki.org/wiki/API:Revisiondelete';
222
	}
223
}
224