ValidatingArrayLoader.php 22 KB

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