PageRenderTime 87ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/app/cache/prod/classes.php

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