Drupal investigation

XmlFileLoader.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Loader;
  11. use Symfony\Component\Config\Resource\FileResource;
  12. use Symfony\Component\Config\Util\XmlUtils;
  13. use Symfony\Component\DependencyInjection\DefinitionDecorator;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\DependencyInjection\Alias;
  16. use Symfony\Component\DependencyInjection\Definition;
  17. use Symfony\Component\DependencyInjection\Reference;
  18. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  19. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  20. use Symfony\Component\ExpressionLanguage\Expression;
  21. /**
  22. * XmlFileLoader loads XML files service definitions.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. */
  26. class XmlFileLoader extends FileLoader
  27. {
  28. const NS = 'http://symfony.com/schema/dic/services';
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function load($resource, $type = null)
  33. {
  34. $path = $this->locator->locate($resource);
  35. $xml = $this->parseFileToDOM($path);
  36. $this->container->addResource(new FileResource($path));
  37. // anonymous services
  38. $this->processAnonymousServices($xml, $path);
  39. // imports
  40. $this->parseImports($xml, $path);
  41. // parameters
  42. $this->parseParameters($xml);
  43. // extensions
  44. $this->loadFromExtensions($xml);
  45. // services
  46. $this->parseDefinitions($xml, $path);
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function supports($resource, $type = null)
  52. {
  53. return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION);
  54. }
  55. /**
  56. * Parses parameters.
  57. *
  58. * @param \DOMDocument $xml
  59. */
  60. private function parseParameters(\DOMDocument $xml)
  61. {
  62. if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) {
  63. $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter'));
  64. }
  65. }
  66. /**
  67. * Parses imports.
  68. *
  69. * @param \DOMDocument $xml
  70. * @param string $file
  71. */
  72. private function parseImports(\DOMDocument $xml, $file)
  73. {
  74. $xpath = new \DOMXPath($xml);
  75. $xpath->registerNamespace('container', self::NS);
  76. if (false === $imports = $xpath->query('//container:imports/container:import')) {
  77. return;
  78. }
  79. $defaultDirectory = dirname($file);
  80. foreach ($imports as $import) {
  81. $this->setCurrentDir($defaultDirectory);
  82. $this->import($import->getAttribute('resource'), null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file);
  83. }
  84. }
  85. /**
  86. * Parses multiple definitions.
  87. *
  88. * @param \DOMDocument $xml
  89. * @param string $file
  90. */
  91. private function parseDefinitions(\DOMDocument $xml, $file)
  92. {
  93. $xpath = new \DOMXPath($xml);
  94. $xpath->registerNamespace('container', self::NS);
  95. if (false === $services = $xpath->query('//container:services/container:service')) {
  96. return;
  97. }
  98. foreach ($services as $service) {
  99. if (null !== $definition = $this->parseDefinition($service, $file)) {
  100. $this->container->setDefinition((string) $service->getAttribute('id'), $definition);
  101. }
  102. }
  103. }
  104. /**
  105. * Parses an individual Definition.
  106. *
  107. * @param \DOMElement $service
  108. * @param string $file
  109. *
  110. * @return Definition|null
  111. */
  112. private function parseDefinition(\DOMElement $service, $file)
  113. {
  114. if ($alias = $service->getAttribute('alias')) {
  115. $public = true;
  116. if ($publicAttr = $service->getAttribute('public')) {
  117. $public = XmlUtils::phpize($publicAttr);
  118. }
  119. $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public));
  120. return;
  121. }
  122. if ($parent = $service->getAttribute('parent')) {
  123. $definition = new DefinitionDecorator($parent);
  124. } else {
  125. $definition = new Definition();
  126. }
  127. foreach (array('class', 'shared', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'lazy', 'abstract') as $key) {
  128. if ($value = $service->getAttribute($key)) {
  129. if (in_array($key, array('factory-class', 'factory-method', 'factory-service'))) {
  130. @trigger_error(sprintf('The "%s" attribute of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use the "factory" element instead.', $key, (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  131. }
  132. $method = 'set'.str_replace('-', '', $key);
  133. $definition->$method(XmlUtils::phpize($value));
  134. }
  135. }
  136. if ($value = $service->getAttribute('autowire')) {
  137. $definition->setAutowired(XmlUtils::phpize($value));
  138. }
  139. if ($value = $service->getAttribute('scope')) {
  140. $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
  141. if ($triggerDeprecation) {
  142. @trigger_error(sprintf('The "scope" attribute of service "%s" in file "%s" is deprecated since version 2.8 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  143. }
  144. $definition->setScope(XmlUtils::phpize($value), false);
  145. }
  146. if ($value = $service->getAttribute('synchronized')) {
  147. $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
  148. if ($triggerDeprecation) {
  149. @trigger_error(sprintf('The "synchronized" attribute of service "%s" in file "%s" is deprecated since version 2.7 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  150. }
  151. $definition->setSynchronized(XmlUtils::phpize($value), $triggerDeprecation);
  152. }
  153. if ($files = $this->getChildren($service, 'file')) {
  154. $definition->setFile($files[0]->nodeValue);
  155. }
  156. if ($deprecated = $this->getChildren($service, 'deprecated')) {
  157. $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
  158. }
  159. $definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
  160. $definition->setProperties($this->getArgumentsAsPhp($service, 'property'));
  161. if ($factories = $this->getChildren($service, 'factory')) {
  162. $factory = $factories[0];
  163. if ($function = $factory->getAttribute('function')) {
  164. $definition->setFactory($function);
  165. } else {
  166. $factoryService = $this->getChildren($factory, 'service');
  167. if (isset($factoryService[0])) {
  168. $class = $this->parseDefinition($factoryService[0], $file);
  169. } elseif ($childService = $factory->getAttribute('service')) {
  170. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
  171. } else {
  172. $class = $factory->getAttribute('class');
  173. }
  174. $definition->setFactory(array($class, $factory->getAttribute('method')));
  175. }
  176. }
  177. if ($configurators = $this->getChildren($service, 'configurator')) {
  178. $configurator = $configurators[0];
  179. if ($function = $configurator->getAttribute('function')) {
  180. $definition->setConfigurator($function);
  181. } else {
  182. $configuratorService = $this->getChildren($configurator, 'service');
  183. if (isset($configuratorService[0])) {
  184. $class = $this->parseDefinition($configuratorService[0], $file);
  185. } elseif ($childService = $configurator->getAttribute('service')) {
  186. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
  187. } else {
  188. $class = $configurator->getAttribute('class');
  189. }
  190. $definition->setConfigurator(array($class, $configurator->getAttribute('method')));
  191. }
  192. }
  193. foreach ($this->getChildren($service, 'call') as $call) {
  194. $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument'));
  195. }
  196. foreach ($this->getChildren($service, 'tag') as $tag) {
  197. $parameters = array();
  198. foreach ($tag->attributes as $name => $node) {
  199. if ('name' === $name) {
  200. continue;
  201. }
  202. if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
  203. $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
  204. }
  205. // keep not normalized key for BC too
  206. $parameters[$name] = XmlUtils::phpize($node->nodeValue);
  207. }
  208. if ('' === $tag->getAttribute('name')) {
  209. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file));
  210. }
  211. $definition->addTag($tag->getAttribute('name'), $parameters);
  212. }
  213. foreach ($this->getChildren($service, 'autowiring-type') as $type) {
  214. $definition->addAutowiringType($type->textContent);
  215. }
  216. if ($value = $service->getAttribute('decorates')) {
  217. $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
  218. $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
  219. $definition->setDecoratedService($value, $renameId, $priority);
  220. }
  221. return $definition;
  222. }
  223. /**
  224. * Parses a XML file to a \DOMDocument.
  225. *
  226. * @param string $file Path to a file
  227. *
  228. * @return \DOMDocument
  229. *
  230. * @throws InvalidArgumentException When loading of XML file returns error
  231. */
  232. private function parseFileToDOM($file)
  233. {
  234. try {
  235. $dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
  236. } catch (\InvalidArgumentException $e) {
  237. throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e);
  238. }
  239. $this->validateExtensions($dom, $file);
  240. return $dom;
  241. }
  242. /**
  243. * Processes anonymous services.
  244. *
  245. * @param \DOMDocument $xml
  246. * @param string $file
  247. */
  248. private function processAnonymousServices(\DOMDocument $xml, $file)
  249. {
  250. $definitions = array();
  251. $count = 0;
  252. $xpath = new \DOMXPath($xml);
  253. $xpath->registerNamespace('container', self::NS);
  254. // anonymous services as arguments/properties
  255. if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
  256. foreach ($nodes as $node) {
  257. // give it a unique name
  258. $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
  259. $node->setAttribute('id', $id);
  260. if ($services = $this->getChildren($node, 'service')) {
  261. $definitions[$id] = array($services[0], $file, false);
  262. $services[0]->setAttribute('id', $id);
  263. // anonymous services are always private
  264. // we could not use the constant false here, because of XML parsing
  265. $services[0]->setAttribute('public', 'false');
  266. }
  267. }
  268. }
  269. // anonymous services "in the wild"
  270. if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
  271. foreach ($nodes as $node) {
  272. // give it a unique name
  273. $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
  274. $node->setAttribute('id', $id);
  275. $definitions[$id] = array($node, $file, true);
  276. }
  277. }
  278. // resolve definitions
  279. krsort($definitions);
  280. foreach ($definitions as $id => $def) {
  281. list($domElement, $file, $wild) = $def;
  282. if (null !== $definition = $this->parseDefinition($domElement, $file)) {
  283. $this->container->setDefinition($id, $definition);
  284. }
  285. if (true === $wild) {
  286. $tmpDomElement = new \DOMElement('_services', null, self::NS);
  287. $domElement->parentNode->replaceChild($tmpDomElement, $domElement);
  288. $tmpDomElement->setAttribute('id', $id);
  289. } else {
  290. $domElement->parentNode->removeChild($domElement);
  291. }
  292. }
  293. }
  294. /**
  295. * Returns arguments as valid php types.
  296. *
  297. * @param \DOMElement $node
  298. * @param string $name
  299. * @param bool $lowercase
  300. *
  301. * @return mixed
  302. */
  303. private function getArgumentsAsPhp(\DOMElement $node, $name, $lowercase = true)
  304. {
  305. $arguments = array();
  306. foreach ($this->getChildren($node, $name) as $arg) {
  307. if ($arg->hasAttribute('name')) {
  308. $arg->setAttribute('key', $arg->getAttribute('name'));
  309. }
  310. // this is used by DefinitionDecorator to overwrite a specific
  311. // argument of the parent definition
  312. if ($arg->hasAttribute('index')) {
  313. $key = 'index_'.$arg->getAttribute('index');
  314. } elseif (!$arg->hasAttribute('key')) {
  315. // Append an empty argument, then fetch its key to overwrite it later
  316. $arguments[] = null;
  317. $keys = array_keys($arguments);
  318. $key = array_pop($keys);
  319. } else {
  320. $key = $arg->getAttribute('key');
  321. // parameter keys are case insensitive
  322. if ('parameter' == $name && $lowercase) {
  323. $key = strtolower($key);
  324. }
  325. }
  326. switch ($arg->getAttribute('type')) {
  327. case 'service':
  328. $onInvalid = $arg->getAttribute('on-invalid');
  329. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  330. if ('ignore' == $onInvalid) {
  331. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  332. } elseif ('null' == $onInvalid) {
  333. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  334. }
  335. if ($strict = $arg->getAttribute('strict')) {
  336. $strict = XmlUtils::phpize($strict);
  337. } else {
  338. $strict = true;
  339. }
  340. $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior, $strict);
  341. break;
  342. case 'expression':
  343. $arguments[$key] = new Expression($arg->nodeValue);
  344. break;
  345. case 'collection':
  346. $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false);
  347. break;
  348. case 'string':
  349. $arguments[$key] = $arg->nodeValue;
  350. break;
  351. case 'constant':
  352. $arguments[$key] = constant(trim($arg->nodeValue));
  353. break;
  354. default:
  355. $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
  356. }
  357. }
  358. return $arguments;
  359. }
  360. /**
  361. * Get child elements by name.
  362. *
  363. * @param \DOMNode $node
  364. * @param mixed $name
  365. *
  366. * @return array
  367. */
  368. private function getChildren(\DOMNode $node, $name)
  369. {
  370. $children = array();
  371. foreach ($node->childNodes as $child) {
  372. if ($child instanceof \DOMElement && $child->localName === $name && $child->namespaceURI === self::NS) {
  373. $children[] = $child;
  374. }
  375. }
  376. return $children;
  377. }
  378. /**
  379. * Validates a documents XML schema.
  380. *
  381. * @param \DOMDocument $dom
  382. *
  383. * @return bool
  384. *
  385. * @throws RuntimeException When extension references a non-existent XSD file
  386. */
  387. public function validateSchema(\DOMDocument $dom)
  388. {
  389. $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
  390. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
  391. $items = preg_split('/\s+/', $element);
  392. for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
  393. if (!$this->container->hasExtension($items[$i])) {
  394. continue;
  395. }
  396. if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  397. $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
  398. if (!is_file($path)) {
  399. throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
  400. }
  401. $schemaLocations[$items[$i]] = $path;
  402. }
  403. }
  404. }
  405. $tmpfiles = array();
  406. $imports = '';
  407. foreach ($schemaLocations as $namespace => $location) {
  408. $parts = explode('/', $location);
  409. if (0 === stripos($location, 'phar://')) {
  410. $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
  411. if ($tmpfile) {
  412. copy($location, $tmpfile);
  413. $tmpfiles[] = $tmpfile;
  414. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  415. }
  416. }
  417. $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  418. $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  419. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  420. }
  421. $source = <<<EOF
  422. <?xml version="1.0" encoding="utf-8" ?>
  423. <xsd:schema xmlns="http://symfony.com/schema"
  424. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  425. targetNamespace="http://symfony.com/schema"
  426. elementFormDefault="qualified">
  427. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  428. $imports
  429. </xsd:schema>
  430. EOF
  431. ;
  432. $disableEntities = libxml_disable_entity_loader(false);
  433. $valid = @$dom->schemaValidateSource($source);
  434. libxml_disable_entity_loader($disableEntities);
  435. foreach ($tmpfiles as $tmpfile) {
  436. @unlink($tmpfile);
  437. }
  438. return $valid;
  439. }
  440. /**
  441. * Validates an extension.
  442. *
  443. * @param \DOMDocument $dom
  444. * @param string $file
  445. *
  446. * @throws InvalidArgumentException When no extension is found corresponding to a tag
  447. */
  448. private function validateExtensions(\DOMDocument $dom, $file)
  449. {
  450. foreach ($dom->documentElement->childNodes as $node) {
  451. if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  452. continue;
  453. }
  454. // can it be handled by an extension?
  455. if (!$this->container->hasExtension($node->namespaceURI)) {
  456. $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  457. throw new InvalidArgumentException(sprintf(
  458. 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
  459. $node->tagName,
  460. $file,
  461. $node->namespaceURI,
  462. $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
  463. ));
  464. }
  465. }
  466. }
  467. /**
  468. * Loads from an extension.
  469. *
  470. * @param \DOMDocument $xml
  471. */
  472. private function loadFromExtensions(\DOMDocument $xml)
  473. {
  474. foreach ($xml->documentElement->childNodes as $node) {
  475. if (!$node instanceof \DOMElement || $node->namespaceURI === self::NS) {
  476. continue;
  477. }
  478. $values = static::convertDomElementToArray($node);
  479. if (!is_array($values)) {
  480. $values = array();
  481. }
  482. $this->container->loadFromExtension($node->namespaceURI, $values);
  483. }
  484. }
  485. /**
  486. * Converts a \DomElement object to a PHP array.
  487. *
  488. * The following rules applies during the conversion:
  489. *
  490. * * Each tag is converted to a key value or an array
  491. * if there is more than one "value"
  492. *
  493. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  494. * if the tag also has some nested tags
  495. *
  496. * * The attributes are converted to keys (<foo foo="bar"/>)
  497. *
  498. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  499. *
  500. * @param \DomElement $element A \DomElement instance
  501. *
  502. * @return array A PHP array
  503. */
  504. public static function convertDomElementToArray(\DOMElement $element)
  505. {
  506. return XmlUtils::convertDomElementToArray($element);
  507. }
  508. }