ValidatingArrayLoader.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Package\Loader;
  12. use Composer\Package\BasePackage;
  13. use Composer\Semver\Constraint\Constraint;
  14. use Composer\Package\Version\VersionParser;
  15. use Composer\Repository\PlatformRepository;
  16. use Composer\Spdx\SpdxLicenses;
  17. /**
  18. * @author Jordi Boggiano <j.boggiano@seld.be>
  19. */
  20. class ValidatingArrayLoader implements LoaderInterface
  21. {
  22. const CHECK_ALL = 3;
  23. const CHECK_UNBOUND_CONSTRAINTS = 1;
  24. const CHECK_STRICT_CONSTRAINTS = 2;
  25. private $loader;
  26. private $versionParser;
  27. private $errors;
  28. private $warnings;
  29. private $config;
  30. private $strictName;
  31. private $flags;
  32. public function __construct(LoaderInterface $loader, $strictName = true, VersionParser $parser = null, $flags = 0)
  33. {
  34. $this->loader = $loader;
  35. $this->versionParser = $parser ?: new VersionParser();
  36. $this->strictName = $strictName;
  37. $this->flags = $flags;
  38. }
  39. public function load(array $config, $class = 'Composer\Package\CompletePackage')
  40. {
  41. $this->errors = array();
  42. $this->warnings = array();
  43. $this->config = $config;
  44. if ($this->strictName) {
  45. $this->validateRegex('name', '[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*', true);
  46. } else {
  47. $this->validateString('name', true);
  48. }
  49. if (!empty($this->config['version'])) {
  50. try {
  51. $this->versionParser->normalize($this->config['version']);
  52. } catch (\Exception $e) {
  53. $this->errors[] = 'version : invalid value ('.$this->config['version'].'): '.$e->getMessage();
  54. unset($this->config['version']);
  55. }
  56. }
  57. if (!empty($this->config['config']['platform'])) {
  58. foreach ((array) $this->config['config']['platform'] as $key => $platform) {
  59. try {
  60. $this->versionParser->normalize($platform);
  61. } catch (\Exception $e) {
  62. $this->errors[] = 'config.platform.' . $key . ' : invalid value ('.$platform.'): '.$e->getMessage();
  63. }
  64. }
  65. }
  66. $this->validateRegex('type', '[A-Za-z0-9-]+');
  67. $this->validateString('target-dir');
  68. $this->validateArray('extra');
  69. if (isset($this->config['bin'])) {
  70. if (is_string($this->config['bin'])) {
  71. $this->validateString('bin');
  72. } else {
  73. $this->validateFlatArray('bin');
  74. }
  75. }
  76. $this->validateArray('scripts'); // TODO validate event names & listener syntax
  77. $this->validateString('description');
  78. $this->validateUrl('homepage');
  79. $this->validateFlatArray('keywords', '[\p{N}\p{L} ._-]+');
  80. $releaseDate = null;
  81. $this->validateString('time');
  82. if (!empty($this->config['time'])) {
  83. try {
  84. $releaseDate = new \DateTime($this->config['time'], new \DateTimeZone('UTC'));
  85. } catch (\Exception $e) {
  86. $this->errors[] = 'time : invalid value ('.$this->config['time'].'): '.$e->getMessage();
  87. unset($this->config['time']);
  88. }
  89. }
  90. // check for license validity on newly updated branches
  91. if (isset($this->config['license']) && (!$releaseDate || $releaseDate->getTimestamp() >= strtotime('-8days'))) {
  92. if (is_array($this->config['license']) || is_string($this->config['license'])) {
  93. $licenses = (array) $this->config['license'];
  94. // strip proprietary since it's not a valid SPDX identifier, but is accepted by composer
  95. foreach ($licenses as $key => $license) {
  96. if ('proprietary' === $license) {
  97. unset($licenses[$key]);
  98. }
  99. }
  100. $licenseValidator = new SpdxLicenses();
  101. if (count($licenses) === 1 && !$licenseValidator->validate($licenses) && $licenseValidator->validate(trim($licenses[0]))) {
  102. $this->warnings[] = sprintf(
  103. 'License %s must not contain extra spaces, make sure to trim it.',
  104. json_encode($this->config['license'])
  105. );
  106. } elseif (array() !== $licenses && !$licenseValidator->validate($licenses)) {
  107. $this->warnings[] = sprintf(
  108. 'License %s is not a valid SPDX license identifier, see https://spdx.org/licenses/ if you use an open license.' . PHP_EOL .
  109. 'If the software is closed-source, you may use "proprietary" as license.',
  110. json_encode($this->config['license'])
  111. );
  112. }
  113. }
  114. }
  115. if ($this->validateArray('authors') && !empty($this->config['authors'])) {
  116. foreach ($this->config['authors'] as $key => $author) {
  117. if (!is_array($author)) {
  118. $this->errors[] = 'authors.'.$key.' : should be an array, '.gettype($author).' given';
  119. unset($this->config['authors'][$key]);
  120. continue;
  121. }
  122. foreach (array('homepage', 'email', 'name', 'role') as $authorData) {
  123. if (isset($author[$authorData]) && !is_string($author[$authorData])) {
  124. $this->errors[] = 'authors.'.$key.'.'.$authorData.' : invalid value, must be a string';
  125. unset($this->config['authors'][$key][$authorData]);
  126. }
  127. }
  128. if (isset($author['homepage']) && !$this->filterUrl($author['homepage'])) {
  129. $this->warnings[] = 'authors.'.$key.'.homepage : invalid value ('.$author['homepage'].'), must be an http/https URL';
  130. unset($this->config['authors'][$key]['homepage']);
  131. }
  132. if (isset($author['email']) && !filter_var($author['email'], FILTER_VALIDATE_EMAIL)) {
  133. $this->warnings[] = 'authors.'.$key.'.email : invalid value ('.$author['email'].'), must be a valid email address';
  134. unset($this->config['authors'][$key]['email']);
  135. }
  136. if (empty($this->config['authors'][$key])) {
  137. unset($this->config['authors'][$key]);
  138. }
  139. }
  140. if (empty($this->config['authors'])) {
  141. unset($this->config['authors']);
  142. }
  143. }
  144. if ($this->validateArray('support') && !empty($this->config['support'])) {
  145. foreach (array('issues', 'forum', 'wiki', 'source', 'email', 'irc', 'docs', 'rss', 'chat') as $key) {
  146. if (isset($this->config['support'][$key]) && !is_string($this->config['support'][$key])) {
  147. $this->errors[] = 'support.'.$key.' : invalid value, must be a string';
  148. unset($this->config['support'][$key]);
  149. }
  150. }
  151. if (isset($this->config['support']['email']) && !filter_var($this->config['support']['email'], FILTER_VALIDATE_EMAIL)) {
  152. $this->warnings[] = 'support.email : invalid value ('.$this->config['support']['email'].'), must be a valid email address';
  153. unset($this->config['support']['email']);
  154. }
  155. if (isset($this->config['support']['irc']) && !$this->filterUrl($this->config['support']['irc'], array('irc'))) {
  156. $this->warnings[] = 'support.irc : invalid value ('.$this->config['support']['irc'].'), must be a irc://<server>/<channel> URL';
  157. unset($this->config['support']['irc']);
  158. }
  159. foreach (array('issues', 'forum', 'wiki', 'source', 'docs', 'chat') as $key) {
  160. if (isset($this->config['support'][$key]) && !$this->filterUrl($this->config['support'][$key])) {
  161. $this->warnings[] = 'support.'.$key.' : invalid value ('.$this->config['support'][$key].'), must be an http/https URL';
  162. unset($this->config['support'][$key]);
  163. }
  164. }
  165. if (empty($this->config['support'])) {
  166. unset($this->config['support']);
  167. }
  168. }
  169. $unboundConstraint = new Constraint('=', $this->versionParser->normalize('dev-master'));
  170. $stableConstraint = new Constraint('=', '1.0.0');
  171. foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) {
  172. if ($this->validateArray($linkType) && isset($this->config[$linkType])) {
  173. foreach ($this->config[$linkType] as $package => $constraint) {
  174. if (!preg_match('{^[A-Za-z0-9_./-]+$}', $package)) {
  175. $this->warnings[] = $linkType.'.'.$package.' : invalid key, package names must be strings containing only [A-Za-z0-9_./-]';
  176. }
  177. if (!is_string($constraint)) {
  178. $this->errors[] = $linkType.'.'.$package.' : invalid value, must be a string containing a version constraint';
  179. unset($this->config[$linkType][$package]);
  180. } elseif ('self.version' !== $constraint) {
  181. try {
  182. $linkConstraint = $this->versionParser->parseConstraints($constraint);
  183. } catch (\Exception $e) {
  184. $this->errors[] = $linkType.'.'.$package.' : invalid version constraint ('.$e->getMessage().')';
  185. unset($this->config[$linkType][$package]);
  186. continue;
  187. }
  188. // check requires for unbound constraints on non-platform packages
  189. if (
  190. ($this->flags & self::CHECK_UNBOUND_CONSTRAINTS)
  191. && 'require' === $linkType
  192. && $linkConstraint->matches($unboundConstraint)
  193. && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $package)
  194. ) {
  195. $this->warnings[] = $linkType.'.'.$package.' : unbound version constraints ('.$constraint.') should be avoided';
  196. } elseif (
  197. // check requires for exact constraints
  198. ($this->flags & self::CHECK_STRICT_CONSTRAINTS)
  199. && 'require' === $linkType
  200. && substr($linkConstraint, 0, 1) === '='
  201. && $stableConstraint->versionCompare($stableConstraint, $linkConstraint, '<=')
  202. ) {
  203. $this->warnings[] = $linkType.'.'.$package.' : exact version constraints ('.$constraint.') should be avoided if the package follows semantic versioning';
  204. }
  205. }
  206. }
  207. }
  208. }
  209. if ($this->validateArray('suggest') && !empty($this->config['suggest'])) {
  210. foreach ($this->config['suggest'] as $package => $description) {
  211. if (!is_string($description)) {
  212. $this->errors[] = 'suggest.'.$package.' : invalid value, must be a string describing why the package is suggested';
  213. unset($this->config['suggest'][$package]);
  214. }
  215. }
  216. }
  217. if ($this->validateString('minimum-stability') && !empty($this->config['minimum-stability'])) {
  218. if (!isset(BasePackage::$stabilities[$this->config['minimum-stability']])) {
  219. $this->errors[] = 'minimum-stability : invalid value ('.$this->config['minimum-stability'].'), must be one of '.implode(', ', array_keys(BasePackage::$stabilities));
  220. unset($this->config['minimum-stability']);
  221. }
  222. }
  223. if ($this->validateArray('autoload') && !empty($this->config['autoload'])) {
  224. $types = array('psr-0', 'psr-4', 'classmap', 'files', 'exclude-from-classmap');
  225. foreach ($this->config['autoload'] as $type => $typeConfig) {
  226. if (!in_array($type, $types)) {
  227. $this->errors[] = 'autoload : invalid value ('.$type.'), must be one of '.implode(', ', $types);
  228. unset($this->config['autoload'][$type]);
  229. }
  230. if ($type === 'psr-4') {
  231. foreach ($typeConfig as $namespace => $dirs) {
  232. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  233. $this->errors[] = 'autoload.psr-4 : invalid value ('.$namespace.'), namespaces must end with a namespace separator, should be '.$namespace.'\\\\';
  234. }
  235. }
  236. }
  237. }
  238. }
  239. if (!empty($this->config['autoload']['psr-4']) && !empty($this->config['target-dir'])) {
  240. $this->errors[] = 'target-dir : this can not be used together with the autoload.psr-4 setting, remove target-dir to upgrade to psr-4';
  241. // Unset the psr-4 setting, since unsetting target-dir might
  242. // interfere with other settings.
  243. unset($this->config['autoload']['psr-4']);
  244. }
  245. // TODO validate dist
  246. // TODO validate source
  247. // TODO validate repositories
  248. // TODO validate package repositories' packages using this recursively
  249. $this->validateFlatArray('include-path');
  250. $this->validateArray('transport-options');
  251. // branch alias validation
  252. if (isset($this->config['extra']['branch-alias'])) {
  253. if (!is_array($this->config['extra']['branch-alias'])) {
  254. $this->errors[] = 'extra.branch-alias : must be an array of versions => aliases';
  255. } else {
  256. foreach ($this->config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
  257. // ensure it is an alias to a -dev package
  258. if ('-dev' !== substr($targetBranch, -4)) {
  259. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must end in -dev';
  260. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  261. continue;
  262. }
  263. // normalize without -dev and ensure it's a numeric branch that is parseable
  264. $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
  265. if ('-dev' !== substr($validatedTargetBranch, -4)) {
  266. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must be a parseable number like 2.0-dev';
  267. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  268. continue;
  269. }
  270. // If using numeric aliases ensure the alias is a valid subversion
  271. if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
  272. && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
  273. && (stripos($targetPrefix, $sourcePrefix) !== 0)
  274. ) {
  275. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') is not a valid numeric alias for this version';
  276. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  277. }
  278. }
  279. }
  280. }
  281. if ($this->errors) {
  282. throw new InvalidPackageException($this->errors, $this->warnings, $config);
  283. }
  284. $package = $this->loader->load($this->config, $class);
  285. $this->config = null;
  286. return $package;
  287. }
  288. public function getWarnings()
  289. {
  290. return $this->warnings;
  291. }
  292. public function getErrors()
  293. {
  294. return $this->errors;
  295. }
  296. public static function hasPackageNamingError($name, $isLink = false)
  297. {
  298. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) {
  299. return;
  300. }
  301. if (!preg_match('{^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*$}iD', $name)) {
  302. return $name.' is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match "[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*".';
  303. }
  304. $reservedNames = array('nul', 'con', 'prn', 'aux', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9', 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9');
  305. $bits = explode('/', strtolower($name));
  306. if (in_array($bits[0], $reservedNames, true) || in_array($bits[1], $reservedNames, true)) {
  307. return $name.' is reserved, package and vendor names can not match any of: '.implode(', ', $reservedNames).'.';
  308. }
  309. if (preg_match('{\.json$}', $name)) {
  310. return $name.' is invalid, package names can not end in .json, consider renaming it or perhaps using a -json suffix instead.';
  311. }
  312. if (preg_match('{[A-Z]}', $name)) {
  313. if ($isLink) {
  314. return $name.' is invalid, it should not contain uppercase characters. Please use '.strtolower($name).' instead.';
  315. }
  316. $suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  317. $suggestName = strtolower($suggestName);
  318. return $name.' is invalid, it should not contain uppercase characters. We suggest using '.$suggestName.' instead.';
  319. }
  320. }
  321. private function validateRegex($property, $regex, $mandatory = false)
  322. {
  323. if (!$this->validateString($property, $mandatory)) {
  324. return false;
  325. }
  326. if (!preg_match('{^'.$regex.'$}u', $this->config[$property])) {
  327. $message = $property.' : invalid value ('.$this->config[$property].'), must match '.$regex;
  328. if ($mandatory) {
  329. $this->errors[] = $message;
  330. } else {
  331. $this->warnings[] = $message;
  332. }
  333. unset($this->config[$property]);
  334. return false;
  335. }
  336. return true;
  337. }
  338. private function validateString($property, $mandatory = false)
  339. {
  340. if (isset($this->config[$property]) && !is_string($this->config[$property])) {
  341. $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given';
  342. unset($this->config[$property]);
  343. return false;
  344. }
  345. if (!isset($this->config[$property]) || trim($this->config[$property]) === '') {
  346. if ($mandatory) {
  347. $this->errors[] = $property.' : must be present';
  348. }
  349. unset($this->config[$property]);
  350. return false;
  351. }
  352. return true;
  353. }
  354. private function validateArray($property, $mandatory = false)
  355. {
  356. if (isset($this->config[$property]) && !is_array($this->config[$property])) {
  357. $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given';
  358. unset($this->config[$property]);
  359. return false;
  360. }
  361. if (!isset($this->config[$property]) || !count($this->config[$property])) {
  362. if ($mandatory) {
  363. $this->errors[] = $property.' : must be present and contain at least one element';
  364. }
  365. unset($this->config[$property]);
  366. return false;
  367. }
  368. return true;
  369. }
  370. private function validateFlatArray($property, $regex = null, $mandatory = false)
  371. {
  372. if (!$this->validateArray($property, $mandatory)) {
  373. return false;
  374. }
  375. $pass = true;
  376. foreach ($this->config[$property] as $key => $value) {
  377. if (!is_string($value) && !is_numeric($value)) {
  378. $this->errors[] = $property.'.'.$key.' : must be a string or int, '.gettype($value).' given';
  379. unset($this->config[$property][$key]);
  380. $pass = false;
  381. continue;
  382. }
  383. if ($regex && !preg_match('{^'.$regex.'$}u', $value)) {
  384. $this->warnings[] = $property.'.'.$key.' : invalid value ('.$value.'), must match '.$regex;
  385. unset($this->config[$property][$key]);
  386. $pass = false;
  387. }
  388. }
  389. return $pass;
  390. }
  391. private function validateUrl($property, $mandatory = false)
  392. {
  393. if (!$this->validateString($property, $mandatory)) {
  394. return false;
  395. }
  396. if (!$this->filterUrl($this->config[$property])) {
  397. $this->warnings[] = $property.' : invalid value ('.$this->config[$property].'), must be an http/https URL';
  398. unset($this->config[$property]);
  399. return false;
  400. }
  401. return true;
  402. }
  403. private function filterUrl($value, array $schemes = array('http', 'https'))
  404. {
  405. if ($value === '') {
  406. return true;
  407. }
  408. $bits = parse_url($value);
  409. if (empty($bits['scheme']) || empty($bits['host'])) {
  410. return false;
  411. }
  412. if (!in_array($bits['scheme'], $schemes, true)) {
  413. return false;
  414. }
  415. return true;
  416. }
  417. }