PageRenderTime 127ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 1ms

/app/cache/dev/classes.php

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