Issues (1401)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

repo/includes/Specials/SpecialNewProperty.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Wikibase\Repo\Specials;
4
5
use OutputPage;
6
use Status;
7
use Wikibase\DataModel\Entity\EntityDocument;
8
use Wikibase\DataModel\Entity\Property;
9
use Wikibase\DataModel\Term\Term;
10
use Wikibase\Lib\Store\EntityNamespaceLookup;
11
use Wikibase\Lib\Store\EntityTitleLookup;
12
use Wikibase\Lib\Summary;
13
use Wikibase\Repo\CopyrightMessageBuilder;
14
use Wikibase\Repo\DataTypeSelector;
15
use Wikibase\Repo\EditEntity\MediawikiEditEntityFactory;
16
use Wikibase\Repo\Specials\HTMLForm\HTMLAliasesField;
17
use Wikibase\Repo\Specials\HTMLForm\HTMLContentLanguageField;
18
use Wikibase\Repo\Specials\HTMLForm\HTMLTrimmedTextField;
19
use Wikibase\Repo\Store\TermsCollisionDetector;
20
use Wikibase\Repo\SummaryFormatter;
21
use Wikibase\Repo\WikibaseRepo;
22
23
/**
24
 * Page for creating new Wikibase properties.
25
 *
26
 * @license GPL-2.0-or-later
27
 * @author John Erling Blad < [email protected] >
28
 */
