PageRenderTime 131ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 2ms

/app/cache/dev/classes.php

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