PageRenderTime 92ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 2ms

/app/cache/dev/classes.php

https://github.com/RomainTweaks/BaseSymfony2
PHP | 7549 lines | 7549 code | 0 blank | 0 comment | 955 complexity | 92b56a0888bf12d0173218f9bf41456a MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. namespace Symfony\Component\EventDispatcher
  3. {
  4. interface EventSubscriberInterface
  5. {
  6. public static function getSubscribedEvents();
  7. }
  8. }
  9. namespace Symfony\Bundle\FrameworkBundle\EventListener
  10. {
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\HttpKernel\HttpKernelInterface;
  13. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. class SessionListener implements EventSubscriberInterface
  17. {
  18. private $container;
  19. public function __construct(ContainerInterface $container)
  20. {
  21. $this->container = $container;
  22. }
  23. public function onKernelRequest(GetResponseEvent $event)
  24. {
  25. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  26. return;
  27. }
  28. $request = $event->getRequest();
  29. if (!$this->container->has('session') || $request->hasSession()) {
  30. return;
  31. }
  32. $request->setSession($this->container->get('session'));
  33. }
  34. public static function getSubscribedEvents()
  35. {
  36. return array(
  37. KernelEvents::REQUEST => array('onKernelRequest', 128),
  38. );
  39. }
  40. }
  41. }
  42. namespace Symfony\Component\HttpFoundation\Session\Storage
  43. {
  44. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  45. use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
  46. interface SessionStorageInterface
  47. {
  48. public function start();
  49. public function isStarted();
  50. public function getId();
  51. public function setId($id);
  52. public function getName();
  53. public function setName($name);
  54. public function regenerate($destroy = false, $lifetime = null);
  55. public function save();
  56. public function clear();
  57. public function getBag($name);
  58. public function registerBag(SessionBagInterface $bag);
  59. public function getMetadataBag();
  60. }
  61. }
  62. namespace Symfony\Component\HttpFoundation\Session\Storage
  63. {
  64. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  65. use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
  66. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
  67. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
  68. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
  69. class NativeSessionStorage implements SessionStorageInterface
  70. {
  71. protected $bags;
  72. protected $started = false;
  73. protected $closed = false;
  74. protected $saveHandler;
  75. protected $metadataBag;
  76. public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null)
  77. {
  78. ini_set('session.cache_limiter',''); ini_set('session.use_cookies', 1);
  79. if (version_compare(phpversion(),'5.4.0','>=')) {
  80. session_register_shutdown();
  81. } else {
  82. register_shutdown_function('session_write_close');
  83. }
  84. $this->setMetadataBag($metaBag);
  85. $this->setOptions($options);
  86. $this->setSaveHandler($handler);
  87. }
  88. public function getSaveHandler()
  89. {
  90. return $this->saveHandler;
  91. }
  92. public function start()
  93. {
  94. if ($this->started && !$this->closed) {
  95. return true;
  96. }
  97. if (!$this->started && !$this->closed && $this->saveHandler->isActive()
  98. && $this->saveHandler->isSessionHandlerInterface()) {
  99. $this->loadSession();
  100. return true;
  101. }
  102. if (ini_get('session.use_cookies') && headers_sent()) {
  103. throw new \RuntimeException('Failed to start the session because headers have already been sent.');
  104. }
  105. if (!session_start()) {
  106. throw new \RuntimeException('Failed to start the session');
  107. }
  108. $this->loadSession();
  109. if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
  110. $this->saveHandler->setActive(false);
  111. }
  112. return true;
  113. }
  114. public function getId()
  115. {
  116. if (!$this->started) {
  117. return''; }
  118. return $this->saveHandler->getId();
  119. }
  120. public function setId($id)
  121. {
  122. $this->saveHandler->setId($id);
  123. }
  124. public function getName()
  125. {
  126. return $this->saveHandler->getName();
  127. }
  128. public function setName($name)
  129. {
  130. $this->saveHandler->setName($name);
  131. }
  132. public function regenerate($destroy = false, $lifetime = null)
  133. {
  134. if (null !== $lifetime) {
  135. ini_set('session.cookie_lifetime', $lifetime);
  136. }
  137. if ($destroy) {
  138. $this->metadataBag->stampNew();
  139. }
  140. return session_regenerate_id($destroy);
  141. }
  142. public function save()
  143. {
  144. session_write_close();
  145. if (!$this->saveHandler->isWrapper() && !$this->getSaveHandler()->isSessionHandlerInterface()) {
  146. $this->saveHandler->setActive(false);
  147. }
  148. $this->closed = true;
  149. }
  150. public function clear()
  151. {
  152. foreach ($this->bags as $bag) {
  153. $bag->clear();
  154. }
  155. $_SESSION = array();
  156. $this->loadSession();
  157. }
  158. public function registerBag(SessionBagInterface $bag)
  159. {
  160. $this->bags[$bag->getName()] = $bag;
  161. }
  162. public function getBag($name)
  163. {
  164. if (!isset($this->bags[$name])) {
  165. throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
  166. }
  167. if ($this->saveHandler->isActive() && !$this->started) {
  168. $this->loadSession();
  169. } elseif (!$this->started) {
  170. $this->start();
  171. }
  172. return $this->bags[$name];
  173. }
  174. public function setMetadataBag(MetadataBag $metaBag = null)
  175. {
  176. if (null === $metaBag) {
  177. $metaBag = new MetadataBag();
  178. }
  179. $this->metadataBag = $metaBag;
  180. }
  181. public function getMetadataBag()
  182. {
  183. return $this->metadataBag;
  184. }
  185. public function isStarted()
  186. {
  187. return $this->started;
  188. }
  189. public function setOptions(array $options)
  190. {
  191. $validOptions = array_flip(array('cache_limiter','cookie_domain','cookie_httponly','cookie_lifetime','cookie_path','cookie_secure','entropy_file','entropy_length','gc_divisor','gc_maxlifetime','gc_probability','hash_bits_per_character','hash_function','name','referer_check','serialize_handler','use_cookies','use_only_cookies','use_trans_sid','upload_progress.enabled','upload_progress.cleanup','upload_progress.prefix','upload_progress.name','upload_progress.freq','upload_progress.min-freq','url_rewriter.tags',
  192. ));
  193. foreach ($options as $key => $value) {
  194. if (isset($validOptions[$key])) {
  195. ini_set('session.'.$key, $value);
  196. }
  197. }
  198. }
  199. public function setSaveHandler($saveHandler = null)
  200. {
  201. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  202. $saveHandler = new SessionHandlerProxy($saveHandler);
  203. } elseif (!$saveHandler instanceof AbstractProxy) {
  204. $saveHandler = new NativeProxy();
  205. }
  206. $this->saveHandler = $saveHandler;
  207. if ($this->saveHandler instanceof \SessionHandlerInterface) {
  208. if (version_compare(phpversion(),'5.4.0','>=')) {
  209. session_set_save_handler($this->saveHandler, false);
  210. } else {
  211. session_set_save_handler(
  212. array($this->saveHandler,'open'),
  213. array($this->saveHandler,'close'),
  214. array($this->saveHandler,'read'),
  215. array($this->saveHandler,'write'),
  216. array($this->saveHandler,'destroy'),
  217. array($this->saveHandler,'gc')
  218. );
  219. }
  220. }
  221. }
  222. protected function loadSession(array &$session = null)
  223. {
  224. if (null === $session) {
  225. $session = &$_SESSION;
  226. }
  227. $bags = array_merge($this->bags, array($this->metadataBag));
  228. foreach ($bags as $bag) {
  229. $key = $bag->getStorageKey();
  230. $session[$key] = isset($session[$key]) ? $session[$key] : array();
  231. $bag->initialize($session[$key]);
  232. }
  233. $this->started = true;
  234. $this->closed = false;
  235. }
  236. }
  237. }
  238. namespace Symfony\Component\HttpFoundation\Session\Storage\Handler
  239. {
  240. if (version_compare(phpversion(),'5.4.0','>=')) {
  241. class NativeSessionHandler extends \SessionHandler {}
  242. } else {
  243. class NativeSessionHandler {}
  244. }
  245. }
  246. namespace Symfony\Component\HttpFoundation\Session\Storage\Handler
  247. {
  248. class NativeFileSessionHandler extends NativeSessionHandler
  249. {
  250. public function __construct($savePath = null)
  251. {
  252. if (null === $savePath) {
  253. $savePath = ini_get('session.save_path');
  254. }
  255. $baseDir = $savePath;
  256. if ($count = substr_count($savePath,';')) {
  257. if ($count > 2) {
  258. throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'', $savePath));
  259. }
  260. $baseDir = ltrim(strrchr($savePath,';'),';');
  261. }
  262. if ($baseDir && !is_dir($baseDir)) {
  263. mkdir($baseDir, 0777, true);
  264. }
  265. ini_set('session.save_path', $savePath);
  266. ini_set('session.save_handler','files');
  267. }
  268. }
  269. }
  270. namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy
  271. {
  272. abstract class AbstractProxy
  273. {
  274. protected $wrapper = false;
  275. protected $active = false;
  276. protected $saveHandlerName;
  277. public function getSaveHandlerName()
  278. {
  279. return $this->saveHandlerName;
  280. }
  281. public function isSessionHandlerInterface()
  282. {
  283. return ($this instanceof \SessionHandlerInterface);
  284. }
  285. public function isWrapper()
  286. {
  287. return $this->wrapper;
  288. }
  289. public function isActive()
  290. {
  291. return $this->active;
  292. }
  293. public function setActive($flag)
  294. {
  295. $this->active = (bool) $flag;
  296. }
  297. public function getId()
  298. {
  299. return session_id();
  300. }
  301. public function setId($id)
  302. {
  303. if ($this->isActive()) {
  304. throw new \LogicException('Cannot change the ID of an active session');
  305. }
  306. session_id($id);
  307. }
  308. public function getName()
  309. {
  310. return session_name();
  311. }
  312. public function setName($name)
  313. {
  314. if ($this->isActive()) {
  315. throw new \LogicException('Cannot change the name of an active session');
  316. }
  317. session_name($name);
  318. }
  319. }
  320. }
  321. namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy
  322. {
  323. class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface
  324. {
  325. protected $handler;
  326. public function __construct(\SessionHandlerInterface $handler)
  327. {
  328. $this->handler = $handler;
  329. $this->wrapper = ($handler instanceof \SessionHandler);
  330. $this->saveHandlerName = $this->wrapper ? ini_get('session.save_handler') :'user';
  331. }
  332. public function open($savePath, $sessionName)
  333. {
  334. $return = (bool) $this->handler->open($savePath, $sessionName);
  335. if (true === $return) {
  336. $this->active = true;
  337. }
  338. return $return;
  339. }
  340. public function close()
  341. {
  342. $this->active = false;
  343. return (bool) $this->handler->close();
  344. }
  345. public function read($id)
  346. {
  347. return (string) $this->handler->read($id);
  348. }
  349. public function write($id, $data)
  350. {
  351. return (bool) $this->handler->write($id, $data);
  352. }
  353. public function destroy($id)
  354. {
  355. return (bool) $this->handler->destroy($id);
  356. }
  357. public function gc($maxlifetime)
  358. {
  359. return (bool) $this->handler->gc($maxlifetime);
  360. }
  361. }
  362. }
  363. namespace Symfony\Component\HttpFoundation\Session
  364. {
  365. use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
  366. interface SessionInterface
  367. {
  368. public function start();
  369. public function getId();
  370. public function setId($id);
  371. public function getName();
  372. public function setName($name);
  373. public function invalidate($lifetime = null);
  374. public function migrate($destroy = false, $lifetime = null);
  375. public function save();
  376. public function has($name);
  377. public function get($name, $default = null);
  378. public function set($name, $value);
  379. public function all();
  380. public function replace(array $attributes);
  381. public function remove($name);
  382. public function clear();
  383. public function isStarted();
  384. public function registerBag(SessionBagInterface $bag);
  385. public function getBag($name);
  386. public function getMetadataBag();
  387. }
  388. }
  389. namespace Symfony\Component\HttpFoundation\Session
  390. {
  391. use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
  392. use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
  393. use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
  394. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  395. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  396. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  397. use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
  398. class Session implements SessionInterface, \IteratorAggregate, \Countable
  399. {
  400. protected $storage;
  401. private $flashName;
  402. private $attributeName;
  403. public function __construct(SessionStorageInterface $storage = null, AttributeBagInterface $attributes = null, FlashBagInterface $flashes = null)
  404. {
  405. $this->storage = $storage ?: new NativeSessionStorage();
  406. $attributes = $attributes ?: new AttributeBag();
  407. $this->attributeName = $attributes->getName();
  408. $this->registerBag($attributes);
  409. $flashes = $flashes ?: new FlashBag();
  410. $this->flashName = $flashes->getName();
  411. $this->registerBag($flashes);
  412. }
  413. public function start()
  414. {
  415. return $this->storage->start();
  416. }
  417. public function has($name)
  418. {
  419. return $this->storage->getBag($this->attributeName)->has($name);
  420. }
  421. public function get($name, $default = null)
  422. {
  423. return $this->storage->getBag($this->attributeName)->get($name, $default);
  424. }
  425. public function set($name, $value)
  426. {
  427. $this->storage->getBag($this->attributeName)->set($name, $value);
  428. }
  429. public function all()
  430. {
  431. return $this->storage->getBag($this->attributeName)->all();
  432. }
  433. public function replace(array $attributes)
  434. {
  435. $this->storage->getBag($this->attributeName)->replace($attributes);
  436. }
  437. public function remove($name)
  438. {
  439. return $this->storage->getBag($this->attributeName)->remove($name);
  440. }
  441. public function clear()
  442. {
  443. $this->storage->getBag($this->attributeName)->clear();
  444. }
  445. public function isStarted()
  446. {
  447. return $this->storage->isStarted();
  448. }
  449. public function getIterator()
  450. {
  451. return new \ArrayIterator($this->storage->getBag($this->attributeName)->all());
  452. }
  453. public function count()
  454. {
  455. return count($this->storage->getBag($this->attributeName)->all());
  456. }
  457. public function invalidate($lifetime = null)
  458. {
  459. $this->storage->clear();
  460. return $this->migrate(true, $lifetime);
  461. }
  462. public function migrate($destroy = false, $lifetime = null)
  463. {
  464. return $this->storage->regenerate($destroy, $lifetime);
  465. }
  466. public function save()
  467. {
  468. $this->storage->save();
  469. }
  470. public function getId()
  471. {
  472. return $this->storage->getId();
  473. }
  474. public function setId($id)
  475. {
  476. $this->storage->setId($id);
  477. }
  478. public function getName()
  479. {
  480. return $this->storage->getName();
  481. }
  482. public function setName($name)
  483. {
  484. $this->storage->setName($name);
  485. }
  486. public function getMetadataBag()
  487. {
  488. return $this->storage->getMetadataBag();
  489. }
  490. public function registerBag(SessionBagInterface $bag)
  491. {
  492. $this->storage->registerBag($bag);
  493. }
  494. public function getBag($name)
  495. {
  496. return $this->storage->getBag($name);
  497. }
  498. public function getFlashBag()
  499. {
  500. return $this->getBag($this->flashName);
  501. }
  502. public function getFlashes()
  503. {
  504. trigger_error('getFlashes() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  505. $all = $this->getBag($this->flashName)->all();
  506. $return = array();
  507. if ($all) {
  508. foreach ($all as $name => $array) {
  509. if (is_numeric(key($array))) {
  510. $return[$name] = reset($array);
  511. } else {
  512. $return[$name] = $array;
  513. }
  514. }
  515. }
  516. return $return;
  517. }
  518. public function setFlashes($values)
  519. {
  520. trigger_error('setFlashes() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  521. foreach ($values as $name => $value) {
  522. $this->getBag($this->flashName)->set($name, $value);
  523. }
  524. }
  525. public function getFlash($name, $default = null)
  526. {
  527. trigger_error('getFlash() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  528. $return = $this->getBag($this->flashName)->get($name);
  529. return empty($return) ? $default : reset($return);
  530. }
  531. public function setFlash($name, $value)
  532. {
  533. trigger_error('setFlash() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  534. $this->getBag($this->flashName)->set($name, $value);
  535. }
  536. public function hasFlash($name)
  537. {
  538. trigger_error('hasFlash() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  539. return $this->getBag($this->flashName)->has($name);
  540. }
  541. public function removeFlash($name)
  542. {
  543. trigger_error('removeFlash() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  544. $this->getBag($this->flashName)->get($name);
  545. }
  546. public function clearFlashes()
  547. {
  548. trigger_error('clearFlashes() is deprecated since version 2.1 and will be removed in 2.3. Use the FlashBag instead.', E_USER_DEPRECATED);
  549. return $this->getBag($this->flashName)->clear();
  550. }
  551. }
  552. }
  553. namespace Symfony\Bundle\FrameworkBundle\Templating
  554. {
  555. use Symfony\Component\DependencyInjection\ContainerInterface;
  556. use Symfony\Component\HttpFoundation\Session\Session;
  557. use Symfony\Component\Security\Core\SecurityContext;
  558. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  559. use Symfony\Component\HttpFoundation\Request;
  560. class GlobalVariables
  561. {
  562. protected $container;
  563. public function __construct(ContainerInterface $container)
  564. {
  565. $this->container = $container;
  566. }
  567. public function getSecurity()
  568. {
  569. if ($this->container->has('security.context')) {
  570. return $this->container->get('security.context');
  571. }
  572. }
  573. public function getUser()
  574. {
  575. if (!$security = $this->getSecurity()) {
  576. return;
  577. }
  578. if (!$token = $security->getToken()) {
  579. return;
  580. }
  581. $user = $token->getUser();
  582. if (!is_object($user)) {
  583. return;
  584. }
  585. return $user;
  586. }
  587. public function getRequest()
  588. {
  589. if ($this->container->has('request') && $request = $this->container->get('request')) {
  590. return $request;
  591. }
  592. }
  593. public function getSession()
  594. {
  595. if ($request = $this->getRequest()) {
  596. return $request->getSession();
  597. }
  598. }
  599. public function getEnvironment()
  600. {
  601. return $this->container->getParameter('kernel.environment');
  602. }
  603. public function getDebug()
  604. {
  605. return (Boolean) $this->container->getParameter('kernel.debug');
  606. }
  607. }
  608. }
  609. namespace Symfony\Component\Templating
  610. {
  611. interface TemplateReferenceInterface
  612. {
  613. public function all();
  614. public function set($name, $value);
  615. public function get($name);
  616. public function getPath();
  617. public function getLogicalName();
  618. }
  619. }
  620. namespace Symfony\Component\Templating
  621. {
  622. class TemplateReference implements TemplateReferenceInterface
  623. {
  624. protected $parameters;
  625. public function __construct($name = null, $engine = null)
  626. {
  627. $this->parameters = array('name'=> $name,'engine'=> $engine,
  628. );
  629. }
  630. public function __toString()
  631. {
  632. return $this->getLogicalName();
  633. }
  634. public function set($name, $value)
  635. {
  636. if (array_key_exists($name, $this->parameters)) {
  637. $this->parameters[$name] = $value;
  638. } else {
  639. throw new \InvalidArgumentException(sprintf('The template does not support the "%s" parameter.', $name));
  640. }
  641. return $this;
  642. }
  643. public function get($name)
  644. {
  645. if (array_key_exists($name, $this->parameters)) {
  646. return $this->parameters[$name];
  647. }
  648. throw new \InvalidArgumentException(sprintf('The template does not support the "%s" parameter.', $name));
  649. }
  650. public function all()
  651. {
  652. return $this->parameters;
  653. }
  654. public function getPath()
  655. {
  656. return $this->parameters['name'];
  657. }
  658. public function getLogicalName()
  659. {
  660. return $this->parameters['name'];
  661. }
  662. }
  663. }
  664. namespace Symfony\Bundle\FrameworkBundle\Templating
  665. {
  666. use Symfony\Component\Templating\TemplateReference as BaseTemplateReference;
  667. class TemplateReference extends BaseTemplateReference
  668. {
  669. public function __construct($bundle = null, $controller = null, $name = null, $format = null, $engine = null)
  670. {
  671. $this->parameters = array('bundle'=> $bundle,'controller'=> $controller,'name'=> $name,'format'=> $format,'engine'=> $engine,
  672. );
  673. }
  674. public function getPath()
  675. {
  676. $controller = str_replace('\\','/', $this->get('controller'));
  677. $path = (empty($controller) ?'': $controller.'/').$this->get('name').'.'.$this->get('format').'.'.$this->get('engine');
  678. return empty($this->parameters['bundle']) ?'views/'.$path :'@'.$this->get('bundle').'/Resources/views/'.$path;
  679. }
  680. public function getLogicalName()
  681. {
  682. return sprintf('%s:%s:%s.%s.%s', $this->parameters['bundle'], $this->parameters['controller'], $this->parameters['name'], $this->parameters['format'], $this->parameters['engine']);
  683. }
  684. }
  685. }
  686. namespace Symfony\Component\Templating
  687. {
  688. interface TemplateNameParserInterface
  689. {
  690. public function parse($name);
  691. }
  692. }
  693. namespace Symfony\Bundle\FrameworkBundle\Templating
  694. {
  695. use Symfony\Component\Templating\TemplateNameParserInterface;
  696. use Symfony\Component\Templating\TemplateReferenceInterface;
  697. use Symfony\Component\HttpKernel\KernelInterface;
  698. class TemplateNameParser implements TemplateNameParserInterface
  699. {
  700. protected $kernel;
  701. protected $cache;
  702. public function __construct(KernelInterface $kernel)
  703. {
  704. $this->kernel = $kernel;
  705. $this->cache = array();
  706. }
  707. public function parse($name)
  708. {
  709. if ($name instanceof TemplateReferenceInterface) {
  710. return $name;
  711. } elseif (isset($this->cache[$name])) {
  712. return $this->cache[$name];
  713. }
  714. $name = str_replace(':/',':', preg_replace('#/{2,}#','/', strtr($name,'\\','/')));
  715. if (false !== strpos($name,'..')) {
  716. throw new \RuntimeException(sprintf('Template name "%s" contains invalid characters.', $name));
  717. }
  718. $parts = explode(':', $name);
  719. if (3 !== count($parts)) {
  720. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid (format is "bundle:section:template.format.engine").', $name));
  721. }
  722. $elements = explode('.', $parts[2]);
  723. if (3 > count($elements)) {
  724. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid (format is "bundle:section:template.format.engine").', $name));
  725. }
  726. $engine = array_pop($elements);
  727. $format = array_pop($elements);
  728. $template = new TemplateReference($parts[0], $parts[1], implode('.', $elements), $format, $engine);
  729. if ($template->get('bundle')) {
  730. try {
  731. $this->kernel->getBundle($template->get('bundle'));
  732. } catch (\Exception $e) {
  733. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid.', $name), 0, $e);
  734. }
  735. }
  736. return $this->cache[$name] = $template;
  737. }
  738. }
  739. }
  740. namespace Symfony\Component\Config
  741. {
  742. interface FileLocatorInterface
  743. {
  744. public function locate($name, $currentPath = null, $first = true);
  745. }
  746. }
  747. namespace Symfony\Bundle\FrameworkBundle\Templating\Loader
  748. {
  749. use Symfony\Component\Config\FileLocatorInterface;
  750. use Symfony\Component\Templating\TemplateReferenceInterface;
  751. class TemplateLocator implements FileLocatorInterface
  752. {
  753. protected $locator;
  754. protected $cache;
  755. public function __construct(FileLocatorInterface $locator, $cacheDir = null)
  756. {
  757. if (null !== $cacheDir && is_file($cache = $cacheDir.'/templates.php')) {
  758. $this->cache = require $cache;
  759. }
  760. $this->locator = $locator;
  761. }
  762. protected function getCacheKey($template)
  763. {
  764. return $template->getLogicalName();
  765. }
  766. public function locate($template, $currentPath = null, $first = true)
  767. {
  768. if (!$template instanceof TemplateReferenceInterface) {
  769. throw new \InvalidArgumentException("The template must be an instance of TemplateReferenceInterface.");
  770. }
  771. $key = $this->getCacheKey($template);
  772. if (isset($this->cache[$key])) {
  773. return $this->cache[$key];
  774. }
  775. try {
  776. return $this->cache[$key] = $this->locator->locate($template->getPath(), $currentPath);
  777. } catch (\InvalidArgumentException $e) {
  778. throw new \InvalidArgumentException(sprintf('Unable to find template "%s" : "%s".', $template, $e->getMessage()), 0, $e);
  779. }
  780. }
  781. }
  782. }
  783. namespace Symfony\Component\Routing
  784. {
  785. interface RequestContextAwareInterface
  786. {
  787. public function setContext(RequestContext $context);
  788. public function getContext();
  789. }
  790. }
  791. namespace Symfony\Component\Routing\Generator
  792. {
  793. use Symfony\Component\Routing\Exception\InvalidParameterException;
  794. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  795. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  796. use Symfony\Component\Routing\RequestContextAwareInterface;
  797. interface UrlGeneratorInterface extends RequestContextAwareInterface
  798. {
  799. const ABSOLUTE_URL = true;
  800. const ABSOLUTE_PATH = false;
  801. const RELATIVE_PATH ='relative';
  802. const NETWORK_PATH ='network';
  803. public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH);
  804. }
  805. }
  806. namespace Symfony\Component\Routing\Generator
  807. {
  808. interface ConfigurableRequirementsInterface
  809. {
  810. public function setStrictRequirements($enabled);
  811. public function isStrictRequirements();
  812. }
  813. }
  814. namespace Symfony\Component\Routing\Generator
  815. {
  816. use Symfony\Component\Routing\RouteCollection;
  817. use Symfony\Component\Routing\RequestContext;
  818. use Symfony\Component\Routing\Exception\InvalidParameterException;
  819. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  820. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  821. use Psr\Log\LoggerInterface;
  822. class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
  823. {
  824. protected $routes;
  825. protected $context;
  826. protected $strictRequirements = true;
  827. protected $logger;
  828. protected $decodedChars = array('%2F'=>'/','%40'=>'@','%3A'=>':','%3B'=>';','%2C'=>',','%3D'=>'=','%2B'=>'+','%21'=>'!','%2A'=>'*','%7C'=>'|',
  829. );
  830. public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
  831. {
  832. $this->routes = $routes;
  833. $this->context = $context;
  834. $this->logger = $logger;
  835. }
  836. public function setContext(RequestContext $context)
  837. {
  838. $this->context = $context;
  839. }
  840. public function getContext()
  841. {
  842. return $this->context;
  843. }
  844. public function setStrictRequirements($enabled)
  845. {
  846. $this->strictRequirements = null === $enabled ? null : (Boolean) $enabled;
  847. }
  848. public function isStrictRequirements()
  849. {
  850. return $this->strictRequirements;
  851. }
  852. public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
  853. {
  854. if (null === $route = $this->routes->get($name)) {
  855. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  856. }
  857. $compiledRoute = $route->compile();
  858. return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens());
  859. }
  860. protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens)
  861. {
  862. $variables = array_flip($variables);
  863. $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
  864. if ($diff = array_diff_key($variables, $mergedParams)) {
  865. throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
  866. }
  867. $url ='';
  868. $optional = true;
  869. foreach ($tokens as $token) {
  870. if ('variable'=== $token[0]) {
  871. if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
  872. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
  873. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  874. if ($this->strictRequirements) {
  875. throw new InvalidParameterException($message);
  876. }
  877. if ($this->logger) {
  878. $this->logger->error($message);
  879. }
  880. return null;
  881. }
  882. $url = $token[1].$mergedParams[$token[3]].$url;
  883. $optional = false;
  884. }
  885. } else {
  886. $url = $token[1].$url;
  887. $optional = false;
  888. }
  889. }
  890. if (''=== $url) {
  891. $url ='/';
  892. }
  893. $url = strtr(rawurlencode($url), $this->decodedChars);
  894. $url = strtr($url, array('/../'=>'/%2E%2E/','/./'=>'/%2E/'));
  895. if ('/..'=== substr($url, -3)) {
  896. $url = substr($url, 0, -2) .'%2E%2E';
  897. } elseif ('/.'=== substr($url, -2)) {
  898. $url = substr($url, 0, -1) .'%2E';
  899. }
  900. $schemeAuthority ='';
  901. if ($host = $this->context->getHost()) {
  902. $scheme = $this->context->getScheme();
  903. if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
  904. $referenceType = self::ABSOLUTE_URL;
  905. $scheme = $req;
  906. }
  907. if ($hostTokens) {
  908. $routeHost ='';
  909. foreach ($hostTokens as $token) {
  910. if ('variable'=== $token[0]) {
  911. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
  912. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  913. if ($this->strictRequirements) {
  914. throw new InvalidParameterException($message);
  915. }
  916. if ($this->logger) {
  917. $this->logger->error($message);
  918. }
  919. return null;
  920. }
  921. $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
  922. } else {
  923. $routeHost = $token[1].$routeHost;
  924. }
  925. }
  926. if ($routeHost !== $host) {
  927. $host = $routeHost;
  928. if (self::ABSOLUTE_URL !== $referenceType) {
  929. $referenceType = self::NETWORK_PATH;
  930. }
  931. }
  932. }
  933. if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
  934. $port ='';
  935. if ('http'=== $scheme && 80 != $this->context->getHttpPort()) {
  936. $port =':'.$this->context->getHttpPort();
  937. } elseif ('https'=== $scheme && 443 != $this->context->getHttpsPort()) {
  938. $port =':'.$this->context->getHttpsPort();
  939. }
  940. $schemeAuthority = self::NETWORK_PATH === $referenceType ?'//': "$scheme://";
  941. $schemeAuthority .= $host.$port;
  942. }
  943. }
  944. if (self::RELATIVE_PATH === $referenceType) {
  945. $url = self::getRelativePath($this->context->getPathInfo(), $url);
  946. } else {
  947. $url = $schemeAuthority.$this->context->getBaseUrl().$url;
  948. }
  949. $extra = array_diff_key($parameters, $variables, $defaults);
  950. if ($extra && $query = http_build_query($extra,'','&')) {
  951. $url .='?'.$query;
  952. }
  953. return $url;
  954. }
  955. public static function getRelativePath($basePath, $targetPath)
  956. {
  957. if ($basePath === $targetPath) {
  958. return'';
  959. }
  960. $sourceDirs = explode('/', isset($basePath[0]) &&'/'=== $basePath[0] ? substr($basePath, 1) : $basePath);
  961. $targetDirs = explode('/', isset($targetPath[0]) &&'/'=== $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  962. array_pop($sourceDirs);
  963. $targetFile = array_pop($targetDirs);
  964. foreach ($sourceDirs as $i => $dir) {
  965. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  966. unset($sourceDirs[$i], $targetDirs[$i]);
  967. } else {
  968. break;
  969. }
  970. }
  971. $targetDirs[] = $targetFile;
  972. $path = str_repeat('../', count($sourceDirs)) . implode('/', $targetDirs);
  973. return''=== $path ||'/'=== $path[0]
  974. || false !== ($colonPos = strpos($path,':')) && ($colonPos < ($slashPos = strpos($path,'/')) || false === $slashPos)
  975. ? "./$path" : $path;
  976. }
  977. }
  978. }
  979. namespace Symfony\Component\Routing
  980. {
  981. use Symfony\Component\HttpFoundation\Request;
  982. class RequestContext
  983. {
  984. private $baseUrl;
  985. private $pathInfo;
  986. private $method;
  987. private $host;
  988. private $scheme;
  989. private $httpPort;
  990. private $httpsPort;
  991. private $parameters = array();
  992. public function __construct($baseUrl ='', $method ='GET', $host ='localhost', $scheme ='http', $httpPort = 80, $httpsPort = 443, $path ='/')
  993. {
  994. $this->baseUrl = $baseUrl;
  995. $this->method = strtoupper($method);
  996. $this->host = $host;
  997. $this->scheme = strtolower($scheme);
  998. $this->httpPort = $httpPort;
  999. $this->httpsPort = $httpsPort;
  1000. $this->pathInfo = $path;
  1001. }
  1002. public function fromRequest(Request $request)
  1003. {
  1004. $this->setBaseUrl($request->getBaseUrl());
  1005. $this->setPathInfo($request->getPathInfo());
  1006. $this->setMethod($request->getMethod());
  1007. $this->setHost($request->getHost());
  1008. $this->setScheme($request->getScheme());
  1009. $this->setHttpPort($request->isSecure() ? $this->httpPort : $request->getPort());
  1010. $this->setHttpsPort($request->isSecure() ? $request->getPort() : $this->httpsPort);
  1011. }
  1012. public function getBaseUrl()
  1013. {
  1014. return $this->baseUrl;
  1015. }
  1016. public function setBaseUrl($baseUrl)
  1017. {
  1018. $this->baseUrl = $baseUrl;
  1019. }
  1020. public function getPathInfo()
  1021. {
  1022. return $this->pathInfo;
  1023. }
  1024. public function setPathInfo($pathInfo)
  1025. {
  1026. $this->pathInfo = $pathInfo;
  1027. }
  1028. public function getMethod()
  1029. {
  1030. return $this->method;
  1031. }
  1032. public function setMethod($method)
  1033. {
  1034. $this->method = strtoupper($method);
  1035. }
  1036. public function getHost()
  1037. {
  1038. return $this->host;
  1039. }
  1040. public function setHost($host)
  1041. {
  1042. $this->host = $host;
  1043. }
  1044. public function getScheme()
  1045. {
  1046. return $this->scheme;
  1047. }
  1048. public function setScheme($scheme)
  1049. {
  1050. $this->scheme = strtolower($scheme);
  1051. }
  1052. public function getHttpPort()
  1053. {
  1054. return $this->httpPort;
  1055. }
  1056. public function setHttpPort($httpPort)
  1057. {
  1058. $this->httpPort = $httpPort;
  1059. }
  1060. public function getHttpsPort()
  1061. {
  1062. return $this->httpsPort;
  1063. }
  1064. public function setHttpsPort($httpsPort)
  1065. {
  1066. $this->httpsPort = $httpsPort;
  1067. }
  1068. public function getParameters()
  1069. {
  1070. return $this->parameters;
  1071. }
  1072. public function setParameters(array $parameters)
  1073. {
  1074. $this->parameters = $parameters;
  1075. return $this;
  1076. }
  1077. public function getParameter($name)
  1078. {
  1079. return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
  1080. }
  1081. public function hasParameter($name)
  1082. {
  1083. return array_key_exists($name, $this->parameters);
  1084. }
  1085. public function setParameter($name, $parameter)
  1086. {
  1087. $this->parameters[$name] = $parameter;
  1088. }
  1089. }
  1090. }
  1091. namespace Symfony\Component\Routing\Matcher
  1092. {
  1093. use Symfony\Component\Routing\RequestContextAwareInterface;
  1094. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  1095. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  1096. interface UrlMatcherInterface extends RequestContextAwareInterface
  1097. {
  1098. public function match($pathinfo);
  1099. }
  1100. }
  1101. namespace Symfony\Component\Routing
  1102. {
  1103. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  1104. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  1105. interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface
  1106. {
  1107. public function getRouteCollection();
  1108. }
  1109. }
  1110. namespace Symfony\Component\Routing
  1111. {
  1112. use Symfony\Component\Config\Loader\LoaderInterface;
  1113. use Symfony\Component\Config\ConfigCache;
  1114. use Psr\Log\LoggerInterface;
  1115. use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface;
  1116. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  1117. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  1118. class Router implements RouterInterface
  1119. {
  1120. protected $matcher;
  1121. protected $generator;
  1122. protected $context;
  1123. protected $loader;
  1124. protected $collection;
  1125. protected $resource;
  1126. protected $options = array();
  1127. protected $logger;
  1128. public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, LoggerInterface $logger = null)
  1129. {
  1130. $this->loader = $loader;
  1131. $this->resource = $resource;
  1132. $this->logger = $logger;
  1133. $this->context = null === $context ? new RequestContext() : $context;
  1134. $this->setOptions($options);
  1135. }
  1136. public function setOptions(array $options)
  1137. {
  1138. $this->options = array('cache_dir'=> null,'debug'=> false,'generator_class'=>'Symfony\\Component\\Routing\\Generator\\UrlGenerator','generator_base_class'=>'Symfony\\Component\\Routing\\Generator\\UrlGenerator','generator_dumper_class'=>'Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper','generator_cache_class'=>'ProjectUrlGenerator','matcher_class'=>'Symfony\\Component\\Routing\\Matcher\\UrlMatcher','matcher_base_class'=>'Symfony\\Component\\Routing\\Matcher\\UrlMatcher','matcher_dumper_class'=>'Symfony\\Component\\Routing\\Matcher\\Dumper\\PhpMatcherDumper','matcher_cache_class'=>'ProjectUrlMatcher','resource_type'=> null,'strict_requirements'=> true,
  1139. );
  1140. $invalid = array();
  1141. foreach ($options as $key => $value) {
  1142. if (array_key_exists($key, $this->options)) {
  1143. $this->options[$key] = $value;
  1144. } else {
  1145. $invalid[] = $key;
  1146. }
  1147. }
  1148. if ($invalid) {
  1149. throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('\', \'', $invalid)));
  1150. }
  1151. }
  1152. public function setOption($key, $value)
  1153. {
  1154. if (!array_key_exists($key, $this->options)) {
  1155. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  1156. }
  1157. $this->options[$key] = $value;
  1158. }
  1159. public function getOption($key)
  1160. {
  1161. if (!array_key_exists($key, $this->options)) {
  1162. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  1163. }
  1164. return $this->options[$key];
  1165. }
  1166. public function getRouteCollection()
  1167. {
  1168. if (null === $this->collection) {
  1169. $this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
  1170. }
  1171. return $this->collection;
  1172. }
  1173. public function setContext(RequestContext $context)
  1174. {
  1175. $this->context = $context;
  1176. if (null !== $this->matcher) {
  1177. $this->getMatcher()->setContext($context);
  1178. }
  1179. if (null !== $this->generator) {
  1180. $this->getGenerator()->setContext($context);
  1181. }
  1182. }
  1183. public function getContext()
  1184. {
  1185. return $this->context;
  1186. }
  1187. public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
  1188. {
  1189. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  1190. }
  1191. public function match($pathinfo)
  1192. {
  1193. return $this->getMatcher()->match($pathinfo);
  1194. }
  1195. public function getMatcher()
  1196. {
  1197. if (null !== $this->matcher) {
  1198. return $this->matcher;
  1199. }
  1200. if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
  1201. return $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context);
  1202. }
  1203. $class = $this->options['matcher_cache_class'];
  1204. $cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
  1205. if (!$cache->isFresh($class)) {
  1206. $dumper = new $this->options['matcher_dumper_class']($this->getRouteCollection());
  1207. $options = array('class'=> $class,'base_class'=> $this->options['matcher_base_class'],
  1208. );
  1209. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  1210. }
  1211. require_once $cache;
  1212. return $this->matcher = new $class($this->context);
  1213. }
  1214. public function getGenerator()
  1215. {
  1216. if (null !== $this->generator) {
  1217. return $this->generator;
  1218. }
  1219. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  1220. $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger);
  1221. } else {
  1222. $class = $this->options['generator_cache_class'];
  1223. $cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
  1224. if (!$cache->isFresh($class)) {
  1225. $dumper = new $this->options['generator_dumper_class']($this->getRouteCollection());
  1226. $options = array('class'=> $class,'base_class'=> $this->options['generator_base_class'],
  1227. );
  1228. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  1229. }
  1230. require_once $cache;
  1231. $this->generator = new $class($this->context, $this->logger);
  1232. }
  1233. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  1234. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  1235. }
  1236. return $this->generator;
  1237. }
  1238. }
  1239. }
  1240. namespace Symfony\Component\Routing\Matcher
  1241. {
  1242. interface RedirectableUrlMatcherInterface
  1243. {
  1244. public function redirect($path, $route, $scheme = null);
  1245. }
  1246. }
  1247. namespace Symfony\Component\Routing\Matcher
  1248. {
  1249. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  1250. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  1251. use Symfony\Component\Routing\RouteCollection;
  1252. use Symfony\Component\Routing\RequestContext;
  1253. use Symfony\Component\Routing\Route;
  1254. class UrlMatcher implements UrlMatcherInterface
  1255. {
  1256. const REQUIREMENT_MATCH = 0;
  1257. const REQUIREMENT_MISMATCH = 1;
  1258. const ROUTE_MATCH = 2;
  1259. protected $context;
  1260. protected $allow = array();
  1261. protected $routes;
  1262. public function __construct(RouteCollection $routes, RequestContext $context)
  1263. {
  1264. $this->routes = $routes;
  1265. $this->context = $context;
  1266. }
  1267. public function setContext(RequestContext $context)
  1268. {
  1269. $this->context = $context;
  1270. }
  1271. public function getContext()
  1272. {
  1273. return $this->context;
  1274. }
  1275. public function match($pathinfo)
  1276. {
  1277. $this->allow = array();
  1278. if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
  1279. return $ret;
  1280. }
  1281. throw 0 < count($this->allow)
  1282. ? new MethodNotAllowedException(array_unique(array_map('strtoupper', $this->allow)))
  1283. : new ResourceNotFoundException();
  1284. }
  1285. protected function matchCollection($pathinfo, RouteCollection $routes)
  1286. {
  1287. foreach ($routes as $name => $route) {
  1288. $compiledRoute = $route->compile();
  1289. if (''!== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
  1290. continue;
  1291. }
  1292. if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
  1293. continue;
  1294. }
  1295. $hostMatches = array();
  1296. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  1297. continue;
  1298. }
  1299. if ($req = $route->getRequirement('_method')) {
  1300. if ('HEAD'=== $method = $this->context->getMethod()) {
  1301. $method ='GET';
  1302. }
  1303. if (!in_array($method, $req = explode('|', strtoupper($req)))) {
  1304. $this->allow = array_merge($this->allow, $req);
  1305. continue;
  1306. }
  1307. }
  1308. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  1309. if (self::ROUTE_MATCH === $status[0]) {
  1310. return $status[1];
  1311. }
  1312. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  1313. continue;
  1314. }
  1315. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
  1316. }
  1317. }
  1318. protected function getAttributes(Route $route, $name, array $attributes)
  1319. {
  1320. $attributes['_route'] = $name;
  1321. return $this->mergeDefaults($attributes, $route->getDefaults());
  1322. }
  1323. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  1324. {
  1325. $scheme = $route->getRequirement('_scheme');
  1326. $status = $scheme && $scheme !== $this->context->getScheme() ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
  1327. return array($status, null);
  1328. }
  1329. protected function mergeDefaults($params, $defaults)
  1330. {
  1331. foreach ($params as $key => $value) {
  1332. if (!is_int($key)) {
  1333. $defaults[$key] = $value;
  1334. }
  1335. }
  1336. return $defaults;
  1337. }
  1338. }
  1339. }
  1340. namespace Symfony\Component\Routing\Matcher
  1341. {
  1342. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  1343. use Symfony\Component\Routing\Route;
  1344. abstract class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
  1345. {
  1346. public function match($pathinfo)
  1347. {
  1348. try {
  1349. $parameters = parent::match($pathinfo);
  1350. } catch (ResourceNotFoundException $e) {
  1351. if ('/'=== substr($pathinfo, -1) || !in_array($this->context->getMethod(), array('HEAD','GET'))) {
  1352. throw $e;
  1353. }
  1354. try {
  1355. parent::match($pathinfo.'/');
  1356. return $this->redirect($pathinfo.'/', null);
  1357. } catch (ResourceNotFoundException $e2) {
  1358. throw $e;
  1359. }
  1360. }
  1361. return $parameters;
  1362. }
  1363. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  1364. {
  1365. $scheme = $route->getRequirement('_scheme');
  1366. if ($scheme && $this->context->getScheme() !== $scheme) {
  1367. return array(self::ROUTE_MATCH, $this->redirect($pathinfo, $name, $scheme));
  1368. }
  1369. return array(self::REQUIREMENT_MATCH, null);
  1370. }
  1371. }
  1372. }
  1373. namespace Symfony\Bundle\FrameworkBundle\Routing
  1374. {
  1375. use Symfony\Component\Routing\Matcher\RedirectableUrlMatcher as BaseMatcher;
  1376. class RedirectableUrlMatcher extends BaseMatcher
  1377. {
  1378. public function redirect($path, $route, $scheme = null)
  1379. {
  1380. return array('_controller'=>'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction','path'=> $path,'permanent'=> true,'scheme'=> $scheme,'httpPort'=> $this->context->getHttpPort(),'httpsPort'=> $this->context->getHttpsPort(),'_route'=> $route,
  1381. );
  1382. }
  1383. }
  1384. }
  1385. namespace Symfony\Component\HttpKernel\CacheWarmer
  1386. {
  1387. interface WarmableInterface
  1388. {
  1389. public function warmUp($cacheDir);
  1390. }
  1391. }
  1392. namespace Symfony\Bundle\FrameworkBundle\Routing
  1393. {
  1394. use Symfony\Component\Routing\Router as BaseRouter;
  1395. use Symfony\Component\Routing\RequestContext;
  1396. use Symfony\Component\DependencyInjection\ContainerInterface;
  1397. use Symfony\Component\Routing\RouteCollection;
  1398. use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
  1399. use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
  1400. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  1401. class Router extends BaseRouter implements WarmableInterface
  1402. {
  1403. private $container;
  1404. public function __construct(ContainerInterface $container, $resource, array $options = array(), RequestContext $context = null)
  1405. {
  1406. $this->container = $container;
  1407. $this->resource = $resource;
  1408. $this->context = null === $context ? new RequestContext() : $context;
  1409. $this->setOptions($options);
  1410. }
  1411. public function getRouteCollection()
  1412. {
  1413. if (null === $this->collection) {
  1414. $this->collection = $this->container->get('routing.loader')->load($this->resource, $this->options['resource_type']);
  1415. $this->resolveParameters($this->collection);
  1416. }
  1417. return $this->collection;
  1418. }
  1419. public function warmUp($cacheDir)
  1420. {
  1421. $currentDir = $this->getOption('cache_dir');
  1422. $this->setOption('cache_dir', $cacheDir);
  1423. $this->getMatcher();
  1424. $this->getGenerator();
  1425. $this->setOption('cache_dir', $currentDir);
  1426. }
  1427. private function resolveParameters(RouteCollection $collection)
  1428. {
  1429. foreach ($collection as $route) {
  1430. foreach ($route->getDefaults() as $name => $value) {
  1431. $route->setDefault($name, $this->resolve($value));
  1432. }
  1433. foreach ($route->getRequirements() as $name => $value) {
  1434. $route->setRequirement($name, $this->resolve($value));
  1435. }
  1436. $route->setPath($this->resolve($route->getPath()));
  1437. $route->setHost($this->resolve($route->getHost()));
  1438. }
  1439. }
  1440. private function resolve($value)
  1441. {
  1442. if (is_array($value)) {
  1443. foreach ($value as $key => $val) {
  1444. $value[$key] = $this->resolve($val);
  1445. }
  1446. return $value;
  1447. }
  1448. if (!is_string($value)) {
  1449. return $value;
  1450. }
  1451. $container = $this->container;
  1452. $escapedValue = preg_replace_callback('/%%|%([^%\s]+)%/', function ($match) use ($container, $value) {
  1453. if (!isset($match[1])) {
  1454. return'%%';
  1455. }
  1456. $key = strtolower($match[1]);
  1457. if (!$container->hasParameter($key)) {
  1458. throw new ParameterNotFoundException($key);
  1459. }
  1460. $resolved = $container->getParameter($key);
  1461. if (is_string($resolved) || is_numeric($resolved)) {
  1462. return (string) $resolved;
  1463. }
  1464. throw new RuntimeException(sprintf('A string value must be composed of strings and/or numbers,'.'but found parameter "%s" of type %s inside string value "%s".',
  1465. $key,
  1466. gettype($resolved),
  1467. $value)
  1468. );
  1469. }, $value);
  1470. return str_replace('%%','%', $escapedValue);
  1471. }
  1472. }
  1473. }
  1474. namespace Symfony\Component\HttpFoundation
  1475. {
  1476. class ParameterBag implements \IteratorAggregate, \Countable
  1477. {
  1478. protected $parameters;
  1479. public function __construct(array $parameters = array())
  1480. {
  1481. $this->parameters = $parameters;
  1482. }
  1483. public function all()
  1484. {
  1485. return $this->parameters;
  1486. }
  1487. public function keys()
  1488. {
  1489. return array_keys($this->parameters);
  1490. }
  1491. public function replace(array $parameters = array())
  1492. {
  1493. $this->parameters = $parameters;
  1494. }
  1495. public function add(array $parameters = array())
  1496. {
  1497. $this->parameters = array_replace($this->parameters, $parameters);
  1498. }
  1499. public function get($path, $default = null, $deep = false)
  1500. {
  1501. if (!$deep || false === $pos = strpos($path,'[')) {
  1502. return array_key_exists($path, $this->parameters) ? $this->parameters[$path] : $default;
  1503. }
  1504. $root = substr($path, 0, $pos);
  1505. if (!array_key_exists($root, $this->parameters)) {
  1506. return $default;
  1507. }
  1508. $value = $this->parameters[$root];
  1509. $currentKey = null;
  1510. for ($i = $pos, $c = strlen($path); $i < $c; $i++) {
  1511. $char = $path[$i];
  1512. if ('['=== $char) {
  1513. if (null !== $currentKey) {
  1514. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "[" at position %d.', $i));
  1515. }
  1516. $currentKey ='';
  1517. } elseif (']'=== $char) {
  1518. if (null === $currentKey) {
  1519. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i));
  1520. }
  1521. if (!is_array($value) || !array_key_exists($currentKey, $value)) {
  1522. return $default;
  1523. }
  1524. $value = $value[$currentKey];
  1525. $currentKey = null;
  1526. } else {
  1527. if (null === $currentKey) {
  1528. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "%s" at position %d.', $char, $i));
  1529. }
  1530. $currentKey .= $char;
  1531. }
  1532. }
  1533. if (null !== $currentKey) {
  1534. throw new \InvalidArgumentException(sprintf('Malformed path. Path must end with "]".'));
  1535. }
  1536. return $value;
  1537. }
  1538. public function set($key, $value)
  1539. {
  1540. $this->parameters[$key] = $value;
  1541. }
  1542. public function has($key)
  1543. {
  1544. return array_key_exists($key, $this->parameters);
  1545. }
  1546. public function remove($key)
  1547. {
  1548. unset($this->parameters[$key]);
  1549. }
  1550. public function getAlpha($key, $default ='', $deep = false)
  1551. {
  1552. return preg_replace('/[^[:alpha:]]/','', $this->get($key, $default, $deep));
  1553. }
  1554. public function getAlnum($key, $default ='', $deep = false)
  1555. {
  1556. return preg_replace('/[^[:alnum:]]/','', $this->get($key, $default, $deep));
  1557. }
  1558. public function getDigits($key, $default ='', $deep = false)
  1559. {
  1560. return str_replace(array('-','+'),'', $this->filter($key, $default, $deep, FILTER_SANITIZE_NUMBER_INT));
  1561. }
  1562. public function getInt($key, $default = 0, $deep = false)
  1563. {
  1564. return (int) $this->get($key, $default, $deep);
  1565. }
  1566. public function filter($key, $default = null, $deep = false, $filter=FILTER_DEFAULT, $options=array())
  1567. {
  1568. $value = $this->get($key, $default, $deep);
  1569. if (!is_array($options) && $options) {
  1570. $options = array('flags'=> $options);
  1571. }
  1572. if (is_array($value) && !isset($options['flags'])) {
  1573. $options['flags'] = FILTER_REQUIRE_ARRAY;
  1574. }
  1575. return filter_var($value, $filter, $options);
  1576. }
  1577. public function getIterator()
  1578. {
  1579. return new \ArrayIterator($this->parameters);
  1580. }
  1581. public function count()
  1582. {
  1583. return count($this->parameters);
  1584. }
  1585. }
  1586. }
  1587. namespace Symfony\Component\HttpFoundation
  1588. {
  1589. class HeaderBag implements \IteratorAggregate, \Countable
  1590. {
  1591. protected $headers;
  1592. protected $cacheControl;
  1593. public function __construct(array $headers = array())
  1594. {
  1595. $this->cacheControl = array();
  1596. $this->headers = array();
  1597. foreach ($headers as $key => $values) {
  1598. $this->set($key, $values);
  1599. }
  1600. }
  1601. public function __toString()
  1602. {
  1603. if (!$this->headers) {
  1604. return'';
  1605. }
  1606. $max = max(array_map('strlen', array_keys($this->headers))) + 1;
  1607. $content ='';
  1608. ksort($this->headers);
  1609. foreach ($this->headers as $name => $values) {
  1610. $name = implode('-', array_map('ucfirst', explode('-', $name)));
  1611. foreach ($values as $value) {
  1612. $content .= sprintf("%-{$max}s %s\r\n", $name.':', $value);
  1613. }
  1614. }
  1615. return $content;
  1616. }
  1617. public function all()
  1618. {
  1619. return $this->headers;
  1620. }
  1621. public function keys()
  1622. {
  1623. return array_keys($this->headers);
  1624. }
  1625. public function replace(array $headers = array())
  1626. {
  1627. $this->headers = array();
  1628. $this->add($headers);
  1629. }
  1630. public function add(array $headers)
  1631. {
  1632. foreach ($headers as $key => $values) {
  1633. $this->set($key, $values);
  1634. }
  1635. }
  1636. public function get($key, $default = null, $first = true)
  1637. {
  1638. $key = strtr(strtolower($key),'_','-');
  1639. if (!array_key_exists($key, $this->headers)) {
  1640. if (null === $default) {
  1641. return $first ? null : array();
  1642. }
  1643. return $first ? $default : array($default);
  1644. }
  1645. if ($first) {
  1646. return count($this->headers[$key]) ? $this->headers[$key][0] : $default;
  1647. }
  1648. return $this->headers[$key];
  1649. }
  1650. public function set($key, $values, $replace = true)
  1651. {
  1652. $key = strtr(strtolower($key),'_','-');
  1653. $values = array_values((array) $values);
  1654. if (true === $replace || !isset($this->headers[$key])) {
  1655. $this->headers[$key] = $values;
  1656. } else {
  1657. $this->headers[$key] = array_merge($this->headers[$key], $values);
  1658. }
  1659. if ('cache-control'=== $key) {
  1660. $this->cacheControl = $this->parseCacheControl($values[0]);
  1661. }
  1662. }
  1663. public function has($key)
  1664. {
  1665. return array_key_exists(strtr(strtolower($key),'_','-'), $this->headers);
  1666. }
  1667. public function contains($key, $value)
  1668. {
  1669. return in_array($value, $this->get($key, null, false));
  1670. }
  1671. public function remove($key)
  1672. {
  1673. $key = strtr(strtolower($key),'_','-');
  1674. unset($this->headers[$key]);
  1675. if ('cache-control'=== $key) {
  1676. $this->cacheControl = array();
  1677. }
  1678. }
  1679. public function getDate($key, \DateTime $default = null)
  1680. {
  1681. if (null === $value = $this->get($key)) {
  1682. return $default;
  1683. }
  1684. if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
  1685. throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
  1686. }
  1687. return $date;
  1688. }
  1689. public function addCacheControlDirective($key, $value = true)
  1690. {
  1691. $this->cacheControl[$key] = $value;
  1692. $this->set('Cache-Control', $this->getCacheControlHeader());
  1693. }
  1694. public function hasCacheControlDirective($key)
  1695. {
  1696. return array_key_exists($key, $this->cacheControl);
  1697. }
  1698. public function getCacheControlDirective($key)
  1699. {
  1700. return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
  1701. }
  1702. public function removeCacheControlDirective($key)
  1703. {
  1704. unset($this->cacheControl[$key]);
  1705. $this->set('Cache-Control', $this->getCacheControlHeader());
  1706. }
  1707. public function getIterator()
  1708. {
  1709. return new \ArrayIterator($this->headers);
  1710. }
  1711. public function count()
  1712. {
  1713. return count($this->headers);
  1714. }
  1715. protected function getCacheControlHeader()
  1716. {
  1717. $parts = array();
  1718. ksort($this->cacheControl);
  1719. foreach ($this->cacheControl as $key => $value) {
  1720. if (true === $value) {
  1721. $parts[] = $key;
  1722. } else {
  1723. if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
  1724. $value ='"'.$value.'"';
  1725. }
  1726. $parts[] = "$key=$value";
  1727. }
  1728. }
  1729. return implode(', ', $parts);
  1730. }
  1731. protected function parseCacheControl($header)
  1732. {
  1733. $cacheControl = array();
  1734. preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
  1735. foreach ($matches as $match) {
  1736. $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] : true);
  1737. }
  1738. return $cacheControl;
  1739. }
  1740. }
  1741. }
  1742. namespace Symfony\Component\HttpFoundation
  1743. {
  1744. use Symfony\Component\HttpFoundation\File\UploadedFile;
  1745. class FileBag extends ParameterBag
  1746. {
  1747. private static $fileKeys = array('error','name','size','tmp_name','type');
  1748. public function __construct(array $parameters = array())
  1749. {
  1750. $this->replace($parameters);
  1751. }
  1752. public function replace(array $files = array())
  1753. {
  1754. $this->parameters = array();
  1755. $this->add($files);
  1756. }
  1757. public function set($key, $value)
  1758. {
  1759. if (!is_array($value) && !$value instanceof UploadedFile) {
  1760. throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
  1761. }
  1762. parent::set($key, $this->convertFileInformation($value));
  1763. }
  1764. public function add(array $files = array())
  1765. {
  1766. foreach ($files as $key => $file) {
  1767. $this->set($key, $file);
  1768. }
  1769. }
  1770. protected function convertFileInformation($file)
  1771. {
  1772. if ($file instanceof UploadedFile) {
  1773. return $file;
  1774. }
  1775. $file = $this->fixPhpFilesArray($file);
  1776. if (is_array($file)) {
  1777. $keys = array_keys($file);
  1778. sort($keys);
  1779. if ($keys == self::$fileKeys) {
  1780. if (UPLOAD_ERR_NO_FILE == $file['error']) {
  1781. $file = null;
  1782. } else {
  1783. $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']);
  1784. }
  1785. } else {
  1786. $file = array_map(array($this,'convertFileInformation'), $file);
  1787. }
  1788. }
  1789. return $file;
  1790. }
  1791. protected function fixPhpFilesArray($data)
  1792. {
  1793. if (!is_array($data)) {
  1794. return $data;
  1795. }
  1796. $keys = array_keys($data);
  1797. sort($keys);
  1798. if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
  1799. return $data;
  1800. }
  1801. $files = $data;
  1802. foreach (self::$fileKeys as $k) {
  1803. unset($files[$k]);
  1804. }
  1805. foreach (array_keys($data['name']) as $key) {
  1806. $files[$key] = $this->fixPhpFilesArray(array('error'=> $data['error'][$key],'name'=> $data['name'][$key],'type'=> $data['type'][$key],'tmp_name'=> $data['tmp_name'][$key],'size'=> $data['size'][$key]
  1807. ));
  1808. }
  1809. return $files;
  1810. }
  1811. }
  1812. }
  1813. namespace Symfony\Component\HttpFoundation
  1814. {
  1815. class ServerBag extends ParameterBag
  1816. {
  1817. public function getHeaders()
  1818. {
  1819. $headers = array();
  1820. foreach ($this->parameters as $key => $value) {
  1821. if (0 === strpos($key,'HTTP_')) {
  1822. $headers[substr($key, 5)] = $value;
  1823. }
  1824. elseif (in_array($key, array('CONTENT_LENGTH','CONTENT_MD5','CONTENT_TYPE'))) {
  1825. $headers[$key] = $value;
  1826. }
  1827. }
  1828. if (isset($this->parameters['PHP_AUTH_USER'])) {
  1829. $headers['PHP_AUTH_USER'] = $this->parameters['PHP_AUTH_USER'];
  1830. $headers['PHP_AUTH_PW'] = isset($this->parameters['PHP_AUTH_PW']) ? $this->parameters['PHP_AUTH_PW'] :'';
  1831. } else {
  1832. $authorizationHeader = null;
  1833. if (isset($this->parameters['HTTP_AUTHORIZATION'])) {
  1834. $authorizationHeader = $this->parameters['HTTP_AUTHORIZATION'];
  1835. } elseif (isset($this->parameters['REDIRECT_HTTP_AUTHORIZATION'])) {
  1836. $authorizationHeader = $this->parameters['REDIRECT_HTTP_AUTHORIZATION'];
  1837. }
  1838. if ((null !== $authorizationHeader) && (0 === stripos($authorizationHeader,'basic'))) {
  1839. $exploded = explode(':', base64_decode(substr($authorizationHeader, 6)));
  1840. if (count($exploded) == 2) {
  1841. list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded;
  1842. }
  1843. }
  1844. }
  1845. if (isset($headers['PHP_AUTH_USER'])) {
  1846. $headers['AUTHORIZATION'] ='Basic '.base64_encode($headers['PHP_AUTH_USER'].':'.$headers['PHP_AUTH_PW']);
  1847. }
  1848. return $headers;
  1849. }
  1850. }
  1851. }
  1852. namespace Symfony\Component\HttpFoundation
  1853. {
  1854. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  1855. class Request
  1856. {
  1857. const HEADER_CLIENT_IP ='client_ip';
  1858. const HEADER_CLIENT_HOST ='client_host';
  1859. const HEADER_CLIENT_PROTO ='client_proto';
  1860. const HEADER_CLIENT_PORT ='client_port';
  1861. protected static $trustProxy = false;
  1862. protected static $trustedProxies = array();
  1863. protected static $trustedHeaders = array(
  1864. self::HEADER_CLIENT_IP =>'X_FORWARDED_FOR',
  1865. self::HEADER_CLIENT_HOST =>'X_FORWARDED_HOST',
  1866. self::HEADER_CLIENT_PROTO =>'X_FORWARDED_PROTO',
  1867. self::HEADER_CLIENT_PORT =>'X_FORWARDED_PORT',
  1868. );
  1869. protected static $httpMethodParameterOverride = false;
  1870. public $attributes;
  1871. public $request;
  1872. public $query;
  1873. public $server;
  1874. public $files;
  1875. public $cookies;
  1876. public $headers;
  1877. protected $content;
  1878. protected $languages;
  1879. protected $charsets;
  1880. protected $acceptableContentTypes;
  1881. protected $pathInfo;
  1882. protected $requestUri;
  1883. protected $baseUrl;
  1884. protected $basePath;
  1885. protected $method;
  1886. protected $format;
  1887. protected $session;
  1888. protected $locale;
  1889. protected $defaultLocale ='en';
  1890. protected static $formats;
  1891. public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1892. {
  1893. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  1894. }
  1895. public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1896. {
  1897. $this->request = new ParameterBag($request);
  1898. $this->query = new ParameterBag($query);
  1899. $this->attributes = new ParameterBag($attributes);
  1900. $this->cookies = new ParameterBag($cookies);
  1901. $this->files = new FileBag($files);
  1902. $this->server = new ServerBag($server);
  1903. $this->headers = new HeaderBag($this->server->getHeaders());
  1904. $this->content = $content;
  1905. $this->languages = null;
  1906. $this->charsets = null;
  1907. $this->acceptableContentTypes = null;
  1908. $this->pathInfo = null;
  1909. $this->requestUri = null;
  1910. $this->baseUrl = null;
  1911. $this->basePath = null;
  1912. $this->method = null;
  1913. $this->format = null;
  1914. }
  1915. public static function createFromGlobals()
  1916. {
  1917. $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
  1918. if (0 === strpos($request->headers->get('CONTENT_TYPE'),'application/x-www-form-urlencoded')
  1919. && in_array(strtoupper($request->server->get('REQUEST_METHOD','GET')), array('PUT','DELETE','PATCH'))
  1920. ) {
  1921. parse_str($request->getContent(), $data);
  1922. $request->request = new ParameterBag($data);
  1923. }
  1924. return $request;
  1925. }
  1926. public static function create($uri, $method ='GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  1927. {
  1928. $server = array_replace(array('SERVER_NAME'=>'localhost','SERVER_PORT'=> 80,'HTTP_HOST'=>'localhost','HTTP_USER_AGENT'=>'Symfony/2.X','HTTP_ACCEPT'=>'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','HTTP_ACCEPT_LANGUAGE'=>'en-us,en;q=0.5','HTTP_ACCEPT_CHARSET'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'','SCRIPT_FILENAME'=>'','SERVER_PROTOCOL'=>'HTTP/1.1','REQUEST_TIME'=> time(),
  1929. ), $server);
  1930. $server['PATH_INFO'] ='';
  1931. $server['REQUEST_METHOD'] = strtoupper($method);
  1932. $components = parse_url($uri);
  1933. if (isset($components['host'])) {
  1934. $server['SERVER_NAME'] = $components['host'];
  1935. $server['HTTP_HOST'] = $components['host'];
  1936. }
  1937. if (isset($components['scheme'])) {
  1938. if ('https'=== $components['scheme']) {
  1939. $server['HTTPS'] ='on';
  1940. $server['SERVER_PORT'] = 443;
  1941. } else {
  1942. unset($server['HTTPS']);
  1943. $server['SERVER_PORT'] = 80;
  1944. }
  1945. }
  1946. if (isset($components['port'])) {
  1947. $server['SERVER_PORT'] = $components['port'];
  1948. $server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port'];
  1949. }
  1950. if (isset($components['user'])) {
  1951. $server['PHP_AUTH_USER'] = $components['user'];
  1952. }
  1953. if (isset($components['pass'])) {
  1954. $server['PHP_AUTH_PW'] = $components['pass'];
  1955. }
  1956. if (!isset($components['path'])) {
  1957. $components['path'] ='/';
  1958. }
  1959. switch (strtoupper($method)) {
  1960. case'POST':
  1961. case'PUT':
  1962. case'DELETE':
  1963. if (!isset($server['CONTENT_TYPE'])) {
  1964. $server['CONTENT_TYPE'] ='application/x-www-form-urlencoded';
  1965. }
  1966. case'PATCH':
  1967. $request = $parameters;
  1968. $query = array();
  1969. break;
  1970. default:
  1971. $request = array();
  1972. $query = $parameters;
  1973. break;
  1974. }
  1975. if (isset($components['query'])) {
  1976. parse_str(html_entity_decode($components['query']), $qs);
  1977. $query = array_replace($qs, $query);
  1978. }
  1979. $queryString = http_build_query($query,'','&');
  1980. $server['REQUEST_URI'] = $components['path'].(''!== $queryString ?'?'.$queryString :'');
  1981. $server['QUERY_STRING'] = $queryString;
  1982. return new static($query, $request, array(), $cookies, $files, $server, $content);
  1983. }
  1984. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
  1985. {
  1986. $dup = clone $this;
  1987. if ($query !== null) {
  1988. $dup->query = new ParameterBag($query);
  1989. }
  1990. if ($request !== null) {
  1991. $dup->request = new ParameterBag($request);
  1992. }
  1993. if ($attributes !== null) {
  1994. $dup->attributes = new ParameterBag($attributes);
  1995. }
  1996. if ($cookies !== null) {
  1997. $dup->cookies = new ParameterBag($cookies);
  1998. }
  1999. if ($files !== null) {
  2000. $dup->files = new FileBag($files);
  2001. }
  2002. if ($server !== null) {
  2003. $dup->server = new ServerBag($server);
  2004. $dup->headers = new HeaderBag($dup->server->getHeaders());
  2005. }
  2006. $dup->languages = null;
  2007. $dup->charsets = null;
  2008. $dup->acceptableContentTypes = null;
  2009. $dup->pathInfo = null;
  2010. $dup->requestUri = null;
  2011. $dup->baseUrl = null;
  2012. $dup->basePath = null;
  2013. $dup->method = null;
  2014. $dup->format = null;
  2015. return $dup;
  2016. }
  2017. public function __clone()
  2018. {
  2019. $this->query = clone $this->query;
  2020. $this->request = clone $this->request;
  2021. $this->attributes = clone $this->attributes;
  2022. $this->cookies = clone $this->cookies;
  2023. $this->files = clone $this->files;
  2024. $this->server = clone $this->server;
  2025. $this->headers = clone $this->headers;
  2026. }
  2027. public function __toString()
  2028. {
  2029. return
  2030. sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  2031. $this->headers."\r\n".
  2032. $this->getContent();
  2033. }
  2034. public function overrideGlobals()
  2035. {
  2036. $_GET = $this->query->all();
  2037. $_POST = $this->request->all();
  2038. $_SERVER = $this->server->all();
  2039. $_COOKIE = $this->cookies->all();
  2040. foreach ($this->headers->all() as $key => $value) {
  2041. $key = strtoupper(str_replace('-','_', $key));
  2042. if (in_array($key, array('CONTENT_TYPE','CONTENT_LENGTH'))) {
  2043. $_SERVER[$key] = implode(', ', $value);
  2044. } else {
  2045. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  2046. }
  2047. }
  2048. $request = array('g'=> $_GET,'p'=> $_POST,'c'=> $_COOKIE);
  2049. $requestOrder = ini_get('request_order') ?: ini_get('variable_order');
  2050. $requestOrder = preg_replace('#[^cgp]#','', strtolower($requestOrder)) ?:'gp';
  2051. $_REQUEST = array();
  2052. foreach (str_split($requestOrder) as $order) {
  2053. $_REQUEST = array_merge($_REQUEST, $request[$order]);
  2054. }
  2055. }
  2056. public static function trustProxyData()
  2057. {
  2058. trigger_error('trustProxyData() is deprecated since version 2.0 and will be removed in 2.3. Use setTrustedProxies() instead.', E_USER_DEPRECATED);
  2059. self::$trustProxy = true;
  2060. }
  2061. public static function setTrustedProxies(array $proxies)
  2062. {
  2063. self::$trustedProxies = $proxies;
  2064. self::$trustProxy = $proxies ? true : false;
  2065. }
  2066. public static function getTrustedProxies()
  2067. {
  2068. return self::$trustedProxies;
  2069. }
  2070. public static function setTrustedHeaderName($key, $value)
  2071. {
  2072. if (!array_key_exists($key, self::$trustedHeaders)) {
  2073. throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
  2074. }
  2075. self::$trustedHeaders[$key] = $value;
  2076. }
  2077. public static function isProxyTrusted()
  2078. {
  2079. return self::$trustProxy;
  2080. }
  2081. public static function normalizeQueryString($qs)
  2082. {
  2083. if (''== $qs) {
  2084. return'';
  2085. }
  2086. $parts = array();
  2087. $order = array();
  2088. foreach (explode('&', $qs) as $param) {
  2089. if (''=== $param ||'='=== $param[0]) {
  2090. continue;
  2091. }
  2092. $keyValuePair = explode('=', $param, 2);
  2093. $parts[] = isset($keyValuePair[1]) ?
  2094. rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
  2095. rawurlencode(urldecode($keyValuePair[0]));
  2096. $order[] = urldecode($keyValuePair[0]);
  2097. }
  2098. array_multisort($order, SORT_ASC, $parts);
  2099. return implode('&', $parts);
  2100. }
  2101. public static function enableHttpMethodParameterOverride()
  2102. {
  2103. self::$httpMethodParameterOverride = true;
  2104. }
  2105. public static function getHttpMethodParameterOverride()
  2106. {
  2107. return self::$httpMethodParameterOverride;
  2108. }
  2109. public function get($key, $default = null, $deep = false)
  2110. {
  2111. return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default, $deep), $deep), $deep);
  2112. }
  2113. public function getSession()
  2114. {
  2115. return $this->session;
  2116. }
  2117. public function hasPreviousSession()
  2118. {
  2119. return $this->hasSession() && $this->cookies->has($this->session->getName());
  2120. }
  2121. public function hasSession()
  2122. {
  2123. return null !== $this->session;
  2124. }
  2125. public function setSession(SessionInterface $session)
  2126. {
  2127. $this->session = $session;
  2128. }
  2129. public function getClientIp()
  2130. {
  2131. $ip = $this->server->get('REMOTE_ADDR');
  2132. if (!self::$trustProxy) {
  2133. return $ip;
  2134. }
  2135. if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
  2136. return $ip;
  2137. }
  2138. $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
  2139. $clientIps[] = $ip;
  2140. $trustedProxies = self::$trustProxy && !self::$trustedProxies ? array($ip) : self::$trustedProxies;
  2141. $clientIps = array_diff($clientIps, $trustedProxies);
  2142. return array_pop($clientIps);
  2143. }
  2144. public function getScriptName()
  2145. {
  2146. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME',''));
  2147. }
  2148. public function getPathInfo()
  2149. {
  2150. if (null === $this->pathInfo) {
  2151. $this->pathInfo = $this->preparePathInfo();
  2152. }
  2153. return $this->pathInfo;
  2154. }
  2155. public function getBasePath()
  2156. {
  2157. if (null === $this->basePath) {
  2158. $this->basePath = $this->prepareBasePath();
  2159. }
  2160. return $this->basePath;
  2161. }
  2162. public function getBaseUrl()
  2163. {
  2164. if (null === $this->baseUrl) {
  2165. $this->baseUrl = $this->prepareBaseUrl();
  2166. }
  2167. return $this->baseUrl;
  2168. }
  2169. public function getScheme()
  2170. {
  2171. return $this->isSecure() ?'https':'http';
  2172. }
  2173. public function getPort()
  2174. {
  2175. if (self::$trustProxy && self::$trustedHeaders[self::HEADER_CLIENT_PORT] && $port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT])) {
  2176. return $port;
  2177. }
  2178. return $this->server->get('SERVER_PORT');
  2179. }
  2180. public function getUser()
  2181. {
  2182. return $this->server->get('PHP_AUTH_USER');
  2183. }
  2184. public function getPassword()
  2185. {
  2186. return $this->server->get('PHP_AUTH_PW');
  2187. }
  2188. public function getUserInfo()
  2189. {
  2190. $userinfo = $this->getUser();
  2191. $pass = $this->getPassword();
  2192. if (''!= $pass) {
  2193. $userinfo .= ":$pass";
  2194. }
  2195. return $userinfo;
  2196. }
  2197. public function getHttpHost()
  2198. {
  2199. $scheme = $this->getScheme();
  2200. $port = $this->getPort();
  2201. if (('http'== $scheme && $port == 80) || ('https'== $scheme && $port == 443)) {
  2202. return $this->getHost();
  2203. }
  2204. return $this->getHost().':'.$port;
  2205. }
  2206. public function getRequestUri()
  2207. {
  2208. if (null === $this->requestUri) {
  2209. $this->requestUri = $this->prepareRequestUri();
  2210. }
  2211. return $this->requestUri;
  2212. }
  2213. public function getSchemeAndHttpHost()
  2214. {
  2215. return $this->getScheme().'://'.$this->getHttpHost();
  2216. }
  2217. public function getUri()
  2218. {
  2219. if (null !== $qs = $this->getQueryString()) {
  2220. $qs ='?'.$qs;
  2221. }
  2222. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  2223. }
  2224. public function getUriForPath($path)
  2225. {
  2226. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
  2227. }
  2228. public function getQueryString()
  2229. {
  2230. $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
  2231. return''=== $qs ? null : $qs;
  2232. }
  2233. public function isSecure()
  2234. {
  2235. if (self::$trustProxy && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
  2236. return in_array(strtolower($proto), array('https','on','1'));
  2237. }
  2238. return'on'== strtolower($this->server->get('HTTPS')) || 1 == $this->server->get('HTTPS');
  2239. }
  2240. public function getHost()
  2241. {
  2242. if (self::$trustProxy && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
  2243. $elements = explode(',', $host);
  2244. $host = $elements[count($elements) - 1];
  2245. } elseif (!$host = $this->headers->get('HOST')) {
  2246. if (!$host = $this->server->get('SERVER_NAME')) {
  2247. $host = $this->server->get('SERVER_ADDR','');
  2248. }
  2249. }
  2250. $host = strtolower(preg_replace('/:\d+$/','', trim($host)));
  2251. if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) {
  2252. throw new \UnexpectedValueException('Invalid Host');
  2253. }
  2254. return $host;
  2255. }
  2256. public function setMethod($method)
  2257. {
  2258. $this->method = null;
  2259. $this->server->set('REQUEST_METHOD', $method);
  2260. }
  2261. public function getMethod()
  2262. {
  2263. if (null === $this->method) {
  2264. $this->method = strtoupper($this->server->get('REQUEST_METHOD','GET'));
  2265. if ('POST'=== $this->method) {
  2266. if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
  2267. $this->method = strtoupper($method);
  2268. } elseif (self::$httpMethodParameterOverride) {
  2269. $this->method = strtoupper($this->request->get('_method', $this->query->get('_method','POST')));
  2270. }
  2271. }
  2272. }
  2273. return $this->method;
  2274. }
  2275. public function getRealMethod()
  2276. {
  2277. return strtoupper($this->server->get('REQUEST_METHOD','GET'));
  2278. }
  2279. public function getMimeType($format)
  2280. {
  2281. if (null === static::$formats) {
  2282. static::initializeFormats();
  2283. }
  2284. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  2285. }
  2286. public function getFormat($mimeType)
  2287. {
  2288. if (false !== $pos = strpos($mimeType,';')) {
  2289. $mimeType = substr($mimeType, 0, $pos);
  2290. }
  2291. if (null === static::$formats) {
  2292. static::initializeFormats();
  2293. }
  2294. foreach (static::$formats as $format => $mimeTypes) {
  2295. if (in_array($mimeType, (array) $mimeTypes)) {
  2296. return $format;
  2297. }
  2298. }
  2299. return null;
  2300. }
  2301. public function setFormat($format, $mimeTypes)
  2302. {
  2303. if (null === static::$formats) {
  2304. static::initializeFormats();
  2305. }
  2306. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  2307. }
  2308. public function getRequestFormat($default ='html')
  2309. {
  2310. if (null === $this->format) {
  2311. $this->format = $this->get('_format', $default);
  2312. }
  2313. return $this->format;
  2314. }
  2315. public function setRequestFormat($format)
  2316. {
  2317. $this->format = $format;
  2318. }
  2319. public function getContentType()
  2320. {
  2321. return $this->getFormat($this->headers->get('CONTENT_TYPE'));
  2322. }
  2323. public function setDefaultLocale($locale)
  2324. {
  2325. $this->defaultLocale = $locale;
  2326. if (null === $this->locale) {
  2327. $this->setPhpDefaultLocale($locale);
  2328. }
  2329. }
  2330. public function setLocale($locale)
  2331. {
  2332. $this->setPhpDefaultLocale($this->locale = $locale);
  2333. }
  2334. public function getLocale()
  2335. {
  2336. return null === $this->locale ? $this->defaultLocale : $this->locale;
  2337. }
  2338. public function isMethod($method)
  2339. {
  2340. return $this->getMethod() === strtoupper($method);
  2341. }
  2342. public function isMethodSafe()
  2343. {
  2344. return in_array($this->getMethod(), array('GET','HEAD'));
  2345. }
  2346. public function getContent($asResource = false)
  2347. {
  2348. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  2349. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  2350. }
  2351. if (true === $asResource) {
  2352. $this->content = false;
  2353. return fopen('php://input','rb');
  2354. }
  2355. if (null === $this->content) {
  2356. $this->content = file_get_contents('php://input');
  2357. }
  2358. return $this->content;
  2359. }
  2360. public function getETags()
  2361. {
  2362. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  2363. }
  2364. public function isNoCache()
  2365. {
  2366. return $this->headers->hasCacheControlDirective('no-cache') ||'no-cache'== $this->headers->get('Pragma');
  2367. }
  2368. public function getPreferredLanguage(array $locales = null)
  2369. {
  2370. $preferredLanguages = $this->getLanguages();
  2371. if (empty($locales)) {
  2372. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  2373. }
  2374. if (!$preferredLanguages) {
  2375. return $locales[0];
  2376. }
  2377. $extendedPreferredLanguages = array();
  2378. foreach ($preferredLanguages as $language) {
  2379. $extendedPreferredLanguages[] = $language;
  2380. if (false !== $position = strpos($language,'_')) {
  2381. $superLanguage = substr($language, 0, $position);
  2382. if (!in_array($superLanguage, $preferredLanguages)) {
  2383. $extendedPreferredLanguages[] = $superLanguage;
  2384. }
  2385. }
  2386. }
  2387. $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
  2388. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  2389. }
  2390. public function getLanguages()
  2391. {
  2392. if (null !== $this->languages) {
  2393. return $this->languages;
  2394. }
  2395. $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
  2396. $this->languages = array();
  2397. foreach (array_keys($languages) as $lang) {
  2398. if (strstr($lang,'-')) {
  2399. $codes = explode('-', $lang);
  2400. if ($codes[0] =='i') {
  2401. if (count($codes) > 1) {
  2402. $lang = $codes[1];
  2403. }
  2404. } else {
  2405. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  2406. if ($i == 0) {
  2407. $lang = strtolower($codes[0]);
  2408. } else {
  2409. $lang .='_'.strtoupper($codes[$i]);
  2410. }
  2411. }
  2412. }
  2413. }
  2414. $this->languages[] = $lang;
  2415. }
  2416. return $this->languages;
  2417. }
  2418. public function getCharsets()
  2419. {
  2420. if (null !== $this->charsets) {
  2421. return $this->charsets;
  2422. }
  2423. return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
  2424. }
  2425. public function getAcceptableContentTypes()
  2426. {
  2427. if (null !== $this->acceptableContentTypes) {
  2428. return $this->acceptableContentTypes;
  2429. }
  2430. return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
  2431. }
  2432. public function isXmlHttpRequest()
  2433. {
  2434. return'XMLHttpRequest'== $this->headers->get('X-Requested-With');
  2435. }
  2436. public function splitHttpAcceptHeader($header)
  2437. {
  2438. trigger_error('splitHttpAcceptHeader() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
  2439. $headers = array();
  2440. foreach (AcceptHeader::fromString($header)->all() as $item) {
  2441. $key = $item->getValue();
  2442. foreach ($item->getAttributes() as $name => $value) {
  2443. $key .= sprintf(';%s=%s', $name, $value);
  2444. }
  2445. $headers[$key] = $item->getQuality();
  2446. }
  2447. return $headers;
  2448. }
  2449. protected function prepareRequestUri()
  2450. {
  2451. $requestUri ='';
  2452. if ($this->headers->has('X_ORIGINAL_URL') && false !== stripos(PHP_OS,'WIN')) {
  2453. $requestUri = $this->headers->get('X_ORIGINAL_URL');
  2454. $this->headers->remove('X_ORIGINAL_URL');
  2455. } elseif ($this->headers->has('X_REWRITE_URL') && false !== stripos(PHP_OS,'WIN')) {
  2456. $requestUri = $this->headers->get('X_REWRITE_URL');
  2457. $this->headers->remove('X_REWRITE_URL');
  2458. } elseif ($this->server->get('IIS_WasUrlRewritten') =='1'&& $this->server->get('UNENCODED_URL') !='') {
  2459. $requestUri = $this->server->get('UNENCODED_URL');
  2460. $this->server->remove('UNENCODED_URL');
  2461. $this->server->remove('IIS_WasUrlRewritten');
  2462. } elseif ($this->server->has('REQUEST_URI')) {
  2463. $requestUri = $this->server->get('REQUEST_URI');
  2464. $schemeAndHttpHost = $this->getSchemeAndHttpHost();
  2465. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  2466. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  2467. }
  2468. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  2469. $requestUri = $this->server->get('ORIG_PATH_INFO');
  2470. if (''!= $this->server->get('QUERY_STRING')) {
  2471. $requestUri .='?'.$this->server->get('QUERY_STRING');
  2472. }
  2473. $this->server->remove('ORIG_PATH_INFO');
  2474. }
  2475. $this->server->set('REQUEST_URI', $requestUri);
  2476. return $requestUri;
  2477. }
  2478. protected function prepareBaseUrl()
  2479. {
  2480. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  2481. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  2482. $baseUrl = $this->server->get('SCRIPT_NAME');
  2483. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  2484. $baseUrl = $this->server->get('PHP_SELF');
  2485. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  2486. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); } else {
  2487. $path = $this->server->get('PHP_SELF','');
  2488. $file = $this->server->get('SCRIPT_FILENAME','');
  2489. $segs = explode('/', trim($file,'/'));
  2490. $segs = array_reverse($segs);
  2491. $index = 0;
  2492. $last = count($segs);
  2493. $baseUrl ='';
  2494. do {
  2495. $seg = $segs[$index];
  2496. $baseUrl ='/'.$seg.$baseUrl;
  2497. ++$index;
  2498. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  2499. }
  2500. $requestUri = $this->getRequestUri();
  2501. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
  2502. return $prefix;
  2503. }
  2504. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, dirname($baseUrl))) {
  2505. return rtrim($prefix,'/');
  2506. }
  2507. $truncatedRequestUri = $requestUri;
  2508. if (($pos = strpos($requestUri,'?')) !== false) {
  2509. $truncatedRequestUri = substr($requestUri, 0, $pos);
  2510. }
  2511. $basename = basename($baseUrl);
  2512. if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
  2513. return'';
  2514. }
  2515. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  2516. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  2517. }
  2518. return rtrim($baseUrl,'/');
  2519. }
  2520. protected function prepareBasePath()
  2521. {
  2522. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  2523. $baseUrl = $this->getBaseUrl();
  2524. if (empty($baseUrl)) {
  2525. return'';
  2526. }
  2527. if (basename($baseUrl) === $filename) {
  2528. $basePath = dirname($baseUrl);
  2529. } else {
  2530. $basePath = $baseUrl;
  2531. }
  2532. if ('\\'=== DIRECTORY_SEPARATOR) {
  2533. $basePath = str_replace('\\','/', $basePath);
  2534. }
  2535. return rtrim($basePath,'/');
  2536. }
  2537. protected function preparePathInfo()
  2538. {
  2539. $baseUrl = $this->getBaseUrl();
  2540. if (null === ($requestUri = $this->getRequestUri())) {
  2541. return'/';
  2542. }
  2543. $pathInfo ='/';
  2544. if ($pos = strpos($requestUri,'?')) {
  2545. $requestUri = substr($requestUri, 0, $pos);
  2546. }
  2547. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  2548. return'/';
  2549. } elseif (null === $baseUrl) {
  2550. return $requestUri;
  2551. }
  2552. return (string) $pathInfo;
  2553. }
  2554. protected static function initializeFormats()
  2555. {
  2556. static::$formats = array('html'=> array('text/html','application/xhtml+xml'),'txt'=> array('text/plain'),'js'=> array('application/javascript','application/x-javascript','text/javascript'),'css'=> array('text/css'),'json'=> array('application/json','application/x-json'),'xml'=> array('text/xml','application/xml','application/x-xml'),'rdf'=> array('application/rdf+xml'),'atom'=> array('application/atom+xml'),'rss'=> array('application/rss+xml'),
  2557. );
  2558. }
  2559. private function setPhpDefaultLocale($locale)
  2560. {
  2561. try {
  2562. if (class_exists('Locale', false)) {
  2563. \Locale::setDefault($locale);
  2564. }
  2565. } catch (\Exception $e) {
  2566. }
  2567. }
  2568. private function getUrlencodedPrefix($string, $prefix)
  2569. {
  2570. if (0 !== strpos(rawurldecode($string), $prefix)) {
  2571. return false;
  2572. }
  2573. $len = strlen($prefix);
  2574. if (preg_match("#^(%[[:xdigit:]]{2}|.){{$len}}#", $string, $match)) {
  2575. return $match[0];
  2576. }
  2577. return false;
  2578. }
  2579. }
  2580. }
  2581. namespace Symfony\Component\HttpFoundation
  2582. {
  2583. class Response
  2584. {
  2585. public $headers;
  2586. protected $content;
  2587. protected $version;
  2588. protected $statusCode;
  2589. protected $statusText;
  2590. protected $charset;
  2591. public static $statusTexts = array(
  2592. 100 =>'Continue',
  2593. 101 =>'Switching Protocols',
  2594. 102 =>'Processing', 200 =>'OK',
  2595. 201 =>'Created',
  2596. 202 =>'Accepted',
  2597. 203 =>'Non-Authoritative Information',
  2598. 204 =>'No Content',
  2599. 205 =>'Reset Content',
  2600. 206 =>'Partial Content',
  2601. 207 =>'Multi-Status', 208 =>'Already Reported', 226 =>'IM Used', 300 =>'Multiple Choices',
  2602. 301 =>'Moved Permanently',
  2603. 302 =>'Found',
  2604. 303 =>'See Other',
  2605. 304 =>'Not Modified',
  2606. 305 =>'Use Proxy',
  2607. 306 =>'Reserved',
  2608. 307 =>'Temporary Redirect',
  2609. 308 =>'Permanent Redirect', 400 =>'Bad Request',
  2610. 401 =>'Unauthorized',
  2611. 402 =>'Payment Required',
  2612. 403 =>'Forbidden',
  2613. 404 =>'Not Found',
  2614. 405 =>'Method Not Allowed',
  2615. 406 =>'Not Acceptable',
  2616. 407 =>'Proxy Authentication Required',
  2617. 408 =>'Request Timeout',
  2618. 409 =>'Conflict',
  2619. 410 =>'Gone',
  2620. 411 =>'Length Required',
  2621. 412 =>'Precondition Failed',
  2622. 413 =>'Request Entity Too Large',
  2623. 414 =>'Request-URI Too Long',
  2624. 415 =>'Unsupported Media Type',
  2625. 416 =>'Requested Range Not Satisfiable',
  2626. 417 =>'Expectation Failed',
  2627. 418 =>'I\'m a teapot', 422 =>'Unprocessable Entity', 423 =>'Locked', 424 =>'Failed Dependency', 425 =>'Reserved for WebDAV advanced collections expired proposal', 426 =>'Upgrade Required', 428 =>'Precondition Required', 429 =>'Too Many Requests', 431 =>'Request Header Fields Too Large', 500 =>'Internal Server Error',
  2628. 501 =>'Not Implemented',
  2629. 502 =>'Bad Gateway',
  2630. 503 =>'Service Unavailable',
  2631. 504 =>'Gateway Timeout',
  2632. 505 =>'HTTP Version Not Supported',
  2633. 506 =>'Variant Also Negotiates (Experimental)', 507 =>'Insufficient Storage', 508 =>'Loop Detected', 510 =>'Not Extended', 511 =>'Network Authentication Required', );
  2634. public function __construct($content ='', $status = 200, $headers = array())
  2635. {
  2636. $this->headers = new ResponseHeaderBag($headers);
  2637. $this->setContent($content);
  2638. $this->setStatusCode($status);
  2639. $this->setProtocolVersion('1.0');
  2640. if (!$this->headers->has('Date')) {
  2641. $this->setDate(new \DateTime(null, new \DateTimeZone('UTC')));
  2642. }
  2643. }
  2644. public static function create($content ='', $status = 200, $headers = array())
  2645. {
  2646. return new static($content, $status, $headers);
  2647. }
  2648. public function __toString()
  2649. {
  2650. return
  2651. sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
  2652. $this->headers."\r\n".
  2653. $this->getContent();
  2654. }
  2655. public function __clone()
  2656. {
  2657. $this->headers = clone $this->headers;
  2658. }
  2659. public function prepare(Request $request)
  2660. {
  2661. $headers = $this->headers;
  2662. if ($this->isInformational() || in_array($this->statusCode, array(204, 304))) {
  2663. $this->setContent(null);
  2664. }
  2665. if (!$headers->has('Content-Type')) {
  2666. $format = $request->getRequestFormat();
  2667. if (null !== $format && $mimeType = $request->getMimeType($format)) {
  2668. $headers->set('Content-Type', $mimeType);
  2669. }
  2670. }
  2671. $charset = $this->charset ?:'UTF-8';
  2672. if (!$headers->has('Content-Type')) {
  2673. $headers->set('Content-Type','text/html; charset='.$charset);
  2674. } elseif (0 === strpos($headers->get('Content-Type'),'text/') && false === strpos($headers->get('Content-Type'),'charset')) {
  2675. $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
  2676. }
  2677. if ($headers->has('Transfer-Encoding')) {
  2678. $headers->remove('Content-Length');
  2679. }
  2680. if ($request->isMethod('HEAD')) {
  2681. $length = $headers->get('Content-Length');
  2682. $this->setContent(null);
  2683. if ($length) {
  2684. $headers->set('Content-Length', $length);
  2685. }
  2686. }
  2687. if ('HTTP/1.0'!= $request->server->get('SERVER_PROTOCOL')) {
  2688. $this->setProtocolVersion('1.1');
  2689. }
  2690. if ('1.0'== $this->getProtocolVersion() &&'no-cache'== $this->headers->get('Cache-Control')) {
  2691. $this->headers->set('pragma','no-cache');
  2692. $this->headers->set('expires', -1);
  2693. }
  2694. if (false !== stripos($this->headers->get('Content-Disposition'),'attachment') && preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) == 1 && true === $request->isSecure()) {
  2695. if (intval(preg_replace("/(MSIE )(.*?);/","$2", $match[0])) < 9) {
  2696. $this->headers->remove('Cache-Control');
  2697. }
  2698. }
  2699. return $this;
  2700. }
  2701. public function sendHeaders()
  2702. {
  2703. if (headers_sent()) {
  2704. return $this;
  2705. }
  2706. header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
  2707. foreach ($this->headers->allPreserveCase() as $name => $values) {
  2708. foreach ($values as $value) {
  2709. header($name.': '.$value, false);
  2710. }
  2711. }
  2712. foreach ($this->headers->getCookies() as $cookie) {
  2713. setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
  2714. }
  2715. return $this;
  2716. }
  2717. public function sendContent()
  2718. {
  2719. echo $this->content;
  2720. return $this;
  2721. }
  2722. public function send()
  2723. {
  2724. $this->sendHeaders();
  2725. $this->sendContent();
  2726. if (function_exists('fastcgi_finish_request')) {
  2727. fastcgi_finish_request();
  2728. } elseif ('cli'!== PHP_SAPI) {
  2729. $previous = null;
  2730. $obStatus = ob_get_status(1);
  2731. while (($level = ob_get_level()) > 0 && $level !== $previous) {
  2732. $previous = $level;
  2733. if ($obStatus[$level - 1] && isset($obStatus[$level - 1]['del']) && $obStatus[$level - 1]['del']) {
  2734. ob_end_flush();
  2735. }
  2736. }
  2737. flush();
  2738. }
  2739. return $this;
  2740. }
  2741. public function setContent($content)
  2742. {
  2743. if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content,'__toString'))) {
  2744. throw new \UnexpectedValueException('The Response content must be a string or object implementing __toString(), "'.gettype($content).'" given.');
  2745. }
  2746. $this->content = (string) $content;
  2747. return $this;
  2748. }
  2749. public function getContent()
  2750. {
  2751. return $this->content;
  2752. }
  2753. public function setProtocolVersion($version)
  2754. {
  2755. $this->version = $version;
  2756. return $this;
  2757. }
  2758. public function getProtocolVersion()
  2759. {
  2760. return $this->version;
  2761. }
  2762. public function setStatusCode($code, $text = null)
  2763. {
  2764. $this->statusCode = $code = (int) $code;
  2765. if ($this->isInvalid()) {
  2766. throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
  2767. }
  2768. if (null === $text) {
  2769. $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] :'';
  2770. return $this;
  2771. }
  2772. if (false === $text) {
  2773. $this->statusText ='';
  2774. return $this;
  2775. }
  2776. $this->statusText = $text;
  2777. return $this;
  2778. }
  2779. public function getStatusCode()
  2780. {
  2781. return $this->statusCode;
  2782. }
  2783. public function setCharset($charset)
  2784. {
  2785. $this->charset = $charset;
  2786. return $this;
  2787. }
  2788. public function getCharset()
  2789. {
  2790. return $this->charset;
  2791. }
  2792. public function isCacheable()
  2793. {
  2794. if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
  2795. return false;
  2796. }
  2797. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  2798. return false;
  2799. }
  2800. return $this->isValidateable() || $this->isFresh();
  2801. }
  2802. public function isFresh()
  2803. {
  2804. return $this->getTtl() > 0;
  2805. }
  2806. public function isValidateable()
  2807. {
  2808. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  2809. }
  2810. public function setPrivate()
  2811. {
  2812. $this->headers->removeCacheControlDirective('public');
  2813. $this->headers->addCacheControlDirective('private');
  2814. return $this;
  2815. }
  2816. public function setPublic()
  2817. {
  2818. $this->headers->addCacheControlDirective('public');
  2819. $this->headers->removeCacheControlDirective('private');
  2820. return $this;
  2821. }
  2822. public function mustRevalidate()
  2823. {
  2824. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->has('proxy-revalidate');
  2825. }
  2826. public function getDate()
  2827. {
  2828. return $this->headers->getDate('Date', new \DateTime());
  2829. }
  2830. public function setDate(\DateTime $date)
  2831. {
  2832. $date->setTimezone(new \DateTimeZone('UTC'));
  2833. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  2834. return $this;
  2835. }
  2836. public function getAge()
  2837. {
  2838. if (null !== $age = $this->headers->get('Age')) {
  2839. return (int) $age;
  2840. }
  2841. return max(time() - $this->getDate()->format('U'), 0);
  2842. }
  2843. public function expire()
  2844. {
  2845. if ($this->isFresh()) {
  2846. $this->headers->set('Age', $this->getMaxAge());
  2847. }
  2848. return $this;
  2849. }
  2850. public function getExpires()
  2851. {
  2852. try {
  2853. return $this->headers->getDate('Expires');
  2854. } catch (\RuntimeException $e) {
  2855. return \DateTime::createFromFormat(DATE_RFC2822,'Sat, 01 Jan 00 00:00:00 +0000');
  2856. }
  2857. }
  2858. public function setExpires(\DateTime $date = null)
  2859. {
  2860. if (null === $date) {
  2861. $this->headers->remove('Expires');
  2862. } else {
  2863. $date = clone $date;
  2864. $date->setTimezone(new \DateTimeZone('UTC'));
  2865. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  2866. }
  2867. return $this;
  2868. }
  2869. public function getMaxAge()
  2870. {
  2871. if ($this->headers->hasCacheControlDirective('s-maxage')) {
  2872. return (int) $this->headers->getCacheControlDirective('s-maxage');
  2873. }
  2874. if ($this->headers->hasCacheControlDirective('max-age')) {
  2875. return (int) $this->headers->getCacheControlDirective('max-age');
  2876. }
  2877. if (null !== $this->getExpires()) {
  2878. return $this->getExpires()->format('U') - $this->getDate()->format('U');
  2879. }
  2880. return null;
  2881. }
  2882. public function setMaxAge($value)
  2883. {
  2884. $this->headers->addCacheControlDirective('max-age', $value);
  2885. return $this;
  2886. }
  2887. public function setSharedMaxAge($value)
  2888. {
  2889. $this->setPublic();
  2890. $this->headers->addCacheControlDirective('s-maxage', $value);
  2891. return $this;
  2892. }
  2893. public function getTtl()
  2894. {
  2895. if (null !== $maxAge = $this->getMaxAge()) {
  2896. return $maxAge - $this->getAge();
  2897. }
  2898. return null;
  2899. }
  2900. public function setTtl($seconds)
  2901. {
  2902. $this->setSharedMaxAge($this->getAge() + $seconds);
  2903. return $this;
  2904. }
  2905. public function setClientTtl($seconds)
  2906. {
  2907. $this->setMaxAge($this->getAge() + $seconds);
  2908. return $this;
  2909. }
  2910. public function getLastModified()
  2911. {
  2912. return $this->headers->getDate('Last-Modified');
  2913. }
  2914. public function setLastModified(\DateTime $date = null)
  2915. {
  2916. if (null === $date) {
  2917. $this->headers->remove('Last-Modified');
  2918. } else {
  2919. $date = clone $date;
  2920. $date->setTimezone(new \DateTimeZone('UTC'));
  2921. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  2922. }
  2923. return $this;
  2924. }
  2925. public function getEtag()
  2926. {
  2927. return $this->headers->get('ETag');
  2928. }
  2929. public function setEtag($etag = null, $weak = false)
  2930. {
  2931. if (null === $etag) {
  2932. $this->headers->remove('Etag');
  2933. } else {
  2934. if (0 !== strpos($etag,'"')) {
  2935. $etag ='"'.$etag.'"';
  2936. }
  2937. $this->headers->set('ETag', (true === $weak ?'W/':'').$etag);
  2938. }
  2939. return $this;
  2940. }
  2941. public function setCache(array $options)
  2942. {
  2943. if ($diff = array_diff(array_keys($options), array('etag','last_modified','max_age','s_maxage','private','public'))) {
  2944. throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff))));
  2945. }
  2946. if (isset($options['etag'])) {
  2947. $this->setEtag($options['etag']);
  2948. }
  2949. if (isset($options['last_modified'])) {
  2950. $this->setLastModified($options['last_modified']);
  2951. }
  2952. if (isset($options['max_age'])) {
  2953. $this->setMaxAge($options['max_age']);
  2954. }
  2955. if (isset($options['s_maxage'])) {
  2956. $this->setSharedMaxAge($options['s_maxage']);
  2957. }
  2958. if (isset($options['public'])) {
  2959. if ($options['public']) {
  2960. $this->setPublic();
  2961. } else {
  2962. $this->setPrivate();
  2963. }
  2964. }
  2965. if (isset($options['private'])) {
  2966. if ($options['private']) {
  2967. $this->setPrivate();
  2968. } else {
  2969. $this->setPublic();
  2970. }
  2971. }
  2972. return $this;
  2973. }
  2974. public function setNotModified()
  2975. {
  2976. $this->setStatusCode(304);
  2977. $this->setContent(null);
  2978. foreach (array('Allow','Content-Encoding','Content-Language','Content-Length','Content-MD5','Content-Type','Last-Modified') as $header) {
  2979. $this->headers->remove($header);
  2980. }
  2981. return $this;
  2982. }
  2983. public function hasVary()
  2984. {
  2985. return null !== $this->headers->get('Vary');
  2986. }
  2987. public function getVary()
  2988. {
  2989. if (!$vary = $this->headers->get('Vary')) {
  2990. return array();
  2991. }
  2992. return is_array($vary) ? $vary : preg_split('/[\s,]+/', $vary);
  2993. }
  2994. public function setVary($headers, $replace = true)
  2995. {
  2996. $this->headers->set('Vary', $headers, $replace);
  2997. return $this;
  2998. }
  2999. public function isNotModified(Request $request)
  3000. {
  3001. if (!$request->isMethodSafe()) {
  3002. return false;
  3003. }
  3004. $lastModified = $request->headers->get('If-Modified-Since');
  3005. $notModified = false;
  3006. if ($etags = $request->getEtags()) {
  3007. $notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
  3008. } elseif ($lastModified) {
  3009. $notModified = $lastModified == $this->headers->get('Last-Modified');
  3010. }
  3011. if ($notModified) {
  3012. $this->setNotModified();
  3013. }
  3014. return $notModified;
  3015. }
  3016. public function isInvalid()
  3017. {
  3018. return $this->statusCode < 100 || $this->statusCode >= 600;
  3019. }
  3020. public function isInformational()
  3021. {
  3022. return $this->statusCode >= 100 && $this->statusCode < 200;
  3023. }
  3024. public function isSuccessful()
  3025. {
  3026. return $this->statusCode >= 200 && $this->statusCode < 300;
  3027. }
  3028. public function isRedirection()
  3029. {
  3030. return $this->statusCode >= 300 && $this->statusCode < 400;
  3031. }
  3032. public function isClientError()
  3033. {
  3034. return $this->statusCode >= 400 && $this->statusCode < 500;
  3035. }
  3036. public function isServerError()
  3037. {
  3038. return $this->statusCode >= 500 && $this->statusCode < 600;
  3039. }
  3040. public function isOk()
  3041. {
  3042. return 200 === $this->statusCode;
  3043. }
  3044. public function isForbidden()
  3045. {
  3046. return 403 === $this->statusCode;
  3047. }
  3048. public function isNotFound()
  3049. {
  3050. return 404 === $this->statusCode;
  3051. }
  3052. public function isRedirect($location = null)
  3053. {
  3054. return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
  3055. }
  3056. public function isEmpty()
  3057. {
  3058. return in_array($this->statusCode, array(201, 204, 304));
  3059. }
  3060. }
  3061. }
  3062. namespace Symfony\Component\HttpFoundation
  3063. {
  3064. class ResponseHeaderBag extends HeaderBag
  3065. {
  3066. const COOKIES_FLAT ='flat';
  3067. const COOKIES_ARRAY ='array';
  3068. const DISPOSITION_ATTACHMENT ='attachment';
  3069. const DISPOSITION_INLINE ='inline';
  3070. protected $computedCacheControl = array();
  3071. protected $cookies = array();
  3072. protected $headerNames = array();
  3073. public function __construct(array $headers = array())
  3074. {
  3075. parent::__construct($headers);
  3076. if (!isset($this->headers['cache-control'])) {
  3077. $this->set('Cache-Control','');
  3078. }
  3079. }
  3080. public function __toString()
  3081. {
  3082. $cookies ='';
  3083. foreach ($this->getCookies() as $cookie) {
  3084. $cookies .='Set-Cookie: '.$cookie."\r\n";
  3085. }
  3086. ksort($this->headerNames);
  3087. return parent::__toString().$cookies;
  3088. }
  3089. public function allPreserveCase()
  3090. {
  3091. return array_combine($this->headerNames, $this->headers);
  3092. }
  3093. public function replace(array $headers = array())
  3094. {
  3095. $this->headerNames = array();
  3096. parent::replace($headers);
  3097. if (!isset($this->headers['cache-control'])) {
  3098. $this->set('Cache-Control','');
  3099. }
  3100. }
  3101. public function set($key, $values, $replace = true)
  3102. {
  3103. parent::set($key, $values, $replace);
  3104. $uniqueKey = strtr(strtolower($key),'_','-');
  3105. $this->headerNames[$uniqueKey] = $key;
  3106. if (in_array($uniqueKey, array('cache-control','etag','last-modified','expires'))) {
  3107. $computed = $this->computeCacheControlValue();
  3108. $this->headers['cache-control'] = array($computed);
  3109. $this->headerNames['cache-control'] ='Cache-Control';
  3110. $this->computedCacheControl = $this->parseCacheControl($computed);
  3111. }
  3112. }
  3113. public function remove($key)
  3114. {
  3115. parent::remove($key);
  3116. $uniqueKey = strtr(strtolower($key),'_','-');
  3117. unset($this->headerNames[$uniqueKey]);
  3118. if ('cache-control'=== $uniqueKey) {
  3119. $this->computedCacheControl = array();
  3120. }
  3121. }
  3122. public function hasCacheControlDirective($key)
  3123. {
  3124. return array_key_exists($key, $this->computedCacheControl);
  3125. }
  3126. public function getCacheControlDirective($key)
  3127. {
  3128. return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
  3129. }
  3130. public function setCookie(Cookie $cookie)
  3131. {
  3132. $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  3133. }
  3134. public function removeCookie($name, $path ='/', $domain = null)
  3135. {
  3136. if (null === $path) {
  3137. $path ='/';
  3138. }
  3139. unset($this->cookies[$domain][$path][$name]);
  3140. if (empty($this->cookies[$domain][$path])) {
  3141. unset($this->cookies[$domain][$path]);
  3142. if (empty($this->cookies[$domain])) {
  3143. unset($this->cookies[$domain]);
  3144. }
  3145. }
  3146. }
  3147. public function getCookies($format = self::COOKIES_FLAT)
  3148. {
  3149. if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
  3150. throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
  3151. }
  3152. if (self::COOKIES_ARRAY === $format) {
  3153. return $this->cookies;
  3154. }
  3155. $flattenedCookies = array();
  3156. foreach ($this->cookies as $path) {
  3157. foreach ($path as $cookies) {
  3158. foreach ($cookies as $cookie) {
  3159. $flattenedCookies[] = $cookie;
  3160. }
  3161. }
  3162. }
  3163. return $flattenedCookies;
  3164. }
  3165. public function clearCookie($name, $path ='/', $domain = null)
  3166. {
  3167. $this->setCookie(new Cookie($name, null, 1, $path, $domain));
  3168. }
  3169. public function makeDisposition($disposition, $filename, $filenameFallback ='')
  3170. {
  3171. if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
  3172. throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE));
  3173. }
  3174. if (''== $filenameFallback) {
  3175. $filenameFallback = $filename;
  3176. }
  3177. if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) {
  3178. throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.');
  3179. }
  3180. if (false !== strpos($filenameFallback,'%')) {
  3181. throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.');
  3182. }
  3183. if (false !== strpos($filename,'/') || false !== strpos($filename,'\\') || false !== strpos($filenameFallback,'/') || false !== strpos($filenameFallback,'\\')) {
  3184. throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.');
  3185. }
  3186. $output = sprintf('%s; filename="%s"', $disposition, str_replace('"','\\"', $filenameFallback));
  3187. if ($filename !== $filenameFallback) {
  3188. $output .= sprintf("; filename*=utf-8''%s", rawurlencode($filename));
  3189. }
  3190. return $output;
  3191. }
  3192. protected function computeCacheControlValue()
  3193. {
  3194. if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
  3195. return'no-cache';
  3196. }
  3197. if (!$this->cacheControl) {
  3198. return'private, must-revalidate';
  3199. }
  3200. $header = $this->getCacheControlHeader();
  3201. if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
  3202. return $header;
  3203. }
  3204. if (!isset($this->cacheControl['s-maxage'])) {
  3205. return $header.', private';
  3206. }
  3207. return $header;
  3208. }
  3209. }
  3210. }
  3211. namespace Symfony\Component\Config
  3212. {
  3213. class FileLocator implements FileLocatorInterface
  3214. {
  3215. protected $paths;
  3216. public function __construct($paths = array())
  3217. {
  3218. $this->paths = (array) $paths;
  3219. }
  3220. public function locate($name, $currentPath = null, $first = true)
  3221. {
  3222. if ($this->isAbsolutePath($name)) {
  3223. if (!file_exists($name)) {
  3224. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $name));
  3225. }
  3226. return $name;
  3227. }
  3228. $filepaths = array();
  3229. if (null !== $currentPath && file_exists($file = $currentPath.DIRECTORY_SEPARATOR.$name)) {
  3230. if (true === $first) {
  3231. return $file;
  3232. }
  3233. $filepaths[] = $file;
  3234. }
  3235. foreach ($this->paths as $path) {
  3236. if (file_exists($file = $path.DIRECTORY_SEPARATOR.$name)) {
  3237. if (true === $first) {
  3238. return $file;
  3239. }
  3240. $filepaths[] = $file;
  3241. }
  3242. }
  3243. if (!$filepaths) {
  3244. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s%s).', $name, null !== $currentPath ? $currentPath.', ':'', implode(', ', $this->paths)));
  3245. }
  3246. return array_values(array_unique($filepaths));
  3247. }
  3248. private function isAbsolutePath($file)
  3249. {
  3250. if ($file[0] =='/'|| $file[0] =='\\'|| (strlen($file) > 3 && ctype_alpha($file[0])
  3251. && $file[1] ==':'&& ($file[2] =='\\'|| $file[2] =='/')
  3252. )
  3253. || null !== parse_url($file, PHP_URL_SCHEME)
  3254. ) {
  3255. return true;
  3256. }
  3257. return false;
  3258. }
  3259. }
  3260. }
  3261. namespace Symfony\Component\EventDispatcher
  3262. {
  3263. class Event
  3264. {
  3265. private $propagationStopped = false;
  3266. private $dispatcher;
  3267. private $name;
  3268. public function isPropagationStopped()
  3269. {
  3270. return $this->propagationStopped;
  3271. }
  3272. public function stopPropagation()
  3273. {
  3274. $this->propagationStopped = true;
  3275. }
  3276. public function setDispatcher(EventDispatcherInterface $dispatcher)
  3277. {
  3278. $this->dispatcher = $dispatcher;
  3279. }
  3280. public function getDispatcher()
  3281. {
  3282. return $this->dispatcher;
  3283. }
  3284. public function getName()
  3285. {
  3286. return $this->name;
  3287. }
  3288. public function setName($name)
  3289. {
  3290. $this->name = $name;
  3291. }
  3292. }
  3293. }
  3294. namespace Symfony\Component\EventDispatcher
  3295. {
  3296. interface EventDispatcherInterface
  3297. {
  3298. public function dispatch($eventName, Event $event = null);
  3299. public function addListener($eventName, $listener, $priority = 0);
  3300. public function addSubscriber(EventSubscriberInterface $subscriber);
  3301. public function removeListener($eventName, $listener);
  3302. public function removeSubscriber(EventSubscriberInterface $subscriber);
  3303. public function getListeners($eventName = null);
  3304. public function hasListeners($eventName = null);
  3305. }
  3306. }
  3307. namespace Symfony\Component\EventDispatcher
  3308. {
  3309. class EventDispatcher implements EventDispatcherInterface
  3310. {
  3311. private $listeners = array();
  3312. private $sorted = array();
  3313. public function dispatch($eventName, Event $event = null)
  3314. {
  3315. if (null === $event) {
  3316. $event = new Event();
  3317. }
  3318. $event->setDispatcher($this);
  3319. $event->setName($eventName);
  3320. if (!isset($this->listeners[$eventName])) {
  3321. return $event;
  3322. }
  3323. $this->doDispatch($this->getListeners($eventName), $eventName, $event);
  3324. return $event;
  3325. }
  3326. public function getListeners($eventName = null)
  3327. {
  3328. if (null !== $eventName) {
  3329. if (!isset($this->sorted[$eventName])) {
  3330. $this->sortListeners($eventName);
  3331. }
  3332. return $this->sorted[$eventName];
  3333. }
  3334. foreach (array_keys($this->listeners) as $eventName) {
  3335. if (!isset($this->sorted[$eventName])) {
  3336. $this->sortListeners($eventName);
  3337. }
  3338. }
  3339. return $this->sorted;
  3340. }
  3341. public function hasListeners($eventName = null)
  3342. {
  3343. return (Boolean) count($this->getListeners($eventName));
  3344. }
  3345. public function addListener($eventName, $listener, $priority = 0)
  3346. {
  3347. $this->listeners[$eventName][$priority][] = $listener;
  3348. unset($this->sorted[$eventName]);
  3349. }
  3350. public function removeListener($eventName, $listener)
  3351. {
  3352. if (!isset($this->listeners[$eventName])) {
  3353. return;
  3354. }
  3355. foreach ($this->listeners[$eventName] as $priority => $listeners) {
  3356. if (false !== ($key = array_search($listener, $listeners, true))) {
  3357. unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]);
  3358. }
  3359. }
  3360. }
  3361. public function addSubscriber(EventSubscriberInterface $subscriber)
  3362. {
  3363. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  3364. if (is_string($params)) {
  3365. $this->addListener($eventName, array($subscriber, $params));
  3366. } elseif (is_string($params[0])) {
  3367. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  3368. } else {
  3369. foreach ($params as $listener) {
  3370. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  3371. }
  3372. }
  3373. }
  3374. }
  3375. public function removeSubscriber(EventSubscriberInterface $subscriber)
  3376. {
  3377. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  3378. if (is_array($params) && is_array($params[0])) {
  3379. foreach ($params as $listener) {
  3380. $this->removeListener($eventName, array($subscriber, $listener[0]));
  3381. }
  3382. } else {
  3383. $this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0]));
  3384. }
  3385. }
  3386. }
  3387. protected function doDispatch($listeners, $eventName, Event $event)
  3388. {
  3389. foreach ($listeners as $listener) {
  3390. call_user_func($listener, $event);
  3391. if ($event->isPropagationStopped()) {
  3392. break;
  3393. }
  3394. }
  3395. }
  3396. private function sortListeners($eventName)
  3397. {
  3398. $this->sorted[$eventName] = array();
  3399. if (isset($this->listeners[$eventName])) {
  3400. krsort($this->listeners[$eventName]);
  3401. $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]);
  3402. }
  3403. }
  3404. }
  3405. }
  3406. namespace Symfony\Component\EventDispatcher
  3407. {
  3408. use Symfony\Component\DependencyInjection\ContainerInterface;
  3409. class ContainerAwareEventDispatcher extends EventDispatcher
  3410. {
  3411. private $container;
  3412. private $listenerIds = array();
  3413. private $listeners = array();
  3414. public function __construct(ContainerInterface $container)
  3415. {
  3416. $this->container = $container;
  3417. }
  3418. public function addListenerService($eventName, $callback, $priority = 0)
  3419. {
  3420. if (!is_array($callback) || 2 !== count($callback)) {
  3421. throw new \InvalidArgumentException('Expected an array("service", "method") argument');
  3422. }
  3423. $this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority);
  3424. }
  3425. public function removeListener($eventName, $listener)
  3426. {
  3427. $this->lazyLoad($eventName);
  3428. if (isset($this->listeners[$eventName])) {
  3429. foreach ($this->listeners[$eventName] as $key => $l) {
  3430. foreach ($this->listenerIds[$eventName] as $i => $args) {
  3431. list($serviceId, $method, $priority) = $args;
  3432. if ($key === $serviceId.'.'.$method) {
  3433. if ($listener === array($l, $method)) {
  3434. unset($this->listeners[$eventName][$key]);
  3435. if (empty($this->listeners[$eventName])) {
  3436. unset($this->listeners[$eventName]);
  3437. }
  3438. unset($this->listenerIds[$eventName][$i]);
  3439. if (empty($this->listenerIds[$eventName])) {
  3440. unset($this->listenerIds[$eventName]);
  3441. }
  3442. }
  3443. }
  3444. }
  3445. }
  3446. }
  3447. parent::removeListener($eventName, $listener);
  3448. }
  3449. public function hasListeners($eventName = null)
  3450. {
  3451. if (null === $eventName) {
  3452. return (Boolean) count($this->listenerIds) || (Boolean) count($this->listeners);
  3453. }
  3454. if (isset($this->listenerIds[$eventName])) {
  3455. return true;
  3456. }
  3457. return parent::hasListeners($eventName);
  3458. }
  3459. public function getListeners($eventName = null)
  3460. {
  3461. if (null === $eventName) {
  3462. foreach (array_keys($this->listenerIds) as $serviceEventName) {
  3463. $this->lazyLoad($serviceEventName);
  3464. }
  3465. } else {
  3466. $this->lazyLoad($eventName);
  3467. }
  3468. return parent::getListeners($eventName);
  3469. }
  3470. public function addSubscriberService($serviceId, $class)
  3471. {
  3472. foreach ($class::getSubscribedEvents() as $eventName => $params) {
  3473. if (is_string($params)) {
  3474. $this->listenerIds[$eventName][] = array($serviceId, $params, 0);
  3475. } elseif (is_string($params[0])) {
  3476. $this->listenerIds[$eventName][] = array($serviceId, $params[0], isset($params[1]) ? $params[1] : 0);
  3477. } else {
  3478. foreach ($params as $listener) {
  3479. $this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0);
  3480. }
  3481. }
  3482. }
  3483. }
  3484. public function dispatch($eventName, Event $event = null)
  3485. {
  3486. $this->lazyLoad($eventName);
  3487. return parent::dispatch($eventName, $event);
  3488. }
  3489. public function getContainer()
  3490. {
  3491. return $this->container;
  3492. }
  3493. protected function lazyLoad($eventName)
  3494. {
  3495. if (isset($this->listenerIds[$eventName])) {
  3496. foreach ($this->listenerIds[$eventName] as $args) {
  3497. list($serviceId, $method, $priority) = $args;
  3498. $listener = $this->container->get($serviceId);
  3499. $key = $serviceId.'.'.$method;
  3500. if (!isset($this->listeners[$eventName][$key])) {
  3501. $this->addListener($eventName, array($listener, $method), $priority);
  3502. } elseif ($listener !== $this->listeners[$eventName][$key]) {
  3503. parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method));
  3504. $this->addListener($eventName, array($listener, $method), $priority);
  3505. }
  3506. $this->listeners[$eventName][$key] = $listener;
  3507. }
  3508. }
  3509. }
  3510. }
  3511. }
  3512. namespace Symfony\Component\HttpKernel\EventListener
  3513. {
  3514. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  3515. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3516. use Symfony\Component\HttpKernel\KernelEvents;
  3517. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  3518. class ResponseListener implements EventSubscriberInterface
  3519. {
  3520. private $charset;
  3521. public function __construct($charset)
  3522. {
  3523. $this->charset = $charset;
  3524. }
  3525. public function onKernelResponse(FilterResponseEvent $event)
  3526. {
  3527. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  3528. return;
  3529. }
  3530. $response = $event->getResponse();
  3531. if (null === $response->getCharset()) {
  3532. $response->setCharset($this->charset);
  3533. }
  3534. $response->prepare($event->getRequest());
  3535. }
  3536. public static function getSubscribedEvents()
  3537. {
  3538. return array(
  3539. KernelEvents::RESPONSE =>'onKernelResponse',
  3540. );
  3541. }
  3542. }
  3543. }
  3544. namespace Symfony\Component\HttpKernel\EventListener
  3545. {
  3546. use Psr\Log\LoggerInterface;
  3547. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  3548. use Symfony\Component\HttpKernel\KernelEvents;
  3549. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  3550. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  3551. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  3552. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  3553. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  3554. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  3555. use Symfony\Component\Routing\RequestContext;
  3556. use Symfony\Component\Routing\RequestContextAwareInterface;
  3557. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  3558. class RouterListener implements EventSubscriberInterface
  3559. {
  3560. private $matcher;
  3561. private $context;
  3562. private $logger;
  3563. public function __construct($matcher, RequestContext $context = null, LoggerInterface $logger = null)
  3564. {
  3565. if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
  3566. throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  3567. }
  3568. if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
  3569. throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
  3570. }
  3571. $this->matcher = $matcher;
  3572. $this->context = $context ?: $matcher->getContext();
  3573. $this->logger = $logger;
  3574. }
  3575. public function onKernelRequest(GetResponseEvent $event)
  3576. {
  3577. $request = $event->getRequest();
  3578. $this->context->fromRequest($request);
  3579. if ($request->attributes->has('_controller')) {
  3580. return;
  3581. }
  3582. try {
  3583. if ($this->matcher instanceof RequestMatcherInterface) {
  3584. $parameters = $this->matcher->matchRequest($request);
  3585. } else {
  3586. $parameters = $this->matcher->match($request->getPathInfo());
  3587. }
  3588. if (null !== $this->logger) {
  3589. $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->parametersToString($parameters)));
  3590. }
  3591. $request->attributes->add($parameters);
  3592. unset($parameters['_route']);
  3593. unset($parameters['_controller']);
  3594. $request->attributes->set('_route_params', $parameters);
  3595. } catch (ResourceNotFoundException $e) {
  3596. $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
  3597. throw new NotFoundHttpException($message, $e);
  3598. } catch (MethodNotAllowedException $e) {
  3599. $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods())));
  3600. throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
  3601. }
  3602. }
  3603. private function parametersToString(array $parameters)
  3604. {
  3605. $pieces = array();
  3606. foreach ($parameters as $key => $val) {
  3607. $pieces[] = sprintf('"%s": "%s"', $key, (is_string($val) ? $val : json_encode($val)));
  3608. }
  3609. return implode(', ', $pieces);
  3610. }
  3611. public static function getSubscribedEvents()
  3612. {
  3613. return array(
  3614. KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
  3615. );
  3616. }
  3617. }
  3618. }
  3619. namespace Symfony\Component\HttpKernel\Controller
  3620. {
  3621. use Symfony\Component\HttpFoundation\Request;
  3622. interface ControllerResolverInterface
  3623. {
  3624. public function getController(Request $request);
  3625. public function getArguments(Request $request, $controller);
  3626. }
  3627. }
  3628. namespace Symfony\Component\HttpKernel\Controller
  3629. {
  3630. use Psr\Log\LoggerInterface;
  3631. use Symfony\Component\HttpFoundation\Request;
  3632. class ControllerResolver implements ControllerResolverInterface
  3633. {
  3634. private $logger;
  3635. public function __construct(LoggerInterface $logger = null)
  3636. {
  3637. $this->logger = $logger;
  3638. }
  3639. public function getController(Request $request)
  3640. {
  3641. if (!$controller = $request->attributes->get('_controller')) {
  3642. if (null !== $this->logger) {
  3643. $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing');
  3644. }
  3645. return false;
  3646. }
  3647. if (is_array($controller) || (is_object($controller) && method_exists($controller,'__invoke'))) {
  3648. return $controller;
  3649. }
  3650. if (false === strpos($controller,':')) {
  3651. if (method_exists($controller,'__invoke')) {
  3652. return new $controller;
  3653. } elseif (function_exists($controller)) {
  3654. return $controller;
  3655. }
  3656. }
  3657. list($controller, $method) = $this->createController($controller);
  3658. if (!method_exists($controller, $method)) {
  3659. throw new \InvalidArgumentException(sprintf('Method "%s::%s" does not exist.', get_class($controller), $method));
  3660. }
  3661. return array($controller, $method);
  3662. }
  3663. public function getArguments(Request $request, $controller)
  3664. {
  3665. if (is_array($controller)) {
  3666. $r = new \ReflectionMethod($controller[0], $controller[1]);
  3667. } elseif (is_object($controller) && !$controller instanceof \Closure) {
  3668. $r = new \ReflectionObject($controller);
  3669. $r = $r->getMethod('__invoke');
  3670. } else {
  3671. $r = new \ReflectionFunction($controller);
  3672. }
  3673. return $this->doGetArguments($request, $controller, $r->getParameters());
  3674. }
  3675. protected function doGetArguments(Request $request, $controller, array $parameters)
  3676. {
  3677. $attributes = $request->attributes->all();
  3678. $arguments = array();
  3679. foreach ($parameters as $param) {
  3680. if (array_key_exists($param->name, $attributes)) {
  3681. $arguments[] = $attributes[$param->name];
  3682. } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
  3683. $arguments[] = $request;
  3684. } elseif ($param->isDefaultValueAvailable()) {
  3685. $arguments[] = $param->getDefaultValue();
  3686. } else {
  3687. if (is_array($controller)) {
  3688. $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
  3689. } elseif (is_object($controller)) {
  3690. $repr = get_class($controller);
  3691. } else {
  3692. $repr = $controller;
  3693. }
  3694. throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name));
  3695. }
  3696. }
  3697. return $arguments;
  3698. }
  3699. protected function createController($controller)
  3700. {
  3701. if (false === strpos($controller,'::')) {
  3702. throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
  3703. }
  3704. list($class, $method) = explode('::', $controller, 2);
  3705. if (!class_exists($class)) {
  3706. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  3707. }
  3708. return array(new $class(), $method);
  3709. }
  3710. }
  3711. }
  3712. namespace Symfony\Component\HttpKernel\Event
  3713. {
  3714. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3715. use Symfony\Component\HttpFoundation\Request;
  3716. use Symfony\Component\EventDispatcher\Event;
  3717. class KernelEvent extends Event
  3718. {
  3719. private $kernel;
  3720. private $request;
  3721. private $requestType;
  3722. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType)
  3723. {
  3724. $this->kernel = $kernel;
  3725. $this->request = $request;
  3726. $this->requestType = $requestType;
  3727. }
  3728. public function getKernel()
  3729. {
  3730. return $this->kernel;
  3731. }
  3732. public function getRequest()
  3733. {
  3734. return $this->request;
  3735. }
  3736. public function getRequestType()
  3737. {
  3738. return $this->requestType;
  3739. }
  3740. }
  3741. }
  3742. namespace Symfony\Component\HttpKernel\Event
  3743. {
  3744. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3745. use Symfony\Component\HttpFoundation\Request;
  3746. class FilterControllerEvent extends KernelEvent
  3747. {
  3748. private $controller;
  3749. public function __construct(HttpKernelInterface $kernel, $controller, Request $request, $requestType)
  3750. {
  3751. parent::__construct($kernel, $request, $requestType);
  3752. $this->setController($controller);
  3753. }
  3754. public function getController()
  3755. {
  3756. return $this->controller;
  3757. }
  3758. public function setController($controller)
  3759. {
  3760. if (!is_callable($controller)) {
  3761. throw new \LogicException(sprintf('The controller must be a callable (%s given).', $this->varToString($controller)));
  3762. }
  3763. $this->controller = $controller;
  3764. }
  3765. private function varToString($var)
  3766. {
  3767. if (is_object($var)) {
  3768. return sprintf('Object(%s)', get_class($var));
  3769. }
  3770. if (is_array($var)) {
  3771. $a = array();
  3772. foreach ($var as $k => $v) {
  3773. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  3774. }
  3775. return sprintf("Array(%s)", implode(', ', $a));
  3776. }
  3777. if (is_resource($var)) {
  3778. return sprintf('Resource(%s)', get_resource_type($var));
  3779. }
  3780. if (null === $var) {
  3781. return'null';
  3782. }
  3783. if (false === $var) {
  3784. return'false';
  3785. }
  3786. if (true === $var) {
  3787. return'true';
  3788. }
  3789. return (string) $var;
  3790. }
  3791. }
  3792. }
  3793. namespace Symfony\Component\HttpKernel\Event
  3794. {
  3795. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3796. use Symfony\Component\HttpFoundation\Request;
  3797. use Symfony\Component\HttpFoundation\Response;
  3798. class FilterResponseEvent extends KernelEvent
  3799. {
  3800. private $response;
  3801. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, Response $response)
  3802. {
  3803. parent::__construct($kernel, $request, $requestType);
  3804. $this->setResponse($response);
  3805. }
  3806. public function getResponse()
  3807. {
  3808. return $this->response;
  3809. }
  3810. public function setResponse(Response $response)
  3811. {
  3812. $this->response = $response;
  3813. }
  3814. }
  3815. }
  3816. namespace Symfony\Component\HttpKernel\Event
  3817. {
  3818. use Symfony\Component\HttpFoundation\Response;
  3819. class GetResponseEvent extends KernelEvent
  3820. {
  3821. private $response;
  3822. public function getResponse()
  3823. {
  3824. return $this->response;
  3825. }
  3826. public function setResponse(Response $response)
  3827. {
  3828. $this->response = $response;
  3829. $this->stopPropagation();
  3830. }
  3831. public function hasResponse()
  3832. {
  3833. return null !== $this->response;
  3834. }
  3835. }
  3836. }
  3837. namespace Symfony\Component\HttpKernel\Event
  3838. {
  3839. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3840. use Symfony\Component\HttpFoundation\Request;
  3841. class GetResponseForControllerResultEvent extends GetResponseEvent
  3842. {
  3843. private $controllerResult;
  3844. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, $controllerResult)
  3845. {
  3846. parent::__construct($kernel, $request, $requestType);
  3847. $this->controllerResult = $controllerResult;
  3848. }
  3849. public function getControllerResult()
  3850. {
  3851. return $this->controllerResult;
  3852. }
  3853. public function setControllerResult($controllerResult)
  3854. {
  3855. $this->controllerResult = $controllerResult;
  3856. }
  3857. }
  3858. }
  3859. namespace Symfony\Component\HttpKernel\Event
  3860. {
  3861. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3862. use Symfony\Component\HttpFoundation\Request;
  3863. class GetResponseForExceptionEvent extends GetResponseEvent
  3864. {
  3865. private $exception;
  3866. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, \Exception $e)
  3867. {
  3868. parent::__construct($kernel, $request, $requestType);
  3869. $this->setException($e);
  3870. }
  3871. public function getException()
  3872. {
  3873. return $this->exception;
  3874. }
  3875. public function setException(\Exception $exception)
  3876. {
  3877. $this->exception = $exception;
  3878. }
  3879. }
  3880. }
  3881. namespace Symfony\Component\HttpKernel
  3882. {
  3883. final class KernelEvents
  3884. {
  3885. const REQUEST ='kernel.request';
  3886. const EXCEPTION ='kernel.exception';
  3887. const VIEW ='kernel.view';
  3888. const CONTROLLER ='kernel.controller';
  3889. const RESPONSE ='kernel.response';
  3890. const TERMINATE ='kernel.terminate';
  3891. }
  3892. }
  3893. namespace Symfony\Component\HttpKernel\Config
  3894. {
  3895. use Symfony\Component\Config\FileLocator as BaseFileLocator;
  3896. use Symfony\Component\HttpKernel\KernelInterface;
  3897. class FileLocator extends BaseFileLocator
  3898. {
  3899. private $kernel;
  3900. private $path;
  3901. public function __construct(KernelInterface $kernel, $path = null, array $paths = array())
  3902. {
  3903. $this->kernel = $kernel;
  3904. $this->path = $path;
  3905. $paths[] = $path;
  3906. parent::__construct($paths);
  3907. }
  3908. public function locate($file, $currentPath = null, $first = true)
  3909. {
  3910. if ('@'=== $file[0]) {
  3911. return $this->kernel->locateResource($file, $this->path, $first);
  3912. }
  3913. return parent::locate($file, $currentPath, $first);
  3914. }
  3915. }
  3916. }
  3917. namespace Symfony\Bundle\FrameworkBundle\Controller
  3918. {
  3919. use Symfony\Component\HttpKernel\KernelInterface;
  3920. class ControllerNameParser
  3921. {
  3922. protected $kernel;
  3923. public function __construct(KernelInterface $kernel)
  3924. {
  3925. $this->kernel = $kernel;
  3926. }
  3927. public function parse($controller)
  3928. {
  3929. if (3 != count($parts = explode(':', $controller))) {
  3930. throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid a:b:c controller string.', $controller));
  3931. }
  3932. list($bundle, $controller, $action) = $parts;
  3933. $controller = str_replace('/','\\', $controller);
  3934. $bundles = array();
  3935. foreach ($this->kernel->getBundle($bundle, false) as $b) {
  3936. $try = $b->getNamespace().'\\Controller\\'.$controller.'Controller';
  3937. if (class_exists($try)) {
  3938. return $try.'::'.$action.'Action';
  3939. }
  3940. $bundles[] = $b->getName();
  3941. $msg = sprintf('Unable to find controller "%s:%s" - class "%s" does not exist.', $bundle, $controller, $try);
  3942. }
  3943. if (count($bundles) > 1) {
  3944. $msg = sprintf('Unable to find controller "%s:%s" in bundles %s.', $bundle, $controller, implode(', ', $bundles));
  3945. }
  3946. throw new \InvalidArgumentException($msg);
  3947. }
  3948. }
  3949. }
  3950. namespace Symfony\Bundle\FrameworkBundle\Controller
  3951. {
  3952. use Psr\Log\LoggerInterface;
  3953. use Symfony\Component\HttpKernel\Controller\ControllerResolver as BaseControllerResolver;
  3954. use Symfony\Component\DependencyInjection\ContainerInterface;
  3955. use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
  3956. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  3957. class ControllerResolver extends BaseControllerResolver
  3958. {
  3959. protected $container;
  3960. protected $parser;
  3961. public function __construct(ContainerInterface $container, ControllerNameParser $parser, LoggerInterface $logger = null)
  3962. {
  3963. $this->container = $container;
  3964. $this->parser = $parser;
  3965. parent::__construct($logger);
  3966. }
  3967. protected function createController($controller)
  3968. {
  3969. if (false === strpos($controller,'::')) {
  3970. $count = substr_count($controller,':');
  3971. if (2 == $count) {
  3972. $controller = $this->parser->parse($controller);
  3973. } elseif (1 == $count) {
  3974. list($service, $method) = explode(':', $controller, 2);
  3975. return array($this->container->get($service), $method);
  3976. } else {
  3977. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  3978. }
  3979. }
  3980. list($class, $method) = explode('::', $controller, 2);
  3981. if (!class_exists($class)) {
  3982. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  3983. }
  3984. $controller = new $class();
  3985. if ($controller instanceof ContainerAwareInterface) {
  3986. $controller->setContainer($this->container);
  3987. }
  3988. return array($controller, $method);
  3989. }
  3990. }
  3991. }
  3992. namespace Symfony\Component\Security\Http
  3993. {
  3994. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3995. use Symfony\Component\HttpKernel\KernelEvents;
  3996. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  3997. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  3998. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  3999. class Firewall implements EventSubscriberInterface
  4000. {
  4001. private $map;
  4002. private $dispatcher;
  4003. public function __construct(FirewallMapInterface $map, EventDispatcherInterface $dispatcher)
  4004. {
  4005. $this->map = $map;
  4006. $this->dispatcher = $dispatcher;
  4007. }
  4008. public function onKernelRequest(GetResponseEvent $event)
  4009. {
  4010. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  4011. return;
  4012. }
  4013. list($listeners, $exception) = $this->map->getListeners($event->getRequest());
  4014. if (null !== $exception) {
  4015. $exception->register($this->dispatcher);
  4016. }
  4017. foreach ($listeners as $listener) {
  4018. $response = $listener->handle($event);
  4019. if ($event->hasResponse()) {
  4020. break;
  4021. }
  4022. }
  4023. }
  4024. public static function getSubscribedEvents()
  4025. {
  4026. return array(KernelEvents::REQUEST => array('onKernelRequest', 8));
  4027. }
  4028. }
  4029. }
  4030. namespace Symfony\Component\Security\Core
  4031. {
  4032. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4033. interface SecurityContextInterface
  4034. {
  4035. const ACCESS_DENIED_ERROR ='_security.403_error';
  4036. const AUTHENTICATION_ERROR ='_security.last_error';
  4037. const LAST_USERNAME ='_security.last_username';
  4038. public function getToken();
  4039. public function setToken(TokenInterface $token = null);
  4040. public function isGranted($attributes, $object = null);
  4041. }
  4042. }
  4043. namespace Symfony\Component\Security\Core
  4044. {
  4045. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  4046. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  4047. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  4048. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4049. class SecurityContext implements SecurityContextInterface
  4050. {
  4051. private $token;
  4052. private $accessDecisionManager;
  4053. private $authenticationManager;
  4054. private $alwaysAuthenticate;
  4055. public function __construct(AuthenticationManagerInterface $authenticationManager, AccessDecisionManagerInterface $accessDecisionManager, $alwaysAuthenticate = false)
  4056. {
  4057. $this->authenticationManager = $authenticationManager;
  4058. $this->accessDecisionManager = $accessDecisionManager;
  4059. $this->alwaysAuthenticate = $alwaysAuthenticate;
  4060. }
  4061. final public function isGranted($attributes, $object = null)
  4062. {
  4063. if (null === $this->token) {
  4064. throw new AuthenticationCredentialsNotFoundException('The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
  4065. }
  4066. if ($this->alwaysAuthenticate || !$this->token->isAuthenticated()) {
  4067. $this->token = $this->authenticationManager->authenticate($this->token);
  4068. }
  4069. if (!is_array($attributes)) {
  4070. $attributes = array($attributes);
  4071. }
  4072. return $this->accessDecisionManager->decide($this->token, $attributes, $object);
  4073. }
  4074. public function getToken()
  4075. {
  4076. return $this->token;
  4077. }
  4078. public function setToken(TokenInterface $token = null)
  4079. {
  4080. $this->token = $token;
  4081. }
  4082. }
  4083. }
  4084. namespace Symfony\Component\Security\Core\User
  4085. {
  4086. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  4087. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  4088. interface UserProviderInterface
  4089. {
  4090. public function loadUserByUsername($username);
  4091. public function refreshUser(UserInterface $user);
  4092. public function supportsClass($class);
  4093. }
  4094. }
  4095. namespace Symfony\Component\Security\Core\Authentication
  4096. {
  4097. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4098. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  4099. interface AuthenticationManagerInterface
  4100. {
  4101. public function authenticate(TokenInterface $token);
  4102. }
  4103. }
  4104. namespace Symfony\Component\Security\Core\Authentication
  4105. {
  4106. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  4107. use Symfony\Component\Security\Core\Event\AuthenticationEvent;
  4108. use Symfony\Component\Security\Core\AuthenticationEvents;
  4109. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  4110. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  4111. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  4112. use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
  4113. use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
  4114. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4115. class AuthenticationProviderManager implements AuthenticationManagerInterface
  4116. {
  4117. private $providers;
  4118. private $eraseCredentials;
  4119. private $eventDispatcher;
  4120. public function __construct(array $providers, $eraseCredentials = true)
  4121. {
  4122. if (!$providers) {
  4123. throw new \InvalidArgumentException('You must at least add one authentication provider.');
  4124. }
  4125. $this->providers = $providers;
  4126. $this->eraseCredentials = (Boolean) $eraseCredentials;
  4127. }
  4128. public function setEventDispatcher(EventDispatcherInterface $dispatcher)
  4129. {
  4130. $this->eventDispatcher = $dispatcher;
  4131. }
  4132. public function authenticate(TokenInterface $token)
  4133. {
  4134. $lastException = null;
  4135. $result = null;
  4136. foreach ($this->providers as $provider) {
  4137. if (!$provider->supports($token)) {
  4138. continue;
  4139. }
  4140. try {
  4141. $result = $provider->authenticate($token);
  4142. if (null !== $result) {
  4143. break;
  4144. }
  4145. } catch (AccountStatusException $e) {
  4146. $e->setToken($token);
  4147. throw $e;
  4148. } catch (AuthenticationException $e) {
  4149. $lastException = $e;
  4150. }
  4151. }
  4152. if (null !== $result) {
  4153. if (true === $this->eraseCredentials) {
  4154. $result->eraseCredentials();
  4155. }
  4156. if (null !== $this->eventDispatcher) {
  4157. $this->eventDispatcher->dispatch(AuthenticationEvents::AUTHENTICATION_SUCCESS, new AuthenticationEvent($result));
  4158. }
  4159. return $result;
  4160. }
  4161. if (null === $lastException) {
  4162. $lastException = new ProviderNotFoundException(sprintf('No Authentication Provider found for token of class "%s".', get_class($token)));
  4163. }
  4164. if (null !== $this->eventDispatcher) {
  4165. $this->eventDispatcher->dispatch(AuthenticationEvents::AUTHENTICATION_FAILURE, new AuthenticationFailureEvent($token, $lastException));
  4166. }
  4167. $lastException->setToken($token);
  4168. throw $lastException;
  4169. }
  4170. }
  4171. }
  4172. namespace Symfony\Component\Security\Core\Authorization
  4173. {
  4174. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4175. interface AccessDecisionManagerInterface
  4176. {
  4177. public function decide(TokenInterface $token, array $attributes, $object = null);
  4178. public function supportsAttribute($attribute);
  4179. public function supportsClass($class);
  4180. }
  4181. }
  4182. namespace Symfony\Component\Security\Core\Authorization
  4183. {
  4184. use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
  4185. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4186. class AccessDecisionManager implements AccessDecisionManagerInterface
  4187. {
  4188. private $voters;
  4189. private $strategy;
  4190. private $allowIfAllAbstainDecisions;
  4191. private $allowIfEqualGrantedDeniedDecisions;
  4192. public function __construct(array $voters, $strategy ='affirmative', $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
  4193. {
  4194. if (!$voters) {
  4195. throw new \InvalidArgumentException('You must at least add one voter.');
  4196. }
  4197. $this->voters = $voters;
  4198. $this->strategy ='decide'.ucfirst($strategy);
  4199. $this->allowIfAllAbstainDecisions = (Boolean) $allowIfAllAbstainDecisions;
  4200. $this->allowIfEqualGrantedDeniedDecisions = (Boolean) $allowIfEqualGrantedDeniedDecisions;
  4201. }
  4202. public function decide(TokenInterface $token, array $attributes, $object = null)
  4203. {
  4204. return $this->{$this->strategy}($token, $attributes, $object);
  4205. }
  4206. public function supportsAttribute($attribute)
  4207. {
  4208. foreach ($this->voters as $voter) {
  4209. if ($voter->supportsAttribute($attribute)) {
  4210. return true;
  4211. }
  4212. }
  4213. return false;
  4214. }
  4215. public function supportsClass($class)
  4216. {
  4217. foreach ($this->voters as $voter) {
  4218. if ($voter->supportsClass($class)) {
  4219. return true;
  4220. }
  4221. }
  4222. return false;
  4223. }
  4224. private function decideAffirmative(TokenInterface $token, array $attributes, $object = null)
  4225. {
  4226. $deny = 0;
  4227. foreach ($this->voters as $voter) {
  4228. $result = $voter->vote($token, $object, $attributes);
  4229. switch ($result) {
  4230. case VoterInterface::ACCESS_GRANTED:
  4231. return true;
  4232. case VoterInterface::ACCESS_DENIED:
  4233. ++$deny;
  4234. break;
  4235. default:
  4236. break;
  4237. }
  4238. }
  4239. if ($deny > 0) {
  4240. return false;
  4241. }
  4242. return $this->allowIfAllAbstainDecisions;
  4243. }
  4244. private function decideConsensus(TokenInterface $token, array $attributes, $object = null)
  4245. {
  4246. $grant = 0;
  4247. $deny = 0;
  4248. $abstain = 0;
  4249. foreach ($this->voters as $voter) {
  4250. $result = $voter->vote($token, $object, $attributes);
  4251. switch ($result) {
  4252. case VoterInterface::ACCESS_GRANTED:
  4253. ++$grant;
  4254. break;
  4255. case VoterInterface::ACCESS_DENIED:
  4256. ++$deny;
  4257. break;
  4258. default:
  4259. ++$abstain;
  4260. break;
  4261. }
  4262. }
  4263. if ($grant > $deny) {
  4264. return true;
  4265. }
  4266. if ($deny > $grant) {
  4267. return false;
  4268. }
  4269. if ($grant == $deny && $grant != 0) {
  4270. return $this->allowIfEqualGrantedDeniedDecisions;
  4271. }
  4272. return $this->allowIfAllAbstainDecisions;
  4273. }
  4274. private function decideUnanimous(TokenInterface $token, array $attributes, $object = null)
  4275. {
  4276. $grant = 0;
  4277. foreach ($attributes as $attribute) {
  4278. foreach ($this->voters as $voter) {
  4279. $result = $voter->vote($token, $object, array($attribute));
  4280. switch ($result) {
  4281. case VoterInterface::ACCESS_GRANTED:
  4282. ++$grant;
  4283. break;
  4284. case VoterInterface::ACCESS_DENIED:
  4285. return false;
  4286. default:
  4287. break;
  4288. }
  4289. }
  4290. }
  4291. if ($grant > 0) {
  4292. return true;
  4293. }
  4294. return $this->allowIfAllAbstainDecisions;
  4295. }
  4296. }
  4297. }
  4298. namespace Symfony\Component\Security\Core\Authorization\Voter
  4299. {
  4300. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4301. interface VoterInterface
  4302. {
  4303. const ACCESS_GRANTED = 1;
  4304. const ACCESS_ABSTAIN = 0;
  4305. const ACCESS_DENIED = -1;
  4306. public function supportsAttribute($attribute);
  4307. public function supportsClass($class);
  4308. public function vote(TokenInterface $token, $object, array $attributes);
  4309. }
  4310. }
  4311. namespace Symfony\Component\Security\Http
  4312. {
  4313. use Symfony\Component\HttpFoundation\Request;
  4314. interface FirewallMapInterface
  4315. {
  4316. public function getListeners(Request $request);
  4317. }
  4318. }
  4319. namespace Symfony\Bundle\SecurityBundle\Security
  4320. {
  4321. use Symfony\Component\Security\Http\FirewallMapInterface;
  4322. use Symfony\Component\HttpFoundation\Request;
  4323. use Symfony\Component\DependencyInjection\ContainerInterface;
  4324. class FirewallMap implements FirewallMapInterface
  4325. {
  4326. protected $container;
  4327. protected $map;
  4328. public function __construct(ContainerInterface $container, array $map)
  4329. {
  4330. $this->container = $container;
  4331. $this->map = $map;
  4332. }
  4333. public function getListeners(Request $request)
  4334. {
  4335. foreach ($this->map as $contextId => $requestMatcher) {
  4336. if (null === $requestMatcher || $requestMatcher->matches($request)) {
  4337. return $this->container->get($contextId)->getContext();
  4338. }
  4339. }
  4340. return array(array(), null);
  4341. }
  4342. }
  4343. }
  4344. namespace Symfony\Bundle\SecurityBundle\Security
  4345. {
  4346. use Symfony\Component\Security\Http\Firewall\ExceptionListener;
  4347. class FirewallContext
  4348. {
  4349. private $listeners;
  4350. private $exceptionListener;
  4351. public function __construct(array $listeners, ExceptionListener $exceptionListener = null)
  4352. {
  4353. $this->listeners = $listeners;
  4354. $this->exceptionListener = $exceptionListener;
  4355. }
  4356. public function getContext()
  4357. {
  4358. return array($this->listeners, $this->exceptionListener);
  4359. }
  4360. }
  4361. }
  4362. namespace Symfony\Component\HttpFoundation
  4363. {
  4364. interface RequestMatcherInterface
  4365. {
  4366. public function matches(Request $request);
  4367. }
  4368. }
  4369. namespace Symfony\Component\HttpFoundation
  4370. {
  4371. class RequestMatcher implements RequestMatcherInterface
  4372. {
  4373. private $path;
  4374. private $host;
  4375. private $methods = array();
  4376. private $ip;
  4377. private $attributes = array();
  4378. public function __construct($path = null, $host = null, $methods = null, $ip = null, array $attributes = array())
  4379. {
  4380. $this->matchPath($path);
  4381. $this->matchHost($host);
  4382. $this->matchMethod($methods);
  4383. $this->matchIp($ip);
  4384. foreach ($attributes as $k => $v) {
  4385. $this->matchAttribute($k, $v);
  4386. }
  4387. }
  4388. public function matchHost($regexp)
  4389. {
  4390. $this->host = $regexp;
  4391. }
  4392. public function matchPath($regexp)
  4393. {
  4394. $this->path = $regexp;
  4395. }
  4396. public function matchIp($ip)
  4397. {
  4398. $this->ip = $ip;
  4399. }
  4400. public function matchMethod($method)
  4401. {
  4402. $this->methods = array_map('strtoupper', (array) $method);
  4403. }
  4404. public function matchAttribute($key, $regexp)
  4405. {
  4406. $this->attributes[$key] = $regexp;
  4407. }
  4408. public function matches(Request $request)
  4409. {
  4410. if ($this->methods && !in_array($request->getMethod(), $this->methods)) {
  4411. return false;
  4412. }
  4413. foreach ($this->attributes as $key => $pattern) {
  4414. if (!preg_match('#'.str_replace('#','\\#', $pattern).'#', $request->attributes->get($key))) {
  4415. return false;
  4416. }
  4417. }
  4418. if (null !== $this->path) {
  4419. $path = str_replace('#','\\#', $this->path);
  4420. if (!preg_match('#'.$path.'#', rawurldecode($request->getPathInfo()))) {
  4421. return false;
  4422. }
  4423. }
  4424. if (null !== $this->host && !preg_match('#'.str_replace('#','\\#', $this->host).'#i', $request->getHost())) {
  4425. return false;
  4426. }
  4427. if (null !== $this->ip && !IpUtils::checkIp($request->getClientIp(), $this->ip)) {
  4428. return false;
  4429. }
  4430. return true;
  4431. }
  4432. }
  4433. }
  4434. namespace
  4435. {
  4436. class Twig_Environment
  4437. {
  4438. const VERSION ='1.12.3';
  4439. protected $charset;
  4440. protected $loader;
  4441. protected $debug;
  4442. protected $autoReload;
  4443. protected $cache;
  4444. protected $lexer;
  4445. protected $parser;
  4446. protected $compiler;
  4447. protected $baseTemplateClass;
  4448. protected $extensions;
  4449. protected $parsers;
  4450. protected $visitors;
  4451. protected $filters;
  4452. protected $tests;
  4453. protected $functions;
  4454. protected $globals;
  4455. protected $runtimeInitialized;
  4456. protected $extensionInitialized;
  4457. protected $loadedTemplates;
  4458. protected $strictVariables;
  4459. protected $unaryOperators;
  4460. protected $binaryOperators;
  4461. protected $templateClassPrefix ='__TwigTemplate_';
  4462. protected $functionCallbacks;
  4463. protected $filterCallbacks;
  4464. protected $staging;
  4465. public function __construct(Twig_LoaderInterface $loader = null, $options = array())
  4466. {
  4467. if (null !== $loader) {
  4468. $this->setLoader($loader);
  4469. }
  4470. $options = array_merge(array('debug'=> false,'charset'=>'UTF-8','base_template_class'=>'Twig_Template','strict_variables'=> false,'autoescape'=>'html','cache'=> false,'auto_reload'=> null,'optimizations'=> -1,
  4471. ), $options);
  4472. $this->debug = (bool) $options['debug'];
  4473. $this->charset = $options['charset'];
  4474. $this->baseTemplateClass = $options['base_template_class'];
  4475. $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
  4476. $this->strictVariables = (bool) $options['strict_variables'];
  4477. $this->runtimeInitialized = false;
  4478. $this->setCache($options['cache']);
  4479. $this->functionCallbacks = array();
  4480. $this->filterCallbacks = array();
  4481. $this->addExtension(new Twig_Extension_Core());
  4482. $this->addExtension(new Twig_Extension_Escaper($options['autoescape']));
  4483. $this->addExtension(new Twig_Extension_Optimizer($options['optimizations']));
  4484. $this->extensionInitialized = false;
  4485. $this->staging = new Twig_Extension_Staging();
  4486. }
  4487. public function getBaseTemplateClass()
  4488. {
  4489. return $this->baseTemplateClass;
  4490. }
  4491. public function setBaseTemplateClass($class)
  4492. {
  4493. $this->baseTemplateClass = $class;
  4494. }
  4495. public function enableDebug()
  4496. {
  4497. $this->debug = true;
  4498. }
  4499. public function disableDebug()
  4500. {
  4501. $this->debug = false;
  4502. }
  4503. public function isDebug()
  4504. {
  4505. return $this->debug;
  4506. }
  4507. public function enableAutoReload()
  4508. {
  4509. $this->autoReload = true;
  4510. }
  4511. public function disableAutoReload()
  4512. {
  4513. $this->autoReload = false;
  4514. }
  4515. public function isAutoReload()
  4516. {
  4517. return $this->autoReload;
  4518. }
  4519. public function enableStrictVariables()
  4520. {
  4521. $this->strictVariables = true;
  4522. }
  4523. public function disableStrictVariables()
  4524. {
  4525. $this->strictVariables = false;
  4526. }
  4527. public function isStrictVariables()
  4528. {
  4529. return $this->strictVariables;
  4530. }
  4531. public function getCache()
  4532. {
  4533. return $this->cache;
  4534. }
  4535. public function setCache($cache)
  4536. {
  4537. $this->cache = $cache ? $cache : false;
  4538. }
  4539. public function getCacheFilename($name)
  4540. {
  4541. if (false === $this->cache) {
  4542. return false;
  4543. }
  4544. $class = substr($this->getTemplateClass($name), strlen($this->templateClassPrefix));
  4545. return $this->getCache().'/'.substr($class, 0, 2).'/'.substr($class, 2, 2).'/'.substr($class, 4).'.php';
  4546. }
  4547. public function getTemplateClass($name, $index = null)
  4548. {
  4549. return $this->templateClassPrefix.md5($this->getLoader()->getCacheKey($name)).(null === $index ?'':'_'.$index);
  4550. }
  4551. public function getTemplateClassPrefix()
  4552. {
  4553. return $this->templateClassPrefix;
  4554. }
  4555. public function render($name, array $context = array())
  4556. {
  4557. return $this->loadTemplate($name)->render($context);
  4558. }
  4559. public function display($name, array $context = array())
  4560. {
  4561. $this->loadTemplate($name)->display($context);
  4562. }
  4563. public function loadTemplate($name, $index = null)
  4564. {
  4565. $cls = $this->getTemplateClass($name, $index);
  4566. if (isset($this->loadedTemplates[$cls])) {
  4567. return $this->loadedTemplates[$cls];
  4568. }
  4569. if (!class_exists($cls, false)) {
  4570. if (false === $cache = $this->getCacheFilename($name)) {
  4571. eval('?>'.$this->compileSource($this->getLoader()->getSource($name), $name));
  4572. } else {
  4573. if (!is_file($cache) || ($this->isAutoReload() && !$this->isTemplateFresh($name, filemtime($cache)))) {
  4574. $this->writeCacheFile($cache, $this->compileSource($this->getLoader()->getSource($name), $name));
  4575. }
  4576. require_once $cache;
  4577. }
  4578. }
  4579. if (!$this->runtimeInitialized) {
  4580. $this->initRuntime();
  4581. }
  4582. return $this->loadedTemplates[$cls] = new $cls($this);
  4583. }
  4584. public function isTemplateFresh($name, $time)
  4585. {
  4586. foreach ($this->extensions as $extension) {
  4587. $r = new ReflectionObject($extension);
  4588. if (filemtime($r->getFileName()) > $time) {
  4589. return false;
  4590. }
  4591. }
  4592. return $this->getLoader()->isFresh($name, $time);
  4593. }
  4594. public function resolveTemplate($names)
  4595. {
  4596. if (!is_array($names)) {
  4597. $names = array($names);
  4598. }
  4599. foreach ($names as $name) {
  4600. if ($name instanceof Twig_Template) {
  4601. return $name;
  4602. }
  4603. try {
  4604. return $this->loadTemplate($name);
  4605. } catch (Twig_Error_Loader $e) {
  4606. }
  4607. }
  4608. if (1 === count($names)) {
  4609. throw $e;
  4610. }
  4611. throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
  4612. }
  4613. public function clearTemplateCache()
  4614. {
  4615. $this->loadedTemplates = array();
  4616. }
  4617. public function clearCacheFiles()
  4618. {
  4619. if (false === $this->cache) {
  4620. return;
  4621. }
  4622. foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->cache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  4623. if ($file->isFile()) {
  4624. @unlink($file->getPathname());
  4625. }
  4626. }
  4627. }
  4628. public function getLexer()
  4629. {
  4630. if (null === $this->lexer) {
  4631. $this->lexer = new Twig_Lexer($this);
  4632. }
  4633. return $this->lexer;
  4634. }
  4635. public function setLexer(Twig_LexerInterface $lexer)
  4636. {
  4637. $this->lexer = $lexer;
  4638. }
  4639. public function tokenize($source, $name = null)
  4640. {
  4641. return $this->getLexer()->tokenize($source, $name);
  4642. }
  4643. public function getParser()
  4644. {
  4645. if (null === $this->parser) {
  4646. $this->parser = new Twig_Parser($this);
  4647. }
  4648. return $this->parser;
  4649. }
  4650. public function setParser(Twig_ParserInterface $parser)
  4651. {
  4652. $this->parser = $parser;
  4653. }
  4654. public function parse(Twig_TokenStream $tokens)
  4655. {
  4656. return $this->getParser()->parse($tokens);
  4657. }
  4658. public function getCompiler()
  4659. {
  4660. if (null === $this->compiler) {
  4661. $this->compiler = new Twig_Compiler($this);
  4662. }
  4663. return $this->compiler;
  4664. }
  4665. public function setCompiler(Twig_CompilerInterface $compiler)
  4666. {
  4667. $this->compiler = $compiler;
  4668. }
  4669. public function compile(Twig_NodeInterface $node)
  4670. {
  4671. return $this->getCompiler()->compile($node)->getSource();
  4672. }
  4673. public function compileSource($source, $name = null)
  4674. {
  4675. try {
  4676. return $this->compile($this->parse($this->tokenize($source, $name)));
  4677. } catch (Twig_Error $e) {
  4678. $e->setTemplateFile($name);
  4679. throw $e;
  4680. } catch (Exception $e) {
  4681. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $name, $e);
  4682. }
  4683. }
  4684. public function setLoader(Twig_LoaderInterface $loader)
  4685. {
  4686. $this->loader = $loader;
  4687. }
  4688. public function getLoader()
  4689. {
  4690. if (null === $this->loader) {
  4691. throw new LogicException('You must set a loader first.');
  4692. }
  4693. return $this->loader;
  4694. }
  4695. public function setCharset($charset)
  4696. {
  4697. $this->charset = $charset;
  4698. }
  4699. public function getCharset()
  4700. {
  4701. return $this->charset;
  4702. }
  4703. public function initRuntime()
  4704. {
  4705. $this->runtimeInitialized = true;
  4706. foreach ($this->getExtensions() as $extension) {
  4707. $extension->initRuntime($this);
  4708. }
  4709. }
  4710. public function hasExtension($name)
  4711. {
  4712. return isset($this->extensions[$name]);
  4713. }
  4714. public function getExtension($name)
  4715. {
  4716. if (!isset($this->extensions[$name])) {
  4717. throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $name));
  4718. }
  4719. return $this->extensions[$name];
  4720. }
  4721. public function addExtension(Twig_ExtensionInterface $extension)
  4722. {
  4723. if ($this->extensionInitialized) {
  4724. throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $extension->getName()));
  4725. }
  4726. $this->extensions[$extension->getName()] = $extension;
  4727. }
  4728. public function removeExtension($name)
  4729. {
  4730. if ($this->extensionInitialized) {
  4731. throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name));
  4732. }
  4733. unset($this->extensions[$name]);
  4734. }
  4735. public function setExtensions(array $extensions)
  4736. {
  4737. foreach ($extensions as $extension) {
  4738. $this->addExtension($extension);
  4739. }
  4740. }
  4741. public function getExtensions()
  4742. {
  4743. return $this->extensions;
  4744. }
  4745. public function addTokenParser(Twig_TokenParserInterface $parser)
  4746. {
  4747. if ($this->extensionInitialized) {
  4748. throw new LogicException('Unable to add a token parser as extensions have already been initialized.');
  4749. }
  4750. $this->staging->addTokenParser($parser);
  4751. }
  4752. public function getTokenParsers()
  4753. {
  4754. if (!$this->extensionInitialized) {
  4755. $this->initExtensions();
  4756. }
  4757. return $this->parsers;
  4758. }
  4759. public function getTags()
  4760. {
  4761. $tags = array();
  4762. foreach ($this->getTokenParsers()->getParsers() as $parser) {
  4763. if ($parser instanceof Twig_TokenParserInterface) {
  4764. $tags[$parser->getTag()] = $parser;
  4765. }
  4766. }
  4767. return $tags;
  4768. }
  4769. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  4770. {
  4771. if ($this->extensionInitialized) {
  4772. throw new LogicException('Unable to add a node visitor as extensions have already been initialized.', $extension->getName());
  4773. }
  4774. $this->staging->addNodeVisitor($visitor);
  4775. }
  4776. public function getNodeVisitors()
  4777. {
  4778. if (!$this->extensionInitialized) {
  4779. $this->initExtensions();
  4780. }
  4781. return $this->visitors;
  4782. }
  4783. public function addFilter($name, $filter = null)
  4784. {
  4785. if (!$name instanceof Twig_SimpleFilter && !($filter instanceof Twig_SimpleFilter || $filter instanceof Twig_FilterInterface)) {
  4786. throw new LogicException('A filter must be an instance of Twig_FilterInterface or Twig_SimpleFilter');
  4787. }
  4788. if ($name instanceof Twig_SimpleFilter) {
  4789. $filter = $name;
  4790. $name = $filter->getName();
  4791. }
  4792. if ($this->extensionInitialized) {
  4793. throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name));
  4794. }
  4795. $this->staging->addFilter($name, $filter);
  4796. }
  4797. public function getFilter($name)
  4798. {
  4799. if (!$this->extensionInitialized) {
  4800. $this->initExtensions();
  4801. }
  4802. if (isset($this->filters[$name])) {
  4803. return $this->filters[$name];
  4804. }
  4805. foreach ($this->filters as $pattern => $filter) {
  4806. $pattern = str_replace('\\*','(.*?)', preg_quote($pattern,'#'), $count);
  4807. if ($count) {
  4808. if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
  4809. array_shift($matches);
  4810. $filter->setArguments($matches);
  4811. return $filter;
  4812. }
  4813. }
  4814. }
  4815. foreach ($this->filterCallbacks as $callback) {
  4816. if (false !== $filter = call_user_func($callback, $name)) {
  4817. return $filter;
  4818. }
  4819. }
  4820. return false;
  4821. }
  4822. public function registerUndefinedFilterCallback($callable)
  4823. {
  4824. $this->filterCallbacks[] = $callable;
  4825. }
  4826. public function getFilters()
  4827. {
  4828. if (!$this->extensionInitialized) {
  4829. $this->initExtensions();
  4830. }
  4831. return $this->filters;
  4832. }
  4833. public function addTest($name, $test = null)
  4834. {
  4835. if (!$name instanceof Twig_SimpleTest && !($test instanceof Twig_SimpleTest || $test instanceof Twig_TestInterface)) {
  4836. throw new LogicException('A test must be an instance of Twig_TestInterface or Twig_SimpleTest');
  4837. }
  4838. if ($name instanceof Twig_SimpleTest) {
  4839. $test = $name;
  4840. $name = $test->getName();
  4841. }
  4842. if ($this->extensionInitialized) {
  4843. throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name));
  4844. }
  4845. $this->staging->addTest($name, $test);
  4846. }
  4847. public function getTests()
  4848. {
  4849. if (!$this->extensionInitialized) {
  4850. $this->initExtensions();
  4851. }
  4852. return $this->tests;
  4853. }
  4854. public function getTest($name)
  4855. {
  4856. if (!$this->extensionInitialized) {
  4857. $this->initExtensions();
  4858. }
  4859. if (isset($this->tests[$name])) {
  4860. return $this->tests[$name];
  4861. }
  4862. return false;
  4863. }
  4864. public function addFunction($name, $function = null)
  4865. {
  4866. if (!$name instanceof Twig_SimpleFunction && !($function instanceof Twig_SimpleFunction || $function instanceof Twig_FunctionInterface)) {
  4867. throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction');
  4868. }
  4869. if ($name instanceof Twig_SimpleFunction) {
  4870. $function = $name;
  4871. $name = $function->getName();
  4872. }
  4873. if ($this->extensionInitialized) {
  4874. throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name));
  4875. }
  4876. $this->staging->addFunction($name, $function);
  4877. }
  4878. public function getFunction($name)
  4879. {
  4880. if (!$this->extensionInitialized) {
  4881. $this->initExtensions();
  4882. }
  4883. if (isset($this->functions[$name])) {
  4884. return $this->functions[$name];
  4885. }
  4886. foreach ($this->functions as $pattern => $function) {
  4887. $pattern = str_replace('\\*','(.*?)', preg_quote($pattern,'#'), $count);
  4888. if ($count) {
  4889. if (preg_match('#^'.$pattern.'$#', $name, $matches)) {
  4890. array_shift($matches);
  4891. $function->setArguments($matches);
  4892. return $function;
  4893. }
  4894. }
  4895. }
  4896. foreach ($this->functionCallbacks as $callback) {
  4897. if (false !== $function = call_user_func($callback, $name)) {
  4898. return $function;
  4899. }
  4900. }
  4901. return false;
  4902. }
  4903. public function registerUndefinedFunctionCallback($callable)
  4904. {
  4905. $this->functionCallbacks[] = $callable;
  4906. }
  4907. public function getFunctions()
  4908. {
  4909. if (!$this->extensionInitialized) {
  4910. $this->initExtensions();
  4911. }
  4912. return $this->functions;
  4913. }
  4914. public function addGlobal($name, $value)
  4915. {
  4916. if ($this->extensionInitialized || $this->runtimeInitialized) {
  4917. if (null === $this->globals) {
  4918. $this->globals = $this->initGlobals();
  4919. }
  4920. }
  4921. if ($this->extensionInitialized || $this->runtimeInitialized) {
  4922. $this->globals[$name] = $value;
  4923. } else {
  4924. $this->staging->addGlobal($name, $value);
  4925. }
  4926. }
  4927. public function getGlobals()
  4928. {
  4929. if (!$this->runtimeInitialized && !$this->extensionInitialized) {
  4930. return $this->initGlobals();
  4931. }
  4932. if (null === $this->globals) {
  4933. $this->globals = $this->initGlobals();
  4934. }
  4935. return $this->globals;
  4936. }
  4937. public function mergeGlobals(array $context)
  4938. {
  4939. foreach ($this->getGlobals() as $key => $value) {
  4940. if (!array_key_exists($key, $context)) {
  4941. $context[$key] = $value;
  4942. }
  4943. }
  4944. return $context;
  4945. }
  4946. public function getUnaryOperators()
  4947. {
  4948. if (!$this->extensionInitialized) {
  4949. $this->initExtensions();
  4950. }
  4951. return $this->unaryOperators;
  4952. }
  4953. public function getBinaryOperators()
  4954. {
  4955. if (!$this->extensionInitialized) {
  4956. $this->initExtensions();
  4957. }
  4958. return $this->binaryOperators;
  4959. }
  4960. public function computeAlternatives($name, $items)
  4961. {
  4962. $alternatives = array();
  4963. foreach ($items as $item) {
  4964. $lev = levenshtein($name, $item);
  4965. if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
  4966. $alternatives[$item] = $lev;
  4967. }
  4968. }
  4969. asort($alternatives);
  4970. return array_keys($alternatives);
  4971. }
  4972. protected function initGlobals()
  4973. {
  4974. $globals = array();
  4975. foreach ($this->extensions as $extension) {
  4976. $globals = array_merge($globals, $extension->getGlobals());
  4977. }
  4978. return array_merge($globals, $this->staging->getGlobals());
  4979. }
  4980. protected function initExtensions()
  4981. {
  4982. if ($this->extensionInitialized) {
  4983. return;
  4984. }
  4985. $this->extensionInitialized = true;
  4986. $this->parsers = new Twig_TokenParserBroker();
  4987. $this->filters = array();
  4988. $this->functions = array();
  4989. $this->tests = array();
  4990. $this->visitors = array();
  4991. $this->unaryOperators = array();
  4992. $this->binaryOperators = array();
  4993. foreach ($this->extensions as $extension) {
  4994. $this->initExtension($extension);
  4995. }
  4996. $this->initExtension($this->staging);
  4997. }
  4998. protected function initExtension(Twig_ExtensionInterface $extension)
  4999. {
  5000. foreach ($extension->getFilters() as $name => $filter) {
  5001. if ($name instanceof Twig_SimpleFilter) {
  5002. $filter = $name;
  5003. $name = $filter->getName();
  5004. } elseif ($filter instanceof Twig_SimpleFilter) {
  5005. $name = $filter->getName();
  5006. }
  5007. $this->filters[$name] = $filter;
  5008. }
  5009. foreach ($extension->getFunctions() as $name => $function) {
  5010. if ($name instanceof Twig_SimpleFunction) {
  5011. $function = $name;
  5012. $name = $function->getName();
  5013. } elseif ($function instanceof Twig_SimpleFunction) {
  5014. $name = $function->getName();
  5015. }
  5016. $this->functions[$name] = $function;
  5017. }
  5018. foreach ($extension->getTests() as $name => $test) {
  5019. if ($name instanceof Twig_SimpleTest) {
  5020. $test = $name;
  5021. $name = $test->getName();
  5022. } elseif ($test instanceof Twig_SimpleTest) {
  5023. $name = $test->getName();
  5024. }
  5025. $this->tests[$name] = $test;
  5026. }
  5027. foreach ($extension->getTokenParsers() as $parser) {
  5028. if ($parser instanceof Twig_TokenParserInterface) {
  5029. $this->parsers->addTokenParser($parser);
  5030. } elseif ($parser instanceof Twig_TokenParserBrokerInterface) {
  5031. $this->parsers->addTokenParserBroker($parser);
  5032. } else {
  5033. throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances');
  5034. }
  5035. }
  5036. foreach ($extension->getNodeVisitors() as $visitor) {
  5037. $this->visitors[] = $visitor;
  5038. }
  5039. if ($operators = $extension->getOperators()) {
  5040. if (2 !== count($operators)) {
  5041. throw new InvalidArgumentException(sprintf('"%s::getOperators()" does not return a valid operators array.', get_class($extension)));
  5042. }
  5043. $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]);
  5044. $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]);
  5045. }
  5046. }
  5047. protected function writeCacheFile($file, $content)
  5048. {
  5049. $dir = dirname($file);
  5050. if (!is_dir($dir)) {
  5051. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  5052. throw new RuntimeException(sprintf("Unable to create the cache directory (%s).", $dir));
  5053. }
  5054. } elseif (!is_writable($dir)) {
  5055. throw new RuntimeException(sprintf("Unable to write in the cache directory (%s).", $dir));
  5056. }
  5057. $tmpFile = tempnam(dirname($file), basename($file));
  5058. if (false !== @file_put_contents($tmpFile, $content)) {
  5059. if (@rename($tmpFile, $file) || (@copy($tmpFile, $file) && unlink($tmpFile))) {
  5060. @chmod($file, 0666 & ~umask());
  5061. return;
  5062. }
  5063. }
  5064. throw new RuntimeException(sprintf('Failed to write cache file "%s".', $file));
  5065. }
  5066. }
  5067. }
  5068. namespace
  5069. {
  5070. interface Twig_ExtensionInterface
  5071. {
  5072. public function initRuntime(Twig_Environment $environment);
  5073. public function getTokenParsers();
  5074. public function getNodeVisitors();
  5075. public function getFilters();
  5076. public function getTests();
  5077. public function getFunctions();
  5078. public function getOperators();
  5079. public function getGlobals();
  5080. public function getName();
  5081. }
  5082. }
  5083. namespace
  5084. {
  5085. abstract class Twig_Extension implements Twig_ExtensionInterface
  5086. {
  5087. public function initRuntime(Twig_Environment $environment)
  5088. {
  5089. }
  5090. public function getTokenParsers()
  5091. {
  5092. return array();
  5093. }
  5094. public function getNodeVisitors()
  5095. {
  5096. return array();
  5097. }
  5098. public function getFilters()
  5099. {
  5100. return array();
  5101. }
  5102. public function getTests()
  5103. {
  5104. return array();
  5105. }
  5106. public function getFunctions()
  5107. {
  5108. return array();
  5109. }
  5110. public function getOperators()
  5111. {
  5112. return array();
  5113. }
  5114. public function getGlobals()
  5115. {
  5116. return array();
  5117. }
  5118. }
  5119. }
  5120. namespace
  5121. {
  5122. if (!defined('ENT_SUBSTITUTE')) {
  5123. define('ENT_SUBSTITUTE', 8);
  5124. }
  5125. class Twig_Extension_Core extends Twig_Extension
  5126. {
  5127. protected $dateFormats = array('F j, Y H:i','%d days');
  5128. protected $numberFormat = array(0,'.',',');
  5129. protected $timezone = null;
  5130. public function setDateFormat($format = null, $dateIntervalFormat = null)
  5131. {
  5132. if (null !== $format) {
  5133. $this->dateFormats[0] = $format;
  5134. }
  5135. if (null !== $dateIntervalFormat) {
  5136. $this->dateFormats[1] = $dateIntervalFormat;
  5137. }
  5138. }
  5139. public function getDateFormat()
  5140. {
  5141. return $this->dateFormats;
  5142. }
  5143. public function setTimezone($timezone)
  5144. {
  5145. $this->timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
  5146. }
  5147. public function getTimezone()
  5148. {
  5149. if (null === $this->timezone) {
  5150. $this->timezone = new DateTimeZone(date_default_timezone_get());
  5151. }
  5152. return $this->timezone;
  5153. }
  5154. public function setNumberFormat($decimal, $decimalPoint, $thousandSep)
  5155. {
  5156. $this->numberFormat = array($decimal, $decimalPoint, $thousandSep);
  5157. }
  5158. public function getNumberFormat()
  5159. {
  5160. return $this->numberFormat;
  5161. }
  5162. public function getTokenParsers()
  5163. {
  5164. return array(
  5165. new Twig_TokenParser_For(),
  5166. new Twig_TokenParser_If(),
  5167. new Twig_TokenParser_Extends(),
  5168. new Twig_TokenParser_Include(),
  5169. new Twig_TokenParser_Block(),
  5170. new Twig_TokenParser_Use(),
  5171. new Twig_TokenParser_Filter(),
  5172. new Twig_TokenParser_Macro(),
  5173. new Twig_TokenParser_Import(),
  5174. new Twig_TokenParser_From(),
  5175. new Twig_TokenParser_Set(),
  5176. new Twig_TokenParser_Spaceless(),
  5177. new Twig_TokenParser_Flush(),
  5178. new Twig_TokenParser_Do(),
  5179. new Twig_TokenParser_Embed(),
  5180. );
  5181. }
  5182. public function getFilters()
  5183. {
  5184. $filters = array(
  5185. new Twig_SimpleFilter('date','twig_date_format_filter', array('needs_environment'=> true)),
  5186. new Twig_SimpleFilter('date_modify','twig_date_modify_filter', array('needs_environment'=> true)),
  5187. new Twig_SimpleFilter('format','sprintf'),
  5188. new Twig_SimpleFilter('replace','strtr'),
  5189. new Twig_SimpleFilter('number_format','twig_number_format_filter', array('needs_environment'=> true)),
  5190. new Twig_SimpleFilter('abs','abs'),
  5191. new Twig_SimpleFilter('url_encode','twig_urlencode_filter'),
  5192. new Twig_SimpleFilter('json_encode','twig_jsonencode_filter'),
  5193. new Twig_SimpleFilter('convert_encoding','twig_convert_encoding'),
  5194. new Twig_SimpleFilter('title','twig_title_string_filter', array('needs_environment'=> true)),
  5195. new Twig_SimpleFilter('capitalize','twig_capitalize_string_filter', array('needs_environment'=> true)),
  5196. new Twig_SimpleFilter('upper','strtoupper'),
  5197. new Twig_SimpleFilter('lower','strtolower'),
  5198. new Twig_SimpleFilter('striptags','strip_tags'),
  5199. new Twig_SimpleFilter('trim','trim'),
  5200. new Twig_SimpleFilter('nl2br','nl2br', array('pre_escape'=>'html','is_safe'=> array('html'))),
  5201. new Twig_SimpleFilter('join','twig_join_filter'),
  5202. new Twig_SimpleFilter('split','twig_split_filter'),
  5203. new Twig_SimpleFilter('sort','twig_sort_filter'),
  5204. new Twig_SimpleFilter('merge','twig_array_merge'),
  5205. new Twig_SimpleFilter('batch','twig_array_batch'),
  5206. new Twig_SimpleFilter('reverse','twig_reverse_filter', array('needs_environment'=> true)),
  5207. new Twig_SimpleFilter('length','twig_length_filter', array('needs_environment'=> true)),
  5208. new Twig_SimpleFilter('slice','twig_slice', array('needs_environment'=> true)),
  5209. new Twig_SimpleFilter('first','twig_first', array('needs_environment'=> true)),
  5210. new Twig_SimpleFilter('last','twig_last', array('needs_environment'=> true)),
  5211. new Twig_SimpleFilter('default','_twig_default_filter', array('node_class'=>'Twig_Node_Expression_Filter_Default')),
  5212. new Twig_SimpleFilter('keys','twig_get_array_keys_filter'),
  5213. new Twig_SimpleFilter('escape','twig_escape_filter', array('needs_environment'=> true,'is_safe_callback'=>'twig_escape_filter_is_safe')),
  5214. new Twig_SimpleFilter('e','twig_escape_filter', array('needs_environment'=> true,'is_safe_callback'=>'twig_escape_filter_is_safe')),
  5215. );
  5216. if (function_exists('mb_get_info')) {
  5217. $filters[] = new Twig_SimpleFilter('upper','twig_upper_filter', array('needs_environment'=> true));
  5218. $filters[] = new Twig_SimpleFilter('lower','twig_lower_filter', array('needs_environment'=> true));
  5219. }
  5220. return $filters;
  5221. }
  5222. public function getFunctions()
  5223. {
  5224. return array(
  5225. new Twig_SimpleFunction('range','range'),
  5226. new Twig_SimpleFunction('constant','twig_constant'),
  5227. new Twig_SimpleFunction('cycle','twig_cycle'),
  5228. new Twig_SimpleFunction('random','twig_random', array('needs_environment'=> true)),
  5229. new Twig_SimpleFunction('date','twig_date_converter', array('needs_environment'=> true)),
  5230. new Twig_SimpleFunction('include','twig_include', array('needs_environment'=> true,'needs_context'=> true)),
  5231. );
  5232. }
  5233. public function getTests()
  5234. {
  5235. return array(
  5236. new Twig_SimpleTest('even', null, array('node_class'=>'Twig_Node_Expression_Test_Even')),
  5237. new Twig_SimpleTest('odd', null, array('node_class'=>'Twig_Node_Expression_Test_Odd')),
  5238. new Twig_SimpleTest('defined', null, array('node_class'=>'Twig_Node_Expression_Test_Defined')),
  5239. new Twig_SimpleTest('sameas', null, array('node_class'=>'Twig_Node_Expression_Test_Sameas')),
  5240. new Twig_SimpleTest('none', null, array('node_class'=>'Twig_Node_Expression_Test_Null')),
  5241. new Twig_SimpleTest('null', null, array('node_class'=>'Twig_Node_Expression_Test_Null')),
  5242. new Twig_SimpleTest('divisibleby', null, array('node_class'=>'Twig_Node_Expression_Test_Divisibleby')),
  5243. new Twig_SimpleTest('constant', null, array('node_class'=>'Twig_Node_Expression_Test_Constant')),
  5244. new Twig_SimpleTest('empty','twig_test_empty'),
  5245. new Twig_SimpleTest('iterable','twig_test_iterable'),
  5246. );
  5247. }
  5248. public function getOperators()
  5249. {
  5250. return array(
  5251. array('not'=> array('precedence'=> 50,'class'=>'Twig_Node_Expression_Unary_Not'),'-'=> array('precedence'=> 500,'class'=>'Twig_Node_Expression_Unary_Neg'),'+'=> array('precedence'=> 500,'class'=>'Twig_Node_Expression_Unary_Pos'),
  5252. ),
  5253. array('or'=> array('precedence'=> 10,'class'=>'Twig_Node_Expression_Binary_Or','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'and'=> array('precedence'=> 15,'class'=>'Twig_Node_Expression_Binary_And','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'b-or'=> array('precedence'=> 16,'class'=>'Twig_Node_Expression_Binary_BitwiseOr','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'b-xor'=> array('precedence'=> 17,'class'=>'Twig_Node_Expression_Binary_BitwiseXor','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'b-and'=> array('precedence'=> 18,'class'=>'Twig_Node_Expression_Binary_BitwiseAnd','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'=='=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_Equal','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'!='=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_NotEqual','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'<'=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_Less','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'>'=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_Greater','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'>='=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_GreaterEqual','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'<='=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_LessEqual','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'not in'=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_NotIn','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'in'=> array('precedence'=> 20,'class'=>'Twig_Node_Expression_Binary_In','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'..'=> array('precedence'=> 25,'class'=>'Twig_Node_Expression_Binary_Range','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'+'=> array('precedence'=> 30,'class'=>'Twig_Node_Expression_Binary_Add','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'-'=> array('precedence'=> 30,'class'=>'Twig_Node_Expression_Binary_Sub','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'~'=> array('precedence'=> 40,'class'=>'Twig_Node_Expression_Binary_Concat','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'*'=> array('precedence'=> 60,'class'=>'Twig_Node_Expression_Binary_Mul','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'/'=> array('precedence'=> 60,'class'=>'Twig_Node_Expression_Binary_Div','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'//'=> array('precedence'=> 60,'class'=>'Twig_Node_Expression_Binary_FloorDiv','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'%'=> array('precedence'=> 60,'class'=>'Twig_Node_Expression_Binary_Mod','associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'is'=> array('precedence'=> 100,'callable'=> array($this,'parseTestExpression'),'associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'is not'=> array('precedence'=> 100,'callable'=> array($this,'parseNotTestExpression'),'associativity'=> Twig_ExpressionParser::OPERATOR_LEFT),'**'=> array('precedence'=> 200,'class'=>'Twig_Node_Expression_Binary_Power','associativity'=> Twig_ExpressionParser::OPERATOR_RIGHT),
  5254. ),
  5255. );
  5256. }
  5257. public function parseNotTestExpression(Twig_Parser $parser, $node)
  5258. {
  5259. return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($parser, $node), $parser->getCurrentToken()->getLine());
  5260. }
  5261. public function parseTestExpression(Twig_Parser $parser, $node)
  5262. {
  5263. $stream = $parser->getStream();
  5264. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  5265. $arguments = null;
  5266. if ($stream->test(Twig_Token::PUNCTUATION_TYPE,'(')) {
  5267. $arguments = $parser->getExpressionParser()->parseArguments(true);
  5268. }
  5269. $class = $this->getTestNodeClass($parser, $name, $node->getLine());
  5270. return new $class($node, $name, $arguments, $parser->getCurrentToken()->getLine());
  5271. }
  5272. protected function getTestNodeClass(Twig_Parser $parser, $name, $line)
  5273. {
  5274. $env = $parser->getEnvironment();
  5275. $testMap = $env->getTests();
  5276. if (!isset($testMap[$name])) {
  5277. $message = sprintf('The test "%s" does not exist', $name);
  5278. if ($alternatives = $env->computeAlternatives($name, array_keys($env->getTests()))) {
  5279. $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
  5280. }
  5281. throw new Twig_Error_Syntax($message, $line, $parser->getFilename());
  5282. }
  5283. if ($testMap[$name] instanceof Twig_SimpleTest) {
  5284. return $testMap[$name]->getNodeClass();
  5285. }
  5286. return $testMap[$name] instanceof Twig_Test_Node ? $testMap[$name]->getClass() :'Twig_Node_Expression_Test';
  5287. }
  5288. public function getName()
  5289. {
  5290. return'core';
  5291. }
  5292. }
  5293. function twig_cycle($values, $position)
  5294. {
  5295. if (!is_array($values) && !$values instanceof ArrayAccess) {
  5296. return $values;
  5297. }
  5298. return $values[$position % count($values)];
  5299. }
  5300. function twig_random(Twig_Environment $env, $values = null)
  5301. {
  5302. if (null === $values) {
  5303. return mt_rand();
  5304. }
  5305. if (is_int($values) || is_float($values)) {
  5306. return $values < 0 ? mt_rand($values, 0) : mt_rand(0, $values);
  5307. }
  5308. if ($values instanceof Traversable) {
  5309. $values = iterator_to_array($values);
  5310. } elseif (is_string($values)) {
  5311. if (''=== $values) {
  5312. return'';
  5313. }
  5314. if (null !== $charset = $env->getCharset()) {
  5315. if ('UTF-8'!= $charset) {
  5316. $values = twig_convert_encoding($values,'UTF-8', $charset);
  5317. }
  5318. $values = preg_split('/(?<!^)(?!$)/u', $values);
  5319. if ('UTF-8'!= $charset) {
  5320. foreach ($values as $i => $value) {
  5321. $values[$i] = twig_convert_encoding($value, $charset,'UTF-8');
  5322. }
  5323. }
  5324. } else {
  5325. return $values[mt_rand(0, strlen($values) - 1)];
  5326. }
  5327. }
  5328. if (!is_array($values)) {
  5329. return $values;
  5330. }
  5331. if (0 === count($values)) {
  5332. throw new Twig_Error_Runtime('The random function cannot pick from an empty array.');
  5333. }
  5334. return $values[array_rand($values, 1)];
  5335. }
  5336. function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null)
  5337. {
  5338. if (null === $format) {
  5339. $formats = $env->getExtension('core')->getDateFormat();
  5340. $format = $date instanceof DateInterval ? $formats[1] : $formats[0];
  5341. }
  5342. if ($date instanceof DateInterval) {
  5343. return $date->format($format);
  5344. }
  5345. return twig_date_converter($env, $date, $timezone)->format($format);
  5346. }
  5347. function twig_date_modify_filter(Twig_Environment $env, $date, $modifier)
  5348. {
  5349. $date = twig_date_converter($env, $date, false);
  5350. $date->modify($modifier);
  5351. return $date;
  5352. }
  5353. function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null)
  5354. {
  5355. if (!$timezone) {
  5356. $defaultTimezone = $env->getExtension('core')->getTimezone();
  5357. } elseif (!$timezone instanceof DateTimeZone) {
  5358. $defaultTimezone = new DateTimeZone($timezone);
  5359. } else {
  5360. $defaultTimezone = $timezone;
  5361. }
  5362. if ($date instanceof DateTime) {
  5363. $date = clone $date;
  5364. if (false !== $timezone) {
  5365. $date->setTimezone($defaultTimezone);
  5366. }
  5367. return $date;
  5368. }
  5369. $asString = (string) $date;
  5370. if (ctype_digit($asString) || (!empty($asString) &&'-'=== $asString[0] && ctype_digit(substr($asString, 1)))) {
  5371. $date ='@'.$date;
  5372. }
  5373. $date = new DateTime($date, $defaultTimezone);
  5374. if (false !== $timezone) {
  5375. $date->setTimezone($defaultTimezone);
  5376. }
  5377. return $date;
  5378. }
  5379. function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null)
  5380. {
  5381. $defaults = $env->getExtension('core')->getNumberFormat();
  5382. if (null === $decimal) {
  5383. $decimal = $defaults[0];
  5384. }
  5385. if (null === $decimalPoint) {
  5386. $decimalPoint = $defaults[1];
  5387. }
  5388. if (null === $thousandSep) {
  5389. $thousandSep = $defaults[2];
  5390. }
  5391. return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
  5392. }
  5393. function twig_urlencode_filter($url, $raw = false)
  5394. {
  5395. if (is_array($url)) {
  5396. return http_build_query($url,'','&');
  5397. }
  5398. if ($raw) {
  5399. return rawurlencode($url);
  5400. }
  5401. return urlencode($url);
  5402. }
  5403. if (version_compare(PHP_VERSION,'5.3.0','<')) {
  5404. function twig_jsonencode_filter($value, $options = 0)
  5405. {
  5406. if ($value instanceof Twig_Markup) {
  5407. $value = (string) $value;
  5408. } elseif (is_array($value)) {
  5409. array_walk_recursive($value,'_twig_markup2string');
  5410. }
  5411. return json_encode($value);
  5412. }
  5413. } else {
  5414. function twig_jsonencode_filter($value, $options = 0)
  5415. {
  5416. if ($value instanceof Twig_Markup) {
  5417. $value = (string) $value;
  5418. } elseif (is_array($value)) {
  5419. array_walk_recursive($value,'_twig_markup2string');
  5420. }
  5421. return json_encode($value, $options);
  5422. }
  5423. }
  5424. function _twig_markup2string(&$value)
  5425. {
  5426. if ($value instanceof Twig_Markup) {
  5427. $value = (string) $value;
  5428. }
  5429. }
  5430. function twig_array_merge($arr1, $arr2)
  5431. {
  5432. if (!is_array($arr1) || !is_array($arr2)) {
  5433. throw new Twig_Error_Runtime('The merge filter only works with arrays or hashes.');
  5434. }
  5435. return array_merge($arr1, $arr2);
  5436. }
  5437. function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false)
  5438. {
  5439. if ($item instanceof Traversable) {
  5440. $item = iterator_to_array($item, false);
  5441. }
  5442. if (is_array($item)) {
  5443. return array_slice($item, $start, $length, $preserveKeys);
  5444. }
  5445. $item = (string) $item;
  5446. if (function_exists('mb_get_info') && null !== $charset = $env->getCharset()) {
  5447. return mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset);
  5448. }
  5449. return null === $length ? substr($item, $start) : substr($item, $start, $length);
  5450. }
  5451. function twig_first(Twig_Environment $env, $item)
  5452. {
  5453. $elements = twig_slice($env, $item, 0, 1, false);
  5454. return is_string($elements) ? $elements[0] : current($elements);
  5455. }
  5456. function twig_last(Twig_Environment $env, $item)
  5457. {
  5458. $elements = twig_slice($env, $item, -1, 1, false);
  5459. return is_string($elements) ? $elements[0] : current($elements);
  5460. }
  5461. function twig_join_filter($value, $glue ='')
  5462. {
  5463. if ($value instanceof Traversable) {
  5464. $value = iterator_to_array($value, false);
  5465. }
  5466. return implode($glue, (array) $value);
  5467. }
  5468. function twig_split_filter($value, $delimiter, $limit = null)
  5469. {
  5470. if (empty($delimiter)) {
  5471. return str_split($value, null === $limit ? 1 : $limit);
  5472. }
  5473. return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit);
  5474. }
  5475. function _twig_default_filter($value, $default ='')
  5476. {
  5477. if (twig_test_empty($value)) {
  5478. return $default;
  5479. }
  5480. return $value;
  5481. }
  5482. function twig_get_array_keys_filter($array)
  5483. {
  5484. if (is_object($array) && $array instanceof Traversable) {
  5485. return array_keys(iterator_to_array($array));
  5486. }
  5487. if (!is_array($array)) {
  5488. return array();
  5489. }
  5490. return array_keys($array);
  5491. }
  5492. function twig_reverse_filter(Twig_Environment $env, $item, $preserveKeys = false)
  5493. {
  5494. if (is_object($item) && $item instanceof Traversable) {
  5495. return array_reverse(iterator_to_array($item), $preserveKeys);
  5496. }
  5497. if (is_array($item)) {
  5498. return array_reverse($item, $preserveKeys);
  5499. }
  5500. if (null !== $charset = $env->getCharset()) {
  5501. $string = (string) $item;
  5502. if ('UTF-8'!= $charset) {
  5503. $item = twig_convert_encoding($string,'UTF-8', $charset);
  5504. }
  5505. preg_match_all('/./us', $item, $matches);
  5506. $string = implode('', array_reverse($matches[0]));
  5507. if ('UTF-8'!= $charset) {
  5508. $string = twig_convert_encoding($string, $charset,'UTF-8');
  5509. }
  5510. return $string;
  5511. }
  5512. return strrev((string) $item);
  5513. }
  5514. function twig_sort_filter($array)
  5515. {
  5516. asort($array);
  5517. return $array;
  5518. }
  5519. function twig_in_filter($value, $compare)
  5520. {
  5521. if (is_array($compare)) {
  5522. return in_array($value, $compare, is_object($value));
  5523. } elseif (is_string($compare)) {
  5524. if (!strlen($value)) {
  5525. return empty($compare);
  5526. }
  5527. return false !== strpos($compare, (string) $value);
  5528. } elseif ($compare instanceof Traversable) {
  5529. return in_array($value, iterator_to_array($compare, false), is_object($value));
  5530. }
  5531. return false;
  5532. }
  5533. function twig_escape_filter(Twig_Environment $env, $string, $strategy ='html', $charset = null, $autoescape = false)
  5534. {
  5535. if ($autoescape && is_object($string) && $string instanceof Twig_Markup) {
  5536. return $string;
  5537. }
  5538. if (!is_string($string) && !(is_object($string) && method_exists($string,'__toString'))) {
  5539. return $string;
  5540. }
  5541. if (null === $charset) {
  5542. $charset = $env->getCharset();
  5543. }
  5544. $string = (string) $string;
  5545. switch ($strategy) {
  5546. case'js':
  5547. if ('UTF-8'!= $charset) {
  5548. $string = twig_convert_encoding($string,'UTF-8', $charset);
  5549. }
  5550. if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
  5551. throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  5552. }
  5553. $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su','_twig_escape_js_callback', $string);
  5554. if ('UTF-8'!= $charset) {
  5555. $string = twig_convert_encoding($string, $charset,'UTF-8');
  5556. }
  5557. return $string;
  5558. case'css':
  5559. if ('UTF-8'!= $charset) {
  5560. $string = twig_convert_encoding($string,'UTF-8', $charset);
  5561. }
  5562. if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
  5563. throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  5564. }
  5565. $string = preg_replace_callback('#[^a-zA-Z0-9]#Su','_twig_escape_css_callback', $string);
  5566. if ('UTF-8'!= $charset) {
  5567. $string = twig_convert_encoding($string, $charset,'UTF-8');
  5568. }
  5569. return $string;
  5570. case'html_attr':
  5571. if ('UTF-8'!= $charset) {
  5572. $string = twig_convert_encoding($string,'UTF-8', $charset);
  5573. }
  5574. if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
  5575. throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  5576. }
  5577. $string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su','_twig_escape_html_attr_callback', $string);
  5578. if ('UTF-8'!= $charset) {
  5579. $string = twig_convert_encoding($string, $charset,'UTF-8');
  5580. }
  5581. return $string;
  5582. case'html':
  5583. static $htmlspecialcharsCharsets = array('iso-8859-1'=> true,'iso8859-1'=> true,'iso-8859-15'=> true,'iso8859-15'=> true,'utf-8'=> true,'cp866'=> true,'ibm866'=> true,'866'=> true,'cp1251'=> true,'windows-1251'=> true,'win-1251'=> true,'1251'=> true,'cp1252'=> true,'windows-1252'=> true,'1252'=> true,'koi8-r'=> true,'koi8-ru'=> true,'koi8r'=> true,'big5'=> true,'950'=> true,'gb2312'=> true,'936'=> true,'big5-hkscs'=> true,'shift_jis'=> true,'sjis'=> true,'932'=> true,'euc-jp'=> true,'eucjp'=> true,'iso8859-5'=> true,'iso-8859-5'=> true,'macroman'=> true,
  5584. );
  5585. if (isset($htmlspecialcharsCharsets[strtolower($charset)])) {
  5586. return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
  5587. }
  5588. $string = twig_convert_encoding($string,'UTF-8', $charset);
  5589. $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE,'UTF-8');
  5590. return twig_convert_encoding($string, $charset,'UTF-8');
  5591. case'url':
  5592. if (version_compare(PHP_VERSION,'5.3.0','<')) {
  5593. return str_replace('%7E','~', rawurlencode($string));
  5594. }
  5595. return rawurlencode($string);
  5596. default:
  5597. throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: html, js, url, css, and html_attr).', $strategy));
  5598. }
  5599. }
  5600. function twig_escape_filter_is_safe(Twig_Node $filterArgs)
  5601. {
  5602. foreach ($filterArgs as $arg) {
  5603. if ($arg instanceof Twig_Node_Expression_Constant) {
  5604. return array($arg->getAttribute('value'));
  5605. }
  5606. return array();
  5607. }
  5608. return array('html');
  5609. }
  5610. if (function_exists('mb_convert_encoding')) {
  5611. function twig_convert_encoding($string, $to, $from)
  5612. {
  5613. return mb_convert_encoding($string, $to, $from);
  5614. }
  5615. } elseif (function_exists('iconv')) {
  5616. function twig_convert_encoding($string, $to, $from)
  5617. {
  5618. return iconv($from, $to, $string);
  5619. }
  5620. } else {
  5621. function twig_convert_encoding($string, $to, $from)
  5622. {
  5623. throw new Twig_Error_Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
  5624. }
  5625. }
  5626. function _twig_escape_js_callback($matches)
  5627. {
  5628. $char = $matches[0];
  5629. if (!isset($char[1])) {
  5630. return'\\x'.strtoupper(substr('00'.bin2hex($char), -2));
  5631. }
  5632. $char = twig_convert_encoding($char,'UTF-16BE','UTF-8');
  5633. return'\\u'.strtoupper(substr('0000'.bin2hex($char), -4));
  5634. }
  5635. function _twig_escape_css_callback($matches)
  5636. {
  5637. $char = $matches[0];
  5638. if (!isset($char[1])) {
  5639. $hex = ltrim(strtoupper(bin2hex($char)),'0');
  5640. if (0 === strlen($hex)) {
  5641. $hex ='0';
  5642. }
  5643. return'\\'.$hex.' ';
  5644. }
  5645. $char = twig_convert_encoding($char,'UTF-16BE','UTF-8');
  5646. return'\\'.ltrim(strtoupper(bin2hex($char)),'0').' ';
  5647. }
  5648. function _twig_escape_html_attr_callback($matches)
  5649. {
  5650. static $entityMap = array(
  5651. 34 =>'quot',
  5652. 38 =>'amp',
  5653. 60 =>'lt',
  5654. 62 =>'gt',
  5655. );
  5656. $chr = $matches[0];
  5657. $ord = ord($chr);
  5658. if (($ord <= 0x1f && $chr !="\t"&& $chr !="\n"&& $chr !="\r") || ($ord >= 0x7f && $ord <= 0x9f)) {
  5659. return'&#xFFFD;';
  5660. }
  5661. if (strlen($chr) == 1) {
  5662. $hex = strtoupper(substr('00'.bin2hex($chr), -2));
  5663. } else {
  5664. $chr = twig_convert_encoding($chr,'UTF-16BE','UTF-8');
  5665. $hex = strtoupper(substr('0000'.bin2hex($chr), -4));
  5666. }
  5667. $int = hexdec($hex);
  5668. if (array_key_exists($int, $entityMap)) {
  5669. return sprintf('&%s;', $entityMap[$int]);
  5670. }
  5671. return sprintf('&#x%s;', $hex);
  5672. }
  5673. if (function_exists('mb_get_info')) {
  5674. function twig_length_filter(Twig_Environment $env, $thing)
  5675. {
  5676. return is_scalar($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing);
  5677. }
  5678. function twig_upper_filter(Twig_Environment $env, $string)
  5679. {
  5680. if (null !== ($charset = $env->getCharset())) {
  5681. return mb_strtoupper($string, $charset);
  5682. }
  5683. return strtoupper($string);
  5684. }
  5685. function twig_lower_filter(Twig_Environment $env, $string)
  5686. {
  5687. if (null !== ($charset = $env->getCharset())) {
  5688. return mb_strtolower($string, $charset);
  5689. }
  5690. return strtolower($string);
  5691. }
  5692. function twig_title_string_filter(Twig_Environment $env, $string)
  5693. {
  5694. if (null !== ($charset = $env->getCharset())) {
  5695. return mb_convert_case($string, MB_CASE_TITLE, $charset);
  5696. }
  5697. return ucwords(strtolower($string));
  5698. }
  5699. function twig_capitalize_string_filter(Twig_Environment $env, $string)
  5700. {
  5701. if (null !== ($charset = $env->getCharset())) {
  5702. return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).
  5703. mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
  5704. }
  5705. return ucfirst(strtolower($string));
  5706. }
  5707. }
  5708. else {
  5709. function twig_length_filter(Twig_Environment $env, $thing)
  5710. {
  5711. return is_scalar($thing) ? strlen($thing) : count($thing);
  5712. }
  5713. function twig_title_string_filter(Twig_Environment $env, $string)
  5714. {
  5715. return ucwords(strtolower($string));
  5716. }
  5717. function twig_capitalize_string_filter(Twig_Environment $env, $string)
  5718. {
  5719. return ucfirst(strtolower($string));
  5720. }
  5721. }
  5722. function twig_ensure_traversable($seq)
  5723. {
  5724. if ($seq instanceof Traversable || is_array($seq)) {
  5725. return $seq;
  5726. }
  5727. return array();
  5728. }
  5729. function twig_test_empty($value)
  5730. {
  5731. if ($value instanceof Countable) {
  5732. return 0 == count($value);
  5733. }
  5734. return''=== $value || false === $value || null === $value || array() === $value;
  5735. }
  5736. function twig_test_iterable($value)
  5737. {
  5738. return $value instanceof Traversable || is_array($value);
  5739. }
  5740. function twig_include(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false)
  5741. {
  5742. if ($withContext) {
  5743. $variables = array_merge($context, $variables);
  5744. }
  5745. if ($isSandboxed = $sandboxed && $env->hasExtension('sandbox')) {
  5746. $sandbox = $env->getExtension('sandbox');
  5747. if (!$alreadySandboxed = $sandbox->isSandboxed()) {
  5748. $sandbox->enableSandbox();
  5749. }
  5750. }
  5751. try {
  5752. return $env->resolveTemplate($template)->display($variables);
  5753. } catch (Twig_Error_Loader $e) {
  5754. if (!$ignoreMissing) {
  5755. throw $e;
  5756. }
  5757. }
  5758. if ($isSandboxed && !$alreadySandboxed) {
  5759. $sandbox->disableSandbox();
  5760. }
  5761. }
  5762. function twig_constant($constant, $object = null)
  5763. {
  5764. if (null !== $object) {
  5765. $constant = get_class($object).'::'.$constant;
  5766. }
  5767. return constant($constant);
  5768. }
  5769. function twig_array_batch($items, $size, $fill = null)
  5770. {
  5771. if ($items instanceof Traversable) {
  5772. $items = iterator_to_array($items, false);
  5773. }
  5774. $size = ceil($size);
  5775. $result = array_chunk($items, $size, true);
  5776. if (null !== $fill) {
  5777. $last = count($result) - 1;
  5778. $result[$last] = array_merge(
  5779. $result[$last],
  5780. array_fill(0, $size - count($result[$last]), $fill)
  5781. );
  5782. }
  5783. return $result;
  5784. }
  5785. }
  5786. namespace
  5787. {
  5788. class Twig_Extension_Escaper extends Twig_Extension
  5789. {
  5790. protected $defaultStrategy;
  5791. public function __construct($defaultStrategy ='html')
  5792. {
  5793. $this->setDefaultStrategy($defaultStrategy);
  5794. }
  5795. public function getTokenParsers()
  5796. {
  5797. return array(new Twig_TokenParser_AutoEscape());
  5798. }
  5799. public function getNodeVisitors()
  5800. {
  5801. return array(new Twig_NodeVisitor_Escaper());
  5802. }
  5803. public function getFilters()
  5804. {
  5805. return array(
  5806. new Twig_SimpleFilter('raw','twig_raw_filter', array('is_safe'=> array('all'))),
  5807. );
  5808. }
  5809. public function setDefaultStrategy($defaultStrategy)
  5810. {
  5811. if (true === $defaultStrategy) {
  5812. $defaultStrategy ='html';
  5813. }
  5814. $this->defaultStrategy = $defaultStrategy;
  5815. }
  5816. public function getDefaultStrategy($filename)
  5817. {
  5818. if (!is_string($this->defaultStrategy) && is_callable($this->defaultStrategy)) {
  5819. return call_user_func($this->defaultStrategy, $filename);
  5820. }
  5821. return $this->defaultStrategy;
  5822. }
  5823. public function getName()
  5824. {
  5825. return'escaper';
  5826. }
  5827. }
  5828. function twig_raw_filter($string)
  5829. {
  5830. return $string;
  5831. }
  5832. }
  5833. namespace
  5834. {
  5835. class Twig_Extension_Optimizer extends Twig_Extension
  5836. {
  5837. protected $optimizers;
  5838. public function __construct($optimizers = -1)
  5839. {
  5840. $this->optimizers = $optimizers;
  5841. }
  5842. public function getNodeVisitors()
  5843. {
  5844. return array(new Twig_NodeVisitor_Optimizer($this->optimizers));
  5845. }
  5846. public function getName()
  5847. {
  5848. return'optimizer';
  5849. }
  5850. }
  5851. }
  5852. namespace
  5853. {
  5854. interface Twig_LoaderInterface
  5855. {
  5856. public function getSource($name);
  5857. public function getCacheKey($name);
  5858. public function isFresh($name, $time);
  5859. }
  5860. }
  5861. namespace
  5862. {
  5863. class Twig_Markup implements Countable
  5864. {
  5865. protected $content;
  5866. protected $charset;
  5867. public function __construct($content, $charset)
  5868. {
  5869. $this->content = (string) $content;
  5870. $this->charset = $charset;
  5871. }
  5872. public function __toString()
  5873. {
  5874. return $this->content;
  5875. }
  5876. public function count()
  5877. {
  5878. return function_exists('mb_get_info') ? mb_strlen($this->content, $this->charset) : strlen($this->content);
  5879. }
  5880. }
  5881. }
  5882. namespace
  5883. {
  5884. interface Twig_TemplateInterface
  5885. {
  5886. const ANY_CALL ='any';
  5887. const ARRAY_CALL ='array';
  5888. const METHOD_CALL ='method';
  5889. public function render(array $context);
  5890. public function display(array $context, array $blocks = array());
  5891. public function getEnvironment();
  5892. }
  5893. }
  5894. namespace
  5895. {
  5896. abstract class Twig_Template implements Twig_TemplateInterface
  5897. {
  5898. protected static $cache = array();
  5899. protected $parent;
  5900. protected $parents;
  5901. protected $env;
  5902. protected $blocks;
  5903. protected $traits;
  5904. public function __construct(Twig_Environment $env)
  5905. {
  5906. $this->env = $env;
  5907. $this->blocks = array();
  5908. $this->traits = array();
  5909. }
  5910. abstract public function getTemplateName();
  5911. public function getEnvironment()
  5912. {
  5913. return $this->env;
  5914. }
  5915. public function getParent(array $context)
  5916. {
  5917. if (null !== $this->parent) {
  5918. return $this->parent;
  5919. }
  5920. $parent = $this->doGetParent($context);
  5921. if (false === $parent) {
  5922. return false;
  5923. } elseif ($parent instanceof Twig_Template) {
  5924. $name = $parent->getTemplateName();
  5925. $this->parents[$name] = $parent;
  5926. $parent = $name;
  5927. } elseif (!isset($this->parents[$parent])) {
  5928. $this->parents[$parent] = $this->env->loadTemplate($parent);
  5929. }
  5930. return $this->parents[$parent];
  5931. }
  5932. protected function doGetParent(array $context)
  5933. {
  5934. return false;
  5935. }
  5936. public function isTraitable()
  5937. {
  5938. return true;
  5939. }
  5940. public function displayParentBlock($name, array $context, array $blocks = array())
  5941. {
  5942. $name = (string) $name;
  5943. if (isset($this->traits[$name])) {
  5944. $this->traits[$name][0]->displayBlock($name, $context, $blocks);
  5945. } elseif (false !== $parent = $this->getParent($context)) {
  5946. $parent->displayBlock($name, $context, $blocks);
  5947. } else {
  5948. throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block', $name), -1, $this->getTemplateName());
  5949. }
  5950. }
  5951. public function displayBlock($name, array $context, array $blocks = array())
  5952. {
  5953. $name = (string) $name;
  5954. if (isset($blocks[$name])) {
  5955. $b = $blocks;
  5956. unset($b[$name]);
  5957. call_user_func($blocks[$name], $context, $b);
  5958. } elseif (isset($this->blocks[$name])) {
  5959. call_user_func($this->blocks[$name], $context, $blocks);
  5960. } elseif (false !== $parent = $this->getParent($context)) {
  5961. $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks));
  5962. }
  5963. }
  5964. public function renderParentBlock($name, array $context, array $blocks = array())
  5965. {
  5966. ob_start();
  5967. $this->displayParentBlock($name, $context, $blocks);
  5968. return ob_get_clean();
  5969. }
  5970. public function renderBlock($name, array $context, array $blocks = array())
  5971. {
  5972. ob_start();
  5973. $this->displayBlock($name, $context, $blocks);
  5974. return ob_get_clean();
  5975. }
  5976. public function hasBlock($name)
  5977. {
  5978. return isset($this->blocks[(string) $name]);
  5979. }
  5980. public function getBlockNames()
  5981. {
  5982. return array_keys($this->blocks);
  5983. }
  5984. public function getBlocks()
  5985. {
  5986. return $this->blocks;
  5987. }
  5988. public function display(array $context, array $blocks = array())
  5989. {
  5990. $this->displayWithErrorHandling($this->env->mergeGlobals($context), $blocks);
  5991. }
  5992. public function render(array $context)
  5993. {
  5994. $level = ob_get_level();
  5995. ob_start();
  5996. try {
  5997. $this->display($context);
  5998. } catch (Exception $e) {
  5999. while (ob_get_level() > $level) {
  6000. ob_end_clean();
  6001. }
  6002. throw $e;
  6003. }
  6004. return ob_get_clean();
  6005. }
  6006. protected function displayWithErrorHandling(array $context, array $blocks = array())
  6007. {
  6008. try {
  6009. $this->doDisplay($context, $blocks);
  6010. } catch (Twig_Error $e) {
  6011. if (!$e->getTemplateFile()) {
  6012. $e->setTemplateFile($this->getTemplateName());
  6013. }
  6014. if (false === $e->getTemplateLine()) {
  6015. $e->setTemplateLine(-1);
  6016. $e->guess();
  6017. }
  6018. throw $e;
  6019. } catch (Exception $e) {
  6020. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e);
  6021. }
  6022. }
  6023. abstract protected function doDisplay(array $context, array $blocks = array());
  6024. final protected function getContext($context, $item, $ignoreStrictCheck = false)
  6025. {
  6026. if (!array_key_exists($item, $context)) {
  6027. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  6028. return null;
  6029. }
  6030. throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist', $item), -1, $this->getTemplateName());
  6031. }
  6032. return $context[$item];
  6033. }
  6034. protected function getAttribute($object, $item, array $arguments = array(), $type = Twig_TemplateInterface::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
  6035. {
  6036. $item = ctype_digit((string) $item) ? (int) $item : (string) $item;
  6037. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  6038. if ((is_array($object) && array_key_exists($item, $object))
  6039. || ($object instanceof ArrayAccess && isset($object[$item]))
  6040. ) {
  6041. if ($isDefinedTest) {
  6042. return true;
  6043. }
  6044. return $object[$item];
  6045. }
  6046. if (Twig_TemplateInterface::ARRAY_CALL === $type) {
  6047. if ($isDefinedTest) {
  6048. return false;
  6049. }
  6050. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  6051. return null;
  6052. }
  6053. if (is_object($object)) {
  6054. throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type "%s" does not exist', $item, get_class($object)), -1, $this->getTemplateName());
  6055. } elseif (is_array($object)) {
  6056. throw new Twig_Error_Runtime(sprintf('Key "%s" for array with keys "%s" does not exist', $item, implode(', ', array_keys($object))), -1, $this->getTemplateName());
  6057. } else {
  6058. throw new Twig_Error_Runtime(sprintf('Impossible to access a key ("%s") on a "%s" variable', $item, gettype($object)), -1, $this->getTemplateName());
  6059. }
  6060. }
  6061. }
  6062. if (!is_object($object)) {
  6063. if ($isDefinedTest) {
  6064. return false;
  6065. }
  6066. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  6067. return null;
  6068. }
  6069. throw new Twig_Error_Runtime(sprintf('Item "%s" for "%s" does not exist', $item, is_array($object) ?'Array': $object), -1, $this->getTemplateName());
  6070. }
  6071. $class = get_class($object);
  6072. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  6073. if (isset($object->$item) || array_key_exists($item, $object)) {
  6074. if ($isDefinedTest) {
  6075. return true;
  6076. }
  6077. if ($this->env->hasExtension('sandbox')) {
  6078. $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
  6079. }
  6080. return $object->$item;
  6081. }
  6082. }
  6083. if (!isset(self::$cache[$class]['methods'])) {
  6084. self::$cache[$class]['methods'] = array_change_key_case(array_flip(get_class_methods($object)));
  6085. }
  6086. $lcItem = strtolower($item);
  6087. if (isset(self::$cache[$class]['methods'][$lcItem])) {
  6088. $method = $item;
  6089. } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) {
  6090. $method ='get'.$item;
  6091. } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) {
  6092. $method ='is'.$item;
  6093. } elseif (isset(self::$cache[$class]['methods']['__call'])) {
  6094. $method = $item;
  6095. } else {
  6096. if ($isDefinedTest) {
  6097. return false;
  6098. }
  6099. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  6100. return null;
  6101. }
  6102. throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist', $item, get_class($object)), -1, $this->getTemplateName());
  6103. }
  6104. if ($isDefinedTest) {
  6105. return true;
  6106. }
  6107. if ($this->env->hasExtension('sandbox')) {
  6108. $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method);
  6109. }
  6110. $ret = call_user_func_array(array($object, $method), $arguments);
  6111. if ($object instanceof Twig_TemplateInterface) {
  6112. return $ret ===''?'': new Twig_Markup($ret, $this->env->getCharset());
  6113. }
  6114. return $ret;
  6115. }
  6116. public static function clearCache()
  6117. {
  6118. self::$cache = array();
  6119. }
  6120. }
  6121. }
  6122. namespace Monolog\Formatter
  6123. {
  6124. interface FormatterInterface
  6125. {
  6126. public function format(array $record);
  6127. public function formatBatch(array $records);
  6128. }
  6129. }
  6130. namespace Monolog\Formatter
  6131. {
  6132. class NormalizerFormatter implements FormatterInterface
  6133. {
  6134. const SIMPLE_DATE ="Y-m-d H:i:s";
  6135. protected $dateFormat;
  6136. public function __construct($dateFormat = null)
  6137. {
  6138. $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
  6139. }
  6140. public function format(array $record)
  6141. {
  6142. return $this->normalize($record);
  6143. }
  6144. public function formatBatch(array $records)
  6145. {
  6146. foreach ($records as $key => $record) {
  6147. $records[$key] = $this->format($record);
  6148. }
  6149. return $records;
  6150. }
  6151. protected function normalize($data)
  6152. {
  6153. if (null === $data || is_scalar($data)) {
  6154. return $data;
  6155. }
  6156. if (is_array($data) || $data instanceof \Traversable) {
  6157. $normalized = array();
  6158. foreach ($data as $key => $value) {
  6159. $normalized[$key] = $this->normalize($value);
  6160. }
  6161. return $normalized;
  6162. }
  6163. if ($data instanceof \DateTime) {
  6164. return $data->format($this->dateFormat);
  6165. }
  6166. if (is_object($data)) {
  6167. return sprintf("[object] (%s: %s)", get_class($data), $this->toJson($data, true));
  6168. }
  6169. if (is_resource($data)) {
  6170. return'[resource]';
  6171. }
  6172. return'[unknown('.gettype($data).')]';
  6173. }
  6174. protected function toJson($data, $ignoreErrors = false)
  6175. {
  6176. if ($ignoreErrors) {
  6177. if (version_compare(PHP_VERSION,'5.4.0','>=')) {
  6178. return @json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  6179. }
  6180. return @json_encode($data);
  6181. }
  6182. if (version_compare(PHP_VERSION,'5.4.0','>=')) {
  6183. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  6184. }
  6185. return json_encode($data);
  6186. }
  6187. }
  6188. }
  6189. namespace Monolog\Formatter
  6190. {
  6191. class LineFormatter extends NormalizerFormatter
  6192. {
  6193. const SIMPLE_FORMAT ="[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
  6194. protected $format;
  6195. public function __construct($format = null, $dateFormat = null)
  6196. {
  6197. $this->format = $format ?: static::SIMPLE_FORMAT;
  6198. parent::__construct($dateFormat);
  6199. }
  6200. public function format(array $record)
  6201. {
  6202. $vars = parent::format($record);
  6203. $output = $this->format;
  6204. foreach ($vars['extra'] as $var => $val) {
  6205. if (false !== strpos($output,'%extra.'.$var.'%')) {
  6206. $output = str_replace('%extra.'.$var.'%', $this->convertToString($val), $output);
  6207. unset($vars['extra'][$var]);
  6208. }
  6209. }
  6210. foreach ($vars as $var => $val) {
  6211. $output = str_replace('%'.$var.'%', $this->convertToString($val), $output);
  6212. }
  6213. return $output;
  6214. }
  6215. public function formatBatch(array $records)
  6216. {
  6217. $message ='';
  6218. foreach ($records as $record) {
  6219. $message .= $this->format($record);
  6220. }
  6221. return $message;
  6222. }
  6223. protected function normalize($data)
  6224. {
  6225. if (is_bool($data) || is_null($data)) {
  6226. return var_export($data, true);
  6227. }
  6228. if ($data instanceof \Exception) {
  6229. $previousText ='';
  6230. if ($previous = $data->getPrevious()) {
  6231. do {
  6232. $previousText .=', '.get_class($previous).': '.$previous->getMessage().' at '.$previous->getFile().':'.$previous->getLine();
  6233. } while ($previous = $previous->getPrevious());
  6234. }
  6235. return'[object] ('.get_class($data).': '.$data->getMessage().' at '.$data->getFile().':'.$data->getLine().$previousText.')';
  6236. }
  6237. return parent::normalize($data);
  6238. }
  6239. protected function convertToString($data)
  6240. {
  6241. if (null === $data || is_scalar($data)) {
  6242. return (string) $data;
  6243. }
  6244. $data = $this->normalize($data);
  6245. if (version_compare(PHP_VERSION,'5.4.0','>=')) {
  6246. return $this->toJson($data);
  6247. }
  6248. return str_replace('\\/','/', json_encode($data));
  6249. }
  6250. }
  6251. }
  6252. namespace Monolog\Handler
  6253. {
  6254. use Monolog\Formatter\FormatterInterface;
  6255. interface HandlerInterface
  6256. {
  6257. public function isHandling(array $record);
  6258. public function handle(array $record);
  6259. public function handleBatch(array $records);
  6260. public function pushProcessor($callback);
  6261. public function popProcessor();
  6262. public function setFormatter(FormatterInterface $formatter);
  6263. public function getFormatter();
  6264. }
  6265. }
  6266. namespace Monolog\Handler
  6267. {
  6268. use Monolog\Logger;
  6269. use Monolog\Formatter\FormatterInterface;
  6270. use Monolog\Formatter\LineFormatter;
  6271. abstract class AbstractHandler implements HandlerInterface
  6272. {
  6273. protected $level = Logger::DEBUG;
  6274. protected $bubble = false;
  6275. protected $formatter;
  6276. protected $processors = array();
  6277. public function __construct($level = Logger::DEBUG, $bubble = true)
  6278. {
  6279. $this->level = $level;
  6280. $this->bubble = $bubble;
  6281. }
  6282. public function isHandling(array $record)
  6283. {
  6284. return $record['level'] >= $this->level;
  6285. }
  6286. public function handleBatch(array $records)
  6287. {
  6288. foreach ($records as $record) {
  6289. $this->handle($record);
  6290. }
  6291. }
  6292. public function close()
  6293. {
  6294. }
  6295. public function pushProcessor($callback)
  6296. {
  6297. if (!is_callable($callback)) {
  6298. throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
  6299. }
  6300. array_unshift($this->processors, $callback);
  6301. }
  6302. public function popProcessor()
  6303. {
  6304. if (!$this->processors) {
  6305. throw new \LogicException('You tried to pop from an empty processor stack.');
  6306. }
  6307. return array_shift($this->processors);
  6308. }
  6309. public function setFormatter(FormatterInterface $formatter)
  6310. {
  6311. $this->formatter = $formatter;
  6312. }
  6313. public function getFormatter()
  6314. {
  6315. if (!$this->formatter) {
  6316. $this->formatter = $this->getDefaultFormatter();
  6317. }
  6318. return $this->formatter;
  6319. }
  6320. public function setLevel($level)
  6321. {
  6322. $this->level = $level;
  6323. }
  6324. public function getLevel()
  6325. {
  6326. return $this->level;
  6327. }
  6328. public function setBubble($bubble)
  6329. {
  6330. $this->bubble = $bubble;
  6331. }
  6332. public function getBubble()
  6333. {
  6334. return $this->bubble;
  6335. }
  6336. public function __destruct()
  6337. {
  6338. try {
  6339. $this->close();
  6340. } catch (\Exception $e) {
  6341. }
  6342. }
  6343. protected function getDefaultFormatter()
  6344. {
  6345. return new LineFormatter();
  6346. }
  6347. }
  6348. }
  6349. namespace Monolog\Handler
  6350. {
  6351. abstract class AbstractProcessingHandler extends AbstractHandler
  6352. {
  6353. public function handle(array $record)
  6354. {
  6355. if ($record['level'] < $this->level) {
  6356. return false;
  6357. }
  6358. $record = $this->processRecord($record);
  6359. $record['formatted'] = $this->getFormatter()->format($record);
  6360. $this->write($record);
  6361. return false === $this->bubble;
  6362. }
  6363. abstract protected function write(array $record);
  6364. protected function processRecord(array $record)
  6365. {
  6366. if ($this->processors) {
  6367. foreach ($this->processors as $processor) {
  6368. $record = call_user_func($processor, $record);
  6369. }
  6370. }
  6371. return $record;
  6372. }
  6373. }
  6374. }
  6375. namespace Monolog\Handler
  6376. {
  6377. use Monolog\Logger;
  6378. class StreamHandler extends AbstractProcessingHandler
  6379. {
  6380. protected $stream;
  6381. protected $url;
  6382. public function __construct($stream, $level = Logger::DEBUG, $bubble = true)
  6383. {
  6384. parent::__construct($level, $bubble);
  6385. if (is_resource($stream)) {
  6386. $this->stream = $stream;
  6387. } else {
  6388. $this->url = $stream;
  6389. }
  6390. }
  6391. public function close()
  6392. {
  6393. if (is_resource($this->stream)) {
  6394. fclose($this->stream);
  6395. }
  6396. $this->stream = null;
  6397. }
  6398. protected function write(array $record)
  6399. {
  6400. if (null === $this->stream) {
  6401. if (!$this->url) {
  6402. throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
  6403. }
  6404. $errorMessage = null;
  6405. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  6406. $errorMessage = preg_replace('{^fopen\(.*?\): }','', $msg);
  6407. });
  6408. $this->stream = fopen($this->url,'a');
  6409. restore_error_handler();
  6410. if (!is_resource($this->stream)) {
  6411. $this->stream = null;
  6412. throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: '.$errorMessage, $this->url));
  6413. }
  6414. }
  6415. fwrite($this->stream, (string) $record['formatted']);
  6416. }
  6417. }
  6418. }
  6419. namespace Monolog\Handler
  6420. {
  6421. use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
  6422. use Monolog\Handler\FingersCrossed\ActivationStrategyInterface;
  6423. use Monolog\Logger;
  6424. class FingersCrossedHandler extends AbstractHandler
  6425. {
  6426. protected $handler;
  6427. protected $activationStrategy;
  6428. protected $buffering = true;
  6429. protected $bufferSize;
  6430. protected $buffer = array();
  6431. protected $stopBuffering;
  6432. public function __construct($handler, $activationStrategy = null, $bufferSize = 0, $bubble = true, $stopBuffering = true)
  6433. {
  6434. if (null === $activationStrategy) {
  6435. $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING);
  6436. }
  6437. if (!$activationStrategy instanceof ActivationStrategyInterface) {
  6438. $activationStrategy = new ErrorLevelActivationStrategy($activationStrategy);
  6439. }
  6440. $this->handler = $handler;
  6441. $this->activationStrategy = $activationStrategy;
  6442. $this->bufferSize = $bufferSize;
  6443. $this->bubble = $bubble;
  6444. $this->stopBuffering = $stopBuffering;
  6445. }
  6446. public function isHandling(array $record)
  6447. {
  6448. return true;
  6449. }
  6450. public function handle(array $record)
  6451. {
  6452. if ($this->processors) {
  6453. foreach ($this->processors as $processor) {
  6454. $record = call_user_func($processor, $record);
  6455. }
  6456. }
  6457. if ($this->buffering) {
  6458. $this->buffer[] = $record;
  6459. if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) {
  6460. array_shift($this->buffer);
  6461. }
  6462. if ($this->activationStrategy->isHandlerActivated($record)) {
  6463. if ($this->stopBuffering) {
  6464. $this->buffering = false;
  6465. }
  6466. if (!$this->handler instanceof HandlerInterface) {
  6467. if (!is_callable($this->handler)) {
  6468. throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object");
  6469. }
  6470. $this->handler = call_user_func($this->handler, $record, $this);
  6471. if (!$this->handler instanceof HandlerInterface) {
  6472. throw new \RuntimeException("The factory callable should return a HandlerInterface");
  6473. }
  6474. }
  6475. $this->handler->handleBatch($this->buffer);
  6476. $this->buffer = array();
  6477. }
  6478. } else {
  6479. $this->handler->handle($record);
  6480. }
  6481. return false === $this->bubble;
  6482. }
  6483. public function reset()
  6484. {
  6485. $this->buffering = true;
  6486. }
  6487. }
  6488. }
  6489. namespace Monolog\Handler
  6490. {
  6491. use Monolog\Logger;
  6492. class TestHandler extends AbstractProcessingHandler
  6493. {
  6494. protected $records = array();
  6495. protected $recordsByLevel = array();
  6496. public function getRecords()
  6497. {
  6498. return $this->records;
  6499. }
  6500. public function hasEmergency($record)
  6501. {
  6502. return $this->hasRecord($record, Logger::EMERGENCY);
  6503. }
  6504. public function hasAlert($record)
  6505. {
  6506. return $this->hasRecord($record, Logger::ALERT);
  6507. }
  6508. public function hasCritical($record)
  6509. {
  6510. return $this->hasRecord($record, Logger::CRITICAL);
  6511. }
  6512. public function hasError($record)
  6513. {
  6514. return $this->hasRecord($record, Logger::ERROR);
  6515. }
  6516. public function hasWarning($record)
  6517. {
  6518. return $this->hasRecord($record, Logger::WARNING);
  6519. }
  6520. public function hasNotice($record)
  6521. {
  6522. return $this->hasRecord($record, Logger::NOTICE);
  6523. }
  6524. public function hasInfo($record)
  6525. {
  6526. return $this->hasRecord($record, Logger::INFO);
  6527. }
  6528. public function hasDebug($record)
  6529. {
  6530. return $this->hasRecord($record, Logger::DEBUG);
  6531. }
  6532. public function hasEmergencyRecords()
  6533. {
  6534. return isset($this->recordsByLevel[Logger::EMERGENCY]);
  6535. }
  6536. public function hasAlertRecords()
  6537. {
  6538. return isset($this->recordsByLevel[Logger::ALERT]);
  6539. }
  6540. public function hasCriticalRecords()
  6541. {
  6542. return isset($this->recordsByLevel[Logger::CRITICAL]);
  6543. }
  6544. public function hasErrorRecords()
  6545. {
  6546. return isset($this->recordsByLevel[Logger::ERROR]);
  6547. }
  6548. public function hasWarningRecords()
  6549. {
  6550. return isset($this->recordsByLevel[Logger::WARNING]);
  6551. }
  6552. public function hasNoticeRecords()
  6553. {
  6554. return isset($this->recordsByLevel[Logger::NOTICE]);
  6555. }
  6556. public function hasInfoRecords()
  6557. {
  6558. return isset($this->recordsByLevel[Logger::INFO]);
  6559. }
  6560. public function hasDebugRecords()
  6561. {
  6562. return isset($this->recordsByLevel[Logger::DEBUG]);
  6563. }
  6564. protected function hasRecord($record, $level)
  6565. {
  6566. if (!isset($this->recordsByLevel[$level])) {
  6567. return false;
  6568. }
  6569. if (is_array($record)) {
  6570. $record = $record['message'];
  6571. }
  6572. foreach ($this->recordsByLevel[$level] as $rec) {
  6573. if ($rec['message'] === $record) {
  6574. return true;
  6575. }
  6576. }
  6577. return false;
  6578. }
  6579. protected function write(array $record)
  6580. {
  6581. $this->recordsByLevel[$record['level']][] = $record;
  6582. $this->records[] = $record;
  6583. }
  6584. }
  6585. }
  6586. namespace Psr\Log
  6587. {
  6588. interface LoggerInterface
  6589. {
  6590. public function emergency($message, array $context = array());
  6591. public function alert($message, array $context = array());
  6592. public function critical($message, array $context = array());
  6593. public function error($message, array $context = array());
  6594. public function warning($message, array $context = array());
  6595. public function notice($message, array $context = array());
  6596. public function info($message, array $context = array());
  6597. public function debug($message, array $context = array());
  6598. public function log($level, $message, array $context = array());
  6599. }
  6600. }
  6601. namespace Monolog
  6602. {
  6603. use Monolog\Handler\HandlerInterface;
  6604. use Monolog\Handler\StreamHandler;
  6605. use Psr\Log\LoggerInterface;
  6606. use Psr\Log\InvalidArgumentException;
  6607. class Logger implements LoggerInterface
  6608. {
  6609. const DEBUG = 100;
  6610. const INFO = 200;
  6611. const NOTICE = 250;
  6612. const WARNING = 300;
  6613. const ERROR = 400;
  6614. const CRITICAL = 500;
  6615. const ALERT = 550;
  6616. const EMERGENCY = 600;
  6617. protected static $levels = array(
  6618. 100 =>'DEBUG',
  6619. 200 =>'INFO',
  6620. 250 =>'NOTICE',
  6621. 300 =>'WARNING',
  6622. 400 =>'ERROR',
  6623. 500 =>'CRITICAL',
  6624. 550 =>'ALERT',
  6625. 600 =>'EMERGENCY',
  6626. );
  6627. protected static $timezone;
  6628. protected $name;
  6629. protected $handlers;
  6630. protected $processors;
  6631. public function __construct($name, array $handlers = array(), array $processors = array())
  6632. {
  6633. $this->name = $name;
  6634. $this->handlers = $handlers;
  6635. $this->processors = $processors;
  6636. }
  6637. public function getName()
  6638. {
  6639. return $this->name;
  6640. }
  6641. public function pushHandler(HandlerInterface $handler)
  6642. {
  6643. array_unshift($this->handlers, $handler);
  6644. }
  6645. public function popHandler()
  6646. {
  6647. if (!$this->handlers) {
  6648. throw new \LogicException('You tried to pop from an empty handler stack.');
  6649. }
  6650. return array_shift($this->handlers);
  6651. }
  6652. public function pushProcessor($callback)
  6653. {
  6654. if (!is_callable($callback)) {
  6655. throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
  6656. }
  6657. array_unshift($this->processors, $callback);
  6658. }
  6659. public function popProcessor()
  6660. {
  6661. if (!$this->processors) {
  6662. throw new \LogicException('You tried to pop from an empty processor stack.');
  6663. }
  6664. return array_shift($this->processors);
  6665. }
  6666. public function addRecord($level, $message, array $context = array())
  6667. {
  6668. if (!$this->handlers) {
  6669. $this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
  6670. }
  6671. if (!static::$timezone) {
  6672. static::$timezone = new \DateTimeZone(date_default_timezone_get() ?:'UTC');
  6673. }
  6674. $record = array('message'=> (string) $message,'context'=> $context,'level'=> $level,'level_name'=> static::getLevelName($level),'channel'=> $this->name,'datetime'=> \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone)->setTimezone(static::$timezone),'extra'=> array(),
  6675. );
  6676. $handlerKey = null;
  6677. foreach ($this->handlers as $key => $handler) {
  6678. if ($handler->isHandling($record)) {
  6679. $handlerKey = $key;
  6680. break;
  6681. }
  6682. }
  6683. if (null === $handlerKey) {
  6684. return false;
  6685. }
  6686. foreach ($this->processors as $processor) {
  6687. $record = call_user_func($processor, $record);
  6688. }
  6689. while (isset($this->handlers[$handlerKey]) &&
  6690. false === $this->handlers[$handlerKey]->handle($record)) {
  6691. $handlerKey++;
  6692. }
  6693. return true;
  6694. }
  6695. public function addDebug($message, array $context = array())
  6696. {
  6697. return $this->addRecord(static::DEBUG, $message, $context);
  6698. }
  6699. public function addInfo($message, array $context = array())
  6700. {
  6701. return $this->addRecord(static::INFO, $message, $context);
  6702. }
  6703. public function addNotice($message, array $context = array())
  6704. {
  6705. return $this->addRecord(static::NOTICE, $message, $context);
  6706. }
  6707. public function addWarning($message, array $context = array())
  6708. {
  6709. return $this->addRecord(static::WARNING, $message, $context);
  6710. }
  6711. public function addError($message, array $context = array())
  6712. {
  6713. return $this->addRecord(static::ERROR, $message, $context);
  6714. }
  6715. public function addCritical($message, array $context = array())
  6716. {
  6717. return $this->addRecord(static::CRITICAL, $message, $context);
  6718. }
  6719. public function addAlert($message, array $context = array())
  6720. {
  6721. return $this->addRecord(static::ALERT, $message, $context);
  6722. }
  6723. public function addEmergency($message, array $context = array())
  6724. {
  6725. return $this->addRecord(static::EMERGENCY, $message, $context);
  6726. }
  6727. public static function getLevels()
  6728. {
  6729. return array_flip(static::$levels);
  6730. }
  6731. public static function getLevelName($level)
  6732. {
  6733. if (!isset(static::$levels[$level])) {
  6734. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  6735. }
  6736. return static::$levels[$level];
  6737. }
  6738. public function isHandling($level)
  6739. {
  6740. $record = array('level'=> $level,
  6741. );
  6742. foreach ($this->handlers as $handler) {
  6743. if ($handler->isHandling($record)) {
  6744. return true;
  6745. }
  6746. }
  6747. return false;
  6748. }
  6749. public function log($level, $message, array $context = array())
  6750. {
  6751. if (is_string($level) && defined(__CLASS__.'::'.strtoupper($level))) {
  6752. $level = constant(__CLASS__.'::'.strtoupper($level));
  6753. }
  6754. return $this->addRecord($level, $message, $context);
  6755. }
  6756. public function debug($message, array $context = array())
  6757. {
  6758. return $this->addRecord(static::DEBUG, $message, $context);
  6759. }
  6760. public function info($message, array $context = array())
  6761. {
  6762. return $this->addRecord(static::INFO, $message, $context);
  6763. }
  6764. public function notice($message, array $context = array())
  6765. {
  6766. return $this->addRecord(static::NOTICE, $message, $context);
  6767. }
  6768. public function warn($message, array $context = array())
  6769. {
  6770. return $this->addRecord(static::WARNING, $message, $context);
  6771. }
  6772. public function warning($message, array $context = array())
  6773. {
  6774. return $this->addRecord(static::WARNING, $message, $context);
  6775. }
  6776. public function err($message, array $context = array())
  6777. {
  6778. return $this->addRecord(static::ERROR, $message, $context);
  6779. }
  6780. public function error($message, array $context = array())
  6781. {
  6782. return $this->addRecord(static::ERROR, $message, $context);
  6783. }
  6784. public function crit($message, array $context = array())
  6785. {
  6786. return $this->addRecord(static::CRITICAL, $message, $context);
  6787. }
  6788. public function critical($message, array $context = array())
  6789. {
  6790. return $this->addRecord(static::CRITICAL, $message, $context);
  6791. }
  6792. public function alert($message, array $context = array())
  6793. {
  6794. return $this->addRecord(static::ALERT, $message, $context);
  6795. }
  6796. public function emerg($message, array $context = array())
  6797. {
  6798. return $this->addRecord(static::EMERGENCY, $message, $context);
  6799. }
  6800. public function emergency($message, array $context = array())
  6801. {
  6802. return $this->addRecord(static::EMERGENCY, $message, $context);
  6803. }
  6804. }
  6805. }
  6806. namespace Symfony\Component\HttpKernel\Log
  6807. {
  6808. use Psr\Log\LoggerInterface as PsrLogger;
  6809. interface LoggerInterface extends PsrLogger
  6810. {
  6811. public function emerg($message, array $context = array());
  6812. public function crit($message, array $context = array());
  6813. public function err($message, array $context = array());
  6814. public function warn($message, array $context = array());
  6815. }
  6816. }
  6817. namespace Symfony\Component\HttpKernel\Log
  6818. {
  6819. interface DebugLoggerInterface
  6820. {
  6821. public function getLogs();
  6822. public function countErrors();
  6823. }
  6824. }
  6825. namespace Symfony\Bridge\Monolog
  6826. {
  6827. use Monolog\Logger as BaseLogger;
  6828. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  6829. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  6830. class Logger extends BaseLogger implements LoggerInterface, DebugLoggerInterface
  6831. {
  6832. public function emerg($message, array $context = array())
  6833. {
  6834. return parent::addRecord(BaseLogger::EMERGENCY, $message, $context);
  6835. }
  6836. public function crit($message, array $context = array())
  6837. {
  6838. return parent::addRecord(BaseLogger::CRITICAL, $message, $context);
  6839. }
  6840. public function err($message, array $context = array())
  6841. {
  6842. return parent::addRecord(BaseLogger::ERROR, $message, $context);
  6843. }
  6844. public function warn($message, array $context = array())
  6845. {
  6846. return parent::addRecord(BaseLogger::WARNING, $message, $context);
  6847. }
  6848. public function getLogs()
  6849. {
  6850. if ($logger = $this->getDebugLogger()) {
  6851. return $logger->getLogs();
  6852. }
  6853. }
  6854. public function countErrors()
  6855. {
  6856. if ($logger = $this->getDebugLogger()) {
  6857. return $logger->countErrors();
  6858. }
  6859. }
  6860. private function getDebugLogger()
  6861. {
  6862. foreach ($this->handlers as $handler) {
  6863. if ($handler instanceof DebugLoggerInterface) {
  6864. return $handler;
  6865. }
  6866. }
  6867. }
  6868. }
  6869. }
  6870. namespace Symfony\Bridge\Monolog\Handler
  6871. {
  6872. use Monolog\Logger;
  6873. use Monolog\Handler\TestHandler;
  6874. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  6875. class DebugHandler extends TestHandler implements DebugLoggerInterface
  6876. {
  6877. public function getLogs()
  6878. {
  6879. $records = array();
  6880. foreach ($this->records as $record) {
  6881. $records[] = array('timestamp'=> $record['datetime']->getTimestamp(),'message'=> $record['message'],'priority'=> $record['level'],'priorityName'=> $record['level_name'],'context'=> $record['context'],
  6882. );
  6883. }
  6884. return $records;
  6885. }
  6886. public function countErrors()
  6887. {
  6888. $cnt = 0;
  6889. $levels = array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY);
  6890. foreach ($levels as $level) {
  6891. if (isset($this->recordsByLevel[$level])) {
  6892. $cnt += count($this->recordsByLevel[$level]);
  6893. }
  6894. }
  6895. return $cnt;
  6896. }
  6897. }
  6898. }
  6899. namespace Monolog\Handler\FingersCrossed
  6900. {
  6901. interface ActivationStrategyInterface
  6902. {
  6903. public function isHandlerActivated(array $record);
  6904. }
  6905. }
  6906. namespace Monolog\Handler\FingersCrossed
  6907. {
  6908. class ErrorLevelActivationStrategy implements ActivationStrategyInterface
  6909. {
  6910. private $actionLevel;
  6911. public function __construct($actionLevel)
  6912. {
  6913. $this->actionLevel = $actionLevel;
  6914. }
  6915. public function isHandlerActivated(array $record)
  6916. {
  6917. return $record['level'] >= $this->actionLevel;
  6918. }
  6919. }
  6920. }
  6921. namespace Sensio\Bundle\FrameworkExtraBundle\EventListener
  6922. {
  6923. use Doctrine\Common\Annotations\Reader;
  6924. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  6925. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
  6926. use Doctrine\Common\Util\ClassUtils;
  6927. class ControllerListener
  6928. {
  6929. protected $reader;
  6930. public function __construct(Reader $reader)
  6931. {
  6932. $this->reader = $reader;
  6933. }
  6934. public function onKernelController(FilterControllerEvent $event)
  6935. {
  6936. if (!is_array($controller = $event->getController())) {
  6937. return;
  6938. }
  6939. $className = class_exists('Doctrine\Common\Util\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
  6940. $object = new \ReflectionClass($className);
  6941. $method = $object->getMethod($controller[1]);
  6942. $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object));
  6943. $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method));
  6944. $configurations = array();
  6945. foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) {
  6946. if (!array_key_exists($key, $classConfigurations)) {
  6947. $configurations[$key] = $methodConfigurations[$key];
  6948. } elseif (!array_key_exists($key, $methodConfigurations)) {
  6949. $configurations[$key] = $classConfigurations[$key];
  6950. } else {
  6951. if (is_array($classConfigurations[$key])) {
  6952. if (!is_array($methodConfigurations[$key])) {
  6953. throw new \UnexpectedValueException('Configurations should both be an array or both not be an array');
  6954. }
  6955. $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]);
  6956. } else {
  6957. $configurations[$key] = $methodConfigurations[$key];
  6958. }
  6959. }
  6960. }
  6961. $request = $event->getRequest();
  6962. foreach ($configurations as $key => $attributes) {
  6963. $request->attributes->set($key, $attributes);
  6964. }
  6965. }
  6966. protected function getConfigurations(array $annotations)
  6967. {
  6968. $configurations = array();
  6969. foreach ($annotations as $configuration) {
  6970. if ($configuration instanceof ConfigurationInterface) {
  6971. if ($configuration->allowArray()) {
  6972. $configurations['_'.$configuration->getAliasName()][] = $configuration;
  6973. } else {
  6974. $configurations['_'.$configuration->getAliasName()] = $configuration;
  6975. }
  6976. }
  6977. }
  6978. return $configurations;
  6979. }
  6980. }
  6981. }
  6982. namespace Sensio\Bundle\FrameworkExtraBundle\EventListener
  6983. {
  6984. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  6985. use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager;
  6986. use Symfony\Component\HttpFoundation\Request;
  6987. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  6988. class ParamConverterListener
  6989. {
  6990. protected $manager;
  6991. public function __construct(ParamConverterManager $manager)
  6992. {
  6993. $this->manager = $manager;
  6994. }
  6995. public function onKernelController(FilterControllerEvent $event)
  6996. {
  6997. $controller = $event->getController();
  6998. $request = $event->getRequest();
  6999. $configurations = array();
  7000. if ($configuration = $request->attributes->get('_converters')) {
  7001. foreach (is_array($configuration) ? $configuration : array($configuration) as $configuration) {
  7002. $configurations[$configuration->getName()] = $configuration;
  7003. }
  7004. }
  7005. if (is_array($controller)) {
  7006. $r = new \ReflectionMethod($controller[0], $controller[1]);
  7007. } else {
  7008. $r = new \ReflectionFunction($controller);
  7009. }
  7010. foreach ($r->getParameters() as $param) {
  7011. if (!$param->getClass() || $param->getClass()->isInstance($request)) {
  7012. continue;
  7013. }
  7014. $name = $param->getName();
  7015. if (!isset($configurations[$name])) {
  7016. $configuration = new ParamConverter(array());
  7017. $configuration->setName($name);
  7018. $configuration->setClass($param->getClass()->getName());
  7019. $configurations[$name] = $configuration;
  7020. } elseif (null === $configurations[$name]->getClass()) {
  7021. $configurations[$name]->setClass($param->getClass()->getName());
  7022. }
  7023. $configurations[$name]->setIsOptional($param->isOptional());
  7024. }
  7025. $this->manager->apply($request, $configurations);
  7026. }
  7027. }
  7028. }
  7029. namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter
  7030. {
  7031. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
  7032. use Symfony\Component\HttpFoundation\Request;
  7033. interface ParamConverterInterface
  7034. {
  7035. function apply(Request $request, ConfigurationInterface $configuration);
  7036. function supports(ConfigurationInterface $configuration);
  7037. }
  7038. }
  7039. namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter
  7040. {
  7041. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
  7042. use Symfony\Component\HttpFoundation\Request;
  7043. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7044. use DateTime;
  7045. class DateTimeParamConverter implements ParamConverterInterface
  7046. {
  7047. public function apply(Request $request, ConfigurationInterface $configuration)
  7048. {
  7049. $param = $configuration->getName();
  7050. if (!$request->attributes->has($param)) {
  7051. return false;
  7052. }
  7053. $options = $configuration->getOptions();
  7054. $value = $request->attributes->get($param);
  7055. $date = isset($options['format'])
  7056. ? DateTime::createFromFormat($options['format'], $value)
  7057. : new DateTime($value);
  7058. if (!$date) {
  7059. throw new NotFoundHttpException('Invalid date given.');
  7060. }
  7061. $request->attributes->set($param, $date);
  7062. return true;
  7063. }
  7064. public function supports(ConfigurationInterface $configuration)
  7065. {
  7066. if (null === $configuration->getClass()) {
  7067. return false;
  7068. }
  7069. return"DateTime"=== $configuration->getClass();
  7070. }
  7071. }
  7072. }
  7073. namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter
  7074. {
  7075. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
  7076. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  7077. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7078. use Symfony\Component\HttpFoundation\Request;
  7079. use Doctrine\Common\Persistence\ManagerRegistry;
  7080. class DoctrineParamConverter implements ParamConverterInterface
  7081. {
  7082. protected $registry;
  7083. public function __construct(ManagerRegistry $registry = null)
  7084. {
  7085. $this->registry = $registry;
  7086. }
  7087. public function apply(Request $request, ConfigurationInterface $configuration)
  7088. {
  7089. $name = $configuration->getName();
  7090. $class = $configuration->getClass();
  7091. $options = $this->getOptions($configuration);
  7092. if (null === $request->attributes->get($name, false)) {
  7093. $configuration->setIsOptional(true);
  7094. }
  7095. if (false === $object = $this->find($class, $request, $options, $name)) {
  7096. if (false === $object = $this->findOneBy($class, $request, $options)) {
  7097. if ($configuration->isOptional()) {
  7098. $object = null;
  7099. } else {
  7100. throw new \LogicException('Unable to guess how to get a Doctrine instance from the request information.');
  7101. }
  7102. }
  7103. }
  7104. if (null === $object && false === $configuration->isOptional()) {
  7105. throw new NotFoundHttpException(sprintf('%s object not found.', $class));
  7106. }
  7107. $request->attributes->set($name, $object);
  7108. return true;
  7109. }
  7110. protected function find($class, Request $request, $options, $name)
  7111. {
  7112. if ($options['mapping'] || $options['exclude']) {
  7113. return false;
  7114. }
  7115. $id = $this->getIdentifier($request, $options, $name);
  7116. if (false === $id || null === $id) {
  7117. return false;
  7118. }
  7119. if (isset($options['repository_method'])) {
  7120. $method = $options['repository_method'];
  7121. } else {
  7122. $method ='find';
  7123. }
  7124. return $this->getManager($options['entity_manager'], $class)->getRepository($class)->$method($id);
  7125. }
  7126. protected function getIdentifier(Request $request, $options, $name)
  7127. {
  7128. if (isset($options['id'])) {
  7129. if (!is_array($options['id'])) {
  7130. $name = $options['id'];
  7131. } elseif (is_array($options['id'])) {
  7132. $id = array();
  7133. foreach ($options['id'] as $field) {
  7134. $id[$field] = $request->attributes->get($field);
  7135. }
  7136. return $id;
  7137. }
  7138. }
  7139. if ($request->attributes->has($name)) {
  7140. return $request->attributes->get($name);
  7141. }
  7142. if ($request->attributes->has('id')) {
  7143. return $request->attributes->get('id');
  7144. }
  7145. return false;
  7146. }
  7147. protected function findOneBy($class, Request $request, $options)
  7148. {
  7149. if (!$options['mapping']) {
  7150. $keys = $request->attributes->keys();
  7151. $options['mapping'] = $keys ? array_combine($keys, $keys) : array();
  7152. }
  7153. foreach ($options['exclude'] as $exclude) {
  7154. unset($options['mapping'][$exclude]);
  7155. }
  7156. if (!$options['mapping']) {
  7157. return false;
  7158. }
  7159. $criteria = array();
  7160. $em = $this->getManager($options['entity_manager'], $class);
  7161. $metadata = $em->getClassMetadata($class);
  7162. foreach ($options['mapping'] as $attribute => $field) {
  7163. if ($metadata->hasField($field) || ($metadata->hasAssociation($field) && $metadata->isSingleValuedAssociation($field))) {
  7164. $criteria[$field] = $request->attributes->get($attribute);
  7165. }
  7166. }
  7167. if (!$criteria) {
  7168. return false;
  7169. }
  7170. if (isset($options['repository_method'])) {
  7171. $method = $options['repository_method'];
  7172. } else {
  7173. $method ='findOneBy';
  7174. }
  7175. return $em->getRepository($class)->$method($criteria);
  7176. }
  7177. public function supports(ConfigurationInterface $configuration)
  7178. {
  7179. if (!$configuration instanceof ParamConverter) {
  7180. return false;
  7181. }
  7182. if (null === $this->registry || !count($this->registry->getManagers())) {
  7183. return false;
  7184. }
  7185. if (null === $configuration->getClass()) {
  7186. return false;
  7187. }
  7188. $options = $this->getOptions($configuration);
  7189. $em = $this->getManager($options['entity_manager'], $configuration->getClass());
  7190. if (null === $em) {
  7191. return false;
  7192. }
  7193. return ! $em->getMetadataFactory()->isTransient($configuration->getClass());
  7194. }
  7195. protected function getOptions(ConfigurationInterface $configuration)
  7196. {
  7197. return array_replace(array('entity_manager'=> null,'exclude'=> array(),'mapping'=> array(),
  7198. ), $configuration->getOptions());
  7199. }
  7200. private function getManager($name, $class)
  7201. {
  7202. if (null === $name) {
  7203. return $this->registry->getManagerForClass($class);
  7204. }
  7205. return $this->registry->getManager($name);
  7206. }
  7207. }
  7208. }
  7209. namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter
  7210. {
  7211. use Symfony\Component\HttpFoundation\Request;
  7212. class ParamConverterManager
  7213. {
  7214. protected $converters = array();
  7215. protected $namedConverters = array();
  7216. public function apply(Request $request, $configurations)
  7217. {
  7218. if (is_object($configurations)) {
  7219. $configurations = array($configurations);
  7220. }
  7221. foreach ($configurations as $configuration) {
  7222. $this->applyConverter($request, $configuration);
  7223. }
  7224. }
  7225. protected function applyConverter(Request $request, $configuration)
  7226. {
  7227. $value = $request->attributes->get($configuration->getName());
  7228. $className = $configuration->getClass();
  7229. if (is_object($value) && $value instanceof $className) {
  7230. return;
  7231. }
  7232. if ($converterName = $configuration->getConverter()) {
  7233. if (!isset($this->namedConverters[$converterName])) {
  7234. throw new \RuntimeException(sprintf("No converter named '%s' found for conversion of parameter '%s'.",
  7235. $converterName, $configuration->getName()
  7236. ));
  7237. }
  7238. $converter = $this->namedConverters[$converterName];
  7239. if (!$converter->supports($configuration)) {
  7240. throw new \RuntimeException(sprintf("Converter '%s' does not support conversion of parameter '%s'.",
  7241. $converterName, $configuration->getName()
  7242. ));
  7243. }
  7244. $converter->apply($request, $configuration);
  7245. return;
  7246. }
  7247. foreach ($this->all() as $converter) {
  7248. if ($converter->supports($configuration)) {
  7249. if ($converter->apply($request, $configuration)) {
  7250. return;
  7251. }
  7252. }
  7253. }
  7254. }
  7255. public function add(ParamConverterInterface $converter, $priority = 0, $name = null)
  7256. {
  7257. if ($priority !== null) {
  7258. if (!isset($this->converters[$priority])) {
  7259. $this->converters[$priority] = array();
  7260. }
  7261. $this->converters[$priority][] = $converter;
  7262. }
  7263. if (null !== $name) {
  7264. $this->namedConverters[$name] = $converter;
  7265. }
  7266. }
  7267. public function all()
  7268. {
  7269. krsort($this->converters);
  7270. $converters = array();
  7271. foreach ($this->converters as $all) {
  7272. $converters = array_merge($converters, $all);
  7273. }
  7274. return $converters;
  7275. }
  7276. }
  7277. }
  7278. namespace Sensio\Bundle\FrameworkExtraBundle\EventListener
  7279. {
  7280. use Symfony\Component\DependencyInjection\ContainerInterface;
  7281. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  7282. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  7283. use Symfony\Component\HttpFoundation\StreamedResponse;
  7284. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  7285. class TemplateListener
  7286. {
  7287. protected $container;
  7288. public function __construct(ContainerInterface $container)
  7289. {
  7290. $this->container = $container;
  7291. }
  7292. public function onKernelController(FilterControllerEvent $event)
  7293. {
  7294. if (!is_array($controller = $event->getController())) {
  7295. return;
  7296. }
  7297. $request = $event->getRequest();
  7298. if (!$configuration = $request->attributes->get('_template')) {
  7299. return;
  7300. }
  7301. if (!$configuration->getTemplate()) {
  7302. $guesser = $this->container->get('sensio_framework_extra.view.guesser');
  7303. $configuration->setTemplate($guesser->guessTemplateName($controller, $request, $configuration->getEngine()));
  7304. }
  7305. $request->attributes->set('_template', $configuration->getTemplate());
  7306. $request->attributes->set('_template_vars', $configuration->getVars());
  7307. $request->attributes->set('_template_streamable', $configuration->isStreamable());
  7308. if (!$configuration->getVars()) {
  7309. $r = new \ReflectionObject($controller[0]);
  7310. $vars = array();
  7311. foreach ($r->getMethod($controller[1])->getParameters() as $param) {
  7312. $vars[] = $param->getName();
  7313. }
  7314. $request->attributes->set('_template_default_vars', $vars);
  7315. }
  7316. }
  7317. public function onKernelView(GetResponseForControllerResultEvent $event)
  7318. {
  7319. $request = $event->getRequest();
  7320. $parameters = $event->getControllerResult();
  7321. $templating = $this->container->get('templating');
  7322. if (null === $parameters) {
  7323. if (!$vars = $request->attributes->get('_template_vars')) {
  7324. if (!$vars = $request->attributes->get('_template_default_vars')) {
  7325. return;
  7326. }
  7327. }
  7328. $parameters = array();
  7329. foreach ($vars as $var) {
  7330. $parameters[$var] = $request->attributes->get($var);
  7331. }
  7332. }
  7333. if (!is_array($parameters)) {
  7334. return $parameters;
  7335. }
  7336. if (!$template = $request->attributes->get('_template')) {
  7337. return $parameters;
  7338. }
  7339. if (!$request->attributes->get('_template_streamable')) {
  7340. $event->setResponse($templating->renderResponse($template, $parameters));
  7341. } else {
  7342. $callback = function () use ($templating, $template, $parameters) {
  7343. return $templating->stream($template, $parameters);
  7344. };
  7345. $event->setResponse(new StreamedResponse($callback));
  7346. }
  7347. }
  7348. }
  7349. }
  7350. namespace Sensio\Bundle\FrameworkExtraBundle\EventListener
  7351. {
  7352. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  7353. use Symfony\Component\HttpFoundation\Response;
  7354. class CacheListener
  7355. {
  7356. public function onKernelResponse(FilterResponseEvent $event)
  7357. {
  7358. if (!$configuration = $event->getRequest()->attributes->get('_cache')) {
  7359. return;
  7360. }
  7361. $response = $event->getResponse();
  7362. if (!$response->isSuccessful()) {
  7363. return;
  7364. }
  7365. if (null !== $configuration->getSMaxAge()) {
  7366. $response->setSharedMaxAge($configuration->getSMaxAge());
  7367. }
  7368. if (null !== $configuration->getMaxAge()) {
  7369. $response->setMaxAge($configuration->getMaxAge());
  7370. }
  7371. if (null !== $configuration->getExpires()) {
  7372. $date = \DateTime::createFromFormat('U', strtotime($configuration->getExpires()), new \DateTimeZone('UTC'));
  7373. $response->setExpires($date);
  7374. }
  7375. if (null !== $configuration->getVary()) {
  7376. $response->setVary($configuration->getVary());
  7377. }
  7378. if ($configuration->isPublic()) {
  7379. $response->setPublic();
  7380. }
  7381. $event->setResponse($response);
  7382. }
  7383. }
  7384. }
  7385. namespace Sensio\Bundle\FrameworkExtraBundle\Configuration
  7386. {
  7387. interface ConfigurationInterface
  7388. {
  7389. function getAliasName();
  7390. function allowArray();
  7391. }
  7392. }
  7393. namespace Sensio\Bundle\FrameworkExtraBundle\Configuration
  7394. {
  7395. abstract class ConfigurationAnnotation implements ConfigurationInterface
  7396. {
  7397. public function __construct(array $values)
  7398. {
  7399. foreach ($values as $k => $v) {
  7400. if (!method_exists($this, $name ='set'.$k)) {
  7401. throw new \RuntimeException(sprintf('Unknown key "%s" for annotation "@%s".', $k, get_class($this)));
  7402. }
  7403. $this->$name($v);
  7404. }
  7405. }
  7406. }
  7407. }
  7408. namespace JMS\DiExtraBundle\HttpKernel
  7409. {
  7410. use Metadata\ClassHierarchyMetadata;
  7411. use JMS\DiExtraBundle\Metadata\ClassMetadata;
  7412. use CG\Core\DefaultNamingStrategy;
  7413. use CG\Proxy\Enhancer;
  7414. use JMS\AopBundle\DependencyInjection\Compiler\PointcutMatchingPass;
  7415. use JMS\DiExtraBundle\Generator\DefinitionInjectorGenerator;
  7416. use JMS\DiExtraBundle\Generator\LookupMethodClassGenerator;
  7417. use JMS\DiExtraBundle\DependencyInjection\Dumper\PhpDumper;
  7418. use Metadata\MetadataFactory;
  7419. use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass;
  7420. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  7421. use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
  7422. use Symfony\Component\DependencyInjection\Parameter;
  7423. use Symfony\Component\DependencyInjection\Reference;
  7424. use Symfony\Component\DependencyInjection\Definition;
  7425. use Symfony\Component\Config\Resource\FileResource;
  7426. use Symfony\Component\DependencyInjection\ContainerBuilder;
  7427. use Symfony\Component\Config\ConfigCache;
  7428. use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver as BaseControllerResolver;
  7429. class ControllerResolver extends BaseControllerResolver
  7430. {
  7431. protected function createController($controller)
  7432. {
  7433. if (false === $pos = strpos($controller,'::')) {
  7434. $count = substr_count($controller,':');
  7435. if (2 == $count) {
  7436. $controller = $this->parser->parse($controller);
  7437. $pos = strpos($controller,'::');
  7438. } elseif (1 == $count) {
  7439. list($service, $method) = explode(':', $controller);
  7440. return array($this->container->get($service), $method);
  7441. } else {
  7442. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  7443. }
  7444. }
  7445. $class = substr($controller, 0, $pos);
  7446. $method = substr($controller, $pos+2);
  7447. if (!class_exists($class)) {
  7448. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  7449. }
  7450. $injector = $this->createInjector($class);
  7451. $controller = call_user_func($injector, $this->container);
  7452. if ($controller instanceof ContainerAwareInterface) {
  7453. $controller->setContainer($this->container);
  7454. }
  7455. return array($controller, $method);
  7456. }
  7457. public function createInjector($class)
  7458. {
  7459. $filename = $this->container->getParameter('jms_di_extra.cache_dir').'/controller_injectors/'.str_replace('\\','', $class).'.php';
  7460. $cache = new ConfigCache($filename, $this->container->getParameter('kernel.debug'));
  7461. if (!$cache->isFresh()) {
  7462. $metadata = $this->container->get('jms_di_extra.metadata.metadata_factory')->getMetadataForClass($class);
  7463. if (null === $metadata) {
  7464. $metadata = new ClassHierarchyMetadata();
  7465. $metadata->addClassMetadata(new ClassMetadata($class));
  7466. }
  7467. if (null !== $metadata->getOutsideClassMetadata()->id
  7468. && 0 !== strpos($metadata->getOutsideClassMetadata()->id,'_jms_di_extra.unnamed.service')) {
  7469. return;
  7470. }
  7471. $this->prepareContainer($cache, $filename, $metadata, $class);
  7472. }
  7473. if ( ! class_exists($class.'__JMSInjector', false)) {
  7474. require $filename;
  7475. }
  7476. return array($class.'__JMSInjector','inject');
  7477. }
  7478. private function prepareContainer($cache, $containerFilename, $metadata, $className)
  7479. {
  7480. $container = new ContainerBuilder();
  7481. $container->setParameter('jms_aop.cache_dir', $this->container->getParameter('jms_di_extra.cache_dir'));
  7482. $def = $container
  7483. ->register('jms_aop.interceptor_loader','JMS\AopBundle\Aop\InterceptorLoader')
  7484. ->addArgument(new Reference('service_container'))
  7485. ->setPublic(false)
  7486. ;
  7487. $ref = $metadata->getOutsideClassMetadata()->reflection;
  7488. while ($ref && false !== $filename = $ref->getFilename()) {
  7489. $container->addResource(new FileResource($filename));
  7490. $ref = $ref->getParentClass();
  7491. }
  7492. $definitions = $this->container->get('jms_di_extra.metadata.converter')->convert($metadata);
  7493. $serviceIds = $parameters = array();
  7494. $controllerDef = array_pop($definitions);
  7495. $container->setDefinition('controller', $controllerDef);
  7496. foreach ($definitions as $id => $def) {
  7497. $container->setDefinition($id, $def);
  7498. }
  7499. $this->generateLookupMethods($controllerDef, $metadata);
  7500. $config = $container->getCompilerPassConfig();
  7501. $config->setOptimizationPasses(array());
  7502. $config->setRemovingPasses(array());
  7503. $config->addPass(new ResolveDefinitionTemplatesPass());
  7504. $config->addPass(new PointcutMatchingPass($this->container->get('jms_aop.pointcut_container')->getPointcuts()));
  7505. $config->addPass(new InlineServiceDefinitionsPass());
  7506. $container->compile();
  7507. if (!file_exists($dir = dirname($containerFilename))) {
  7508. if (false === @mkdir($dir, 0777, true)) {
  7509. throw new \RuntimeException(sprintf('Could not create directory "%s".', $dir));
  7510. }
  7511. }
  7512. static $generator;
  7513. if (null === $generator) {
  7514. $generator = new DefinitionInjectorGenerator();
  7515. }
  7516. $cache->write($generator->generate($container->getDefinition('controller'), $className), $container->getResources());
  7517. }
  7518. private function generateLookupMethods($def, $metadata)
  7519. {
  7520. $found = false;
  7521. foreach ($metadata->classMetadata as $cMetadata) {
  7522. if (!empty($cMetadata->lookupMethods)) {
  7523. $found = true;
  7524. break;
  7525. }
  7526. }
  7527. if (!$found) {
  7528. return;
  7529. }
  7530. $generator = new LookupMethodClassGenerator($metadata);
  7531. $outerClass = $metadata->getOutsideClassMetadata()->reflection;
  7532. if ($file = $def->getFile()) {
  7533. $generator->setRequiredFile($file);
  7534. }
  7535. $enhancer = new Enhancer(
  7536. $outerClass,
  7537. array(),
  7538. array(
  7539. $generator,
  7540. )
  7541. );
  7542. $filename = $this->container->getParameter('jms_di_extra.cache_dir').'/lookup_method_classes/'.str_replace('\\','-', $outerClass->name).'.php';
  7543. $enhancer->writeClass($filename);
  7544. $def->setFile($filename);
  7545. $def->setClass($enhancer->getClassName($outerClass));
  7546. $def->addMethodCall('__jmsDiExtra_setContainer', array(new Reference('service_container')));
  7547. }
  7548. }
  7549. }