29
class SpecialNewProperty extends SpecialNewEntity {
30
	const FIELD_LANG = 'lang';
31
	const FIELD_DATATYPE = 'datatype';
32
	const FIELD_LABEL = 'label';
33
	const FIELD_DESCRIPTION = 'description';
34
	const FIELD_ALIASES = 'aliases';
35
36
	/**
37
	 * @var TermsCollisionDetector
38
	 */
39
	private $termsCollisionDetector;
40
41
	public function __construct(
42
		SpecialPageCopyrightView $specialPageCopyrightView,
43
		EntityNamespaceLookup $entityNamespaceLookup,
44
		SummaryFormatter $summaryFormatter,
45
		EntityTitleLookup $entityTitleLookup,
46
		MediawikiEditEntityFactory $editEntityFactory,
47
		TermsCollisionDetector $termsCollisionDetector
48
	) {
49
		parent::__construct(
50
			'NewProperty',
51
			'property-create',
52
			$specialPageCopyrightView,
53
			$entityNamespaceLookup,
54
			$summaryFormatter,
55
			$entityTitleLookup,
56
			$editEntityFactory
57
		);
58
59
		$this->termsCollisionDetector = $termsCollisionDetector;
60
	}
61
62
	public static function factory(): self {
63
		$wikibaseRepo = WikibaseRepo::getDefaultInstance();
64
65
		$settings = $wikibaseRepo->getSettings();
66
		$copyrightView = new SpecialPageCopyrightView(
67
			new CopyrightMessageBuilder(),
68
			$settings->getSetting( 'dataRightsUrl' ),
69
			$settings->getSetting( 'dataRightsText' )
70
		);
71
72
		return new self(
73
			$copyrightView,
74
			$wikibaseRepo->getEntityNamespaceLookup(),
75
			$wikibaseRepo->getSummaryFormatter(),
76
			$wikibaseRepo->getEntityTitleLookup(),
77
			$wikibaseRepo->newEditEntityFactory(),
78
			$wikibaseRepo->getPropertyTermsCollisionDetector()
79
		);
80
	}
81
82
	/**
83
	 * @see SpecialNewEntity::doesWrites
84
	 *
85
	 * @return bool
86
	 */
87
	public function doesWrites() {
88
		return true;
89
	}
90
91
	/**
92
	 * @see SpecialNewEntity::createEntityFromFormData
93
	 *
94
	 * @param array $formData
95
	 *
96
	 * @return Property
97
	 */
98
	protected function createEntityFromFormData( array $formData ) {
99
		$languageCode = $formData[ self::FIELD_LANG ];
100
101
		$property = Property::newFromType( $formData[ self::FIELD_DATATYPE ] );
102
103
		$property->setLabel( $languageCode, $formData[ self::FIELD_LABEL ] );
104
		$property->setDescription( $languageCode, $formData[ self::FIELD_DESCRIPTION ] );
105
106
		$property->setAliases( $languageCode, $formData[ self::FIELD_ALIASES ] );
107
108
		return $property;
109
	}
110
111
	/**
112
	 * @param string $dataType
113
	 *
114
	 * @return bool
115
	 */
116
	private function dataTypeExists( $dataType ) {
117
		$dataTypeFactory = WikibaseRepo::getDefaultInstance()->getDataTypeFactory();
118
119
		return in_array( $dataType, $dataTypeFactory->getTypeIds() );
120
	}
121
122
	/**
123
	 * @see SpecialNewEntity::getFormFields()
124
	 *
125
	 * @return array[]
126
	 */
127
	protected function getFormFields() {
128
		$formFields = [
129
			self::FIELD_LANG => [
130
				'name' => self::FIELD_LANG,
131
				'class' => HTMLContentLanguageField::class,
132
				'id' => 'wb-newentity-language',
133
			],
134
			self::FIELD_LABEL => [
135
				'name' => self::FIELD_LABEL,
136
				'default' => $this->parts[0] ?? '',
137
				'class' => HTMLTrimmedTextField::class,
138
				'id' => 'wb-newentity-label',
139
				'placeholder-message' => 'wikibase-label-edit-placeholder',
140
				'label-message' => 'wikibase-newentity-label'
141
			],
142
			self::FIELD_DESCRIPTION => [
143
				'name' => self::FIELD_DESCRIPTION,
144
				'default' => $this->parts[1] ?? '',
145
				'class' => HTMLTrimmedTextField::class,
146
				'id' => 'wb-newentity-description',
147
				'placeholder-message' => 'wikibase-description-edit-placeholder',
148
				'label-message' => 'wikibase-newentity-description'
149
			],
150
			self::FIELD_ALIASES => [
151
				'name' => self::FIELD_ALIASES,
152
				'class' => HTMLAliasesField::class,
153
				'id' => 'wb-newentity-aliases',
154
			]
155
		];
156
157
		$dataTypeFactory = WikibaseRepo::getDefaultInstance()->getDataTypeFactory();
158
		$selector = new DataTypeSelector(
159
			$dataTypeFactory->getTypes(),
160
			$this->getLanguage()->getCode()
161
		);
162
163
		$options = [
164
			$this->msg( 'wikibase-newproperty-pick-data-type' )->text() => ''
165
		];
166
		$formFields[ self::FIELD_DATATYPE ] = [
167
			'name' => self::FIELD_DATATYPE,
168
			'type' => 'select',
169
			'default' => $this->parts[2] ?? '',
170
			'options' => array_merge( $options, $selector->getOptionsArray() ),
171
			'id' => 'wb-newproperty-datatype',
172
			'validation-callback' => function ( $dataType, $formData, $form ) {
0 ignored issues
show
The parameter $formData is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
173
				if ( !$this->dataTypeExists( $dataType ) ) {
174
					return [ $this->msg( 'wikibase-newproperty-invalid-datatype' )->text() ];
175
				}
176
177
				return true;
178
			},
179
			'label-message' => 'wikibase-newproperty-datatype'
180
		];
181
182
		return $formFields;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $formFields; (array<string,array>) is incompatible with the return type declared by the abstract method Wikibase\Repo\Specials\S...ewEntity::getFormFields of type array[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
183
	}
184
185
	/**
186
	 * @inheritDoc
187
	 */
188
	protected function getLegend() {
189
		return $this->msg( 'wikibase-newproperty-fieldset' );
190
	}
191
192
	/**
193
	 * @see SpecialNewEntity::getWarnings
194
	 *
195
	 * @return string[]
196
	 */
197
	protected function getWarnings() {
198
		if ( $this->getUser()->isAnon() ) {
199
			return [
200
				$this->msg(
201
					'wikibase-anonymouseditwarning',
202
					$this->msg( 'wikibase-entity-property' )
203
				)->parse(),
204
			];
205
		}
206
207
		return [];
208
	}
209
210
	/**
211
	 * @param array $formData
212
	 *
213
	 * @return Status
214
	 */
215
	protected function validateFormData( array $formData ) {
216
		if ( $formData[ self::FIELD_LABEL ] == ''
217
			 && $formData[ self::FIELD_DESCRIPTION ] == ''
218
			 && $formData[ self::FIELD_ALIASES ] === []
219
		) {
220
			return Status::newFatal( 'wikibase-newproperty-insufficient-data' );
221
		}
222
223
		if ( $formData[ self::FIELD_LABEL ] !== '' &&
224
			$formData[ self::FIELD_LABEL ] === $formData[ self::FIELD_DESCRIPTION ]
225
		) {
226
			return Status::newFatal( 'wikibase-newproperty-same-label-and-description' );
227
		}
228
229
		$collidingPropertyId = $this->termsCollisionDetector->detectLabelCollision(
230
			$formData[ self::FIELD_LANG ],
231
			$formData[ self::FIELD_LABEL ]
232
		);
233
		if ( $collidingPropertyId !== null ) {
234
			return Status::newFatal(
235
				'wikibase-validator-label-conflict',
236
				$formData[ self::FIELD_LABEL ],
237
				$formData[ self::FIELD_LANG ],
238
				$collidingPropertyId
239
			);
240
		}
241
242
		return Status::newGood();
243
	}
244
245
	/**
246
	 * @param Property $property
247
	 *
248
	 * @return Summary
249
	 * @suppress PhanParamSignatureMismatch Uses intersection types
250
	 */
251
	protected function createSummary( EntityDocument $property ) {
252
		$uiLanguageCode = $this->getLanguage()->getCode();
253
254
		$summary = new Summary( 'wbeditentity', 'create' );
255
		$summary->setLanguage( $uiLanguageCode );
256
		/** @var Term|null $labelTerm */
257
		$labelTerm = $property->getLabels()->getIterator()->current();
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Wikibase\DataModel\Entity\EntityDocument as the method getLabels() does only exist in the following implementations of said interface: Wikibase\DataModel\Entity\Item, Wikibase\DataModel\Entity\Property.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
258
		/** @var Term|null $descriptionTerm */
259
		$descriptionTerm = $property->getDescriptions()->getIterator()->current();
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Wikibase\DataModel\Entity\EntityDocument as the method getDescriptions() does only exist in the following implementations of said interface: Wikibase\DataModel\Entity\Item, Wikibase\DataModel\Entity\Property.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
260
		$summary->addAutoSummaryArgs(
261
			$labelTerm ? $labelTerm->getText() : '',
262
			$descriptionTerm ? $descriptionTerm->getText() : ''
263
		);
264
265
		return $summary;
266
	}
267
268
	protected function displayBeforeForm( OutputPage $output ) {
269
		parent::displayBeforeForm( $output );
270
		$output->addModules( 'wikibase.special.languageLabelDescriptionAliases' );
271
	}
272
273
	/**
274
	 * @inheritDoc
275
	 */
276
	protected function getEntityType() {
277
		return Property::ENTITY_TYPE;
278
	}
279
280
}
281