PageRenderTime 94ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/app/cache/dev/classes.php

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