PageRenderTime 62ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/libs/Nette/loader.php

https://github.com/vrana/mvc-exception-demo
PHP | 5110 lines | 4867 code | 207 blank | 36 comment | 172 complexity | dd45e470084c05f79f3a6bac5f762b97 MD5 | raw file
  1. <?php //netteloader=IComponent
  2. /**
  3. * Nette Framework
  4. *
  5. * Copyright (c) 2004, 2010 David Grudl (http://davidgrudl.com)
  6. *
  7. * This source file is subject to the "Nette license" that is bundled
  8. * with this package in the file license.txt, and/or GPL license.
  9. *
  10. * For more information please see http://nette.org
  11. *
  12. * @copyright Copyright (c) 2004, 2010 David Grudl
  13. * @license http://nette.org/license Nette license
  14. * @link http://nette.org
  15. * @category Nette
  16. * @package Nette
  17. */
  18. if(!defined('PHP_VERSION_ID')){$tmp=explode('.',PHP_VERSION);define('PHP_VERSION_ID',($tmp[0]*10000+$tmp[1]*100+$tmp[2]));}if(PHP_VERSION_ID<50200){throw
  19. new
  20. Exception('Nette Framework requires PHP 5.2.0 or newer.');}error_reporting(E_ALL|E_STRICT);@set_magic_quotes_runtime(FALSE);iconv_set_encoding('internal_encoding','UTF-8');extension_loaded('mbstring')&&mb_internal_encoding('UTF-8');header('X-Powered-By: Nette Framework');define('NETTE',TRUE);define('NETTE_VERSION_ID',10000);define('NETTE_PACKAGE','PHP 5.2');function
  21. callback($callback,$m=NULL){return($m===NULL&&$callback
  22. instanceof
  23. Callback)?$callback:new
  24. Callback($callback,$m);}function
  25. dump($var){foreach(func_get_args()as$arg)Debug::dump($arg);return$var;}interface
  26. IComponent{const
  27. NAME_SEPARATOR='-';function
  28. getName();function
  29. getParent();function
  30. setParent(IComponentContainer$parent=NULL,$name=NULL);}interface
  31. IComponentContainer
  32. extends
  33. IComponent{function
  34. addComponent(IComponent$component,$name);function
  35. removeComponent(IComponent$component);function
  36. getComponent($name);function
  37. getComponents($deep=FALSE,$filterType=NULL);}interface
  38. INamingContainer
  39. extends
  40. IComponentContainer{}interface
  41. ISignalReceiver{function
  42. signalReceived($signal);}interface
  43. IStatePersistent{function
  44. loadState(array$params);function
  45. saveState(array&$params);}interface
  46. IRenderable{function
  47. invalidateControl();function
  48. isControlInvalid();}interface
  49. IPartiallyRenderable
  50. extends
  51. IRenderable{}interface
  52. IPresenter{function
  53. run(PresenterRequest$request);}interface
  54. IPresenterLoader{function
  55. getPresenterClass(&$name);}interface
  56. IPresenterResponse{function
  57. send();}interface
  58. IRouter{const
  59. ONE_WAY=1;const
  60. SECURED=2;function
  61. match(IHttpRequest$httpRequest);function
  62. constructUrl(PresenterRequest$appRequest,IHttpRequest$httpRequest);}interface
  63. IDebugPanel{function
  64. getTab();function
  65. getPanel();function
  66. getId();}interface
  67. ICacheStorage{function
  68. read($key);function
  69. write($key,$data,array$dependencies);function
  70. remove($key);function
  71. clean(array$conds);}interface
  72. IConfigAdapter{static
  73. function
  74. load($file,$section=NULL);static
  75. function
  76. save($config,$file,$section=NULL);}interface
  77. IServiceLocator{function
  78. addService($name,$service,$singleton=TRUE,array$options=NULL);function
  79. getService($name,array$options=NULL);function
  80. removeService($name);function
  81. hasService($name);}interface
  82. IFormControl{function
  83. loadHttpData();function
  84. setValue($value);function
  85. getValue();function
  86. getRules();function
  87. getErrors();function
  88. isDisabled();function
  89. translate($s,$count=NULL);}interface
  90. ISubmitterControl
  91. extends
  92. IFormControl{function
  93. isSubmittedBy();function
  94. getValidationScope();}interface
  95. IFormRenderer{function
  96. render(Form$form);}interface
  97. IMailer{function
  98. send(Mail$mail);}interface
  99. IAnnotation{function
  100. __construct(array$values);}interface
  101. IAuthenticator{const
  102. USERNAME='username';const
  103. PASSWORD='password';const
  104. IDENTITY_NOT_FOUND=1;const
  105. INVALID_CREDENTIAL=2;const
  106. FAILURE=3;const
  107. NOT_APPROVED=4;function
  108. authenticate(array$credentials);}interface
  109. IAuthorizator{const
  110. ALL=NULL;const
  111. ALLOW=TRUE;const
  112. DENY=FALSE;function
  113. isAllowed($role=self::ALL,$resource=self::ALL,$privilege=self::ALL);}interface
  114. IIdentity{function
  115. getId();function
  116. getRoles();}interface
  117. IResource{function
  118. getResourceId();}interface
  119. IRole{function
  120. getRoleId();}interface
  121. ITemplate{function
  122. render();}interface
  123. IFileTemplate
  124. extends
  125. ITemplate{function
  126. setFile($file);function
  127. getFile();}interface
  128. ITranslator{function
  129. translate($message,$count=NULL);}interface
  130. IHttpRequest{const
  131. GET='GET',POST='POST',HEAD='HEAD',PUT='PUT',DELETE='DELETE';function
  132. getUri();function
  133. getQuery($key=NULL,$default=NULL);function
  134. getPost($key=NULL,$default=NULL);function
  135. getPostRaw();function
  136. getFile($key);function
  137. getFiles();function
  138. getCookie($key,$default=NULL);function
  139. getCookies();function
  140. getMethod();function
  141. isMethod($method);function
  142. getHeader($header,$default=NULL);function
  143. getHeaders();function
  144. isSecured();function
  145. isAjax();function
  146. getRemoteAddress();function
  147. getRemoteHost();}interface
  148. IHttpResponse{const
  149. PERMANENT=2116333333;const
  150. BROWSER=0;const
  151. S200_OK=200,S204_NO_CONTENT=204,S300_MULTIPLE_CHOICES=300,S301_MOVED_PERMANENTLY=301,S302_FOUND=302,S303_SEE_OTHER=303,S303_POST_GET=303,S304_NOT_MODIFIED=304,S307_TEMPORARY_REDIRECT=307,S400_BAD_REQUEST=400,S401_UNAUTHORIZED=401,S403_FORBIDDEN=403,S404_NOT_FOUND=404,S405_METHOD_NOT_ALLOWED=405,S410_GONE=410,S500_INTERNAL_SERVER_ERROR=500,S501_NOT_IMPLEMENTED=501,S503_SERVICE_UNAVAILABLE=503;function
  152. setCode($code);function
  153. getCode();function
  154. setHeader($name,$value);function
  155. addHeader($name,$value);function
  156. setContentType($type,$charset=NULL);function
  157. redirect($url,$code=self::S302_FOUND);function
  158. setExpiration($seconds);function
  159. isSent();function
  160. getHeaders();function
  161. setCookie($name,$value,$expire,$path=NULL,$domain=NULL,$secure=NULL);function
  162. deleteCookie($name,$path=NULL,$domain=NULL,$secure=NULL);}interface
  163. IUser{function
  164. login($username,$password,$extra=NULL);function
  165. logout($clearIdentity=FALSE);function
  166. isLoggedIn();function
  167. getIdentity();function
  168. setAuthenticationHandler(IAuthenticator$handler);function
  169. getAuthenticationHandler();function
  170. setNamespace($namespace);function
  171. getNamespace();function
  172. getRoles();function
  173. isInRole($role);function
  174. isAllowed();function
  175. setAuthorizationHandler(IAuthorizator$handler);function
  176. getAuthorizationHandler();}class
  177. ArgumentOutOfRangeException
  178. extends
  179. InvalidArgumentException{}class
  180. InvalidStateException
  181. extends
  182. RuntimeException{function
  183. __construct($message='',$code=0,Exception$previous=NULL){if(PHP_VERSION_ID<50300){$this->previous=$previous;parent::__construct($message,$code);}else{parent::__construct($message,$code,$previous);}}}class
  184. NotImplementedException
  185. extends
  186. LogicException{}class
  187. NotSupportedException
  188. extends
  189. LogicException{}class
  190. DeprecatedException
  191. extends
  192. NotSupportedException{}class
  193. MemberAccessException
  194. extends
  195. LogicException{}class
  196. IOException
  197. extends
  198. RuntimeException{}class
  199. FileNotFoundException
  200. extends
  201. IOException{}class
  202. DirectoryNotFoundException
  203. extends
  204. IOException{}class
  205. FatalErrorException
  206. extends
  207. Exception{private$severity;function
  208. __construct($message,$code,$severity,$file,$line,$context){parent::__construct($message,$code);$this->severity=$severity;$this->file=$file;$this->line=$line;$this->context=$context;}function
  209. getSeverity(){return$this->severity;}}final
  210. class
  211. Framework{const
  212. NAME='Nette Framework';const
  213. VERSION='1.0-dev';const
  214. REVISION='1ac0863 released on 2010-07-01';final
  215. function
  216. __construct(){throw
  217. new
  218. LogicException("Cannot instantiate static class ".get_class($this));}static
  219. function
  220. promo(){echo'<a href="http://nette.org" title="Nette Framework - The Most Innovative PHP Framework"><img ','src="http://files.nette.org/icons/nette-powered.gif" alt="Powered by Nette Framework" width="80" height="15" /></a>';}}abstract
  221. class
  222. Object{function
  223. getReflection(){return
  224. new
  225. ClassReflection($this);}function
  226. __call($name,$args){return
  227. ObjectMixin::call($this,$name,$args);}static
  228. function
  229. __callStatic($name,$args){$class=get_called_class();throw
  230. new
  231. MemberAccessException("Call to undefined static method $class::$name().");}static
  232. function
  233. extensionMethod($name,$callback=NULL){if(strpos($name,'::')===FALSE){$class=get_called_class();}else{list($class,$name)=explode('::',$name);}$class=new
  234. ClassReflection($class);if($callback===NULL){return$class->getExtensionMethod($name);}else{$class->setExtensionMethod($name,$callback);}}function&__get($name){return
  235. ObjectMixin::get($this,$name);}function
  236. __set($name,$value){return
  237. ObjectMixin::set($this,$name,$value);}function
  238. __isset($name){return
  239. ObjectMixin::has($this,$name);}function
  240. __unset($name){throw
  241. new
  242. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}final
  243. class
  244. ObjectMixin{private
  245. static$methods;final
  246. function
  247. __construct(){throw
  248. new
  249. LogicException("Cannot instantiate static class ".get_class($this));}static
  250. function
  251. call($_this,$name,$args){$class=new
  252. ClassReflection($_this);if($name===''){throw
  253. new
  254. MemberAccessException("Call to class '$class->name' method without name.");}if($class->hasEventProperty($name)){if(is_array($list=$_this->$name)||$list
  255. instanceof
  256. Traversable){foreach($list
  257. as$handler){callback($handler)->invokeArgs($args);}}return
  258. NULL;}if($cb=$class->getExtensionMethod($name)){array_unshift($args,$_this);return$cb->invokeArgs($args);}throw
  259. new
  260. MemberAccessException("Call to undefined method $class->name::$name().");}static
  261. function&get($_this,$name){$class=get_class($_this);if($name===''){throw
  262. new
  263. MemberAccessException("Cannot read a class '$class' property without name.");}if(!isset(self::$methods[$class])){self::$methods[$class]=array_flip(get_class_methods($class));}$name[0]=$name[0]&"\xDF";$m='get'.$name;if(isset(self::$methods[$class][$m])){$val=$_this->$m();return$val;}$m='is'.$name;if(isset(self::$methods[$class][$m])){$val=$_this->$m();return$val;}$name=func_get_arg(1);throw
  264. new
  265. MemberAccessException("Cannot read an undeclared property $class::\$$name.");}static
  266. function
  267. set($_this,$name,$value){$class=get_class($_this);if($name===''){throw
  268. new
  269. MemberAccessException("Cannot write to a class '$class' property without name.");}if(!isset(self::$methods[$class])){self::$methods[$class]=array_flip(get_class_methods($class));}$name[0]=$name[0]&"\xDF";if(isset(self::$methods[$class]['get'.$name])||isset(self::$methods[$class]['is'.$name])){$m='set'.$name;if(isset(self::$methods[$class][$m])){$_this->$m($value);return;}else{$name=func_get_arg(1);throw
  270. new
  271. MemberAccessException("Cannot write to a read-only property $class::\$$name.");}}$name=func_get_arg(1);throw
  272. new
  273. MemberAccessException("Cannot write to an undeclared property $class::\$$name.");}static
  274. function
  275. has($_this,$name){if($name===''){return
  276. FALSE;}$class=get_class($_this);if(!isset(self::$methods[$class])){self::$methods[$class]=array_flip(get_class_methods($class));}$name[0]=$name[0]&"\xDF";return
  277. isset(self::$methods[$class]['get'.$name])||isset(self::$methods[$class]['is'.$name]);}}final
  278. class
  279. Callback
  280. extends
  281. Object{private$cb;function
  282. __construct($t,$m=NULL){if($m===NULL){$this->cb=$t;}else{$this->cb=array($t,$m);}if(is_object($this->cb)){$this->cb=array($this->cb,'__invoke');}elseif(PHP_VERSION_ID<50202){if(is_string($this->cb)&&strpos($this->cb,':')){$this->cb=explode('::',$this->cb);}if(is_array($this->cb)&&is_string($this->cb[0])&&$a=strrpos($this->cb[0],'\\')){$this->cb[0]=substr($this->cb[0],$a+1);}}else{if(is_string($this->cb)&&$a=strrpos($this->cb,'\\')){$this->cb=substr($this->cb,$a+1);}elseif(is_array($this->cb)&&is_string($this->cb[0])&&$a=strrpos($this->cb[0],'\\')){$this->cb[0]=substr($this->cb[0],$a+1);}}if(!is_callable($this->cb,TRUE)){throw
  283. new
  284. InvalidArgumentException("Invalid callback.");}}function
  285. __invoke(){if(!is_callable($this->cb)){throw
  286. new
  287. InvalidStateException("Callback '$this' is not callable.");}$args=func_get_args();return
  288. call_user_func_array($this->cb,$args);}function
  289. invoke(){if(!is_callable($this->cb)){throw
  290. new
  291. InvalidStateException("Callback '$this' is not callable.");}$args=func_get_args();return
  292. call_user_func_array($this->cb,$args);}function
  293. invokeArgs(array$args){if(!is_callable($this->cb)){throw
  294. new
  295. InvalidStateException("Callback '$this' is not callable.");}return
  296. call_user_func_array($this->cb,$args);}function
  297. isCallable(){return
  298. is_callable($this->cb);}function
  299. getNative(){return$this->cb;}function
  300. __toString(){is_callable($this->cb,TRUE,$textual);return$textual;}}final
  301. class
  302. LimitedScope{private
  303. static$vars;final
  304. function
  305. __construct(){throw
  306. new
  307. LogicException("Cannot instantiate static class ".get_class($this));}static
  308. function
  309. evaluate(){if(func_num_args()>1){self::$vars=func_get_arg(1);extract(self::$vars);}return
  310. eval('?>'.func_get_arg(0));}static
  311. function
  312. load(){if(func_num_args()>1){self::$vars=func_get_arg(1);extract(self::$vars);}return include func_get_arg(0);}}abstract
  313. class
  314. AutoLoader
  315. extends
  316. Object{static
  317. private$loaders=array();public
  318. static$count=0;final
  319. static
  320. function
  321. load($type){foreach(func_get_args()as$type){if(!class_exists($type)){throw
  322. new
  323. InvalidStateException("Unable to load class or interface '$type'.");}}}final
  324. static
  325. function
  326. getLoaders(){return
  327. array_values(self::$loaders);}function
  328. register(){if(!function_exists('spl_autoload_register')){throw
  329. new
  330. RuntimeException('spl_autoload does not exist in this PHP installation.');}spl_autoload_register(array($this,'tryLoad'));self::$loaders[spl_object_hash($this)]=$this;}function
  331. unregister(){unset(self::$loaders[spl_object_hash($this)]);return
  332. spl_autoload_unregister(array($this,'tryLoad'));}abstract
  333. function
  334. tryLoad($type);}abstract
  335. class
  336. Component
  337. extends
  338. Object
  339. implements
  340. IComponent{private$parent;private$name;private$monitors=array();function
  341. __construct(IComponentContainer$parent=NULL,$name=NULL){if($parent!==NULL){$parent->addComponent($this,$name);}elseif(is_string($name)){$this->name=$name;}}function
  342. lookup($type,$need=TRUE){if($a=strrpos($type,'\\'))$type=substr($type,$a+1);if(!isset($this->monitors[$type])){$obj=$this->parent;$path=self::NAME_SEPARATOR.$this->name;$depth=1;while($obj!==NULL){if($obj
  343. instanceof$type)break;$path=self::NAME_SEPARATOR.$obj->getName().$path;$depth++;$obj=$obj->getParent();if($obj===$this)$obj=NULL;}if($obj){$this->monitors[$type]=array($obj,$depth,substr($path,1),FALSE);}else{$this->monitors[$type]=array(NULL,NULL,NULL,FALSE);}}if($need&&$this->monitors[$type][0]===NULL){throw
  344. new
  345. InvalidStateException("Component '$this->name' is not attached to '$type'.");}return$this->monitors[$type][0];}function
  346. lookupPath($type,$need=TRUE){if($a=strrpos($type,'\\'))$type=substr($type,$a+1);$this->lookup($type,$need);return$this->monitors[$type][2];}function
  347. monitor($type){if($a=strrpos($type,'\\'))$type=substr($type,$a+1);if(empty($this->monitors[$type][3])){if($obj=$this->lookup($type,FALSE)){$this->attached($obj);}$this->monitors[$type][3]=TRUE;}}function
  348. unmonitor($type){if($a=strrpos($type,'\\'))$type=substr($type,$a+1);unset($this->monitors[$type]);}protected
  349. function
  350. attached($obj){}protected
  351. function
  352. detached($obj){}final
  353. function
  354. getName(){return$this->name;}final
  355. function
  356. getParent(){return$this->parent;}function
  357. setParent(IComponentContainer$parent=NULL,$name=NULL){if($parent===NULL&&$this->parent===NULL&&$name!==NULL){$this->name=$name;return$this;}elseif($parent===$this->parent&&$name===NULL){return$this;}if($this->parent!==NULL&&$parent!==NULL){throw
  358. new
  359. InvalidStateException("Component '$this->name' already has a parent.");}if($parent===NULL){$this->refreshMonitors(0);$this->parent=NULL;}else{$this->validateParent($parent);$this->parent=$parent;if($name!==NULL)$this->name=$name;$tmp=array();$this->refreshMonitors(0,$tmp);}return$this;}protected
  360. function
  361. validateParent(IComponentContainer$parent){}private
  362. function
  363. refreshMonitors($depth,&$missing=NULL,&$listeners=array()){if($this
  364. instanceof
  365. IComponentContainer){foreach($this->getComponents()as$component){if($component
  366. instanceof
  367. Component){$component->refreshMonitors($depth+1,$missing,$listeners);}}}if($missing===NULL){foreach($this->monitors
  368. as$type=>$rec){if(isset($rec[1])&&$rec[1]>$depth){if($rec[3]){$this->monitors[$type]=array(NULL,NULL,NULL,TRUE);$listeners[]=array($this,$rec[0]);}else{unset($this->monitors[$type]);}}}}else{foreach($this->monitors
  369. as$type=>$rec){if(isset($rec[0])){continue;}elseif(!$rec[3]){unset($this->monitors[$type]);}elseif(isset($missing[$type])){$this->monitors[$type]=array(NULL,NULL,NULL,TRUE);}else{$this->monitors[$type]=NULL;if($obj=$this->lookup($type,FALSE)){$listeners[]=array($this,$obj);}else{$missing[$type]=TRUE;}$this->monitors[$type][3]=TRUE;}}}if($depth===0){$method=$missing===NULL?'detached':'attached';foreach($listeners
  370. as$item){$item[0]->$method($item[1]);}}}function
  371. __clone(){if($this->parent===NULL){return;}elseif($this->parent
  372. instanceof
  373. ComponentContainer){$this->parent=$this->parent->_isCloning();if($this->parent===NULL){$this->refreshMonitors(0);}}else{$this->parent=NULL;$this->refreshMonitors(0);}}final
  374. function
  375. __wakeup(){throw
  376. new
  377. NotImplementedException;}}class
  378. ComponentContainer
  379. extends
  380. Component
  381. implements
  382. IComponentContainer{private$components=array();private$cloning;function
  383. addComponent(IComponent$component,$name,$insertBefore=NULL){if($name===NULL){$name=$component->getName();}if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw
  384. new
  385. InvalidArgumentException("Component name must be integer or string, ".gettype($name)." given.");}elseif(!preg_match('#^[a-zA-Z0-9_]+$#',$name)){throw
  386. new
  387. InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");}if(isset($this->components[$name])){throw
  388. new
  389. InvalidStateException("Component with name '$name' already exists.");}$obj=$this;do{if($obj===$component){throw
  390. new
  391. InvalidStateException("Circular reference detected while adding component '$name'.");}$obj=$obj->getParent();}while($obj!==NULL);$this->validateChildComponent($component);try{if(isset($this->components[$insertBefore])){$tmp=array();foreach($this->components
  392. as$k=>$v){if($k===$insertBefore)$tmp[$name]=$component;$tmp[$k]=$v;}$this->components=$tmp;}else{$this->components[$name]=$component;}$component->setParent($this,$name);}catch(Exception$e){unset($this->components[$name]);throw$e;}}function
  393. removeComponent(IComponent$component){$name=$component->getName();if(!isset($this->components[$name])||$this->components[$name]!==$component){throw
  394. new
  395. InvalidArgumentException("Component named '$name' is not located in this container.");}unset($this->components[$name]);$component->setParent(NULL);}final
  396. function
  397. getComponent($name,$need=TRUE){if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw
  398. new
  399. InvalidArgumentException("Component name must be integer or string, ".gettype($name)." given.");}else{$a=strpos($name,self::NAME_SEPARATOR);if($a!==FALSE){$ext=(string)substr($name,$a+1);$name=substr($name,0,$a);}if($name===''){throw
  400. new
  401. InvalidArgumentException("Component or subcomponent name must not be empty string.");}}if(!isset($this->components[$name])){$component=$this->createComponent($name);if($component
  402. instanceof
  403. IComponent&&$component->getParent()===NULL){$this->addComponent($component,$name);}}if(isset($this->components[$name])){if(!isset($ext)){return$this->components[$name];}elseif($this->components[$name]instanceof
  404. IComponentContainer){return$this->components[$name]->getComponent($ext,$need);}elseif($need){throw
  405. new
  406. InvalidArgumentException("Component with name '$name' is not container and cannot have '$ext' component.");}}elseif($need){throw
  407. new
  408. InvalidArgumentException("Component with name '$name' does not exist.");}}protected
  409. function
  410. createComponent($name){$ucname=ucfirst($name);$method='createComponent'.$ucname;if($ucname!==$name&&method_exists($this,$method)&&$this->getReflection()->getMethod($method)->getName()===$method){return$this->$method($name);}}final
  411. function
  412. getComponents($deep=FALSE,$filterType=NULL){$iterator=new
  413. RecursiveComponentIterator($this->components);if($deep){$deep=$deep>0?RecursiveIteratorIterator::SELF_FIRST:RecursiveIteratorIterator::CHILD_FIRST;$iterator=new
  414. RecursiveIteratorIterator($iterator,$deep);}if($filterType){if($a=strrpos($filterType,'\\'))$filterType=substr($filterType,$a+1);$iterator=new
  415. InstanceFilterIterator($iterator,$filterType);}return$iterator;}protected
  416. function
  417. validateChildComponent(IComponent$child){}function
  418. __clone(){if($this->components){$oldMyself=reset($this->components)->getParent();$oldMyself->cloning=$this;foreach($this->components
  419. as$name=>$component){$this->components[$name]=clone$component;}$oldMyself->cloning=NULL;}parent::__clone();}function
  420. _isCloning(){return$this->cloning;}}class
  421. RecursiveComponentIterator
  422. extends
  423. RecursiveArrayIterator
  424. implements
  425. Countable{function
  426. hasChildren(){return$this->current()instanceof
  427. IComponentContainer;}function
  428. getChildren(){return$this->current()->getComponents();}function
  429. count(){return
  430. iterator_count($this);}}class
  431. FormContainer
  432. extends
  433. ComponentContainer
  434. implements
  435. ArrayAccess,INamingContainer{public$onValidate;protected$currentGroup;protected$valid;function
  436. setDefaults($values,$erase=FALSE){$form=$this->getForm(FALSE);if(!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValues($values,$erase);}return$this;}function
  437. setValues($values,$erase=FALSE){if($values
  438. instanceof
  439. Traversable){$values=iterator_to_array($values);}elseif(!is_array($values)){throw
  440. new
  441. InvalidArgumentException("Values must be an array, ".gettype($values)." given.");}$cursor=&$values;$iterator=$this->getComponents(TRUE);foreach($iterator
  442. as$name=>$control){$sub=$iterator->getSubIterator();if(!isset($sub->cursor)){$sub->cursor=&$cursor;}if($control
  443. instanceof
  444. IFormControl){if((is_array($sub->cursor)||$sub->cursor
  445. instanceof
  446. ArrayAccess)&&array_key_exists($name,$sub->cursor)){$control->setValue($sub->cursor[$name]);}elseif($erase){$control->setValue(NULL);}}if($control
  447. instanceof
  448. INamingContainer){if((is_array($sub->cursor)||$sub->cursor
  449. instanceof
  450. ArrayAccess)&&isset($sub->cursor[$name])){$cursor=&$sub->cursor[$name];}else{unset($cursor);$cursor=NULL;}}}return$this;}function
  451. getValues(){$values=array();$cursor=&$values;$iterator=$this->getComponents(TRUE);foreach($iterator
  452. as$name=>$control){$sub=$iterator->getSubIterator();if(!isset($sub->cursor)){$sub->cursor=&$cursor;}if($control
  453. instanceof
  454. IFormControl&&!$control->isDisabled()&&!($control
  455. instanceof
  456. ISubmitterControl)){$sub->cursor[$name]=$control->getValue();}if($control
  457. instanceof
  458. INamingContainer){$cursor=&$sub->cursor[$name];$cursor=array();}}return$values;}function
  459. isValid(){if($this->valid===NULL){$this->validate();}return$this->valid;}function
  460. validate(){$this->valid=TRUE;$this->onValidate($this);foreach($this->getControls()as$control){if(!$control->getRules()->validate()){$this->valid=FALSE;}}}function
  461. setCurrentGroup(FormGroup$group=NULL){$this->currentGroup=$group;return$this;}function
  462. getCurrentGroup(){return$this->currentGroup;}function
  463. addComponent(IComponent$component,$name,$insertBefore=NULL){parent::addComponent($component,$name,$insertBefore);if($this->currentGroup!==NULL&&$component
  464. instanceof
  465. IFormControl){$this->currentGroup->add($component);}}function
  466. getControls(){return$this->getComponents(TRUE,'IFormControl');}function
  467. getForm($need=TRUE){return$this->lookup('Form',$need);}function
  468. addText($name,$label=NULL,$cols=NULL,$maxLength=NULL){return$this[$name]=new
  469. TextInput($label,$cols,$maxLength);}function
  470. addPassword($name,$label=NULL,$cols=NULL,$maxLength=NULL){$control=new
  471. TextInput($label,$cols,$maxLength);$control->setPasswordMode(TRUE);return$this[$name]=$control;}function
  472. addTextArea($name,$label=NULL,$cols=40,$rows=10){return$this[$name]=new
  473. TextArea($label,$cols,$rows);}function
  474. addFile($name,$label=NULL){return$this[$name]=new
  475. FileUpload($label);}function
  476. addHidden($name,$default=NULL){$control=new
  477. HiddenField;$control->setDefaultValue($default);return$this[$name]=$control;}function
  478. addCheckbox($name,$caption=NULL){return$this[$name]=new
  479. Checkbox($caption);}function
  480. addRadioList($name,$label=NULL,array$items=NULL){return$this[$name]=new
  481. RadioList($label,$items);}function
  482. addSelect($name,$label=NULL,array$items=NULL,$size=NULL){return$this[$name]=new
  483. SelectBox($label,$items,$size);}function
  484. addMultiSelect($name,$label=NULL,array$items=NULL,$size=NULL){return$this[$name]=new
  485. MultiSelectBox($label,$items,$size);}function
  486. addSubmit($name,$caption=NULL){return$this[$name]=new
  487. SubmitButton($caption);}function
  488. addButton($name,$caption){return$this[$name]=new
  489. Button($caption);}function
  490. addImage($name,$src=NULL,$alt=NULL){return$this[$name]=new
  491. ImageButton($src,$alt);}function
  492. addContainer($name){$control=new
  493. FormContainer;$control->currentGroup=$this->currentGroup;return$this[$name]=$control;}final
  494. function
  495. offsetSet($name,$component){$this->addComponent($component,$name);}final
  496. function
  497. offsetGet($name){return$this->getComponent($name,TRUE);}final
  498. function
  499. offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}final
  500. function
  501. offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}final
  502. function
  503. __clone(){throw
  504. new
  505. NotImplementedException('Form cloning is not supported yet.');}}class
  506. Form
  507. extends
  508. FormContainer{const
  509. EQUAL=':equal';const
  510. IS_IN=':equal';const
  511. FILLED=':filled';const
  512. VALID=':valid';const
  513. SUBMITTED=':submitted';const
  514. MIN_LENGTH=':minLength';const
  515. MAX_LENGTH=':maxLength';const
  516. LENGTH=':length';const
  517. EMAIL=':email';const
  518. URL=':url';const
  519. REGEXP=':regexp';const
  520. INTEGER=':integer';const
  521. NUMERIC=':integer';const
  522. FLOAT=':float';const
  523. RANGE=':range';const
  524. MAX_FILE_SIZE=':fileSize';const
  525. MIME_TYPE=':mimeType';const
  526. IMAGE=':image';const
  527. SCRIPT='Nette\\Forms\\InstantClientScript::javascript';const
  528. GET='get';const
  529. POST='post';const
  530. TRACKER_ID='_form_';const
  531. PROTECTOR_ID='_token_';public$onSubmit;public$onInvalidSubmit;private$submittedBy;private$httpData;private$element;private$renderer;private$translator;private$groups=array();private$errors=array();function
  532. __construct($name=NULL){$this->element=Html::el('form');$this->element->action='';$this->element->method=self::POST;$this->element->id='frm-'.$name;$this->monitor(__CLASS__);if($name!==NULL){$tracker=new
  533. HiddenField($name);$tracker->unmonitor(__CLASS__);$this[self::TRACKER_ID]=$tracker;}parent::__construct(NULL,$name);}protected
  534. function
  535. attached($obj){if($obj
  536. instanceof
  537. self){throw
  538. new
  539. InvalidStateException('Nested forms are forbidden.');}}final
  540. function
  541. getForm($need=TRUE){return$this;}function
  542. setAction($url){$this->element->action=$url;return$this;}function
  543. getAction(){return$this->element->action;}function
  544. setMethod($method){if($this->httpData!==NULL){throw
  545. new
  546. InvalidStateException(__METHOD__.'() must be called until the form is empty.');}$this->element->method=strtolower($method);return$this;}function
  547. getMethod(){return$this->element->method;}function
  548. addProtection($message=NULL,$timeout=NULL){$session=$this->getSession()->getNamespace('Nette.Forms.Form/CSRF');$key="key$timeout";if(isset($session->$key)){$token=$session->$key;}else{$session->$key=$token=md5(uniqid('',TRUE));}$session->setExpiration($timeout,$key);$this[self::PROTECTOR_ID]=new
  549. HiddenField($token);$this[self::PROTECTOR_ID]->addRule(':equal',empty($message)?'Security token did not match. Possible CSRF attack.':$message,$token);}function
  550. addGroup($caption=NULL,$setAsCurrent=TRUE){$group=new
  551. FormGroup;$group->setOption('label',$caption);$group->setOption('visual',TRUE);if($setAsCurrent){$this->setCurrentGroup($group);}if(isset($this->groups[$caption])){return$this->groups[]=$group;}else{return$this->groups[$caption]=$group;}}function
  552. removeGroup($name){if(is_string($name)&&isset($this->groups[$name])){$group=$this->groups[$name];}elseif($name
  553. instanceof
  554. FormGroup&&in_array($name,$this->groups,TRUE)){$group=$name;$name=array_search($group,$this->groups,TRUE);}else{throw
  555. new
  556. InvalidArgumentException("Group not found in form '$this->name'");}foreach($group->getControls()as$control){$this->removeComponent($control);}unset($this->groups[$name]);}function
  557. getGroups(){return$this->groups;}function
  558. getGroup($name){return
  559. isset($this->groups[$name])?$this->groups[$name]:NULL;}function
  560. setTranslator(ITranslator$translator=NULL){$this->translator=$translator;return$this;}final
  561. function
  562. getTranslator(){return$this->translator;}function
  563. isAnchored(){return
  564. TRUE;}final
  565. function
  566. isSubmitted(){if($this->submittedBy===NULL){$this->getHttpData();$this->submittedBy=!empty($this->httpData);}return$this->submittedBy;}function
  567. setSubmittedBy(ISubmitterControl$by=NULL){$this->submittedBy=$by===NULL?FALSE:$by;return$this;}final
  568. function
  569. getHttpData(){if($this->httpData===NULL){if(!$this->isAnchored()){throw
  570. new
  571. InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');}$this->httpData=(array)$this->receiveHttpData();}return$this->httpData;}function
  572. fireEvents(){if(!$this->isSubmitted()){return;}elseif($this->submittedBy
  573. instanceof
  574. ISubmitterControl){if(!$this->submittedBy->getValidationScope()||$this->isValid()){$this->submittedBy->click();$this->onSubmit($this);}else{$this->submittedBy->onInvalidClick($this->submittedBy);$this->onInvalidSubmit($this);}}elseif($this->isValid()){$this->onSubmit($this);}else{$this->onInvalidSubmit($this);}}protected
  575. function
  576. receiveHttpData(){$httpRequest=$this->getHttpRequest();if(strcasecmp($this->getMethod(),$httpRequest->getMethod())){return;}$httpRequest->setEncoding('utf-8');if($httpRequest->isMethod('post')){$data=ArrayTools::mergeTree($httpRequest->getPost(),$httpRequest->getFiles());}else{$data=$httpRequest->getQuery();}if($tracker=$this->getComponent(self::TRACKER_ID,FALSE)){if(!isset($data[self::TRACKER_ID])||$data[self::TRACKER_ID]!==$tracker->getValue()){return;}}return$data;}function
  577. getValues(){$values=parent::getValues();unset($values[self::TRACKER_ID],$values[self::PROTECTOR_ID]);return$values;}function
  578. addError($message){$this->valid=FALSE;if($message!==NULL&&!in_array($message,$this->errors,TRUE)){$this->errors[]=$message;}}function
  579. getErrors(){return$this->errors;}function
  580. hasErrors(){return(bool)$this->getErrors();}function
  581. cleanErrors(){$this->errors=array();$this->valid=NULL;}function
  582. getElementPrototype(){return$this->element;}function
  583. setRenderer(IFormRenderer$renderer){$this->renderer=$renderer;return$this;}final
  584. function
  585. getRenderer(){if($this->renderer===NULL){$this->renderer=new
  586. ConventionalRenderer;}return$this->renderer;}function
  587. render(){$args=func_get_args();array_unshift($args,$this);echo
  588. call_user_func_array(array($this->getRenderer(),'render'),$args);}function
  589. __toString(){try{return$this->getRenderer()->render($this);}catch(Exception$e){if(func_get_args()&&func_get_arg(0)){throw$e;}else{Debug::toStringException($e);}}}protected
  590. function
  591. getHttpRequest(){return
  592. class_exists('Environment')?Environment::getHttpRequest():new
  593. HttpRequest;}protected
  594. function
  595. getSession(){return
  596. Environment::getSession();}}class
  597. AppForm
  598. extends
  599. Form
  600. implements
  601. ISignalReceiver{function
  602. __construct(IComponentContainer$parent=NULL,$name=NULL){parent::__construct();$this->monitor('Presenter');if($parent!==NULL){$parent->addComponent($this,$name);}}function
  603. getPresenter($need=TRUE){return$this->lookup('Presenter',$need);}protected
  604. function
  605. attached($presenter){if($presenter
  606. instanceof
  607. Presenter){$name=$this->lookupPath('Presenter');if(!isset($this->getElementPrototype()->id)){$this->getElementPrototype()->id='frm-'.$name;}$this->setAction(new
  608. Link($presenter,$name.self::NAME_SEPARATOR.'submit!',array()));if($this->isSubmitted()){foreach($this->getControls()as$control){$control->loadHttpData();}}}parent::attached($presenter);}function
  609. isAnchored(){return(bool)$this->getPresenter(FALSE);}protected
  610. function
  611. receiveHttpData(){$presenter=$this->getPresenter();if(!$presenter->isSignalReceiver($this,'submit')){return;}$isPost=$this->getMethod()===self::POST;$request=$presenter->getRequest();if($request->isMethod('forward')||$request->isMethod('post')!==$isPost){return;}if($isPost){return
  612. ArrayTools::mergeTree($request->getPost(),$request->getFiles());}else{return$request->getParams();}}function
  613. signalReceived($signal){if($signal==='submit'){$this->fireEvents();}else{throw
  614. new
  615. BadSignalException("There is no handler for signal '$signal' in {$this->reflection->name}.");}}}class
  616. Application
  617. extends
  618. Object{public
  619. static$maxLoop=20;public$defaultServices=array('Nette\\Application\\IRouter'=>'MultiRouter','Nette\\Application\\IPresenterLoader'=>array(__CLASS__,'createPresenterLoader'));public$catchExceptions;public$errorPresenter;public$onStartup;public$onShutdown;public$onRequest;public$onError;public$allowedMethods=array('GET','POST','HEAD','PUT','DELETE');private$requests=array();private$presenter;private$serviceLocator;function
  620. run(){$httpRequest=$this->getHttpRequest();$httpResponse=$this->getHttpResponse();$httpRequest->setEncoding('UTF-8');if(Environment::getVariable('baseUri')===NULL){Environment::setVariable('baseUri',$httpRequest->getUri()->getBasePath());}$session=$this->getSession();if(!$session->isStarted()&&$session->exists()){$session->start();}Debug::addPanel(new
  621. RoutingDebugger($this->getRouter(),$httpRequest));if($this->allowedMethods){$method=$httpRequest->getMethod();if(!in_array($method,$this->allowedMethods,TRUE)){$httpResponse->setCode(IHttpResponse::S501_NOT_IMPLEMENTED);$httpResponse->setHeader('Allow',implode(',',$this->allowedMethods));echo'<h1>Method '.htmlSpecialChars($method).' is not implemented</h1>';return;}}$request=NULL;$repeatedError=FALSE;do{try{if(count($this->requests)>self::$maxLoop){throw
  622. new
  623. ApplicationException('Too many loops detected in application life cycle.');}if(!$request){$this->onStartup($this);$router=$this->getRouter();if($router
  624. instanceof
  625. MultiRouter&&!count($router)){$router[]=new
  626. SimpleRouter(array('presenter'=>'Default','action'=>'default'));}$request=$router->match($httpRequest);if(!($request
  627. instanceof
  628. PresenterRequest)){$request=NULL;throw
  629. new
  630. BadRequestException('No route for HTTP request.');}if(strcasecmp($request->getPresenterName(),$this->errorPresenter)===0){throw
  631. new
  632. BadRequestException('Invalid request.');}}$this->requests[]=$request;$this->onRequest($this,$request);$presenter=$request->getPresenterName();try{$class=$this->getPresenterLoader()->getPresenterClass($presenter);$request->setPresenterName($presenter);}catch(InvalidPresenterException$e){throw
  633. new
  634. BadRequestException($e->getMessage(),404,$e);}$request->freeze();$this->presenter=new$class;$response=$this->presenter->run($request);if($response
  635. instanceof
  636. ForwardingResponse){$request=$response->getRequest();continue;}elseif($response
  637. instanceof
  638. IPresenterResponse){$response->send();}break;}catch(Exception$e){if($this->catchExceptions===NULL){$this->catchExceptions=Environment::isProduction();}$this->onError($this,$e);if(!$this->catchExceptions){$this->onShutdown($this,$e);throw$e;}if($repeatedError){$e=new
  639. ApplicationException('An error occured while executing error-presenter',0,$e);}if(!$httpResponse->isSent()){$httpResponse->setCode($e
  640. instanceof
  641. BadRequestException?$e->getCode():500);}if(!$repeatedError&&$this->errorPresenter){$repeatedError=TRUE;$request=new
  642. PresenterRequest($this->errorPresenter,PresenterRequest::FORWARD,array('exception'=>$e));}else{echo"<meta name='robots' content='noindex'>\n\n";if($e
  643. instanceof
  644. BadRequestException){echo"<title>404 Not Found</title>\n\n<h1>Not Found</h1>\n\n<p>The requested URL was not found on this server.</p>";}else{Debug::processException($e,FALSE);echo"<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n","<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";}echo"\n\n<hr>\n<small><i>Nette Framework</i></small>";break;}}}while(1);$this->onShutdown($this,isset($e)?$e:NULL);}final
  645. function
  646. getRequests(){return$this->requests;}final
  647. function
  648. getPresenter(){return$this->presenter;}final
  649. function
  650. getServiceLocator(){if($this->serviceLocator===NULL){$this->serviceLocator=new
  651. ServiceLocator(Environment::getServiceLocator());foreach($this->defaultServices
  652. as$name=>$service){if(!$this->serviceLocator->hasService($name)){$this->serviceLocator->addService($name,$service);}}}return$this->serviceLocator;}final
  653. function
  654. getService($name,array$options=NULL){return$this->getServiceLocator()->getService($name,$options);}function
  655. getRouter(){return$this->getServiceLocator()->getService('Nette\\Application\\IRouter');}function
  656. setRouter(IRouter$router){$this->getServiceLocator()->addService('Nette\\Application\\IRouter',$router);return$this;}function
  657. getPresenterLoader(){return$this->getServiceLocator()->getService('Nette\\Application\\IPresenterLoader');}static
  658. function
  659. createPresenterLoader(){return
  660. new
  661. PresenterLoader(Environment::getVariable('appDir'));}function
  662. storeRequest($expiration='+ 10 minutes'){$session=$this->getSession('Nette.Application/requests');do{$key=substr(md5(lcg_value()),0,4);}while(isset($session[$key]));$session[$key]=end($this->requests);$session->setExpiration($expiration,$key);return$key;}function
  663. restoreRequest($key){$session=$this->getSession('Nette.Application/requests');if(isset($session[$key])){$request=clone$session[$key];unset($session[$key]);$request->setFlag(PresenterRequest::RESTORED,TRUE);$this->presenter->terminate(new
  664. ForwardingResponse($request));}}protected
  665. function
  666. getHttpRequest(){return
  667. Environment::getHttpRequest();}protected
  668. function
  669. getHttpResponse(){return
  670. Environment::getHttpResponse();}protected
  671. function
  672. getSession($namespace=NULL){return
  673. Environment::getSession($namespace);}}abstract
  674. class
  675. PresenterComponent
  676. extends
  677. ComponentContainer
  678. implements
  679. ISignalReceiver,IStatePersistent,ArrayAccess{protected$params=array();function
  680. __construct(IComponentContainer$parent=NULL,$name=NULL){$this->monitor('Presenter');parent::__construct($parent,$name);}function
  681. getPresenter($need=TRUE){return$this->lookup('Presenter',$need);}function
  682. getUniqueId(){return$this->lookupPath('Presenter',TRUE);}protected
  683. function
  684. attached($presenter){if($presenter
  685. instanceof
  686. Presenter){$this->loadState($presenter->popGlobalParams($this->getUniqueId()));}}protected
  687. function
  688. tryCall($method,array$params){$rc=$this->getReflection();if($rc->hasMethod($method)){$rm=$rc->getMethod($method);if($rm->isPublic()&&!$rm->isAbstract()&&!$rm->isStatic()){$rm->invokeNamedArgs($this,$params);return
  689. TRUE;}}return
  690. FALSE;}function
  691. getReflection(){return
  692. new
  693. PresenterComponentReflection($this);}function
  694. loadState(array$params){foreach($this->getReflection()->getPersistentParams()as$nm=>$meta){if(isset($params[$nm])){if(isset($meta['def'])){if(is_array($params[$nm])&&!is_array($meta['def'])){$params[$nm]=$meta['def'];}else{settype($params[$nm],gettype($meta['def']));}}$this->$nm=&$params[$nm];}}$this->params=$params;}function
  695. saveState(array&$params,$reflection=NULL){$reflection=$reflection===NULL?$this->getReflection():$reflection;foreach($reflection->getPersistentParams()as$nm=>$meta){if(isset($params[$nm])){$val=$params[$nm];}elseif(array_key_exists($nm,$params)){continue;}elseif(!isset($meta['since'])||$this
  696. instanceof$meta['since']){$val=$this->$nm;}else{continue;}if(is_object($val)){throw
  697. new
  698. InvalidStateException("Persistent parameter must be scalar or array, {$this->reflection->name}::\$$nm is ".gettype($val));}else{if(isset($meta['def'])){settype($val,gettype($meta['def']));if($val===$meta['def'])$val=NULL;}else{if((string)$val==='')$val=NULL;}$params[$nm]=$val;}}}final
  699. function
  700. getParam($name=NULL,$default=NULL){if(func_num_args()===0){return$this->params;}elseif(isset($this->params[$name])){return$this->params[$name];}else{return$default;}}final
  701. function
  702. getParamId($name){$uid=$this->getUniqueId();return$uid===''?$name:$uid.self::NAME_SEPARATOR.$name;}static
  703. function
  704. getPersistentParams(){$rc=new
  705. ClassReflection(func_get_arg(0));$params=array();foreach($rc->getProperties(ReflectionProperty::IS_PUBLIC)as$rp){if(!$rp->isStatic()&&$rp->hasAnnotation('persistent')){$params[]=$rp->getName();}}return$params;}function
  706. signalReceived($signal){if(!$this->tryCall($this->formatSignalMethod($signal),$this->params)){throw
  707. new
  708. BadSignalException("There is no handler for signal '$signal' in {$this->reflection->name} class.");}}function
  709. formatSignalMethod($signal){return$signal==NULL?NULL:'handle'.$signal;}function
  710. link($destination,$args=array()){if(!is_array($args)){$args=func_get_args();array_shift($args);}try{return$this->getPresenter()->createRequest($this,$destination,$args,'link');}catch(InvalidLinkException$e){return$this->getPresenter()->handleInvalidLink($e);}}function
  711. lazyLink($destination,$args=array()){if(!is_array($args)){$args=func_get_args();array_shift($args);}return
  712. new
  713. Link($this,$destination,$args);}function
  714. redirect($code,$destination=NULL,$args=array()){if(!is_numeric($code)){$args=$destination;$destination=$code;$code=NULL;}if(!is_array($args)){$args=func_get_args();if(is_numeric(array_shift($args)))array_shift($args);}$presenter=$this->getPresenter();$presenter->redirectUri($presenter->createRequest($this,$destination,$args,'redirect'),$code);}final
  715. function
  716. offsetSet($name,$component){$this->addComponent($component,$name);}final
  717. function
  718. offsetGet($name){return$this->getComponent($name,TRUE);}final
  719. function
  720. offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}final
  721. function
  722. offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}}abstract
  723. class
  724. Control
  725. extends
  726. PresenterComponent
  727. implements
  728. IPartiallyRenderable{private$template;private$invalidSnippets=array();final
  729. function
  730. getTemplate(){if($this->template===NULL){$value=$this->createTemplate();if(!($value
  731. instanceof
  732. ITemplate||$value===NULL)){$class=get_class($value);throw
  733. new
  734. UnexpectedValueException("Object returned by {$this->reflection->name}::createTemplate() must be instance of Nette\\Templates\\ITemplate, '$class' given.");}$this->template=$value;}return$this->template;}protected
  735. function
  736. createTemplate(){$template=new
  737. Template;$presenter=$this->getPresenter(FALSE);$template->onPrepareFilters[]=callback($this,'templatePrepareFilters');$template->component=$this;$template->control=$this;$template->presenter=$presenter;$template->baseUri=Environment::getVariable('baseUri');$template->basePath=rtrim($template->baseUri,'/');if($presenter!==NULL&&$presenter->hasFlashSession()){$id=$this->getParamId('flash');$template->flashes=$presenter->getFlashSession()->$id;}if(!isset($template->flashes)||!is_array($template->flashes)){$template->flashes=array();}$template->registerHelper('escape','TemplateHelpers::escapeHtml');$template->registerHelper('escapeUrl','rawurlencode');$template->registerHelper('stripTags','strip_tags');$template->registerHelper('nl2br','nl2br');$template->registerHelper('substr','iconv_substr');$template->registerHelper('repeat','str_repeat');$template->registerHelper('replaceRE','String::replace');$template->registerHelper('implode','implode');$template->registerHelper('number','number_format');$template->registerHelperLoader('TemplateHelpers::loader');return$template;}function
  738. templatePrepareFilters($template){$template->registerFilter(new
  739. LatteFilter);}function
  740. getWidget($name){return$this->getComponent($name);}function
  741. flashMessage($message,$type='info'){$id=$this->getParamId('flash');$messages=$this->getPresenter()->getFlashSession()->$id;$messages[]=$flash=(object)array('message'=>$message,'type'=>$type);$this->getTemplate()->flashes=$messages;$this->getPresenter()->getFlashSession()->$id=$messages;return$flash;}function
  742. invalidateControl($snippet=NULL){$this->invalidSnippets[$snippet]=TRUE;}function
  743. validateControl($snippet=NULL){if($snippet===NULL){$this->invalidSnippets=array();}else{unset($this->invalidSnippets[$snippet]);}}function
  744. isControlInvalid($snippet=NULL){if($snippet===NULL){if(count($this->invalidSnippets)>0){return
  745. TRUE;}else{foreach($this->getComponents()as$component){if($component
  746. instanceof
  747. IRenderable&&$component->isControlInvalid()){return
  748. TRUE;}}return
  749. FALSE;}}else{return
  750. isset($this->invalidSnippets[NULL])||isset($this->invalidSnippets[$snippet]);}}function
  751. getSnippetId($name=NULL){return'snippet-'.$this->getUniqueId().'-'.$name;}}class
  752. AbortException
  753. extends
  754. Exception{}class
  755. ApplicationException
  756. extends
  757. Exception{function
  758. __construct($message='',$code=0,Exception$previous=NULL){if(PHP_VERSION_ID<50300){$this->previous=$previous;parent::__construct($message,$code);}else{parent::__construct($message,$code,$previous);}}}class
  759. BadRequestException
  760. extends
  761. Exception{protected$defaultCode=404;function
  762. __construct($message='',$code=0,Exception$previous=NULL){if($code<200||$code>504){$code=$this->defaultCode;}if(PHP_VERSION_ID<50300){$this->previous=$previous;parent::__construct($message,$code);}else{parent::__construct($message,$code,$previous);}}}class
  763. BadSignalException
  764. extends
  765. BadRequestException{protected$defaultCode=403;}class
  766. ForbiddenRequestException
  767. extends
  768. BadRequestException{protected$defaultCode=403;}class
  769. InvalidLinkException
  770. extends
  771. Exception{}class
  772. InvalidPresenterException
  773. extends
  774. InvalidLinkException{}class
  775. Link
  776. extends
  777. Object{private$component;private$destination;private$params;function
  778. __construct(PresenterComponent$component,$destination,array$params){$this->component=$component;$this->destination=$destination;$this->params=$params;}function
  779. getDestination(){return$this->destination;}function
  780. setParam($key,$value){$this->params[$key]=$value;return$this;}function
  781. getParam($key){return
  782. isset($this->params[$key])?$this->params[$key]:NULL;}function
  783. getParams(){return$this->params;}function
  784. __toString(){try{return$this->component->link($this->destination,$this->params);}catch(Exception$e){Debug::toStringException($e);}}}abstract
  785. class
  786. Presenter
  787. extends
  788. Control
  789. implements
  790. IPresenter{const
  791. INVALID_LINK_SILENT=1;const
  792. INVALID_LINK_WARNING=2;const
  793. INVALID_LINK_EXCEPTION=3;const
  794. SIGNAL_KEY='do';const
  795. ACTION_KEY='action';const
  796. FLASH_KEY='_fid';public
  797. static$defaultAction='default';public
  798. static$invalidLinkMode;public$onShutdown;private$request;private$response;public$autoCanonicalize=TRUE;public$absoluteUrls=FALSE;private$globalParams;private$globalState;private$globalStateSinces;private$action;private$view;private$layout;private$payload;private$signalReceiver;private$signal;private$ajaxMode;private$startupCheck;private$lastCreatedRequest;private$lastCreatedRequestFlag;final
  799. function
  800. getRequest(){return$this->request;}final
  801. function
  802. getPresenter($need=TRUE){return$this;}final
  803. function
  804. getUniqueId(){return'';}function
  805. run(PresenterRequest$request){try{$this->request=$request;$this->payload=(object)NULL;$this->setParent($this->getParent(),$request->getPresenterName());$this->initGlobalParams();$this->startup();if(!$this->startupCheck){$class=$this->reflection->getMethod('startup')->getDeclaringClass()->getName();throw
  806. new
  807. InvalidStateException("Method $class::startup() or its descendant doesn't call parent::startup().");}$this->tryCall($this->formatActionMethod($this->getAction()),$this->params);if($this->autoCanonicalize){$this->canonicalize();}if($this->getHttpRequest()->isMethod('head')){$this->terminate();}$this->processSignal();$this->beforeRender();$this->tryCall($this->formatRenderMethod($this->getView()),$this->params);$this->afterRender();$this->saveGlobalState();if($this->isAjax()){$this->payload->state=$this->getGlobalState();}$this->sendTemplate();}catch(AbortException$e){}{if($this->isAjax())try{$hasPayload=(array)$this->payload;unset($hasPayload['state']);if($this->response
  808. instanceof
  809. RenderResponse&&($this->isControlInvalid()||$hasPayload)){SnippetHelper::$outputAllowed=FALSE;$this->response->send();$this->sendPayload();}elseif(!$this->response&&$hasPayload){$this->sendPayload();}}catch(AbortException$e){}if($this->hasFlashSession()){$this->getFlashSession()->setExpiration($this->response
  810. instanceof
  811. RedirectingResponse?'+ 30 seconds':'+ 3 seconds');}$this->onShutdown($this,$this->response);$this->shutdown($this->response);return$this->response;}}protected
  812. function
  813. startup(){$this->startupCheck=TRUE;}protected
  814. function
  815. beforeRender(){}protected
  816. function
  817. afterRender(){}protected
  818. function
  819. shutdown($response){}function
  820. processSignal(){if($this->signal===NULL)return;$component=$this->signalReceiver===''?$this:$this->getComponent($this->signalReceiver,FALSE);if($component===NULL){throw
  821. new
  822. BadSignalException("The signal receiver component '$this->signalReceiver' is not found.");}elseif(!$component
  823. instanceof
  824. ISignalReceiver){throw
  825. new
  826. BadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");}$component->signalReceived($this->signal);$this->signal=NULL;}final
  827. function
  828. getSignal(){return$this->signal===NULL?NULL:array($this->signalReceiver,$this->signal);}final
  829. function
  830. isSignalReceiver($component,$signal=NULL){if($component
  831. instanceof
  832. Component){$component=$component===$this?'':$component->lookupPath(__CLASS__,TRUE);}if($this->signal===NULL){return
  833. FALSE;}elseif($signal===TRUE){return$component===''||strncmp($this->signalReceiver.'-',$component.'-',strlen($component)+1)===0;}elseif($signal===NULL){return$this->signalReceiver===$component;}else{return$this->signalReceiver===$component&&strcasecmp($signal,$this->signal)===0;}}final
  834. function
  835. getAction($fullyQualified=FALSE){return$fullyQualified?':'.$this->getName().':'.$this->action:$this->action;}function
  836. changeAction($action){if(String::match($action,"#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*$#")){$this->action=$action;$this->view=$action;}else{throw
  837. new
  838. BadRequestException("Action name '$action' is not alphanumeric string.");}}final
  839. function
  840. getView(){return$this->view;}function
  841. setView($view){$this->view=(string)$view;return$this;}final
  842. function
  843. getLayout(){return$this->layout;}function
  844. setLayout($layout){$this->layout=$layout===FALSE?FALSE:(string)$layout;return$this;}function
  845. sendTemplate(){$template=$this->getTemplate();if(!$template)return;if($template
  846. instanceof
  847. IFileTemplate&&!$template->getFile()){$files=$this->formatTemplateFiles($this->getName(),$this->view);foreach($files
  848. as$file){if(is_file($file)){$template->setFile($file);break;}}if(!$template->getFile()){$file=str_replace(Environment::getVariable('appDir'),"\xE2\x80\xA6",reset($files));throw
  849. new
  850. BadRequestException("Page not found. Missing template '$file'.");}if($this->layout!==FALSE){$files=$this->formatLayoutTemplateFiles($this->getName(),$this->layout?$this->layout:'layout');foreach($files
  851. as$file){if(is_file($file)){$template->layout=$file;$template->_extends=$file;break;}}if(empty($template->layout)&&$this->layout!==NULL){$file=str_replace(Environment::getVariable('appDir'),"\xE2\x80\xA6",reset($files));throw
  852. new
  853. FileNotFoundException("Layout not found. Missing template '$file'.");}}}$this->terminate(new
  854. RenderResponse($template));}function
  855. formatLayoutTemplateFiles($presenter,$layout){$appDir=Environment::getVariable('appDir');$path='/'.str_replace(':','Module/',$presenter);$pathP=substr_replace($path,'/templates',strrpos($path,'/'),0);$list=array("$appDir$pathP/@$layout.phtml","$appDir$pathP.@$layout.phtml");while(($path=substr($path,0,strrpos($path,'/')))!==FALSE){$list[]="$appDir$path/templates/@$layout.phtml";}return$list;}function
  856. formatTemplateFiles($presenter,$view){$appDir=Environment::getVariable('appDir');$path='/'.str_replace(':','Module/',$presenter);$pathP=substr_replace($path,'/templates',strrpos($path,'/'),0);$path=substr_replace($path,'/templates',strrpos($path,'/'));return
  857. array("$appDir$pathP/$view.phtml","$appDir$pathP.$view.phtml","$appDir$path/@global.$view.phtml");}protected
  858. static
  859. function
  860. formatActionMethod($action){return'action'.$action;}protected
  861. static
  862. function
  863. formatRenderMethod($view){return'render'.$view;}final
  864. function
  865. getPayload(){return$this->payload;}function
  866. isAjax(){if($this->ajaxMode===NULL){$this->ajaxMode=$this->getHttpRequest()->isAjax();}return$this->ajaxMode;}function
  867. sendPayload(){$this->terminate(new
  868. JsonResponse($this->payload));}function
  869. forward($destination,$args=array()){if($destination
  870. instanceof
  871. PresenterRequest){$this->terminate(new
  872. ForwardingResponse($destination));}elseif(!is_array($args)){$args=func_get_args();array_shift($args);}$this->createRequest($this,$destination,$args,'forward');$this->terminate(new
  873. ForwardingResponse($this->lastCreatedRequest));}function
  874. redirectUri($uri,$code=NULL){if($this->isAjax()){$this->payload->redirect=(string)$uri;$this->sendPayload();}elseif(!$code){$code=$this->getHttpRequest()->isMethod('post')?IHttpResponse::S303_POST_GET:IHttpResponse::S302_FOUND;}$this->terminate(new
  875. RedirectingResponse($uri,$code));}function
  876. backlink(){return$this->getAction(TRUE);}function
  877. getLastCreatedRequest(){return$this->lastCreatedRequest;}function
  878. getLastCreatedRequestFlag($flag){return!empty($this->lastCreatedRequestFlag[$flag]);}function
  879. terminate(IPresenterResponse$response=NULL){$this->response=$response;throw
  880. new
  881. AbortException();}function
  882. canonicalize(){if(!$this->isAjax()&&($this->request->isMethod('get')||$this->request->isMethod('head'))){$uri=$this->createRequest($this,$this->action,$this->getGlobalState()+$this->request->params,'redirectX');if($uri!==NULL&&!$this->getHttpRequest()->getUri()->isEqual($uri)){$this->terminate(new
  883. RedirectingResponse($uri,IHttpResponse::S301_MOVED_PERMANENTLY));}}}function
  884. lastModified($lastModified,$etag=NULL,$expire=NULL){if(!Environment::isProduction()){return;}if($expire!==NULL){$this->getHttpResponse()->setExpiration($expire);}if(!$this->getHttpContext()->isModified($lastModified,$etag)){$this->terminate();}}final
  885. protected
  886. function
  887. createRequest($component,$destination,array$args,$mode){static$presenterLoader,$router,$httpRequest;if($presenterLoader===NULL){$presenterLoader=$this->getApplication()->getPresenterLoader();$router=$this->getApplication()->getRouter();$httpRequest=$this->getHttpRequest();}$this->lastCreatedRequest=$this->lastCreatedRequestFlag=NULL;$a=strpos($destination,'#');if($a===FALSE){$fragment='';}else{$fragment=substr($destination,$a);$destination=substr($destination,0,$a);}$a=strpos($destination,'?');if($a!==FALSE){parse_str(substr($destination,$a+1),$args);$destination=substr($destination,0,$a);}$a=strpos($destination,'//');if($a===FALSE){$scheme=FALSE;}else{$scheme=substr($destination,0,$a);$destination=substr($destination,$a+2);}if(!($component
  888. instanceof
  889. Presenter)||substr($destination,-1)==='!'){$signal=rtrim($destination,'!');$a=strrpos($signal,':');if($a!==FALSE){$component=$component->getComponent(strtr(substr($signal,0,$a),':','-'));$signal=(string)substr($signal,$a+1);}if($signal==NULL){throw
  890. new
  891. InvalidLinkException("Signal must be non-empty string.");}$destination='this';}if($destination==NULL){throw
  892. new
  893. InvalidLinkException("Destination must be non-empty string.");}$current=FALSE;$a=strrpos($destination,':');if($a===FALSE){$action=$destination==='this'?$this->action:$destination;$presenter=$this->getName();$presenterClass=get_class($this);}else{$action=(string)substr($destination,$a+1);if($destination[0]===':'){if($a<2){throw
  894. new
  895. InvalidLinkException("Missing presenter name in '$destination'.");}$presenter=substr($destination,1,$a-1);}else{$presenter=$this->getName();$b=strrpos($presenter,':');if($b===FALSE){$presenter=substr($destination,0,$a);}else{$presenter=substr($presenter,0,$b+1).substr($destination,0,$a);}}$presenterClass=$presenterLoader->getPresenterClass($presenter);}if(isset($signal)){$reflection=new
  896. PresenterComponentReflection(get_class($component));if($signal==='this'){$signal='';if(array_key_exists(0,$args)){throw
  897. new
  898. InvalidLinkException("Extra parameter for signal '{$reflection->name}:$signal!'.");}}elseif(strpos($signal,self::NAME_SEPARATOR)===FALSE){$method=$component->formatSignalMethod($signal);if(!$reflection->hasCallableMethod($method)){throw
  899. new
  900. InvalidLinkException("Unknown signal '{$reflection->name}:$signal!'.");}if($args){self::argsToParams(get_class($component),$method,$args);}}if($args&&array_intersect_key($args,$reflection->getPersistentParams())){$component->saveState($args);}if($args&&$component!==$this){$prefix=$component->getUniqueId().self::NAME_SEPARATOR;foreach($args
  901. as$key=>$val){unset($args[$key]);$args[$prefix.$key]=$val;}}}if(is_subclass_of($presenterClass,__CLASS__)){if($action===''){$action=self::$defaultAction;}$current=($action==='*'||$action===$this->action)&&$presenterClass===get_class($this);$reflection=new
  902. PresenterComponentReflection($presenterClass);if($args||$destination==='this'){$method=call_user_func(array($presenterClass,'formatActionMethod'),$action);if(!$reflection->hasCallableMethod($method)){$method=call_user_func(array($presenterClass,'formatRenderMethod'),$action);if(!$reflection->hasCallableMethod($method)){$method=NULL;}}if($method===NULL){if(array_key_exists(0,$args)){throw
  903. new
  904. InvalidLinkException("Extra parameter for '$presenter:$action'.");}}elseif($destination==='this'){self::argsToParams($presenterClass,$method,$args,$this->params);}else{self::argsToParams($presenterClass,$method,$args);}}if($args&&array_intersect_key($args,$reflection->getPersistentParams())){$this->saveState($args,$reflection);}$globalState=$this->getGlobalState($destination==='this'?NULL:$presenterClass);if($current&&$args){$tmp=$globalState+$this->params;foreach($args
  905. as$key=>$val){if((string)$val!==(isset($tmp[$key])?(string)$tmp[$key]:'')){$current=FALSE;break;}}}$args+=$globalState;}$args[self::ACTION_KEY]=$action;if(!empty($signal)){$args[self::SIGNAL_KEY]=$component->getParamId($signal);$current=$current&&$args[self::SIGNAL_KEY]===$this->getParam(self::SIGNAL_KEY);}if(($mode==='redirect'||$mode==='forward')&&$this->hasFlashSession()){$args[self::FLASH_KEY]=$this->getParam(self::FLASH_KEY);}$this->lastCreatedRequest=new
  906. PresenterRequest($presenter,PresenterRequest::FORWARD,$args,array(),array());$this->lastCreatedRequestFlag=array('current'=>$current);if($mode==='forward')return;$uri=$router->constructUrl($this->lastCreatedRequest,$httpRequest);if($uri===NULL){unset($args[self::ACTION_KEY]);$params=urldecode(http_build_query($args,NULL,', '));throw
  907. new
  908. InvalidLinkException("No route for $presenter:$action($params)");}if($mode==='link'&&$scheme===FALSE&&!$this->absoluteUrls){$hostUri=$httpRequest->getUri()->getHostUri();if(strncmp($uri,$hostUri,strlen($hostUri))===0){$uri=substr($uri,strlen($hostUri));}}return$uri.$fragment;}private
  909. static
  910. function
  911. argsToParams($class,$method,&$args,$supplemental=array()){static$cache;$params=&$cache[strtolower($class.':'.$method)];if($params===NULL){$params=MethodReflection::from($class,$method)->getDefaultParameters();}$i=0;foreach($params
  912. as$name=>$def){if(array_key_exists($i,$args)){$args[$name]=$args[$i];unset($args[$i]);$i++;}elseif(array_key_exists($name,$args)){}elseif(array_key_exists($name,$supplemental)){$args[$name]=$supplemental[$name];}else{continue;}if($def===NULL){if((string)$args[$name]==='')$args[$name]=NULL;}else{settype($args[$name],gettype($def));if($args[$name]===$def)$args[$name]=NULL;}}if(array_key_exists($i,$args)){throw
  913. new
  914. InvalidLinkException("Extra parameter for signal '$class:$method'.");}}protected
  915. function
  916. handleInvalidLink($e){if(self::$invalidLinkMode===NULL){self::$invalidLinkMode=Environment::isProduction()?self::INVALID_LINK_SILENT:self::INVALID_LINK_WARNING;}if(self::$invalidLinkMode===self::INVALID_LINK_SILENT){return'#';}elseif(self::$invalidLinkMode===self::INVALID_LINK_WARNING){return'error: '.$e->getMessage();}else{throw$e;}}static
  917. function
  918. getPersistentComponents(){return(array)ClassReflection::from(func_get_arg(0))->getAnnotation('persistent');}private
  919. function
  920. getGlobalState($forClass=NULL){$sinces=&$this->globalStateSinces;if($this->globalState===NULL){$state=array();foreach($this->globalParams
  921. as$id=>$params){$prefix=$id.self::NAME_SEPARATOR;foreach($params
  922. as$key=>$val){$state[$prefix.$key]=$val;}}$this->saveState($state,$forClass?new
  923. PresenterComponentReflection($forClass):NULL);if($sinces===NULL){$sinces=array();foreach($this->getReflection()->getPersistentParams()as$nm=>$meta){$sinces[$nm]=$meta['since'];}}$components=$this->getReflection()->getPersistentComponents();$iterator=$this->getComponents(TRUE,'IStatePersistent');foreach($iterator
  924. as$name=>$component){if($iterator->getDepth()===0){$since=isset($components[$name]['since'])?$components[$name]['since']:FALSE;}$prefix=$component->getUniqueId().self::NAME_SEPARATOR;$params=array();$component->saveState($params);foreach($params
  925. as$key=>$val){$state[$prefix.$key]=$val;$sinces[$prefix.$key]=$since;}}}else{$state=$this->globalState;}if($forClass!==NULL){$since=NULL;foreach($state
  926. as$key=>$foo){if(!isset($sinces[$key])){$x=strpos($key,self::NAME_SEPARATOR);$x=$x===FALSE?$key:substr($key,0,$x);$sinces[$key]=isset($sinces[$x])?$sinces[$x]:FALSE;}if($since!==$sinces[$key]){$since=$sinces[$key];$ok=$since&&(is_subclass_of($forClass,$since)||$forClass===$since);}if(!$ok){unset($state[$key]);}}}return$state;}protected
  927. function
  928. saveGlobalState(){foreach($this->globalParams
  929. as$id=>$foo){$this->getComponent($id,FALSE);}$this->globalParams=array();$this->globalState=$this->getGlobalState();}private
  930. function
  931. initGlobalParams(){$this->globalParams=array();$selfParams=array();$params=$this->request->getParams();if($this->isAjax()){$params=$this->request->getPost()+$params;}foreach($params
  932. as$key=>$value){$a=strlen($key)>2?strrpos($key,self::NAME_SEPARATOR,-2):FALSE;if($a===FALSE){$selfParams[$key]=$value;}else{$this->globalParams[substr($key,0,$a)][substr($key,$a+1)]=$value;}}$this->changeAction(isset($selfParams[self::ACTION_KEY])?$selfParams[self::ACTION_KEY]:self::$defaultAction);$this->signalReceiver=$this->getUniqueId();if(!empty($selfParams[self::SIGNAL_KEY])){$param=$selfParams[self::SIGNAL_KEY];$pos=strrpos($param,'-');if($pos){$this->signalReceiver=substr($param,0,$pos);$this->signal=substr($param,$pos+1);}else{$this->signalReceiver=$this->getUniqueId();$this->signal=$param;}if($this->signal==NULL){$this->signal=NULL;}}$this->loadState($selfParams);}final
  933. function
  934. popGlobalParams($id){if(isset($this->globalParams[$id])){$res=$this->globalParams[$id];unset($this->globalParams[$id]);return$res;}else{return
  935. array();}}function
  936. hasFlashSession(){return!empty($this->params[self::FLASH_KEY])&&$this->getSession()->hasNamespace('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}function
  937. getFlashSession(){if(empty($this->params[self::FLASH_KEY])){$this->params[self::FLASH_KEY]=substr(md5(lcg_value()),0,4);}return$this->getSession('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}protected
  938. function
  939. getHttpRequest(){return
  940. Environment::getHttpRequest();}protected
  941. function
  942. getHttpResponse(){return
  943. Environment::getHttpResponse();}protected
  944. function
  945. getHttpContext(){return
  946. Environment::getHttpContext();}function
  947. getApplication(){return
  948. Environment::getApplication();}protected
  949. function
  950. getSession($namespace=NULL){return
  951. Environment::getSession($namespace);}protected
  952. function
  953. getUser(){return
  954. Environment::getUser();}}class
  955. ClassReflection
  956. extends
  957. ReflectionClass{private
  958. static$extMethods;static
  959. function
  960. from($class){return
  961. new
  962. self($class);}function
  963. __toString(){return'Class '.$this->getName();}function
  964. hasEventProperty($name){if(preg_match('#^on[A-Z]#',$name)&&$this->hasProperty($name)){$rp=$this->getProperty($name);return$rp->isPublic()&&!$rp->isStatic();}return
  965. FALSE;}function
  966. setExtensionMethod($name,$callback){$l=&self::$extMethods[strtolower($name)];$l[strtolower($this->getName())]=callback($callback);$l['']=NULL;return$this;}function
  967. getExtensionMethod($name){if(self::$extMethods===NULL||$name===NULL){$list=get_defined_functions();foreach($list['user']as$fce){$pair=explode('_prototype_',$fce);if(count($pair)===2){self::$extMethods[$pair[1]][$pair[0]]=callback($fce);self::$extMethods[$pair[1]]['']=NULL;}}if($name===NULL)return
  968. NULL;}$class=strtolower($this->getName());$l=&self::$extMethods[strtolower($name)];if(empty($l)){return
  969. FALSE;}elseif(isset($l[''][$class])){return$l[''][$class];}$cl=$class;do{if(isset($l[$cl])){return$l[''][$class]=$l[$cl];}}while(($cl=strtolower(get_parent_class($cl)))!=='');foreach(class_implements($class)as$cl){$cl=strtolower($cl);if(isset($l[$cl])){return$l[''][$class]=$l[$cl];}}return$l[''][$class]=FALSE;}static
  970. function
  971. import(ReflectionClass$ref){return
  972. new
  973. self($ref->getName());}function
  974. getConstructor(){return($ref=parent::getConstructor())?MethodReflection::import($ref):NULL;}function
  975. getExtension(){return($ref=parent::getExtension())?ExtensionReflection::import($ref):NULL;}function
  976. getInterfaces(){return
  977. array_map(array('ClassReflection','import'),parent::getInterfaces());}function
  978. getMethod($name){return
  979. MethodReflection::import(parent::getMethod($name));}function
  980. getMethods($filter=-1){return
  981. array_map(array('MethodReflection','import'),parent::getMethods($filter));}function
  982. getParentClass(){return($ref=parent::getParentClass())?self::import($ref):NULL;}function
  983. getProperties($filter=-1){return
  984. array_map(array('PropertyReflection','import'),parent::getProperties($filter));}function
  985. getProperty($name){return
  986. PropertyReflection::import(parent::getProperty($name));}function
  987. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  988. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  989. isset($res[$name])?end($res[$name]):NULL;}function
  990. getAnnotations(){return
  991. AnnotationsParser::getAll($this);}function
  992. getReflection(){return
  993. new
  994. ClassReflection($this);}function
  995. __call($name,$args){return
  996. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  997. ObjectMixin::get($this,$name);}function
  998. __set($name,$value){return
  999. ObjectMixin::set($this,$name,$value);}function
  1000. __isset($name){return
  1001. ObjectMixin::has($this,$name);}function
  1002. __unset($name){throw
  1003. new
  1004. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  1005. PresenterComponentReflection
  1006. extends
  1007. ClassReflection{private
  1008. static$ppCache=array();private
  1009. static$pcCache=array();private
  1010. static$mcCache=array();function
  1011. getPersistentParams($class=NULL){$class=$class===NULL?$this->getName():$class;$params=&self::$ppCache[$class];if($params!==NULL)return$params;$params=array();if(is_subclass_of($class,'PresenterComponent')){$defaults=get_class_vars($class);foreach(call_user_func(array($class,'getPersistentParams'),$class)as$name=>$meta){if(is_string($meta))$name=$meta;$params[$name]=array('def'=>$defaults[$name],'since'=>$class);}$params=$this->getPersistentParams(get_parent_class($class))+$params;}return$params;}function
  1012. getPersistentComponents(){$class=$this->getName();$components=&self::$pcCache[$class];if($components!==NULL)return$components;$components=array();if(is_subclass_of($class,'Presenter')){foreach(call_user_func(array($class,'getPersistentComponents'),$class)as$name=>$meta){if(is_string($meta))$name=$meta;$components[$name]=array('since'=>$class);}$components=self::getPersistentComponents(get_parent_class($class))+$components;}return$components;}function
  1013. hasCallableMethod($method){$class=$this->getName();$cache=&self::$mcCache[strtolower($class.':'.$method)];if($cache===NULL)try{$cache=FALSE;$rm=MethodReflection::from($class,$method);$cache=$this->isInstantiable()&&$rm->isPublic()&&!$rm->isAbstract()&&!$rm->isStatic();}catch(ReflectionException$e){}return$cache;}}class
  1014. PresenterLoader
  1015. implements
  1016. IPresenterLoader{public$caseSensitive=FALSE;private$baseDir;private$cache=array();function
  1017. __construct($baseDir){$this->baseDir=$baseDir;}function
  1018. getPresenterClass(&$name){if(isset($this->cache[$name])){list($class,$name)=$this->cache[$name];return$class;}if(!is_string($name)||!String::match($name,"#^[a-zA-Z\x7f-\xff][a-zA-Z0-9\x7f-\xff:]*$#")){throw
  1019. new
  1020. InvalidPresenterException("Presenter name must be alphanumeric string, '$name' is invalid.");}$class=$this->formatPresenterClass($name);if(!class_exists($class)){$file=$this->formatPresenterFile($name);if(is_file($file)&&is_readable($file)){LimitedScope::load($file);}if(!class_exists($class)){throw
  1021. new
  1022. InvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");}}$reflection=new
  1023. ClassReflection($class);$class=$reflection->getName();if(!$reflection->implementsInterface('IPresenter')){throw
  1024. new
  1025. InvalidPresenterException("Cannot load presenter '$name', class '$class' is not Nette\\Application\\IPresenter implementor.");}if($reflection->isAbstract()){throw
  1026. new
  1027. InvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");}$realName=$this->unformatPresenterClass($class);if($name!==$realName){if($this->caseSensitive){throw
  1028. new
  1029. InvalidPresenterException("Cannot load presenter '$name', case mismatch. Real name is '$realName'.");}else{$this->cache[$name]=array($class,$realName);$name=$realName;}}else{$this->cache[$name]=array($class,$realName);}return$class;}function
  1030. formatPresenterClass($presenter){return
  1031. strtr($presenter,':','_').'Presenter';return
  1032. str_replace(':','Module\\',$presenter).'Presenter';}function
  1033. unformatPresenterClass($class){return
  1034. strtr(substr($class,0,-9),'_',':');return
  1035. str_replace('Module\\',':',substr($class,0,-9));}function
  1036. formatPresenterFile($presenter){$path='/'.str_replace(':','Module/',$presenter);return$this->baseDir.substr_replace($path,'/presenters',strrpos($path,'/'),0).'Presenter.php';}}abstract
  1037. class
  1038. FreezableObject
  1039. extends
  1040. Object{private$frozen=FALSE;function
  1041. freeze(){$this->frozen=TRUE;}final
  1042. function
  1043. isFrozen(){return$this->frozen;}function
  1044. __clone(){$this->frozen=FALSE;}protected
  1045. function
  1046. updating(){if($this->frozen){throw
  1047. new
  1048. InvalidStateException("Cannot modify a frozen object {$this->reflection->name}.");}}}final
  1049. class
  1050. PresenterRequest
  1051. extends
  1052. FreezableObject{const
  1053. FORWARD='FORWARD';const
  1054. SECURED='secured';const
  1055. RESTORED='restored';private$method;private$flags=array();private$name;private$params;private$post;private$files;function
  1056. __construct($name,$method,array$params,array$post=array(),array$files=array(),array$flags=array()){$this->name=$name;$this->method=$method;$this->params=$params;$this->post=$post;$this->files=$files;$this->flags=$flags;}function
  1057. setPresenterName($name){$this->updating();$this->name=$name;return$this;}function
  1058. getPresenterName(){return$this->name;}function
  1059. setParams(array$params){$this->updating();$this->params=$params;return$this;}function
  1060. getParams(){return$this->params;}function
  1061. setPost(array$params){$this->updating();$this->post=$params;return$this;}function
  1062. getPost(){return$this->post;}function
  1063. setFiles(array$files){$this->updating();$this->files=$files;return$this;}function
  1064. getFiles(){return$this->files;}function
  1065. setMethod($method){$this->method=$method;return$this;}function
  1066. getMethod(){return$this->method;}function
  1067. isMethod($method){return
  1068. strcasecmp($this->method,$method)===0;}function
  1069. isPost(){return
  1070. strcasecmp($this->method,'post')===0;}function
  1071. setFlag($flag,$value=TRUE){$this->updating();$this->flags[$flag]=(bool)$value;return$this;}function
  1072. hasFlag($flag){return!empty($this->flags[$flag]);}}class
  1073. DownloadResponse
  1074. extends
  1075. Object
  1076. implements
  1077. IPresenterResponse{private$file;private$contentType;private$name;function
  1078. __construct($file,$name=NULL,$contentType=NULL){if(!is_file($file)){throw
  1079. new
  1080. BadRequestException("File '$file' doesn't exist.");}$this->file=$file;$this->name=$name?$name:basename($file);$this->contentType=$contentType?$contentType:'application/octet-stream';}final
  1081. function
  1082. getFile(){return$this->file;}final
  1083. function
  1084. getName(){return$this->name;}final
  1085. function
  1086. getContentType(){return$this->contentType;}function
  1087. send(){Environment::getHttpResponse()->setContentType($this->contentType);Environment::getHttpResponse()->setHeader('Content-Disposition','attachment; filename="'.$this->name.'"');readfile($this->file);}}class
  1088. ForwardingResponse
  1089. extends
  1090. Object
  1091. implements
  1092. IPresenterResponse{private$request;function
  1093. __construct(PresenterRequest$request){$this->request=$request;}final
  1094. function
  1095. getRequest(){return$this->request;}function
  1096. send(){}}class
  1097. JsonResponse
  1098. extends
  1099. Object
  1100. implements
  1101. IPresenterResponse{private$payload;private$contentType;function
  1102. __construct($payload,$contentType=NULL){if(!is_array($payload)&&!($payload
  1103. instanceof
  1104. stdClass)){throw
  1105. new
  1106. InvalidArgumentException("Payload must be array or anonymous class, ".gettype($payload)." given.");}$this->payload=$payload;$this->contentType=$contentType?$contentType:'application/json';}final
  1107. function
  1108. getPayload(){return$this->payload;}function
  1109. send(){Environment::getHttpResponse()->setContentType($this->contentType);Environment::getHttpResponse()->setExpiration(FALSE);echo
  1110. json_encode($this->payload);}}class
  1111. RedirectingResponse
  1112. extends
  1113. Object
  1114. implements
  1115. IPresenterResponse{private$uri;private$code;function
  1116. __construct($uri,$code=IHttpResponse::S302_FOUND){$this->uri=(string)$uri;$this->code=(int)$code;}final
  1117. function
  1118. getUri(){return$this->uri;}final
  1119. function
  1120. getCode(){return$this->code;}function
  1121. send(){Environment::getHttpResponse()->redirect($this->uri,$this->code);}}class
  1122. RenderResponse
  1123. extends
  1124. Object
  1125. implements
  1126. IPresenterResponse{private$source;function
  1127. __construct($source){$this->source=$source;}final
  1128. function
  1129. getSource(){return$this->source;}function
  1130. send(){if($this->source
  1131. instanceof
  1132. ITemplate){$this->source->render();}else{echo$this->source;}}}class
  1133. CliRouter
  1134. extends
  1135. Object
  1136. implements
  1137. IRouter{const
  1138. PRESENTER_KEY='action';private$defaults;function
  1139. __construct($defaults=array()){$this->defaults=$defaults;}function
  1140. match(IHttpRequest$httpRequest){if(empty($_SERVER['argv'])||!is_array($_SERVER['argv'])){return
  1141. NULL;}$names=array(self::PRESENTER_KEY);$params=$this->defaults;$args=$_SERVER['argv'];array_shift($args);$args[]='--';foreach($args
  1142. as$arg){$opt=preg_replace('#/|-+#A','',$arg);if($opt===$arg){if(isset($flag)||$flag=array_shift($names)){$params[$flag]=$arg;}else{$params[]=$arg;}$flag=NULL;continue;}if(isset($flag)){$params[$flag]=TRUE;$flag=NULL;}if($opt!==''){$pair=explode('=',$opt,2);if(isset($pair[1])){$params[$pair[0]]=$pair[1];}else{$flag=$pair[0];}}}if(!isset($params[self::PRESENTER_KEY])){throw
  1143. new
  1144. InvalidStateException('Missing presenter & action in route definition.');}$presenter=$params[self::PRESENTER_KEY];if($a=strrpos($presenter,':')){$params[self::PRESENTER_KEY]=substr($presenter,$a+1);$presenter=substr($presenter,0,$a);}return
  1145. new
  1146. PresenterRequest($presenter,'CLI',$params);}function
  1147. constructUrl(PresenterRequest$appRequest,IHttpRequest$httpRequest){return
  1148. NULL;}function
  1149. getDefaults(){return$this->defaults;}}class
  1150. MultiRouter
  1151. extends
  1152. Object
  1153. implements
  1154. IRouter,ArrayAccess,Countable,IteratorAggregate{private$routes;private$cachedRoutes;function
  1155. __construct(){$this->routes=new
  1156. ArrayList;}function
  1157. match(IHttpRequest$httpRequest){foreach($this->routes
  1158. as$route){$appRequest=$route->match($httpRequest);if($appRequest!==NULL){return$appRequest;}}return
  1159. NULL;}function
  1160. constructUrl(PresenterRequest$appRequest,IHttpRequest$httpRequest){if($this->cachedRoutes===NULL){$routes=array();$routes['*']=array();foreach($this->routes
  1161. as$route){$presenter=$route
  1162. instanceof
  1163. Route?$route->getTargetPresenter():NULL;if($presenter===FALSE)continue;if(is_string($presenter)){$presenter=strtolower($presenter);if(!isset($routes[$presenter])){$routes[$presenter]=$routes['*'];}$routes[$presenter][]=$route;}else{foreach($routes
  1164. as$id=>$foo){$routes[$id][]=$route;}}}$this->cachedRoutes=$routes;}$presenter=strtolower($appRequest->getPresenterName());if(!isset($this->cachedRoutes[$presenter]))$presenter='*';foreach($this->cachedRoutes[$presenter]as$route){$uri=$route->constructUrl($appRequest,$httpRequest);if($uri!==NULL){return$uri;}}return
  1165. NULL;}function
  1166. offsetSet($index,$route){if(!($route
  1167. instanceof
  1168. IRouter)){throw
  1169. new
  1170. InvalidArgumentException("Argument must be IRouter descendant.");}$this->routes[$index]=$route;}function
  1171. offsetGet($index){return$this->routes[$index];}function
  1172. offsetExists($index){return
  1173. isset($this->routes[$index]);}function
  1174. offsetUnset($index){unset($this->routes[$index]);}function
  1175. getIterator(){return$this->routes;}function
  1176. count(){return
  1177. count($this->routes);}}class
  1178. Route
  1179. extends
  1180. Object
  1181. implements
  1182. IRouter{const
  1183. PRESENTER_KEY='presenter';const
  1184. MODULE_KEY='module';const
  1185. CASE_SENSITIVE=256;const
  1186. HOST=1;const
  1187. PATH=2;const
  1188. RELATIVE=3;const
  1189. VALUE='value';const
  1190. PATTERN='pattern';const
  1191. FILTER_IN='filterIn';const
  1192. FILTER_OUT='filterOut';const
  1193. FILTER_TABLE='filterTable';const
  1194. OPTIONAL=0;const
  1195. PATH_OPTIONAL=1;const
  1196. CONSTANT=2;public
  1197. static$defaultFlags=0;public
  1198. static$styles=array('#'=>array(self::PATTERN=>'[^/]+',self::FILTER_IN=>'rawurldecode',self::FILTER_OUT=>'rawurlencode'),'?#'=>array(),'module'=>array(self::PATTERN=>'[a-z][a-z0-9.-]*',self::FILTER_IN=>array(__CLASS__,'path2presenter'),self::FILTER_OUT=>array(__CLASS__,'presenter2path')),'presenter'=>array(self::PATTERN=>'[a-z][a-z0-9.-]*',self::FILTER_IN=>array(__CLASS__,'path2presenter'),self::FILTER_OUT=>array(__CLASS__,'presenter2path')),'action'=>array(self::PATTERN=>'[a-z][a-z0-9-]*',self::FILTER_IN=>array(__CLASS__,'path2action'),self::FILTER_OUT=>array(__CLASS__,'action2path')),'?module'=>array(),'?presenter'=>array(),'?action'=>array());private$mask;private$sequence;private$re;private$metadata=array();private$xlat;private$type;private$flags;function
  1199. __construct($mask,array$metadata=array(),$flags=0){$this->flags=$flags|self::$defaultFlags;$this->setMask($mask,$metadata);}function
  1200. match(IHttpRequest$httpRequest){$uri=$httpRequest->getUri();if($this->type===self::HOST){$path='//'.$uri->getHost().$uri->getPath();}elseif($this->type===self::RELATIVE){$basePath=$uri->getBasePath();if(strncmp($uri->getPath(),$basePath,strlen($basePath))!==0){return
  1201. NULL;}$path=(string)substr($uri->getPath(),strlen($basePath));}else{$path=$uri->getPath();}if($path!==''){$path=rtrim($path,'/').'/';}if(!$matches=String::match($path,$this->re)){return
  1202. NULL;}$params=array();foreach($matches
  1203. as$k=>$v){if(is_string($k)&&$v!==''){$params[str_replace('___','-',$k)]=$v;}}foreach($this->metadata
  1204. as$name=>$meta){if(isset($params[$name])){}elseif(isset($meta['fixity'])&&$meta['fixity']!==self::OPTIONAL){$params[$name]=NULL;}}if($this->xlat){$params+=self::renameKeys($httpRequest->getQuery(),array_flip($this->xlat));}else{$params+=$httpRequest->getQuery();}foreach($this->metadata
  1205. as$name=>$meta){if(isset($params[$name])){if(!is_scalar($params[$name])){}elseif(isset($meta[self::FILTER_TABLE][$params[$name]])){$params[$name]=$meta[self::FILTER_TABLE][$params[$name]];}elseif(isset($meta[self::FILTER_IN])){$params[$name]=call_user_func($meta[self::FILTER_IN],(string)$params[$name]);if($params[$name]===NULL&&!isset($meta['fixity'])){return
  1206. NULL;}}}elseif(isset($meta['fixity'])){$params[$name]=$meta[self::VALUE];}}if(!isset($params[self::PRESENTER_KEY])){throw
  1207. new
  1208. InvalidStateException('Missing presenter in route definition.');}if(isset($this->metadata[self::MODULE_KEY])){if(!isset($params[self::MODULE_KEY])){throw
  1209. new
  1210. InvalidStateException('Missing module in route definition.');}$presenter=$params[self::MODULE_KEY].':'.$params[self::PRESENTER_KEY];unset($params[self::MODULE_KEY],$params[self::PRESENTER_KEY]);}else{$presenter=$params[self::PRESENTER_KEY];unset($params[self::PRESENTER_KEY]);}return
  1211. new
  1212. PresenterRequest($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(PresenterRequest::SECURED=>$httpRequest->isSecured()));}function
  1213. constructUrl(PresenterRequest$appRequest,IHttpRequest$httpRequest){if($this->flags&self::ONE_WAY){return
  1214. NULL;}$params=$appRequest->getParams();$metadata=$this->metadata;$presenter=$appRequest->getPresenterName();$params[self::PRESENTER_KEY]=$presenter;if(isset($metadata[self::MODULE_KEY])){$module=$metadata[self::MODULE_KEY];if(isset($module['fixity'])&&strncasecmp($presenter,$module[self::VALUE].':',strlen($module[self::VALUE])+1)===0){$a=strlen($module[self::VALUE]);}else{$a=strrpos($presenter,':');}if($a===FALSE){$params[self::MODULE_KEY]='';}else{$params[self::MODULE_KEY]=substr($presenter,0,$a);$params[self::PRESENTER_KEY]=substr($presenter,$a+1);}}foreach($metadata
  1215. as$name=>$meta){if(!isset($params[$name]))continue;if(isset($meta['fixity'])){if(is_scalar($params[$name])&&strcasecmp($params[$name],$meta[self::VALUE])===0){unset($params[$name]);continue;}elseif($meta['fixity']===self::CONSTANT){return
  1216. NULL;}}if(!is_scalar($params[$name])){}elseif(isset($meta['filterTable2'][$params[$name]])){$params[$name]=$meta['filterTable2'][$params[$name]];}elseif(isset($meta[self::FILTER_OUT])){$params[$name]=call_user_func($meta[self::FILTER_OUT],$params[$name]);}if(isset($meta[self::PATTERN])&&!preg_match($meta[self::PATTERN],rawurldecode($params[$name]))){return
  1217. NULL;}}$sequence=$this->sequence;$brackets=array();$required=0;$uri='';$i=count($sequence)-1;do{$uri=$sequence[$i].$uri;if($i===0)break;$i--;$name=$sequence[$i];$i--;if($name===']'){$brackets[]=$uri;}elseif($name[0]==='['){$tmp=array_pop($brackets);if($required<count($brackets)+1){if($name!=='[!'){$uri=$tmp;}}else{$required=count($brackets);}}elseif($name[0]==='?'){continue;}elseif(isset($params[$name])&&$params[$name]!=''){$required=count($brackets);$uri=$params[$name].$uri;unset($params[$name]);}elseif(isset($metadata[$name]['fixity'])){$uri=$metadata[$name]['defOut'].$uri;}else{return
  1218. NULL;}}while(TRUE);if($this->xlat){$params=self::renameKeys($params,$this->xlat);}$sep=ini_get('arg_separator.input');$query=http_build_query($params,'',$sep?$sep[0]:'&');if($query!='')$uri.='?'.$query;if($this->type===self::RELATIVE){$uri='//'.$httpRequest->getUri()->getAuthority().$httpRequest->getUri()->getBasePath().$uri;}elseif($this->type===self::PATH){$uri='//'.$httpRequest->getUri()->getAuthority().$uri;}if(strpos($uri,'//',2)!==FALSE){return
  1219. NULL;}$uri=($this->flags&self::SECURED?'https:':'http:').$uri;return$uri;}private
  1220. function
  1221. setMask($mask,array$metadata){$this->mask=$mask;if(substr($mask,0,2)==='//'){$this->type=self::HOST;}elseif(substr($mask,0,1)==='/'){$this->type=self::PATH;}else{$this->type=self::RELATIVE;}foreach($metadata
  1222. as$name=>$meta){if(!is_array($meta)){$metadata[$name]=array(self::VALUE=>$meta,'fixity'=>self::CONSTANT);}elseif(array_key_exists(self::VALUE,$meta)){$metadata[$name]['fixity']=self::CONSTANT;}}$parts=String::split($mask,'/<([^># ]+) *([^>#]*)(#?[^>\[\]]*)>|(\[!?|\]|\s*\?.*)/');$this->xlat=array();$i=count($parts)-1;if(isset($parts[$i-1])&&substr(ltrim($parts[$i-1]),0,1)==='?'){$matches=String::matchAll($parts[$i-1],'/(?:([a-zA-Z0-9_.-]+)=)?<([^># ]+) *([^>#]*)(#?[^>]*)>/');foreach($matches
  1223. as$match){list(,$param,$name,$pattern,$class)=$match;if($class!==''){if(!isset(self::$styles[$class])){throw
  1224. new
  1225. InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");}$meta=self::$styles[$class];}elseif(isset(self::$styles['?'.$name])){$meta=self::$styles['?'.$name];}else{$meta=self::$styles['?#'];}if(isset($metadata[$name])){$meta=$metadata[$name]+$meta;}if(array_key_exists(self::VALUE,$meta)){$meta['fixity']=self::OPTIONAL;}unset($meta['pattern']);$meta['filterTable2']=empty($meta[self::FILTER_TABLE])?NULL:array_flip($meta[self::FILTER_TABLE]);$metadata[$name]=$meta;if($param!==''){$this->xlat[$name]=$param;}}$i-=5;}$brackets=0;$re='';$sequence=array();$autoOptional=array(0,0);do{array_unshift($sequence,$parts[$i]);$re=preg_quote($parts[$i],'#').$re;if($i===0)break;$i--;$part=$parts[$i];if($part==='['||$part===']'||$part==='[!'){$brackets+=$part[0]==='['?-1:1;if($brackets<0){throw
  1226. new
  1227. InvalidArgumentException("Unexpected '$part' in mask '$mask'.");}array_unshift($sequence,$part);$re=($part[0]==='['?'(?:':')?').$re;$i-=4;continue;}$class=$parts[$i];$i--;$pattern=trim($parts[$i]);$i--;$name=$parts[$i];$i--;array_unshift($sequence,$name);if($name[0]==='?'){$re='(?:'.preg_quote(substr($name,1),'#').'|'.$pattern.')'.$re;$sequence[1]=substr($name,1).$sequence[1];continue;}if(preg_match('#[^a-z0-9_-]#i',$name)){throw
  1228. new
  1229. InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '$name' given.");}if($class!==''){if(!isset(self::$styles[$class])){throw
  1230. new
  1231. InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");}$meta=self::$styles[$class];}elseif(isset(self::$styles[$name])){$meta=self::$styles[$name];}else{$meta=self::$styles['#'];}if(isset($metadata[$name])){$meta=$metadata[$name]+$meta;}if($pattern==''&&isset($meta[self::PATTERN])){$pattern=$meta[self::PATTERN];}$meta['filterTable2']=empty($meta[self::FILTER_TABLE])?NULL:array_flip($meta[self::FILTER_TABLE]);if(array_key_exists(self::VALUE,$meta)){if(isset($meta['filterTable2'][$meta[self::VALUE]])){$meta['defOut']=$meta['filterTable2'][$meta[self::VALUE]];}elseif(isset($meta[self::FILTER_OUT])){$meta['defOut']=call_user_func($meta[self::FILTER_OUT],$meta[self::VALUE]);}else{$meta['defOut']=$meta[self::VALUE];}}$meta[self::PATTERN]="#(?:$pattern)$#A".($this->flags&self::CASE_SENSITIVE?'':'iu');$re='(?P<'.str_replace('-','___',$name).'>'.$pattern.')'.$re;if($brackets){if(!isset($meta[self::VALUE])){$meta[self::VALUE]=$meta['defOut']=NULL;}$meta['fixity']=self::PATH_OPTIONAL;}elseif(isset($meta['fixity'])){$re='(?:'.substr_replace($re,')?',strlen($re)-$autoOptional[0],0);array_splice($sequence,count($sequence)-$autoOptional[1],0,array(']',''));array_unshift($sequence,'[','');$meta['fixity']=self::PATH_OPTIONAL;}else{$autoOptional=array(strlen($re),count($sequence));}$metadata[$name]=$meta;}while(TRUE);if($brackets){throw
  1232. new
  1233. InvalidArgumentException("Missing closing ']' in mask '$mask'.");}$this->re='#'.$re.'/?$#A'.($this->flags&self::CASE_SENSITIVE?'':'iu');$this->metadata=$metadata;$this->sequence=$sequence;}function
  1234. getMask(){return$this->mask;}function
  1235. getDefaults(){$defaults=array();foreach($this->metadata
  1236. as$name=>$meta){if(isset($meta['fixity'])){$defaults[$name]=$meta[self::VALUE];}}return$defaults;}function
  1237. getTargetPresenter(){if($this->flags&self::ONE_WAY){return
  1238. FALSE;}$m=$this->metadata;$module='';if(isset($m[self::MODULE_KEY])){if(isset($m[self::MODULE_KEY]['fixity'])&&$m[self::MODULE_KEY]['fixity']===self::CONSTANT){$module=$m[self::MODULE_KEY][self::VALUE].':';}else{return
  1239. NULL;}}if(isset($m[self::PRESENTER_KEY]['fixity'])&&$m[self::PRESENTER_KEY]['fixity']===self::CONSTANT){return$module.$m[self::PRESENTER_KEY][self::VALUE];}return
  1240. NULL;}private
  1241. static
  1242. function
  1243. renameKeys($arr,$xlat){if(empty($xlat))return$arr;$res=array();$occupied=array_flip($xlat);foreach($arr
  1244. as$k=>$v){if(isset($xlat[$k])){$res[$xlat[$k]]=$v;}elseif(!isset($occupied[$k])){$res[$k]=$v;}}return$res;}private
  1245. static
  1246. function
  1247. action2path($s){$s=preg_replace('#(.)(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private
  1248. static
  1249. function
  1250. path2action($s){$s=strtolower($s);$s=preg_replace('#-(?=[a-z])#',' ',$s);$s=substr(ucwords('x'.$s),1);$s=str_replace(' ','',$s);return$s;}private
  1251. static
  1252. function
  1253. presenter2path($s){$s=strtr($s,':','.');$s=preg_replace('#([^.])(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private
  1254. static
  1255. function
  1256. path2presenter($s){$s=strtolower($s);$s=preg_replace('#([.-])(?=[a-z])#','$1 ',$s);$s=ucwords($s);$s=str_replace('. ',':',$s);$s=str_replace('- ','',$s);return$s;}static
  1257. function
  1258. addStyle($style,$parent='#'){if(isset(self::$styles[$style])){throw
  1259. new
  1260. InvalidArgumentException("Style '$style' already exists.");}if($parent!==NULL){if(!isset(self::$styles[$parent])){throw
  1261. new
  1262. InvalidArgumentException("Parent style '$parent' doesn't exist.");}self::$styles[$style]=self::$styles[$parent];}else{self::$styles[$style]=array();}}static
  1263. function
  1264. setStyleProperty($style,$key,$value){if(!isset(self::$styles[$style])){throw
  1265. new
  1266. InvalidArgumentException("Style '$style' doesn't exist.");}self::$styles[$style][$key]=$value;}}class
  1267. SimpleRouter
  1268. extends
  1269. Object
  1270. implements
  1271. IRouter{const
  1272. PRESENTER_KEY='presenter';const
  1273. MODULE_KEY='module';private$module='';private$defaults;private$flags;function
  1274. __construct($defaults=array(),$flags=0){if(is_string($defaults)){$a=strrpos($defaults,':');$defaults=array(self::PRESENTER_KEY=>substr($defaults,0,$a),'action'=>substr($defaults,$a+1));}if(isset($defaults[self::MODULE_KEY])){$this->module=$defaults[self::MODULE_KEY].':';unset($defaults[self::MODULE_KEY]);}$this->defaults=$defaults;$this->flags=$flags;}function
  1275. match(IHttpRequest$httpRequest){$params=$httpRequest->getQuery();$params+=$this->defaults;if(!isset($params[self::PRESENTER_KEY])){throw
  1276. new
  1277. InvalidStateException('Missing presenter.');}$presenter=$this->module.$params[self::PRESENTER_KEY];unset($params[self::PRESENTER_KEY]);return
  1278. new
  1279. PresenterRequest($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(PresenterRequest::SECURED=>$httpRequest->isSecured()));}function
  1280. constructUrl(PresenterRequest$appRequest,IHttpRequest$httpRequest){$params=$appRequest->getParams();$presenter=$appRequest->getPresenterName();if(strncasecmp($presenter,$this->module,strlen($this->module))===0){$params[self::PRESENTER_KEY]=substr($presenter,strlen($this->module));}else{return
  1281. NULL;}foreach($this->defaults
  1282. as$key=>$value){if(isset($params[$key])&&$params[$key]==$value){unset($params[$key]);}}$uri=$httpRequest->getUri();$uri=($this->flags&self::SECURED?'https://':'http://').$uri->getAuthority().$uri->getScriptPath();$sep=ini_get('arg_separator.input');$query=http_build_query($params,'',$sep?$sep[0]:'&');if($query!=''){$uri.='?'.$query;}return$uri;}function
  1283. getDefaults(){return$this->defaults;}}class
  1284. DebugPanel
  1285. extends
  1286. Object
  1287. implements
  1288. IDebugPanel{private$id;private$tabCb;private$panelCb;function
  1289. __construct($id,$tabCb,$panelCb){$this->id=$id;$this->tabCb=$tabCb;$this->panelCb=$panelCb;}function
  1290. getId(){return$this->id;}function
  1291. getTab(){ob_start();call_user_func($this->tabCb,$this->id);return
  1292. ob_get_clean();}function
  1293. getPanel(){ob_start();call_user_func($this->panelCb,$this->id);return
  1294. ob_get_clean();}}class
  1295. RoutingDebugger
  1296. extends
  1297. DebugPanel{private$router;private$httpRequest;private$routers;private$request;function
  1298. __construct(IRouter$router,IHttpRequest$httpRequest){$this->router=$router;$this->httpRequest=$httpRequest;$this->routers=new
  1299. ArrayObject;parent::__construct('RoutingDebugger',array($this,'renderTab'),array($this,'renderPanel'));}function
  1300. renderTab(){$this->analyse($this->router);?>
  1301. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJHSURBVDjLlZPNi81hFMc/z7137p1mTCFvNZfGSzLIWNjZKRvFRoqNhRCSYm8xS3+AxRRZ2JAFJWJHSQqTQkbEzYwIM+6Yid/znJfH4prLXShOnb6r8/nWOd8Tcs78bz0/f+KMu50y05nK/wy+uHDylbutqS5extvGcxaWqtoGDA8PZ3dnrs2srQc2Zko41UXLmLdyDW5OfvsUkUgbYGbU63UAQggdmvMzFmzZCgTi7CQmkZwdEaX0JwDgTnGbTCaE0G4zw80omhPI92lcEtkNkdgJCCHwJX7mZvNaB0A14SaYJlwTrpHsTkoFlV1nt2c3x5YYo1/vM9A/gKpxdfwyu/v3teCayKq4JEwT5EB2R6WgYmrs2bYbcUNNUVfEhIfFYy69uci+1fuRX84mkawFSxd/4nVWUopUVIykwlQxRTJBTIDA4Pp1jBZPuNW4wUAPmCqWIn29X1k4f5Ku8g9mpKCkakRLVEs1auVuauVuyqHMo8ejNCe+sWPVTkQKXCMmkeZUmUZjETF1tc6ooly+fgUVw9So1/tRN6YnZji46QghBFKKuAouERNhMlbAHZFE6e7pB+He8MMw+GGI4xtOMf1+lsl3TQ4NHf19BSlaO1DB9BfMHdX0O0iqSgiBbJkjm491hClJbA1LxCURgpPzXwAHhg63necAIi3XngXLcRU0fof8ETMljIyM5LGxMcbHxzvy/6fuXdWgt6+PWncv1e4euqo1ZmabvHs5+jn8yzufO7hiiZmuNpNBM13rbvVSpbrXJE7/BMkHtU9jFIC/AAAAAElFTkSuQmCC"
  1302. ><?php if(empty($this->request)):?>no route<?php else:echo$this->request->getPresenterName().':'.(isset($this->request->params[Presenter::ACTION_KEY])?$this->request->params[Presenter::ACTION_KEY]:Presenter::$defaultAction);endif?>
  1303. <?php }function
  1304. renderPanel(){?>
  1305. <style>#nette-debug-RoutingDebugger table{font:9pt/1.5 Consolas,monospace}#nette-debug-RoutingDebugger .yes td{color:green}#nette-debug-RoutingDebugger .may td{color:#67F}#nette-debug-RoutingDebugger pre,#nette-debug-RoutingDebugger code{display:inline}</style>
  1306. <h1>
  1307. <?php if(empty($this->request)):?>
  1308. no route
  1309. <?php else:?>
  1310. <?php echo$this->request->getPresenterName().':'.(isset($this->request->params[Presenter::ACTION_KEY])?$this->request->params[Presenter::ACTION_KEY]:Presenter::$defaultAction)?>
  1311. <?php endif?>
  1312. </h1>
  1313. <?php if(!empty($this->request)):?>
  1314. <?php $params=$this->request->getParams()?>
  1315. <?php if(empty($params)):?>
  1316. <p>No parameters.</p>
  1317. <?php else:?>
  1318. <table>
  1319. <thead>
  1320. <tr>
  1321. <th>Parameter</th>
  1322. <th>Value</th>
  1323. </tr>
  1324. </thead>
  1325. <tbody>
  1326. <?php unset($params[Presenter::ACTION_KEY])?>
  1327. <?php foreach($params
  1328. as$key=>$value):?>
  1329. <tr>
  1330. <td><code><?php echo
  1331. htmlSpecialChars($key)?></code></td>
  1332. <td><?php if(is_string($value)):?><code><?php echo
  1333. htmlSpecialChars($value)?></code><?php else:echo
  1334. Debug::dump($value,TRUE);endif?></td>
  1335. </tr>
  1336. <?php endforeach?>
  1337. </tbody>
  1338. </table>
  1339. <?php endif?>
  1340. <?php endif?>
  1341. <h2>Routers</h2>
  1342. <?php if(empty($this->routers)):?>
  1343. <p>No routers defined.</p>
  1344. <?php else:?>
  1345. <div class="nette-inner">
  1346. <table>
  1347. <thead>
  1348. <tr>
  1349. <th>Matched?</th>
  1350. <th>Class</th>
  1351. <th>Mask</th>
  1352. <th>Defaults</th>
  1353. <th>Request</th>
  1354. </tr>
  1355. </thead>
  1356. <tbody>
  1357. <?php foreach($this->routers
  1358. as$router):?>
  1359. <tr class="<?php echo$router['matched']?>">
  1360. <td><?php echo$router['matched']?></td>
  1361. <td><code><?php echo
  1362. htmlSpecialChars($router['class'])?></code></td>
  1363. <td><code><strong><?php echo
  1364. htmlSpecialChars($router['mask'])?></strong></code></td>
  1365. <td><code>
  1366. <?php foreach($router['defaults']as$key=>$value):?>
  1367. <?php echo
  1368. htmlSpecialChars($key),"&nbsp;=&nbsp;",is_string($value)?htmlSpecialChars($value):str_replace("\n</pre",'</pre',Debug::dump($value,TRUE))?><br>
  1369. <?php endforeach?>
  1370. </code></td>
  1371. <td><?php if($router['request']):?><code>
  1372. <?php $params=$router['request']->getParams();?>
  1373. <strong><?php echo
  1374. htmlSpecialChars($router['request']->getPresenterName().':'.(isset($params[Presenter::ACTION_KEY])?$params[Presenter::ACTION_KEY]:Presenter::$defaultAction))?></strong><br>
  1375. <?php unset($params[Presenter::ACTION_KEY])?>
  1376. <?php foreach($params
  1377. as$key=>$value):?>
  1378. <?php echo
  1379. htmlSpecialChars($key),"&nbsp;=&nbsp;",is_string($value)?htmlSpecialChars($value):str_replace("\n</pre",'</pre',Debug::dump($value,TRUE))?><br>
  1380. <?php endforeach?>
  1381. </code><?php endif?></td>
  1382. </tr>
  1383. <?php endforeach?>
  1384. </tbody>
  1385. </table>
  1386. </div>
  1387. <?php endif?>
  1388. <?php }private
  1389. function
  1390. analyse($router){if($router
  1391. instanceof
  1392. MultiRouter){foreach($router
  1393. as$subRouter){$this->analyse($subRouter);}return;}$request=$router->match($this->httpRequest);$matched=$request===NULL?'no':'may';if($request!==NULL&&empty($this->request)){$this->request=$request;$matched='yes';}$this->routers[]=array('matched'=>$matched,'class'=>get_class($router),'defaults'=>$router
  1394. instanceof
  1395. Route||$router
  1396. instanceof
  1397. SimpleRouter?$router->getDefaults():array(),'mask'=>$router
  1398. instanceof
  1399. Route?$router->getMask():NULL,'request'=>$request);}}class
  1400. Cache
  1401. extends
  1402. Object
  1403. implements
  1404. ArrayAccess{const
  1405. PRIORITY='priority';const
  1406. EXPIRE='expire';const
  1407. SLIDING='sliding';const
  1408. TAGS='tags';const
  1409. FILES='files';const
  1410. ITEMS='items';const
  1411. CONSTS='consts';const
  1412. CALLBACKS='callbacks';const
  1413. ALL='all';const
  1414. NAMESPACE_SEPARATOR="\x00";private$storage;private$namespace;private$key;private$data;function
  1415. __construct(ICacheStorage$storage,$namespace=NULL){$this->storage=$storage;$this->namespace=(string)$namespace;if(strpos($this->namespace,self::NAMESPACE_SEPARATOR)!==FALSE){throw
  1416. new
  1417. InvalidArgumentException("Namespace name contains forbidden character.");}}function
  1418. getStorage(){return$this->storage;}function
  1419. getNamespace(){return$this->namespace;}function
  1420. release(){$this->key=$this->data=NULL;}function
  1421. save($key,$data,array$dp=NULL){if(!is_string($key)&&!is_int($key)){throw
  1422. new
  1423. InvalidArgumentException("Cache key name must be string or integer, ".gettype($key)." given.");}$this->key=(string)$key;$key=$this->namespace.self::NAMESPACE_SEPARATOR.$key;if(!empty($dp[Cache::EXPIRE])){$dp[Cache::EXPIRE]=Tools::createDateTime($dp[Cache::EXPIRE])->format('U')-time();}if(isset($dp[self::FILES])){foreach((array)$dp[self::FILES]as$item){$dp[self::CALLBACKS][]=array(array(__CLASS__,'checkFile'),$item,@filemtime($item));}unset($dp[self::FILES]);}if(isset($dp[self::ITEMS])){$dp[self::ITEMS]=(array)$dp[self::ITEMS];foreach($dp[self::ITEMS]as$k=>$item){$dp[self::ITEMS][$k]=$this->namespace.self::NAMESPACE_SEPARATOR.$item;}}if(isset($dp[self::CONSTS])){foreach((array)$dp[self::CONSTS]as$item){$dp[self::CALLBACKS][]=array(array(__CLASS__,'checkConst'),$item,constant($item));}unset($dp[self::CONSTS]);}if($data
  1424. instanceof
  1425. Callback||$data
  1426. instanceof
  1427. Closure){Environment::enterCriticalSection('Nette\Caching/'.$key);$data=$data->__invoke();Environment::leaveCriticalSection('Nette\Caching/'.$key);}if(is_object($data)){$dp[self::CALLBACKS][]=array(array(__CLASS__,'checkSerializationVersion'),get_class($data),ClassReflection::from($data)->getAnnotation('serializationVersion'));}$this->data=$data;if($data===NULL){$this->storage->remove($key);}else{$this->storage->write($key,$data,(array)$dp);}return$data;}function
  1428. clean(array$conds=NULL){$this->release();$this->storage->clean((array)$conds);}function
  1429. offsetSet($key,$data){$this->save($key,$data);}function
  1430. offsetGet($key){if(!is_string($key)&&!is_int($key)){throw
  1431. new
  1432. InvalidArgumentException("Cache key name must be string or integer, ".gettype($key)." given.");}$key=(string)$key;if($this->key===$key){return$this->data;}$this->key=$key;$this->data=$this->storage->read($this->namespace.self::NAMESPACE_SEPARATOR.$key);return$this->data;}function
  1433. offsetExists($key){return$this->offsetGet($key)!==NULL;}function
  1434. offsetUnset($key){$this->save($key,NULL);}static
  1435. function
  1436. checkCallbacks($callbacks){foreach($callbacks
  1437. as$callback){$func=array_shift($callback);if(!call_user_func_array($func,$callback)){return
  1438. FALSE;}}return
  1439. TRUE;}private
  1440. static
  1441. function
  1442. checkConst($const,$value){return
  1443. defined($const)&&constant($const)===$value;}private
  1444. static
  1445. function
  1446. checkFile($file,$time){return@filemtime($file)==$time;}private
  1447. static
  1448. function
  1449. checkSerializationVersion($class,$value){return
  1450. ClassReflection::from($class)->getAnnotation('serializationVersion')===$value;}}class
  1451. DummyStorage
  1452. extends
  1453. Object
  1454. implements
  1455. ICacheStorage{function
  1456. read($key){return
  1457. NULL;}function
  1458. write($key,$data,array$dp){}function
  1459. remove($key){}function
  1460. clean(array$conds){}}class
  1461. FileStorage
  1462. extends
  1463. Object
  1464. implements
  1465. ICacheStorage{const
  1466. META_HEADER_LEN=28;const
  1467. META_TIME='time';const
  1468. META_SERIALIZED='serialized';const
  1469. META_EXPIRE='expire';const
  1470. META_DELTA='delta';const
  1471. META_ITEMS='di';const
  1472. META_CALLBACKS='callbacks';const
  1473. FILE='file';const
  1474. HANDLE='handle';public
  1475. static$gcProbability=0.001;public
  1476. static$useDirectories;private$dir;private$useDirs;private$db;function
  1477. __construct($dir){if(self::$useDirectories===NULL){$uniq=uniqid('_',TRUE);umask(0000);if(!@mkdir("$dir/$uniq",0777)){throw
  1478. new
  1479. InvalidStateException("Unable to write to directory '$dir'. Make this directory writable.");}self::$useDirectories=!ini_get('safe_mode');if(!self::$useDirectories&&@file_put_contents("$dir/$uniq/_",'')!==FALSE){self::$useDirectories=TRUE;unlink("$dir/$uniq/_");}rmdir("$dir/$uniq");}$this->dir=$dir;$this->useDirs=(bool)self::$useDirectories;if(mt_rand()/mt_getrandmax()<self::$gcProbability){$this->clean(array());}}function
  1480. read($key){$meta=$this->readMeta($this->getCacheFile($key),LOCK_SH);if($meta&&$this->verify($meta)){return$this->readData($meta);}else{return
  1481. NULL;}}private
  1482. function
  1483. verify($meta){do{if(!empty($meta[self::META_DELTA])){if(filemtime($meta[self::FILE])+$meta[self::META_DELTA]<time())break;touch($meta[self::FILE]);}elseif(!empty($meta[self::META_EXPIRE])&&$meta[self::META_EXPIRE]<time()){break;}if(!empty($meta[self::META_CALLBACKS])&&!Cache::checkCallbacks($meta[self::META_CALLBACKS])){break;}if(!empty($meta[self::META_ITEMS])){foreach($meta[self::META_ITEMS]as$depFile=>$time){$m=$this->readMeta($depFile,LOCK_SH);if($m[self::META_TIME]!==$time)break
  1484. 2;if($m&&!$this->verify($m))break
  1485. 2;}}return
  1486. TRUE;}while(FALSE);$this->delete($meta[self::FILE],$meta[self::HANDLE]);return
  1487. FALSE;}function
  1488. write($key,$data,array$dp){$meta=array(self::META_TIME=>microtime());if(!empty($dp[Cache::EXPIRE])){if(empty($dp[Cache::SLIDING])){$meta[self::META_EXPIRE]=$dp[Cache::EXPIRE]+time();}else{$meta[self::META_DELTA]=(int)$dp[Cache::EXPIRE];}}if(!empty($dp[Cache::ITEMS])){foreach((array)$dp[Cache::ITEMS]as$item){$depFile=$this->getCacheFile($item);$m=$this->readMeta($depFile,LOCK_SH);$meta[self::META_ITEMS][$depFile]=$m[self::META_TIME];unset($m);}}if(!empty($dp[Cache::CALLBACKS])){$meta[self::META_CALLBACKS]=$dp[Cache::CALLBACKS];}$cacheFile=$this->getCacheFile($key);if($this->useDirs&&!is_dir($dir=dirname($cacheFile))){umask(0000);if(!mkdir($dir,0777,TRUE)){return;}}$handle=@fopen($cacheFile,'r+b');if(!$handle){$handle=fopen($cacheFile,'wb');if(!$handle){return;}}if(!empty($dp[Cache::TAGS])||isset($dp[Cache::PRIORITY])){$db=$this->getDb();$dbFile=sqlite_escape_string($cacheFile);$query='';if(!empty($dp[Cache::TAGS])){foreach((array)$dp[Cache::TAGS]as$tag){$query.="INSERT INTO cache (file, tag) VALUES ('$dbFile', '".sqlite_escape_string($tag)."');";}}if(isset($dp[Cache::PRIORITY])){$query.="INSERT INTO cache (file, priority) VALUES ('$dbFile', '".(int)$dp[Cache::PRIORITY]."');";}if(!sqlite_exec($db,"BEGIN; DELETE FROM cache WHERE file = '$dbFile'; $query COMMIT;")){sqlite_exec($db,"ROLLBACK");return;}}flock($handle,LOCK_EX);ftruncate($handle,0);if(!is_string($data)){$data=serialize($data);$meta[self::META_SERIALIZED]=TRUE;}$head=serialize($meta).'?>';$head='<?php //netteCache[01]'.str_pad((string)strlen($head),6,'0',STR_PAD_LEFT).$head;$headLen=strlen($head);$dataLen=strlen($data);do{if(fwrite($handle,str_repeat("\x00",$headLen),$headLen)!==$headLen){break;}if(fwrite($handle,$data,$dataLen)!==$dataLen){break;}fseek($handle,0);if(fwrite($handle,$head,$headLen)!==$headLen){break;}fclose($handle);return
  1489. TRUE;}while(FALSE);$this->delete($cacheFile,$handle);}function
  1490. remove($key){$this->delete($this->getCacheFile($key));}function
  1491. clean(array$conds){$all=!empty($conds[Cache::ALL]);$collector=empty($conds);if($all||$collector){$now=time();$base=$this->dir.DIRECTORY_SEPARATOR.'c';$iterator=new
  1492. RecursiveIteratorIterator(new
  1493. RecursiveDirectoryIterator($this->dir),RecursiveIteratorIterator::CHILD_FIRST);foreach($iterator
  1494. as$entry){$path=(string)$entry;if(strncmp($path,$base,strlen($base))){continue;}if($entry->isDir()){@rmdir($path);continue;}if($all){$this->delete($path);}else{$meta=$this->readMeta($path,LOCK_SH);if(!$meta)continue;if(!empty($meta[self::META_EXPIRE])&&$meta[self::META_EXPIRE]<$now){$this->delete($path,$meta[self::HANDLE]);continue;}fclose($meta[self::HANDLE]);}}if($all&&extension_loaded('sqlite')){sqlite_exec("DELETE FROM cache",$this->getDb());}return;}if(!empty($conds[Cache::TAGS])){$db=$this->getDb();foreach((array)$conds[Cache::TAGS]as$tag){$tmp[]="'".sqlite_escape_string($tag)."'";}$query[]="tag IN (".implode(',',$tmp).")";}if(isset($conds[Cache::PRIORITY])){$query[]="priority <= ".(int)$conds[Cache::PRIORITY];}if(isset($query)){$db=$this->getDb();$query=implode(' OR ',$query);$files=sqlite_single_query("SELECT file FROM cache WHERE $query",$db,FALSE);foreach($files
  1495. as$file){$this->delete($file);}sqlite_exec("DELETE FROM cache WHERE $query",$db);}}protected
  1496. function
  1497. readMeta($file,$lock){$handle=@fopen($file,'r+b');if(!$handle)return
  1498. NULL;flock($handle,$lock);$head=stream_get_contents($handle,self::META_HEADER_LEN);if($head&&strlen($head)===self::META_HEADER_LEN){$size=(int)substr($head,-6);$meta=stream_get_contents($handle,$size,self::META_HEADER_LEN);$meta=@unserialize($meta);if(is_array($meta)){fseek($handle,$size+self::META_HEADER_LEN);$meta[self::FILE]=$file;$meta[self::HANDLE]=$handle;return$meta;}}fclose($handle);return
  1499. NULL;}protected
  1500. function
  1501. readData($meta){$data=stream_get_contents($meta[self::HANDLE]);fclose($meta[self::HANDLE]);if(empty($meta[self::META_SERIALIZED])){return$data;}else{return@unserialize($data);}}protected
  1502. function
  1503. getCacheFile($key){if($this->useDirs){$key=explode(Cache::NAMESPACE_SEPARATOR,$key,2);return$this->dir.'/c'.(isset($key[1])?'-'.urlencode($key[0]).'/_'.urlencode($key[1]):'_'.urlencode($key[0]));}else{return$this->dir.'/c_'.urlencode($key);}}private
  1504. static
  1505. function
  1506. delete($file,$handle=NULL){if(@unlink($file)){if($handle)fclose($handle);return;}if(!$handle){$handle=@fopen($file,'r+');}if($handle){flock($handle,LOCK_EX);ftruncate($handle,0);fclose($handle);@unlink($file);}}protected
  1507. function
  1508. getDb(){if($this->db===NULL){if(!extension_loaded('sqlite')){throw
  1509. new
  1510. InvalidStateException("SQLite extension is required for storing tags and priorities.");}$this->db=sqlite_open($this->dir.'/cachejournal.sdb');@sqlite_exec($this->db,'CREATE TABLE cache (file VARCHAR NOT NULL, priority, tag VARCHAR);
  1511. CREATE INDEX IDX_FILE ON cache (file); CREATE INDEX IDX_PRI ON cache (priority); CREATE INDEX IDX_TAG ON cache (tag);');}return$this->db;}}class
  1512. MemcachedStorage
  1513. extends
  1514. Object
  1515. implements
  1516. ICacheStorage{const
  1517. META_CALLBACKS='callbacks';const
  1518. META_DATA='data';const
  1519. META_DELTA='delta';private$memcache;private$prefix;static
  1520. function
  1521. isAvailable(){return
  1522. extension_loaded('memcache');}function
  1523. __construct($host='localhost',$port=11211,$prefix=''){if(!self::isAvailable()){throw
  1524. new
  1525. Exception("PHP extension 'memcache' is not loaded.");}$this->prefix=$prefix;$this->memcache=new
  1526. Memcache;$this->memcache->connect($host,$port);}function
  1527. read($key){$key=$this->prefix.$key;$meta=$this->memcache->get($key);if(!$meta)return
  1528. NULL;if(!empty($meta[self::META_CALLBACKS])&&!Cache::checkCallbacks($meta[self::META_CALLBACKS])){$this->memcache->delete($key);return
  1529. NULL;}if(!empty($meta[self::META_DELTA])){$this->memcache->replace($key,$meta,0,$meta[self::META_DELTA]+time());}return$meta[self::META_DATA];}function
  1530. write($key,$data,array$dp){if(!empty($dp[Cache::TAGS])||isset($dp[Cache::PRIORITY])||!empty($dp[Cache::ITEMS])){throw
  1531. new
  1532. NotSupportedException('Tags, priority and dependent items are not supported by MemcachedStorage.');}$meta=array(self::META_DATA=>$data);$expire=0;if(!empty($dp[Cache::EXPIRE])){$expire=(int)$dp[Cache::EXPIRE];if(!empty($dp[Cache::SLIDING])){$meta[self::META_DELTA]=$expire;}}if(!empty($dp[Cache::CALLBACKS])){$meta[self::META_CALLBACKS]=$dp[Cache::CALLBACKS];}$this->memcache->set($this->prefix.$key,$meta,0,$expire);}function
  1533. remove($key){$this->memcache->delete($this->prefix.$key);}function
  1534. clean(array$conds){if(!empty($conds[Cache::ALL])){$this->memcache->flush();}elseif(isset($conds[Cache::TAGS])||isset($conds[Cache::PRIORITY])){throw
  1535. new
  1536. NotSupportedException('Tags and priority is not supported by MemcachedStorage.');}}}class
  1537. Config
  1538. implements
  1539. ArrayAccess,IteratorAggregate{private
  1540. static$extensions=array('ini'=>'ConfigAdapterIni');static
  1541. function
  1542. registerExtension($extension,$class){if(!class_exists($class)){throw
  1543. new
  1544. InvalidArgumentException("Class '$class' was not found.");}if(!ClassReflection::from($class)->implementsInterface('IConfigAdapter')){throw
  1545. new
  1546. InvalidArgumentException("Configuration adapter '$class' is not Nette\\Config\\IConfigAdapter implementor.");}self::$extensions[strtolower($extension)]=$class;}static
  1547. function
  1548. fromFile($file,$section=NULL){$extension=strtolower(pathinfo($file,PATHINFO_EXTENSION));if(isset(self::$extensions[$extension])){$arr=call_user_func(array(self::$extensions[$extension],'load'),$file,$section);return
  1549. new
  1550. self($arr);}else{throw
  1551. new
  1552. InvalidArgumentException("Unknown file extension '$file'.");}}function
  1553. __construct($arr=NULL){foreach((array)$arr
  1554. as$k=>$v){$this->$k=is_array($v)?new
  1555. self($v):$v;}}function
  1556. save($file,$section=NULL){$extension=strtolower(pathinfo($file,PATHINFO_EXTENSION));if(isset(self::$extensions[$extension])){return
  1557. call_user_func(array(self::$extensions[$extension],'save'),$this,$file,$section);}else{throw
  1558. new
  1559. InvalidArgumentException("Unknown file extension '$file'.");}}function
  1560. __set($key,$value){if(!is_scalar($key)){throw
  1561. new
  1562. InvalidArgumentException("Key must be either a string or an integer.");}elseif($value===NULL){unset($this->$key);}else{$this->$key=$value;}}function&__get($key){if(!is_scalar($key)){throw
  1563. new
  1564. InvalidArgumentException("Key must be either a string or an integer.");}return$this->$key;}function
  1565. __isset($key){return
  1566. FALSE;}function
  1567. __unset($key){}function
  1568. offsetSet($key,$value){$this->__set($key,$value);}function
  1569. offsetGet($key){if(!is_scalar($key)){throw
  1570. new
  1571. InvalidArgumentException("Key must be either a string or an integer.");}elseif(!isset($this->$key)){return
  1572. NULL;}return$this->$key;}function
  1573. offsetExists($key){if(!is_scalar($key)){throw
  1574. new
  1575. InvalidArgumentException("Key must be either a string or an integer.");}return
  1576. isset($this->$key);}function
  1577. offsetUnset($key){if(!is_scalar($key)){throw
  1578. new
  1579. InvalidArgumentException("Key must be either a string or an integer.");}unset($this->$key);}function
  1580. getIterator(){return
  1581. new
  1582. GenericRecursiveIterator(new
  1583. ArrayIterator($this));}function
  1584. toArray(){$arr=array();foreach($this
  1585. as$k=>$v){$arr[$k]=$v
  1586. instanceof
  1587. self?$v->toArray():$v;}return$arr;}}final
  1588. class
  1589. ConfigAdapterIni
  1590. implements
  1591. IConfigAdapter{public
  1592. static$keySeparator='.';public
  1593. static$sectionSeparator=' < ';public
  1594. static$rawSection='!';final
  1595. function
  1596. __construct(){throw
  1597. new
  1598. LogicException("Cannot instantiate static class ".get_class($this));}static
  1599. function
  1600. load($file,$section=NULL){if(!is_file($file)||!is_readable($file)){throw
  1601. new
  1602. FileNotFoundException("File '$file' is missing or is not readable.");}Tools::tryError();$ini=parse_ini_file($file,TRUE);if(Tools::catchError($msg)){throw
  1603. new
  1604. Exception($msg);}$separator=trim(self::$sectionSeparator);$data=array();foreach($ini
  1605. as$secName=>$secData){if(is_array($secData)){if(substr($secName,-1)===self::$rawSection){$secName=substr($secName,0,-1);}elseif(self::$keySeparator){$tmp=array();foreach($secData
  1606. as$key=>$val){$cursor=&$tmp;foreach(explode(self::$keySeparator,$key)as$part){if(!isset($cursor[$part])||is_array($cursor[$part])){$cursor=&$cursor[$part];}else{throw
  1607. new
  1608. InvalidStateException("Invalid key '$key' in section [$secName] in '$file'.");}}$cursor=$val;}$secData=$tmp;}$parts=$separator?explode($separator,strtr($secName,':',$separator)):array($secName);if(count($parts)>1){$parent=trim($parts[1]);$cursor=&$data;foreach(self::$keySeparator?explode(self::$keySeparator,$parent):array($parent)as$part){if(isset($cursor[$part])&&is_array($cursor[$part])){$cursor=&$cursor[$part];}else{throw
  1609. new
  1610. InvalidStateException("Missing parent section [$parent] in '$file'.");}}$secData=ArrayTools::mergeTree($secData,$cursor);}$secName=trim($parts[0]);if($secName===''){throw
  1611. new
  1612. InvalidStateException("Invalid empty section name in '$file'.");}}if(self::$keySeparator){$cursor=&$data;foreach(explode(self::$keySeparator,$secName)as$part){if(!isset($cursor[$part])||is_array($cursor[$part])){$cursor=&$cursor[$part];}else{throw
  1613. new
  1614. InvalidStateException("Invalid section [$secName] in '$file'.");}}}else{$cursor=&$data[$secName];}if(is_array($secData)&&is_array($cursor)){$secData=ArrayTools::mergeTree($secData,$cursor);}$cursor=$secData;}if($section===NULL){return$data;}elseif(!isset($data[$section])||!is_array($data[$section])){throw
  1615. new
  1616. InvalidStateException("There is not section [$section] in '$file'.");}else{return$data[$section];}}static
  1617. function
  1618. save($config,$file,$section=NULL){$output=array();$output[]='; generated by Nette';$output[]='';if($section===NULL){foreach($config
  1619. as$secName=>$secData){if(!(is_array($secData)||$secData
  1620. instanceof
  1621. Traversable)){throw
  1622. new
  1623. InvalidStateException("Invalid section '$section'.");}$output[]="[$secName]";self::build($secData,$output,'');$output[]='';}}else{$output[]="[$section]";self::build($config,$output,'');$output[]='';}if(!file_put_contents($file,implode(PHP_EOL,$output))){throw
  1624. new
  1625. IOException("Cannot write file '$file'.");}}private
  1626. static
  1627. function
  1628. build($input,&$output,$prefix){foreach($input
  1629. as$key=>$val){if(is_array($val)||$val
  1630. instanceof
  1631. Traversable){self::build($val,$output,$prefix.$key.self::$keySeparator);}elseif(is_bool($val)){$output[]="$prefix$key = ".($val?'true':'false');}elseif(is_numeric($val)){$output[]="$prefix$key = $val";}elseif(is_string($val)){$output[]="$prefix$key = \"$val\"";}else{throw
  1632. new
  1633. InvalidArgumentException("The '$prefix$key' item must be scalar or array, ".gettype($val)." given.");}}}}final
  1634. class
  1635. Debug{public
  1636. static$productionMode;public
  1637. static$consoleMode;public
  1638. static$time;private
  1639. static$firebugDetected;private
  1640. static$ajaxDetected;private
  1641. static$uri;public
  1642. static$maxDepth=3;public
  1643. static$maxLen=150;public
  1644. static$showLocation=FALSE;const
  1645. DEVELOPMENT=FALSE;const
  1646. PRODUCTION=TRUE;const
  1647. DETECT=NULL;public
  1648. static$strictMode=FALSE;public
  1649. static$onFatalError=array();public
  1650. static$mailer=array(__CLASS__,'defaultMailer');public
  1651. static$emailSnooze=172800;private
  1652. static$enabled=FALSE;private
  1653. static$logFile;private
  1654. static$logHandle;private
  1655. static$sendEmails;private
  1656. static$emailHeaders=array('To'=>'','From'=>'noreply@%host%','X-Mailer'=>'Nette Framework','Subject'=>'PHP: An error occurred on the server %host%','Body'=>'[%date%] %message%');public
  1657. static$showBar=TRUE;private
  1658. static$panels=array();private
  1659. static$dumps;private
  1660. static$errors;public
  1661. static$counters=array();const
  1662. LOG='LOG';const
  1663. INFO='INFO';const
  1664. WARN='WARN';const
  1665. ERROR='ERROR';const
  1666. TRACE='TRACE';const
  1667. EXCEPTION='EXCEPTION';const
  1668. GROUP_START='GROUP_START';const
  1669. GROUP_END='GROUP_END';final
  1670. function
  1671. __construct(){throw
  1672. new
  1673. LogicException("Cannot instantiate static class ".get_class($this));}static
  1674. function
  1675. _init(){self::$time=microtime(TRUE);self::$consoleMode=PHP_SAPI==='cli';self::$productionMode=self::DETECT;self::$firebugDetected=isset($_SERVER['HTTP_USER_AGENT'])&&strpos($_SERVER['HTTP_USER_AGENT'],'FirePHP/');self::$ajaxDetected=isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';if(isset($_SERVER['REQUEST_URI'])){self::$uri=(isset($_SERVER['HTTPS'])&&strcasecmp($_SERVER['HTTPS'],'off')?'https://':'http://').(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'')).$_SERVER['REQUEST_URI'];}$tab=array(__CLASS__,'renderTab');$panel=array(__CLASS__,'renderPanel');self::addPanel(new
  1676. DebugPanel('time',$tab,$panel));self::addPanel(new
  1677. DebugPanel('memory',$tab,$panel));self::addPanel(new
  1678. DebugPanel('errors',$tab,$panel));self::addPanel(new
  1679. DebugPanel('dumps',$tab,$panel));}static
  1680. function
  1681. dump($var,$return=FALSE){if(!$return&&self::$productionMode){return$var;}$output="<pre class=\"nette-dump\">".self::_dump($var,0)."</pre>\n";if(!$return&&self::$showLocation){$trace=debug_backtrace();$i=isset($trace[1]['class'])&&$trace[1]['class']===__CLASS__?1:0;if(isset($trace[$i]['file'],$trace[$i]['line'])){$output=substr_replace($output,' <small>'.htmlspecialchars("in file {$trace[$i]['file']} on line {$trace[$i]['line']}",ENT_NOQUOTES).'</small>',-8,0);}}if(self::$consoleMode){$output=htmlspecialchars_decode(strip_tags($output),ENT_NOQUOTES);}if($return){return$output;}else{echo$output;return$var;}}static
  1682. function
  1683. barDump($var,$title=NULL){if(!self::$productionMode){$dump=array();foreach((is_array($var)?$var:array(''=>$var))as$key=>$val){$dump[$key]=self::dump($val,TRUE);}self::$dumps[]=array('title'=>$title,'dump'=>$dump);}return$var;}private
  1684. static
  1685. function
  1686. _dump(&$var,$level){static$tableUtf,$tableBin,$re='#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';if($tableUtf===NULL){foreach(range("\x00","\xFF")as$ch){if(ord($ch)<32&&strpos("\r\n\t",$ch)===FALSE)$tableUtf[$ch]=$tableBin[$ch]='\\x'.str_pad(dechex(ord($ch)),2,'0',STR_PAD_LEFT);elseif(ord($ch)<127)$tableUtf[$ch]=$tableBin[$ch]=$ch;else{$tableUtf[$ch]=$ch;$tableBin[$ch]='\\x'.dechex(ord($ch));}}$tableUtf['\\x']=$tableBin['\\x']='\\\\x';}if(is_bool($var)){return"<span>bool</span>(".($var?'TRUE':'FALSE').")\n";}elseif($var===NULL){return"<span>NULL</span>\n";}elseif(is_int($var)){return"<span>int</span>($var)\n";}elseif(is_float($var)){return"<span>float</span>($var)\n";}elseif(is_string($var)){if(self::$maxLen&&strlen($var)>self::$maxLen){$s=htmlSpecialChars(substr($var,0,self::$maxLen),ENT_NOQUOTES).' ... ';}else{$s=htmlSpecialChars($var,ENT_NOQUOTES);}$s=strtr($s,preg_match($re,$s)||preg_last_error()?$tableBin:$tableUtf);return"<span>string</span>(".strlen($var).") \"$s\"\n";}elseif(is_array($var)){$s="<span>array</span>(".count($var).") ";$space=str_repeat($space1=' ',$level);static$marker;if($marker===NULL)$marker=uniqid("\x00",TRUE);if(empty($var)){}elseif(isset($var[$marker])){$s.="{\n$space$space1*RECURSION*\n$space}";}elseif($level<self::$maxDepth||!self::$maxDepth){$s.="<code>{\n";$var[$marker]=0;foreach($var
  1687. as$k=>&$v){if($k===$marker)continue;$k=is_int($k)?$k:'"'.strtr($k,preg_match($re,$k)||preg_last_error()?$tableBin:$tableUtf).'"';$s.="$space$space1$k => ".self::_dump($v,$level+1);}unset($var[$marker]);$s.="$space}</code>";}else{$s.="{\n$space$space1...\n$space}";}return$s."\n";}elseif(is_object($var)){$arr=(array)$var;$s="<span>object</span>(".get_class($var).") (".count($arr).") ";$space=str_repeat($space1=' ',$level);static$list=array();if(empty($arr)){$s.="{}";}elseif(in_array($var,$list,TRUE)){$s.="{\n$space$space1*RECURSION*\n$space}";}elseif($level<self::$maxDepth||!self::$maxDepth){$s.="<code>{\n";$list[]=$var;foreach($arr
  1688. as$k=>&$v){$m='';if($k[0]==="\x00"){$m=$k[1]==='*'?' <span>protected</span>':' <span>private</span>';$k=substr($k,strrpos($k,"\x00")+1);}$k=strtr($k,preg_match($re,$k)||preg_last_error()?$tableBin:$tableUtf);$s.="$space$space1\"$k\"$m => ".self::_dump($v,$level+1);}array_pop($list);$s.="$space}</code>";}else{$s.="{\n$space$space1...\n$space}";}return$s."\n";}elseif(is_resource($var)){return"<span>resource of type</span>(".get_resource_type($var).")\n";}else{return"<span>unknown type</span>\n";}}static
  1689. function
  1690. timer($name=NULL){static$time=array();$now=microtime(TRUE);$delta=isset($time[$name])?$now-$time[$name]:0;$time[$name]=$now;return$delta;}static
  1691. function
  1692. enable($mode=NULL,$logFile=NULL,$email=NULL){error_reporting(E_ALL|E_STRICT);if(is_bool($mode)){self::$productionMode=$mode;}elseif(is_string($mode)){$mode=preg_split('#[,\s]+#',$mode);}if(is_array($mode)){self::$productionMode=!isset($_SERVER['REMOTE_ADDR'])||!in_array($_SERVER['REMOTE_ADDR'],$mode,TRUE);}if(self::$productionMode===self::DETECT){if(class_exists('Environment')){self::$productionMode=Environment::isProduction();}elseif(isset($_SERVER['SERVER_ADDR'])||isset($_SERVER['LOCAL_ADDR'])){$addr=isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:$_SERVER['LOCAL_ADDR'];$oct=explode('.',$addr);self::$productionMode=$addr!=='::1'&&(count($oct)!==4||($oct[0]!=='10'&&$oct[0]!=='127'&&($oct[0]!=='172'||$oct[1]<16||$oct[1]>31)&&($oct[0]!=='169'||$oct[1]!=='254')&&($oct[0]!=='192'||$oct[1]!=='168')));}else{self::$productionMode=!self::$consoleMode;}}if(self::$productionMode&&$logFile!==FALSE){self::$logFile='log/php_error.log';if(class_exists('Environment')){if(is_string($logFile)){self::$logFile=Environment::expand($logFile);}else
  1693. try{self::$logFile=Environment::expand('%logDir%/php_error.log');}catch(InvalidStateException$e){}}elseif(is_string($logFile)){self::$logFile=$logFile;}ini_set('error_log',self::$logFile);}if(function_exists('ini_set')){ini_set('display_errors',!self::$productionMode);ini_set('html_errors',!self::$logFile&&!self::$consoleMode);ini_set('log_errors',FALSE);}elseif(ini_get('display_errors')!=!self::$productionMode&&ini_get('display_errors')!==(self::$productionMode?'stderr':'stdout')){throw
  1694. new
  1695. NotSupportedException('Function ini_set() must be enabled.');}self::$sendEmails=self::$logFile&&$email;if(self::$sendEmails){if(is_string($email)){self::$emailHeaders['To']=$email;}elseif(is_array($email)){self::$emailHeaders=$email+self::$emailHeaders;}}if(!defined('E_DEPRECATED')){define('E_DEPRECATED',8192);}if(!defined('E_USER_DEPRECATED')){define('E_USER_DEPRECATED',16384);}register_shutdown_function(array(__CLASS__,'_shutdownHandler'));set_exception_handler(array(__CLASS__,'_exceptionHandler'));set_error_handler(array(__CLASS__,'_errorHandler'));self::$enabled=TRUE;}static
  1696. function
  1697. isEnabled(){return
  1698. self::$enabled;}static
  1699. function
  1700. log($message){error_log(@date('[Y-m-d H-i-s] ').trim($message).PHP_EOL,3,self::$logFile);}static
  1701. function
  1702. _shutdownHandler(){static$types=array(E_ERROR=>1,E_CORE_ERROR=>1,E_COMPILE_ERROR=>1,E_PARSE=>1);$error=error_get_last();if(isset($types[$error['type']])){if(!headers_sent()){header('HTTP/1.1 500 Internal Server Error');}if(ini_get('html_errors')){$error['message']=html_entity_decode(strip_tags($error['message']),ENT_QUOTES,'UTF-8');}self::processException(new
  1703. FatalErrorException($error['message'],0,$error['type'],$error['file'],$error['line'],NULL),TRUE);}if(self::$showBar&&!self::$productionMode&&!self::$ajaxDetected&&!self::$consoleMode){foreach(headers_list()as$header){if(strncasecmp($header,'Content-Type:',13)===0){if(substr($header,14,9)==='text/html'){break;}return;}}$panels=array();foreach(self::$panels
  1704. as$panel){$panels[]=array('id'=>preg_replace('#[^a-z0-9]+#i','-',$panel->getId()),'tab'=>$tab=(string)$panel->getTab(),'panel'=>$tab?(string)$panel->getPanel():NULL);}ob_start();?>
  1705. <!-- Nette Debug Bar -->
  1706. <style id="nette-debug-style">#nette-debug{display:none}body#nette-debug{margin:5px 5px 0;display:block}#nette-debug *{font:inherit;color:inherit;background:transparent;margin:0;padding:0;border:none;text-align:inherit;list-style:inherit}#nette-debug .nette-fixed-coords{position:fixed;_position:absolute;right:0;bottom:0}#nette-debug a{color:#125eae;text-decoration:none}#nette-debug .nette-panel a{color:#125eae;text-decoration:none}#nette-debug a:hover,#nette-debug a:active,#nette-debug a:focus{background-color:#125eae;color:white}#nette-debug .nette-panel h2,#nette-debug .nette-panel h3,#nette-debug .nette-panel p{margin:.4em 0}#nette-debug .nette-panel table{border-collapse:collapse;background:#fcfae5}#nette-debug .nette-panel .nette-alt td{background:#f5f2db}#nette-debug .nette-panel td,#nette-debug .nette-panel th{border:1px solid #dcd7c8;padding:2px 5px;vertical-align:top;text-align:left}#nette-debug .nette-panel th{background:#f0eee6;color:#655e5e;font-size:90%;font-weight:bold}#nette-debug .nette-panel pre,#nette-debug .nette-panel code{font:9pt/1.5 Consolas,monospace}.nette-hidden{display:none}#nette-debug-bar{font:normal normal 12px/21px Tahoma,sans-serif;color:#333;background:#edeae0;position:relative;top:-5px;left:-5px;height:21px;_float:left;min-width:50px;white-space:nowrap;z-index:23181;opacity:.9}#nette-debug-bar:hover{opacity:1}#nette-debug-bar ul{list-style:none none}#nette-debug-bar li{float:left}#nette-debug-bar img{vertical-align:middle;position:relative;top:-1px;margin-right:3px}#nette-debug-bar li a{color:#000;display:block;padding:0 4px}#nette-debug-bar li a:hover{color:black;background:#c3c1b8}#nette-debug-bar li .nette-warning{color:#d32b2b;font-weight:bold}#nette-debug-bar li div{padding:0 4px}#nette-debug-logo{background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAPCAYAAABwfkanAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABiFJREFUSMe1VglPlGcQ5i+1xjZNqxREtGq8ahCPWsVGvEDBA1BBRQFBDjkE5BYUzwpovRBUREBEBbl3OVaWPfj2vi82eTrvbFHamLRJ4yYTvm+u95mZZ96PoKAv+LOatXBYZ+Bx6uFy6DGnt1m0EOKwSmQzwmHTgX5B/1W+yM9GYJ02CX6/B/5ZF+w2A4x6FYGTYDVp4PdY2Tbrs5N+mnRa2Km4/wV6rhPzQQj5fDc1mJM5nd0iYdZtQWtrCxobGnDpUiledTynbuvg99mgUMhw924Trl2rR01NNSTNJE9iDpTV8innv4K2kZPLroPXbYLHZeSu2K1aeF0muJ2GvwGzmNSwU2E+svm8ZrgdBliMaha/34Vx+RAKCgpwpa4OdbW1UE/L2cc/68WtWzdRVlaG6uoqtD1/BA/pA1MIxLvtes7pc5vhoDOE/rOgbVSdf9aJWa8dBp0Kyg+jdLiTx2vQKWEyqGmcNkqg4iTC1+dzQatWkK+cJqPD7KyFaKEjvRuNjY24fLkGdXW1ePjwAeX4QHonDNI0A75+/RpqqqshH+6F2UAUMaupYXouykV0mp6SQ60coxgL8Z4aMg/4x675/V60v3jKB+Xl5WJibIC4KPEIS0qKqWv5GOh7BZ/HSIk9kA33o7y8DOfPZ6GQOipkXDZAHXKxr4ipqqpkKS6+iIrycgz2dyMnJxtVlZUsotNZWZmor79KBbvgpdjm5sfIzc1hv4L8fKJPDTfJZZc+gRYKr8sAEy2DcBRdEEk62ltx9uwZ5qNILoDU1l6mbrvx5EkzUlKSuTiR7PHjR3x4fv4FyIbeIic7G5WVFUyN+qtX+Lnt2SPcvn2LfURjhF7kE4WPDr+Bx+NEUVEhkpNPoImm5CSOl5aUIC3tLOMR59gtAY4HidGIzj14cB8ZGRkM8kJeHk6cOI4xWR8vSl5uLlJTT6O74xnT5lB8PM6cSYXVqILb5UBWZiYSExMYkE4zzjqX00QHG+h9AjPqMei0k3ywy2khMdNiq6BVCf04T6ekuBgJCUdRUVHOBQwPvkNSUiLjaGi4Q/5qFgYtHgTXRJdTT59GenoaA5gY64deq0Bc3EGuNj4+DnppEheLijhZRkY6SktLsGPHdi6irOwSFTRAgO04deokTSIFsbExuHfvLnFSx8DevelAfFwcA0lJTqZi5PDS9aci/sbE7Oe4wsICbtD27b/ye1NTI3FeSX4W2gdFALRD3A4eM44ePcKViuD79/8gnZP5Kg4+cCAW2dnnqUM2Lujw4UM4ePAA2ztfPsHIYA/sdOt43A50d7UFCjkUj+joXVBMDJDeDhcVk08cjd61C3v37uFYp8PKXX3X8xJRUTtw7FgSn3Xzxg10d7ZCqRjkM+02C7pettDNogqAFjzxuI3YHR2Nffv2coXy0V44HGZERm7kJNu2/cK8bW9rwbp1axnMnj27uUijQQOb1QyTcYZ3YMOGn/Hbzp1crAAvaDfY38O5hW3//n0ce+TIYWiUcub1xo0R2Lp1y8cYsUMWM125VhPe93Zj7do1vEPi26GfUdBFbhK8tGHrli1YsWwpgoOD0dXRQqAtXMCy8DBs3rwJoSGLsWrVclylBdoUGYlVK1dg9eqVCFsSSs8/4btvvmUwEnE0KTERISE/IiIiAsGLF2HhwgU8qbc97QgPX8qFr1mzGgu+/opzdL5o5l1aEhqC9evXYWlYKFYsD6e/YVj0w/dMGZVyBDMqeaDTRuKpkxYjIz2dOyeup6H3r2kkOuJ1H3N5Z1QUzp3LQF9vJ4xGLQYHXiM9LY0pEhsTg+PHj9HNcJu4OcL3uaQZY86LiZw8mcJTkmhBTUYJbU8fcoygobgWR4Z6iKtTPLE7d35HYkICT1dIZuY59HQ9412StBPQTMvw8Z6WaMNFxy3Gab4TeQT0M9IHwUT/G0i0MGIJ9CTiJjBIH+iQaQbC7+QnfEXiQL6xgF09TjETHCt8RbeMuil+D8RNsV1LHdQoZfR/iJJzCZuYmEE/Bd3MJNs/+0UURgFWJJ//aQ8k+CsxVTqnVytHObkQrUoG8T4/bs4u4ubbxLPwFzYNPc8HI2zijLm84l39Dx8hfwJenFezFBKKQwAAAABJRU5ErkJggg==') 0 50% no-repeat;min-width:45px;cursor:move}#nette-debug-logo span{display:none}#nette-debug-bar-bgl,#nette-debug-bar-bgx,#nette-debug-bar-bgr{position:absolute;z-index:-1;top:-7px;height:37px}#nette-debug-bar-bgl{background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAlCAMAAABBCPgrAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALdQTFRFPj4+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAISEhAAAAIyMjAAAAHR0dISEhNzc3Nzc3NjY2NTU1PT09PT09PDw8Pj4+SkpJS0tKy8nDxcO7zMrEx8S97evj4+HY5uPb7uzk5+Ta6OXb6Obc6ebd6ufe6+jf7Onf7erg7uvh7+zi8O3j8O3k8e7k8e7l8e/l8u/m8u/n8vDn8vDo8/Do8/Ho8/HpTk+bYwAAACd0Uk5TAAECAwQFBgcICQoLDA0ODxAQERMVLi8wM0hJSk9TU6qsrLDs7vHxx6CxnwAAAKJJREFUGBkFwUGKVEEARMF49WuEQdy5Ee9/R6HpTiMCCIEQISRFpNSFUlVSVacuqO8f93Gp+vmr+8eN6uv5i6N07hccVOc3HKr4jAtgc0UZuUjGXBKDCxhcwIYLGHMBM7uAjV3AZrvM+JhdzMy2a9lstgN8/m3bYdveL9ueSj338zl7orx7v1+vVJ1zzjnnEcLskcJsD2Ha9hAwHgQzgRABhP+DAUz8vYhDMAAAAABJRU5ErkJggg==') no-repeat;left:-12px;width:12px}#nette-debug-bar-bgx{background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAlCAYAAACDKIOpAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAF5JREFUeNpUjjEOgDAMA932DXynA/8X6sAnGBErjYlLW8Fy8jlRFAAI0RH/SC9yziuu86AUDjroiR+ldA6a0hDNHLUqSWmj6yvo2i6rS1vZi2xRd0/UNL4ypSDgEWAAvWU1L9Te5UYAAAAASUVORK5CYII=') repeat-x;left:0;right:5px}#nette-debug-bar-bgr{background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAlCAYAAACZFGMnAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAb5JREFUeNq8Vb1OwzAQtlNTIoRYYIhEFfUVGLp2YykDA48FG8/AUvEKqFIGQDwEA20CKv9UUFWkPuzUTi/pOW0XTjolvfrL951/PnPGGGelaLfbwIiIoih7aoBX+g9cH7AgHcJkzaRnkuNU4BygC3XEAI73ggqB5EFpsFOylYVB0vEBMMqgprR2wjDcD4JAy/wZjUayiiWLz7cBPD/dv9xe97pHnc5Jo9HYU+Utlb7pV6AJ4jno41VnH+5uepetVutAlbcNcFPlBuo9m0kPYC692QwPfd8P0AAPLb6d/uwLTAN1CiF2OOd1MxhQ8xz3JixgxlhYPypn6ySlzAEI55mpJ8MwsWVMuA6KybKQG5uXnohpcf04AZj3BCCrmKp6Wh2Qz966IdZlMSD2P0yeA0Qdd8Ant2r2KJ9YykQd+ZmpWGCapl9qCX6RT9A94R8P/fhqPB4PCSZY6EkxvA/ix+j07PwiSZLYMLlcKXPOYy1pMpkM4zhWmORb1acGNEW2lkvWO3cXFaQjCzK1vJQwSnIw7ild0WELtjwldoGsugwEMpBVbo2C68hSPwvy8OUmCKuCZVepoOhdd66NPwEGACivHvMuwfIKAAAAAElFTkSuQmCC') no-repeat;right:-8px;width:13px}#nette-debug .nette-panel{font:normal normal 12px/1.5 sans-serif;background:white;color:#333}#nette-debug h1{font:normal normal 23px/1.4 Tahoma,sans-serif;color:#575753;background:#edeae0;margin:-5px -5px 5px;padding:0 25px 5px 5px}#nette-debug .nette-mode-peek .nette-inner,#nette-debug .nette-mode-float .nette-inner{max-width:700px;max-height:500px;overflow:auto}#nette-debug .nette-panel .nette-icons{display:none}#nette-debug .nette-mode-peek{display:none;position:relative;z-index:23180;padding:5px;min-width:150px;min-height:50px;border:5px solid #edeae0;border-radius:5px;-moz-border-radius:5px}#nette-debug .nette-mode-peek h1{cursor:move}#nette-debug .nette-mode-float{position:relative;z-index:23179;padding:5px;min-width:150px;min-height:50px;border:5px solid #edeae0;border-radius:5px;-moz-border-radius:5px;opacity:.9;-moz-box-shadow:1px 1px 6px #666;-webkit-box-shadow:1px 1px 6px #666;box-shadow:1px 1px 6px #666}#nette-debug .nette-focused{z-index:23180;opacity:1}#nette-debug .nette-mode-float h1{cursor:move}#nette-debug .nette-mode-float .nette-icons{display:block;position:absolute;top:0;right:0;font-size:18px}#nette-debug .nette-icons a{color:#575753}#nette-debug .nette-icons a:hover{color:white}</style>
  1707. <!--[if lt IE 8]><style>#nette-debug-bar img{display:none}#nette-debug-bar li{border-left:1px solid #DCD7C8;padding:0 3px}#nette-debug-logo span{background:#edeae0;display:inline}</style><![endif]-->
  1708. <script id="nette-debug-script">
  1709. /* <![CDATA[ */
  1710. <?php ?>/**
  1711. * NetteJs
  1712. *
  1713. * @copyright Copyright (c) 2010 David Grudl
  1714. * @license http://nette.org/license Nette license
  1715. */
  1716. var Nette = Nette || {};
  1717. (function(){
  1718. // simple class builder
  1719. Nette.Class = function(def) {
  1720. var cl = def.constructor || function(){}, nm;
  1721. delete def.constructor;
  1722. if (def.Extends) {
  1723. var foo = function() { this.constructor = cl };
  1724. foo.prototype = def.Extends.prototype;
  1725. cl.prototype = new foo;
  1726. delete def.Extends;
  1727. }
  1728. if (def.Static) {
  1729. for (nm in def.Static) cl[nm] = def.Static[nm];
  1730. delete def.Static;
  1731. }
  1732. for (nm in def) cl.prototype[nm] = def[nm];
  1733. return cl;
  1734. };
  1735. // supported cross-browser selectors: #id | div | div.class | .class
  1736. Nette.Q = Nette.Class({
  1737. Static: {
  1738. factory: function(selector) {
  1739. return new Nette.Q(selector)
  1740. },
  1741. implement: function(methods) {
  1742. var nm, fn = Nette.Q.implement, prot = Nette.Q.prototype;
  1743. for (nm in methods) {
  1744. fn[nm] = methods[nm];
  1745. prot[nm] = (function(nm){
  1746. return function() { return this.each(fn[nm], arguments) }
  1747. }(nm));
  1748. }
  1749. }
  1750. },
  1751. constructor: function(selector) {
  1752. if (typeof selector === "string") {
  1753. selector = this._find(document, selector);
  1754. } else if (!selector || selector.nodeType || selector.length === void 0 || selector === window) {
  1755. selector = [selector];
  1756. }
  1757. for (var i = 0, len = selector.length; i < len; i++) {
  1758. if (selector[i]) this[this.length++] = selector[i];
  1759. }
  1760. },
  1761. length: 0,
  1762. find: function(selector) {
  1763. return new Nette.Q(this._find(this[0], selector));
  1764. },
  1765. _find: function(context, selector) {
  1766. if (!context || !selector) {
  1767. return [];
  1768. } else if (document.querySelectorAll) {
  1769. return context.querySelectorAll(selector);
  1770. } else if (selector.charAt(0) === '#') { // #id
  1771. return [document.getElementById(selector.substring(1))];
  1772. } else { // div | div.class | .class
  1773. selector = selector.split('.');
  1774. var elms = context.getElementsByTagName(selector[0] || '*');
  1775. if (selector[1]) {
  1776. var list = [], pattern = new RegExp('(^|\\s)' + selector[1] + '(\\s|$)');
  1777. for (var i = 0, len = elms.length; i < len; i++) {
  1778. if (pattern.test(elms[i].className)) list.push(elms[i]);
  1779. }
  1780. return list;
  1781. } else {
  1782. return elms;
  1783. }
  1784. }
  1785. },
  1786. dom: function() {
  1787. return this[0];
  1788. },
  1789. each: function(callback, args) {
  1790. for (var i = 0, res; i < this.length; i++) {
  1791. if ((res = callback.apply(this[i], args || [])) !== void 0) { return res; }
  1792. }
  1793. return this;
  1794. }
  1795. });
  1796. var $ = Nette.Q.factory, fn = Nette.Q.implement;
  1797. fn({
  1798. // cross-browser event attach
  1799. bind: function(event, handler) {
  1800. if (document.addEventListener && (event === 'mouseenter' || event === 'mouseleave')) { // simulate mouseenter & mouseleave using mouseover & mouseout
  1801. var old = handler;
  1802. event = event === 'mouseenter' ? 'mouseover' : 'mouseout';
  1803. handler = function(e) {
  1804. for (var target = e.relatedTarget; target; target = target.parentNode) {
  1805. if (target === this) return; // target must not be inside this
  1806. }
  1807. old.call(this, e);
  1808. };
  1809. }
  1810. var data = fn.data.call(this),
  1811. events = data.events = data.events || {}; // use own handler queue
  1812. if (!events[event]) {
  1813. var el = this, // fixes 'this' in iE
  1814. handlers = events[event] = [],
  1815. generic = fn.bind.genericHandler = function(e) { // dont worry, 'e' is passed in IE
  1816. if (!e.target) e.target = e.srcElement;
  1817. if (!e.preventDefault) e.preventDefault = function() { e.returnValue = false }; // emulate preventDefault()
  1818. if (!e.stopPropagation) e.stopPropagation = function() { e.cancelBubble = true }; // emulate stopPropagation()
  1819. e.stopImmediatePropagation = function() { this.stopPropagation(); i = handlers.length };
  1820. for (var i = 0; i < handlers.length; i++) {
  1821. handlers[i].call(el, e);
  1822. }
  1823. };
  1824. if (document.addEventListener) { // non-IE
  1825. this.addEventListener(event, generic, false);
  1826. } else if (document.attachEvent) { // IE < 9
  1827. this.attachEvent('on' + event, generic);
  1828. }
  1829. }
  1830. events[event].push(handler);
  1831. },
  1832. // adds class to element
  1833. addClass: function(className) {
  1834. this.className = this.className.replace(/^|\s+|$/g, ' ').replace(' '+className+' ', ' ') + ' ' + className;
  1835. },
  1836. // removes class from element
  1837. removeClass: function(className) {
  1838. this.className = this.className.replace(/^|\s+|$/g, ' ').replace(' '+className+' ', ' ');
  1839. },
  1840. // tests whether element has given class
  1841. hasClass: function(className) {
  1842. return this.className.replace(/^|\s+|$/g, ' ').indexOf(' '+className+' ') > -1;
  1843. },
  1844. show: function() {
  1845. var dsp = fn.show.display = fn.show.display || {}, tag = this.tagName;
  1846. if (!dsp[tag]) {
  1847. var el = document.body.appendChild(document.createElement(tag));
  1848. dsp[tag] = fn.css.call(el, 'display');
  1849. }
  1850. this.style.display = dsp[tag];
  1851. },
  1852. hide: function() {
  1853. this.style.display = 'none';
  1854. },
  1855. css: function(property) {
  1856. return this.currentStyle ? this.currentStyle[property]
  1857. : (window.getComputedStyle ? document.defaultView.getComputedStyle(this, null).getPropertyValue(property) : void 0);
  1858. },
  1859. data: function() {
  1860. return this.nette = this.nette || {};
  1861. },
  1862. _trav: function(el, selector, fce) {
  1863. selector = selector.split('.');
  1864. while (el && !(el.nodeType === 1 && (!selector[0] || el.tagName.toLowerCase() === selector[0]) && (!selector[1] || fn.hasClass.call(el, selector[1])))) el = el[fce];
  1865. return $(el);
  1866. },
  1867. closest: function(selector) {
  1868. return fn._trav(this, selector, 'parentNode');
  1869. },
  1870. prev: function(selector) {
  1871. return fn._trav(this.previousSibling, selector, 'previousSibling');
  1872. },
  1873. next: function(selector) {
  1874. return fn._trav(this.nextSibling, selector, 'nextSibling');
  1875. },
  1876. // returns total offset for element
  1877. offset: function(coords) {
  1878. var el = this, ofs = coords ? {left: -coords.left || 0, top: -coords.top || 0} : fn.position.call(el);
  1879. while (el = el.offsetParent) { ofs.left += el.offsetLeft; ofs.top += el.offsetTop; }
  1880. if (coords) {
  1881. fn.position.call(this, {left: -ofs.left, top: -ofs.top});
  1882. } else {
  1883. return ofs;
  1884. }
  1885. },
  1886. // returns current position or move to new position
  1887. position: function(coords) {
  1888. if (coords) {
  1889. this.nette && this.nette.onmove && this.nette.onmove.call(this, coords);
  1890. this.style.left = (coords.left || 0) + 'px';
  1891. this.style.top = (coords.top || 0) + 'px';
  1892. } else {
  1893. return {left: this.offsetLeft, top: this.offsetTop, width: this.offsetWidth, height: this.offsetHeight};
  1894. }
  1895. },
  1896. // makes element draggable
  1897. draggable: function(options) {
  1898. var $el = $(this), dE = document.documentElement, started, options = options || {};
  1899. $(options.handle || this).bind('mousedown', function(e) {
  1900. e.preventDefault();
  1901. e.stopPropagation();
  1902. if (fn.draggable.binded) { // missed mouseup out of window?
  1903. return dE.onmouseup(e);
  1904. }
  1905. var deltaX = $el[0].offsetLeft - e.clientX, deltaY = $el[0].offsetTop - e.clientY;
  1906. fn.draggable.binded = true;
  1907. started = false;
  1908. dE.onmousemove = function(e) {
  1909. e = e || event;
  1910. if (!started) {
  1911. options.draggedClass && $el.addClass(options.draggedClass);
  1912. options.start && options.start(e, $el);
  1913. started = true;
  1914. }
  1915. $el.position({left: e.clientX + deltaX, top: e.clientY + deltaY});
  1916. return false;
  1917. };
  1918. dE.onmouseup = function(e) {
  1919. if (started) {
  1920. options.draggedClass && $el.removeClass(options.draggedClass);
  1921. options.stop && options.stop(e || event, $el);
  1922. }
  1923. fn.draggable.binded = dE.onmousemove = dE.onmouseup = null;
  1924. return false;
  1925. };
  1926. }).bind('click', function(e) {
  1927. if (started) {
  1928. e.stopImmediatePropagation();
  1929. preventClick = false;
  1930. }
  1931. });
  1932. }
  1933. });
  1934. })();
  1935. (function(){
  1936. Nette.Debug = {};
  1937. var $ = Nette.Q.factory;
  1938. var Panel = Nette.Debug.Panel = Nette.Class({
  1939. Extends: Nette.Q,
  1940. Static: {
  1941. PEEK: 'nette-mode-peek',
  1942. FLOAT: 'nette-mode-float',
  1943. WINDOW: 'nette-mode-window',
  1944. FOCUSED: 'nette-focused',
  1945. factory: function(selector) {
  1946. return new Panel(selector)
  1947. },
  1948. _toggle: function(link) { // .nette-toggler
  1949. var rel = link.rel, el = rel.charAt(0) === '#' ? $(rel) : $(link)[rel.charAt(0) === '<' ? 'prev' : 'next'](rel.substring(1));
  1950. if (el.css('display') === 'none') {
  1951. el.show(); link.innerHTML = link.innerHTML.replace("\u25ba", "\u25bc");
  1952. } else {
  1953. el.hide(); link.innerHTML = link.innerHTML.replace("\u25bc", "\u25ba");
  1954. }
  1955. }
  1956. },
  1957. constructor: function(id) {
  1958. Nette.Q.call(this, '#nette-debug-panel-' + id.replace('nette-debug-panel-', ''));
  1959. },
  1960. reposition: function() {
  1961. if (this.hasClass(Panel.WINDOW)) {
  1962. window.resizeBy(document.documentElement.scrollWidth - document.documentElement.clientWidth, document.documentElement.scrollHeight - document.documentElement.clientHeight);
  1963. } else {
  1964. this.position(this.position());
  1965. if (this.position().width) { // is visible?
  1966. document.cookie = this.dom().id + '=' + this.position().left + ':' + this.position().top + '; path=/';
  1967. }
  1968. }
  1969. },
  1970. focus: function() {
  1971. if (this.hasClass(Panel.WINDOW)) {
  1972. this.data().win.focus();
  1973. } else {
  1974. clearTimeout(this.data().blurTimeout);
  1975. this.addClass(Panel.FOCUSED).show();
  1976. }
  1977. },
  1978. blur: function() {
  1979. this.removeClass(Panel.FOCUSED);
  1980. if (this.hasClass(Panel.PEEK)) {
  1981. var panel = this;
  1982. this.data().blurTimeout = setTimeout(function() {
  1983. panel.hide();
  1984. }, 50);
  1985. }
  1986. },
  1987. toFloat: function() {
  1988. this.removeClass(Panel.WINDOW).removeClass(Panel.PEEK).addClass(Panel.FLOAT).show().reposition();
  1989. return this;
  1990. },
  1991. toPeek: function() {
  1992. this.removeClass(Panel.WINDOW).removeClass(Panel.FLOAT).addClass(Panel.PEEK).hide();
  1993. document.cookie = this.dom().id + '=; path=/'; // delete position
  1994. },
  1995. toWindow: function() {
  1996. var panel = this, win, doc, offset = this.offset(), id = this.dom().id;
  1997. offset.left += typeof window.screenLeft === 'number' ? window.screenLeft : (window.screenX + 10);
  1998. offset.top += typeof window.screenTop === 'number' ? window.screenTop : (window.screenY + 50);
  1999. win = window.open('', id.replace(/-/g, '_'), 'left='+offset.left+',top='+offset.top+',width='+offset.width+',height='+(offset.height+15)+',resizable=yes,scrollbars=yes');
  2000. if (!win) return;
  2001. doc = win.document;
  2002. doc.write('<!DOCTYPE html><meta http-equiv="Content-Type" content="text\/html; charset=utf-8"><style>' + $('#nette-debug-style').dom().innerHTML + '<\/style><script>' + $('#nette-debug-script').dom().innerHTML + '<\/script><body id="nette-debug">');
  2003. doc.body.innerHTML = '<div class="nette-panel nette-mode-window" id="' + id + '">' + this.dom().innerHTML + '<\/div>';
  2004. win.Nette.Debug.Panel.factory(id).initToggler().reposition();
  2005. doc.title = panel.find('h1').dom().innerHTML;
  2006. $([win]).bind('unload', function() {
  2007. panel.toPeek();
  2008. win.close(); // forces closing, can be invoked by F5
  2009. });
  2010. $(doc).bind('keyup', function(e) {
  2011. if (e.keyCode === 27) win.close();
  2012. });
  2013. document.cookie = id + '=window; path=/'; // save position
  2014. this.hide().removeClass(Panel.FLOAT).removeClass(Panel.PEEK).addClass(Panel.WINDOW).data().win = win;
  2015. },
  2016. init: function() {
  2017. var panel = this, pos;
  2018. panel.data().onmove = function(coords) { // forces constrained inside window
  2019. var d = document, width = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth, height = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight;
  2020. coords.left = Math.max(Math.min(coords.left, .8 * this.offsetWidth), .2 * this.offsetWidth - width);
  2021. coords.top = Math.max(Math.min(coords.top, .8 * this.offsetHeight), this.offsetHeight - height);
  2022. };
  2023. $(window).bind('resize', function() {
  2024. panel.reposition();
  2025. });
  2026. panel.draggable({
  2027. handle: panel.find('h1'),
  2028. stop: function() {
  2029. panel.toFloat();
  2030. }
  2031. }).bind('mouseenter', function(e) {
  2032. panel.focus();
  2033. }).bind('mouseleave', function(e) {
  2034. panel.blur();
  2035. });
  2036. this.initToggler();
  2037. panel.find('.nette-icons').find('a').bind('click', function(e) {
  2038. if (this.rel === 'close') panel.toPeek(); else panel.toWindow();
  2039. e.preventDefault();
  2040. });
  2041. // restore saved position
  2042. if (pos = document.cookie.match(new RegExp(panel.dom().id + '=(window|(-?[0-9]+):(-?[0-9]+))'))) {
  2043. if (pos[2]) {
  2044. panel.toFloat().position({left: pos[2], top: pos[3]});
  2045. } else {
  2046. panel.toWindow();
  2047. }
  2048. } else {
  2049. panel.addClass(Panel.PEEK);
  2050. }
  2051. },
  2052. initToggler: function() { // enable .nette-toggler
  2053. var panel = this;
  2054. this.bind('click', function(e) {
  2055. var $link = $(e.target).closest('a'), link = $link.dom();
  2056. if (link && $link.hasClass('nette-toggler')) {
  2057. Panel._toggle(link);
  2058. e.preventDefault();
  2059. panel.reposition();
  2060. }
  2061. });
  2062. return this;
  2063. }
  2064. });
  2065. Nette.Debug.Bar = Nette.Class({
  2066. Extends: Nette.Q,
  2067. constructor: function() {
  2068. Nette.Q.call(this, '#nette-debug-bar');
  2069. },
  2070. init: function() {
  2071. var bar = this, pos;
  2072. bar.data().onmove = function(coords) { // forces constrained inside window
  2073. var d = document, width = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth, height = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight;
  2074. coords.left = Math.max(Math.min(coords.left, 0), this.offsetWidth - width);
  2075. coords.top = Math.max(Math.min(coords.top, 0), this.offsetHeight - height);
  2076. };
  2077. $(window).bind('resize', function() {
  2078. bar.position(bar.position());
  2079. });
  2080. bar.draggable({
  2081. draggedClass: 'nette-dragged',
  2082. stop: function() {
  2083. document.cookie = bar.dom().id + '=' + bar.position().left + ':' + bar.position().top + '; path=/';
  2084. }
  2085. });
  2086. bar.find('a').bind('click', function(e) {
  2087. if (this.rel === 'close') {
  2088. $('#nette-debug').hide();
  2089. } else if (this.rel) {
  2090. var panel = Panel.factory(this.rel);
  2091. if (e.shiftKey) {
  2092. panel.toFloat().toWindow();
  2093. } else if (panel.hasClass(Panel.FLOAT)) {
  2094. var offset = $(this).offset();
  2095. panel.offset({left: offset.left - panel.position().width + offset.width + 4, top: offset.top - panel.position().height - 4}).toPeek();
  2096. } else {
  2097. panel.toFloat().position({left: panel.position().left - Math.round(Math.random() * 100) - 20, top: panel.position().top - Math.round(Math.random() * 100) - 20}).reposition();
  2098. }
  2099. }
  2100. e.preventDefault();
  2101. }).bind('mouseenter', function(e) {
  2102. if (!this.rel || this.rel === 'close' || bar.hasClass('nette-dragged')) return;
  2103. var panel = Panel.factory(this.rel);
  2104. panel.focus();
  2105. if (panel.hasClass(Panel.PEEK)) {
  2106. var offset = $(this).offset();
  2107. panel.offset({left: offset.left - panel.position().width + offset.width + 4, top: offset.top - panel.position().height - 4});
  2108. }
  2109. }).bind('mouseleave', function(e) {
  2110. if (!this.rel || this.rel === 'close' || bar.hasClass('nette-dragged')) return;
  2111. Panel.factory(this.rel).blur();
  2112. });
  2113. // restore saved position
  2114. if (pos = document.cookie.match(new RegExp(bar.dom().id + '=(-?[0-9]+):(-?[0-9]+)'))) {
  2115. bar.position({left: pos[1], top: pos[2]}); // TODO
  2116. }
  2117. bar.find('a').each(function() {
  2118. if (!this.rel || this.rel === 'close') return;
  2119. Panel.factory(this.rel).init();
  2120. });
  2121. }
  2122. });
  2123. })();
  2124. /* ]]> */
  2125. </script>
  2126. <div id="nette-debug">
  2127. <?php foreach($panels
  2128. as$id=>$panel):?>
  2129. <div class="nette-fixed-coords">
  2130. <div class="nette-panel" id="nette-debug-panel-<?php echo$panel['id']?>">
  2131. <div id="nette-debug-<?php echo$panel['id']?>"><?php echo$panel['panel']?></div>
  2132. <div class="nette-icons">
  2133. <a href="#" title="open in window">&curren;</a>
  2134. <a href="#" rel="close" title="close window">&times;</a>
  2135. </div>
  2136. </div>
  2137. </div>
  2138. <?php endforeach?>
  2139. <div class="nette-fixed-coords">
  2140. <div id="nette-debug-bar">
  2141. <ul>
  2142. <li id="nette-debug-logo">&nbsp;<span>Nette Framework</span></li>
  2143. <?php foreach($panels
  2144. as$panel):if(!$panel['tab'])continue;?>
  2145. <li><?php if($panel['panel']):?><a href="#" rel="<?php echo$panel['id']?>"><?php echo
  2146. trim($panel['tab'])?></a><?php else:echo'<div>',trim($panel['tab']),'</div>';endif?></li>
  2147. <?php endforeach?>
  2148. <li><a href="#" rel="close" title="close debug bar">&times;</a></li>
  2149. </ul>
  2150. <div id="nette-debug-bar-bgl"></div><div id="nette-debug-bar-bgx"></div><div id="nette-debug-bar-bgr"></div>
  2151. </div>
  2152. </div>
  2153. </div>
  2154. <script>(function(){(new Nette.Debug.Bar).init();document.body.appendChild(Nette.Q.factory("#nette-debug").show().dom())})();</script>
  2155. <!-- /Nette Debug Bar -->
  2156. <?php
  2157. echo"\n\n\n\n".preg_replace_callback('#(</textarea|</pre|</script|^).*?(?=<textarea|<pre|<script|$)#si',create_function('$m','return trim(preg_replace("#[ \t\r\n]+#", " ", $m[0]));'),ob_get_clean());}}static
  2158. function
  2159. _exceptionHandler(Exception$exception){if(!headers_sent()){header('HTTP/1.1 500 Internal Server Error');}self::processException($exception,TRUE);exit;}static
  2160. function
  2161. _errorHandler($severity,$message,$file,$line,$context){if($severity===E_RECOVERABLE_ERROR||$severity===E_USER_ERROR){throw
  2162. new
  2163. FatalErrorException($message,0,$severity,$file,$line,$context);}elseif(($severity&error_reporting())!==$severity){return
  2164. NULL;}elseif(self::$strictMode){self::_exceptionHandler(new
  2165. FatalErrorException($message,0,$severity,$file,$line,$context),TRUE);}static$types=array(E_WARNING=>'Warning',E_USER_WARNING=>'Warning',E_NOTICE=>'Notice',E_USER_NOTICE=>'Notice',E_STRICT=>'Strict standards',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'Deprecated');$message='PHP '.(isset($types[$severity])?$types[$severity]:'Unknown error').": $message in $file:$line";if(self::$logFile){if(self::$uri)$message.=' @ '.self::$uri;self::log($message);if(self::$sendEmails){self::sendEmail($message);}return
  2166. NULL;}elseif(!self::$productionMode){if(self::$showBar){self::$errors[]=$message;}if(self::$firebugDetected&&!headers_sent()){self::fireLog(strip_tags($message),self::ERROR);}return
  2167. self::$consoleMode||(!self::$showBar&&!self::$ajaxDetected)?FALSE:NULL;}return
  2168. FALSE;}static
  2169. function
  2170. processException(Exception$exception,$outputAllowed=FALSE){if(!self::$enabled){return;}elseif(self::$logFile){try{$hash=md5($exception.(method_exists($exception,'getPrevious')?$exception->getPrevious():(isset($exception->previous)?$exception->previous:'')));self::log("PHP Fatal error: Uncaught ".str_replace("Stack trace:\n".$exception->getTraceAsString(),'',$exception));foreach(new
  2171. DirectoryIterator(dirname(self::$logFile))as$entry){if(strpos($entry,$hash)){$skip=TRUE;break;}}$file=dirname(self::$logFile)."/exception ".@date('Y-m-d H-i-s')." $hash.html";if(empty($skip)&&self::$logHandle=@fopen($file,'w')){ob_start();ob_start(array(__CLASS__,'_writeFile'),1);self::_paintBlueScreen($exception);ob_end_flush();ob_end_clean();fclose(self::$logHandle);}if(self::$sendEmails){self::sendEmail((string)$exception);}}catch(Exception$e){if(!headers_sent()){header('HTTP/1.1 500 Internal Server Error');}echo'Debug fatal error: ',get_class($e),': ',($e->getCode()?'#'.$e->getCode().' ':'').$e->getMessage(),"\n";exit;}}elseif(self::$productionMode){}elseif(self::$consoleMode){if($outputAllowed){echo"$exception\n";}}elseif(self::$firebugDetected&&self::$ajaxDetected&&!headers_sent()){self::fireLog($exception,self::EXCEPTION);}elseif($outputAllowed){if(!headers_sent()){@ob_end_clean();while(ob_get_level()&&@ob_end_clean());if(in_array('Content-Encoding: gzip',headers_list()))header('Content-Encoding: identity',TRUE);}self::_paintBlueScreen($exception);}elseif(self::$firebugDetected&&!headers_sent()){self::fireLog($exception,self::EXCEPTION);}foreach(self::$onFatalError
  2172. as$handler){call_user_func($handler,$exception);}}static
  2173. function
  2174. toStringException(Exception$exception){if(self::$enabled){self::_exceptionHandler($exception);}else{trigger_error($exception->getMessage(),E_USER_ERROR);}}static
  2175. function
  2176. _paintBlueScreen(Exception$exception){$internals=array();foreach(array('Object','ObjectMixin')as$class){if(class_exists($class,FALSE)){$rc=new
  2177. ReflectionClass($class);$internals[$rc->getFileName()]=TRUE;}}if(class_exists('Environment',FALSE)){$application=Environment::getServiceLocator()->hasService('Nette\\Application\\Application',TRUE)?Environment::getServiceLocator()->getService('Nette\\Application\\Application'):NULL;}if(!function_exists('_netteDebugPrintCode')){function
  2178. _netteDebugPrintCode($file,$line,$count=15){if(function_exists('ini_set')){ini_set('highlight.comment','#999; font-style: italic');ini_set('highlight.default','#000');ini_set('highlight.html','#06b');ini_set('highlight.keyword','#d24; font-weight: bold');ini_set('highlight.string','#080');}$start=max(1,$line-floor($count/2));$source=@file_get_contents($file);if(!$source)return;$source=explode("\n",highlight_string($source,TRUE));$spans=1;echo$source[0];$source=explode('<br />',$source[1]);array_unshift($source,NULL);$i=$start;while(--$i>=1){if(preg_match('#.*(</?span[^>]*>)#',$source[$i],$m)){if($m[1]!=='</span>'){$spans++;echo$m[1];}break;}}$source=array_slice($source,$start,$count,TRUE);end($source);$numWidth=strlen((string)key($source));foreach($source
  2179. as$n=>$s){$spans+=substr_count($s,'<span')-substr_count($s,'</span');$s=str_replace(array("\r","\n"),array('',''),$s);if($n===$line){printf("<span class='highlight'>Line %{$numWidth}s: %s\n</span>%s",$n,strip_tags($s),preg_replace('#[^>]*(<[^>]+>)[^<]*#','$1',$s));}else{printf("<span class='line'>Line %{$numWidth}s:</span> %s\n",$n,$s);}}echo
  2180. str_repeat('</span>',$spans),'</code>';}function
  2181. _netteDump($dump){return'<pre class="nette-dump">'.preg_replace_callback('#(^|\s+)?(.*)\((\d+)\) <code>#','_netteDumpCb',$dump).'</pre>';}function
  2182. _netteDumpCb($m){return"$m[1]<a href='#' onclick='return !netteToggle(this)'>$m[2]($m[3]) ".(trim($m[1])||$m[3]<7?'<abbr>&#x25bc;</abbr> </a><code>':'<abbr>&#x25ba;</abbr> </a><code class="collapsed">');}function
  2183. _netteOpenPanel($name,$collapsed){static$id;$id++;?>
  2184. <div class="panel">
  2185. <h2><a href="#" onclick="return !netteToggle(this, 'pnl<?php echo$id?>')"><?php echo
  2186. htmlSpecialChars($name)?> <abbr><?php echo$collapsed?'&#x25ba;':'&#x25bc;'?></abbr></a></h2>
  2187. <div id="pnl<?php echo$id?>" class="<?php echo$collapsed?'collapsed ':''?>inner">
  2188. <?php
  2189. }function
  2190. _netteClosePanel(){?>
  2191. </div>
  2192. </div>
  2193. <?php
  2194. }}static$errorTypes=array(E_ERROR=>'Fatal Error',E_USER_ERROR=>'User Error',E_RECOVERABLE_ERROR=>'Recoverable Error',E_CORE_ERROR=>'Core Error',E_COMPILE_ERROR=>'Compile Error',E_PARSE=>'Parse Error',E_WARNING=>'Warning',E_CORE_WARNING=>'Core Warning',E_COMPILE_WARNING=>'Compile Warning',E_USER_WARNING=>'User Warning',E_NOTICE=>'Notice',E_USER_NOTICE=>'User Notice',E_STRICT=>'Strict',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'User Deprecated');$title=($exception
  2195. instanceof
  2196. FatalErrorException&&isset($errorTypes[$exception->getSeverity()]))?$errorTypes[$exception->getSeverity()]:get_class($exception);$rn=0;if(headers_sent()){echo'</pre></xmp></table>';}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2197. <html lang="en">
  2198. <head>
  2199. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  2200. <meta name="robots" content="noindex,noarchive">
  2201. <meta name="generator" content="Nette Framework">
  2202. <title><?php echo
  2203. htmlspecialchars($title)?></title><!-- <?php echo$exception->getMessage(),($exception->getCode()?' #'.$exception->getCode():'')?> -->
  2204. <style type="text/css">body{margin:0 0 2em;padding:0}#netteBluescreen{font:9pt/1.5 Verdana,sans-serif;background:white;color:#333;position:absolute;left:0;top:0;width:100%;z-index:23178;text-align:left}#netteBluescreen *{color:inherit;background:inherit;text-align:inherit}#netteBluescreenIcon{position:absolute;right:.5em;top:.5em;z-index:23179;text-decoration:none;background:red;padding:3px}#netteBluescreenIcon abbr{color:black!important}#netteBluescreen h1{font:18pt/1.5 Verdana,sans-serif!important;margin:.6em 0}#netteBluescreen h2{font:14pt/1.5 sans-serif!important;color:#888;margin:.6em 0}#netteBluescreen a{text-decoration:none;color:#4197E3}#netteBluescreen a abbr{font-family:sans-serif;color:#999}#netteBluescreen h3{font:bold 10pt/1.5 Verdana,sans-serif!important;margin:1em 0;padding:0}#netteBluescreen p{margin:.8em 0}#netteBluescreen pre,#netteBluescreen code,#netteBluescreen table{font:9pt/1.5 Consolas,monospace!important}#netteBluescreen pre,#netteBluescreen table{background:#fffbcc;padding:.4em .7em;border:1px dotted silver}#netteBluescreen table pre{padding:0;margin:0;border:none}#netteBluescreen pre.nette-dump span{color:#c16549}#netteBluescreen pre.nette-dump a{color:#333}#netteBluescreen div.panel{border-bottom:1px solid #eee;padding:1px 2em}#netteBluescreen div.inner{padding:.1em 1em 1em;background:#f5f5f5}#netteBluescreen table{border-collapse:collapse;width:100%}#netteBluescreen td,#netteBluescreen th{vertical-align:top;text-align:left;padding:2px 3px;border:1px solid #eeb}#netteBluescreen th{width:10%;font-weight:bold}#netteBluescreen .odd,#netteBluescreen .odd pre{background-color:#faf5c3}#netteBluescreen ul{font:7pt/1.5 Verdana,sans-serif!important;padding:1em 2em 50px}#netteBluescreen .highlight,#netteBluescreenError{background:red;color:white;font-weight:bold;font-style:normal;display:block}#netteBluescreen .line{color:#9e9e7e;font-weight:normal;font-style:normal}</style>
  2205. <script type="text/javascript">/*<![CDATA[*/document.write("<style> .collapsed { display: none; } </style>");function netteToggle(a,b){var c=a.getElementsByTagName("abbr")[0];for(a=b?document.getElementById(b):a.nextSibling;a.nodeType!==1;)a=a.nextSibling;b=a.currentStyle?a.currentStyle.display=="none":getComputedStyle(a,null).display=="none";try{c.innerHTML=String.fromCharCode(b?9660:9658)}catch(d){}a.style.display=b?a.tagName.toLowerCase()==="code"?"inline":"block":"none";return true};/*]]>*/</script>
  2206. </head>
  2207. <body>
  2208. <div id="netteBluescreen">
  2209. <a id="netteBluescreenIcon" href="#" onclick="return !netteToggle(this)"><abbr>&#x25bc;</abbr></a
  2210. ><div>
  2211. <div id="netteBluescreenError" class="panel">
  2212. <h1><?php echo
  2213. htmlspecialchars($title),($exception->getCode()?' #'.$exception->getCode():'')?></h1>
  2214. <p><?php echo
  2215. htmlspecialchars($exception->getMessage())?></p>
  2216. </div>
  2217. <?php $ex=$exception;$level=0;?>
  2218. <?php do{?>
  2219. <?php if($level++):?>
  2220. <?php _netteOpenPanel('Caused by',$level>2)?>
  2221. <div class="panel">
  2222. <h1><?php echo
  2223. htmlspecialchars(get_class($ex)),($ex->getCode()?' #'.$ex->getCode():'')?></h1>
  2224. <p><?php echo
  2225. htmlspecialchars($ex->getMessage())?></p>
  2226. </div>
  2227. <?php endif?>
  2228. <?php $collapsed=isset($internals[$ex->getFile()]);?>
  2229. <?php if(is_file($ex->getFile())):?>
  2230. <?php _netteOpenPanel('Source file',$collapsed)?>
  2231. <p><strong>File:</strong> <?php echo
  2232. htmlspecialchars($ex->getFile())?> &nbsp; <strong>Line:</strong> <?php echo$ex->getLine()?></p>
  2233. <pre><?php _netteDebugPrintCode($ex->getFile(),$ex->getLine())?></pre>
  2234. <?php _netteClosePanel()?>
  2235. <?php endif?>
  2236. <?php _netteOpenPanel('Call stack',FALSE)?>
  2237. <ol>
  2238. <?php foreach($ex->getTrace()as$key=>$row):?>
  2239. <li><p>
  2240. <?php if(isset($row['file'])):?>
  2241. <span title="<?php echo
  2242. htmlSpecialChars($row['file'])?>"><?php echo
  2243. htmlSpecialChars(basename(dirname($row['file']))),'/<b>',htmlSpecialChars(basename($row['file'])),'</b></span> (',$row['line'],')'?>
  2244. <?php else:?>
  2245. &lt;PHP inner-code&gt;
  2246. <?php endif?>
  2247. <?php if(isset($row['file'])&&is_file($row['file'])):?><a href="#" onclick="return !netteToggle(this, 'src<?php echo"$level-$key"?>')">source <abbr>&#x25ba;</abbr></a>&nbsp; <?php endif?>
  2248. <?php if(isset($row['class']))echo$row['class'].$row['type']?>
  2249. <?php echo$row['function']?>
  2250. (<?php if(!empty($row['args'])):?><a href="#" onclick="return !netteToggle(this, 'args<?php echo"$level-$key"?>')">arguments <abbr>&#x25ba;</abbr></a><?php endif?>)
  2251. </p>
  2252. <?php if(!empty($row['args'])):?>
  2253. <div class="collapsed" id="args<?php echo"$level-$key"?>">
  2254. <table>
  2255. <?php
  2256. try{$r=isset($row['class'])?new
  2257. ReflectionMethod($row['class'],$row['function']):new
  2258. ReflectionFunction($row['function']);$params=$r->getParameters();}catch(Exception$e){$params=array();}foreach($row['args']as$k=>$v){echo'<tr><th>',(isset($params[$k])?'$'.$params[$k]->name:"#$k"),'</th><td>';echo
  2259. _netteDump(self::_dump($v,0));echo"</td></tr>\n";}?>
  2260. </table>
  2261. </div>
  2262. <?php endif?>
  2263. <?php if(isset($row['file'])&&is_file($row['file'])):?>
  2264. <pre <?php if(!$collapsed||isset($internals[$row['file']]))echo'class="collapsed"';else$collapsed=FALSE?> id="src<?php echo"$level-$key"?>"><?php _netteDebugPrintCode($row['file'],$row['line'])?></pre>
  2265. <?php endif?>
  2266. </li>
  2267. <?php endforeach?>
  2268. <?php if(!isset($row)):?>
  2269. <li><i>empty</i></li>
  2270. <?php endif?>
  2271. </ol>
  2272. <?php _netteClosePanel()?>
  2273. <?php if($ex
  2274. instanceof
  2275. IDebugPanel&&($tab=$ex->getTab())&&($panel=$ex->getPanel())):?>
  2276. <?php _netteOpenPanel($tab,FALSE)?>
  2277. <?php echo$panel?>
  2278. <?php _netteClosePanel()?>
  2279. <?php endif?>
  2280. <?php if(isset($ex->context)&&is_array($ex->context)):?>
  2281. <?php _netteOpenPanel('Variables',TRUE)?>
  2282. <table>
  2283. <?php
  2284. foreach($ex->context
  2285. as$k=>$v){echo'<tr><th>$',htmlspecialchars($k),'</th><td>',_netteDump(self::_dump($v,0)),"</td></tr>\n";}?>
  2286. </table>
  2287. <?php _netteClosePanel()?>
  2288. <?php endif?>
  2289. <?php }while((method_exists($ex,'getPrevious')&&$ex=$ex->getPrevious())||(isset($ex->previous)&&$ex=$ex->previous));?>
  2290. <?php while(--$level)_netteClosePanel()?>
  2291. <?php if(!empty($application)):?>
  2292. <?php _netteOpenPanel('Nette Application',TRUE)?>
  2293. <h3>Requests</h3>
  2294. <?php $tmp=$application->getRequests();echo
  2295. _netteDump(self::_dump($tmp,0))?>
  2296. <h3>Presenter</h3>
  2297. <?php $tmp=$application->getPresenter();echo
  2298. _netteDump(self::_dump($tmp,0))?>
  2299. <?php _netteClosePanel()?>
  2300. <?php endif?>
  2301. <?php _netteOpenPanel('Environment',TRUE)?>
  2302. <?php
  2303. $list=get_defined_constants(TRUE);if(!empty($list['user'])):?>
  2304. <h3><a href="#" onclick="return !netteToggle(this, 'pnl-env-const')">Constants <abbr>&#x25bc;</abbr></a></h3>
  2305. <table id="pnl-env-const">
  2306. <?php
  2307. foreach($list['user']as$k=>$v){echo'<tr'.($rn++%2?' class="odd"':'').'><th>',htmlspecialchars($k),'</th>';echo'<td>',_netteDump(self::_dump($v,0)),"</td></tr>\n";}?>
  2308. </table>
  2309. <?php endif?>
  2310. <h3><a href="#" onclick="return !netteToggle(this, 'pnl-env-files')">Included files <abbr>&#x25ba;</abbr></a>(<?php echo
  2311. count(get_included_files())?>)</h3>
  2312. <table id="pnl-env-files" class="collapsed">
  2313. <?php
  2314. foreach(get_included_files()as$v){echo'<tr'.($rn++%2?' class="odd"':'').'><td>',htmlspecialchars($v),"</td></tr>\n";}?>
  2315. </table>
  2316. <h3>$_SERVER</h3>
  2317. <?php if(empty($_SERVER)):?>
  2318. <p><i>empty</i></p>
  2319. <?php else:?>
  2320. <table>
  2321. <?php
  2322. foreach($_SERVER
  2323. as$k=>$v)echo'<tr'.($rn++%2?' class="odd"':'').'><th>',htmlspecialchars($k),'</th><td>',_netteDump(self::_dump($v,0)),"</td></tr>\n";?>
  2324. </table>
  2325. <?php endif?>
  2326. <?php _netteClosePanel()?>
  2327. <?php _netteOpenPanel('HTTP request',TRUE)?>
  2328. <?php if(function_exists('apache_request_headers')):?>
  2329. <h3>Headers</h3>
  2330. <table>
  2331. <?php
  2332. foreach(apache_request_headers()as$k=>$v)echo'<tr'.($rn++%2?' class="odd"':'').'><th>',htmlspecialchars($k),'</th><td>',htmlspecialchars($v),"</td></tr>\n";?>
  2333. </table>
  2334. <?php endif?>
  2335. <?php foreach(array('_GET','_POST','_COOKIE')as$name):?>
  2336. <h3>$<?php echo$name?></h3>
  2337. <?php if(empty($GLOBALS[$name])):?>
  2338. <p><i>empty</i></p>
  2339. <?php else:?>
  2340. <table>
  2341. <?php
  2342. foreach($GLOBALS[$name]as$k=>$v)echo'<tr'.($rn++%2?' class="odd"':'').'><th>',htmlspecialchars($k),'</th><td>',_netteDump(self::_dump($v,0)),"</td></tr>\n";?>
  2343. </table>
  2344. <?php endif?>
  2345. <?php endforeach?>
  2346. <?php _netteClosePanel()?>
  2347. <?php _netteOpenPanel('HTTP response',TRUE)?>
  2348. <h3>Headers</h3>
  2349. <?php if(headers_list()):?>
  2350. <pre><?php
  2351. foreach(headers_list()as$s)echo
  2352. htmlspecialchars($s),'<br>';?></pre>
  2353. <?php else:?>
  2354. <p><i>no headers</i></p>
  2355. <?php endif?>
  2356. <?php _netteClosePanel()?>
  2357. <ul>
  2358. <li>Report generated at <?php echo@date('Y/m/d H:i:s',self::$time)?></li>
  2359. <?php if(self::$uri):?>
  2360. <li><a href="<?php echo
  2361. htmlSpecialChars(self::$uri)?>"><?php echo
  2362. htmlSpecialChars(self::$uri)?></a></li>
  2363. <?php endif?>
  2364. <li>PHP <?php echo
  2365. htmlSpecialChars(PHP_VERSION)?></li>
  2366. <?php if(isset($_SERVER['SERVER_SOFTWARE'])):?><li><?php echo
  2367. htmlSpecialChars($_SERVER['SERVER_SOFTWARE'])?></li><?php endif?>
  2368. <?php if(class_exists('Framework')):?><li><?php echo
  2369. htmlSpecialChars('Nette Framework '.Framework::VERSION)?> <i>(revision <?php echo
  2370. htmlSpecialChars(Framework::REVISION)?>)</i></li><?php endif?>
  2371. </ul>
  2372. </div>
  2373. </div>
  2374. <script type="text/javascript">document.body.appendChild(document.getElementById("netteBluescreen"));</script>
  2375. </body>
  2376. </html><?php }static
  2377. function
  2378. _writeFile($buffer){fwrite(self::$logHandle,$buffer);}private
  2379. static
  2380. function
  2381. sendEmail($message){$monitorFile=self::$logFile.'.monitor';if(@filemtime($monitorFile)+self::$emailSnooze<time()&&@file_put_contents($monitorFile,'sent')){call_user_func(self::$mailer,$message);}}private
  2382. static
  2383. function
  2384. defaultMailer($message){$host=isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'');$headers=str_replace(array('%host%','%date%','%message%'),array($host,@date('Y-m-d H:i:s',self::$time),$message),self::$emailHeaders);$subject=$headers['Subject'];$to=$headers['To'];$body=str_replace("\r\n",PHP_EOL,$headers['Body']);unset($headers['Subject'],$headers['To'],$headers['Body']);$header='';foreach($headers
  2385. as$key=>$value){$header.="$key: $value".PHP_EOL;}mail($to,$subject,$body,$header);}static
  2386. function
  2387. addPanel(IDebugPanel$panel){self::$panels[]=$panel;}static
  2388. function
  2389. renderTab($id){switch($id){case'time':?>
  2390. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJ6SURBVDjLjZO7T1NhGMY7Mji6uJgYt8bElTjof6CDg4sMSqIxJsRGB5F4TwQSIg1QKC0KWmkZEEsKtEcSxF5ohV5pKSicXqX3aqGn957z+PUEGopiGJ583/A+v3znvPkJAAjWR0VNJG0kGhKahCFhXcN3YBFfx8Kry6ym4xIzce88/fbWGY2k5WRb77UTTbWuYA9gDGg7EVmSIOF4g5T7HZKuMcSW5djWDyL0uRf0dCc8inYYxTcw9fAiCMBYB3gVj1z7gLhNTjKCqHkYP79KENC9Bq3uxrrqORzy+9D3tPAAccspVx1gWg0KbaZFbGllWFM+xrKkFQudV0CeDfJsjN4+C2nracjunoPq5VXIBrowMK4V1gG1LGyWdbZwCalsBYUyh2KFQzpXxVqkAGswD3+qBDpZwow9iYE5v26/VwfUQnnznyhvjguQYabIIpKpYD1ahI8UTT92MUSFuP5Z/9TBTgOgFrVjp3nakaG/0VmEfpX58pwzjUEquNk362s+PP8XYD/KpYTBHmRg9Wch0QX1R80dCZhYipudYQY2Auib8RmODVCa4hfUK4ngaiiLNFNFdKeCWWscXZMbWy9Unv9/gsIQU09a4pwvUeA3Uapy2C2wCKXL0DqTePLexbWPOv79E8f0UWrencZ2poxciUWZlKssB4bcHeE83NsFuMgpo2iIpMuNa1TNu4XjhggWvb+R2K3wZdLlAZl8Fd9jRb5sD+Xx0RJBx5gdom6VsMEFDyWF0WyCeSOFcDKPnRxZYTQL5Rc/nn1w4oFsBaIhC3r6FRh5erPRhYMyHdeFw4C6zkRhmijM7CnMu0AUZonCDCnRJBqSus5/ABD6Ba5CkQS8AAAAAElFTkSuQmCC"
  2391. ><?php echo
  2392. number_format((microtime(TRUE)-self::$time)*1000,1,'.',' ')?>ms
  2393. <?php
  2394. return;case'memory':?>
  2395. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGvSURBVDjLpZO7alZREEbXiSdqJJDKYJNCkPBXYq12prHwBezSCpaidnY+graCYO0DpLRTQcR3EFLl8p+9525xgkRIJJApB2bN+gZmqCouU+NZzVef9isyUYeIRD0RTz482xouBBBNHi5u4JlkgUfx+evhxQ2aJRrJ/oFjUWysXeG45cUBy+aoJ90Sj0LGFY6anw2o1y/mK2ZS5pQ50+2XiBbdCvPk+mpw2OM/Bo92IJMhgiGCox+JeNEksIC11eLwvAhlzuAO37+BG9y9x3FTuiWTzhH61QFvdg5AdAZIB3Mw50AKsaRJYlGsX0tymTzf2y1TR9WwbogYY3ZhxR26gBmocrxMuhZNE435FtmSx1tP8QgiHEvj45d3jNlONouAKrjjzWaDv4CkmmNu/Pz9CzVh++Yd2rIz5tTnwdZmAzNymXT9F5AtMFeaTogJYkJfdsaaGpyO4E62pJ0yUCtKQFxo0hAT1JU2CWNOJ5vvP4AIcKeao17c2ljFE8SKEkVdWWxu42GYK9KE4c3O20pzSpyyoCx4v/6ECkCTCqccKorNxR5uSXgQnmQkw2Xf+Q+0iqQ9Ap64TwAAAABJRU5ErkJggg=="
  2396. ><?php echo
  2397. number_format(memory_get_peak_usage()/1000,1,'.',' ')?> kB
  2398. <?php
  2399. return;case'dumps':if(!Debug::$dumps)return;?>
  2400. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAIASURBVDjLpVPPaxNREJ6Vt01caH4oWk1T0ZKlGIo9RG+BUsEK4kEP/Q8qPXnpqRdPBf8A8Wahhx7FQ0GF9FJ6UksqwfTSBDGyB5HkkphC9tfb7jfbtyQQTx142byZ75v5ZnZWC4KALmICPy+2DkvKIX2f/POz83LxCL7nrz+WPNcll49DrhM9v7xdO9JW330DuXrrqkFSgig5iR2Cfv3t3gNxOnv5BwU+eZ5HuON5/PMPJZKJ+yKQfpW0S7TxdC6WJaWkyvff1LDaFRAeLZj05MHsiPTS6hua0PUqtwC5sHq9zv9RYWl+nu5cETcnJ1M0M5WlWq3GsX6/T+VymRzHDluZiGYAAsw0TQahV8uyyGq1qFgskm0bHIO/1+sx1rFtchJhArwEyIQ1Gg2WD2A6nWawHQJVDIWgIJfLhQowTIeE9D0mKAU8qPC0220afsWFQoH93W6X7yCDJ+DEBeBmsxnPIJVKxWQVUwry+XyUwBlKMKwA8jqdDhOVCqVAzQDVvXAXhOdGBFgymYwrGoZBmUyGjxCCdF0fSahaFdgoTHRxfTveMCXvWfkuE3Y+f40qhgT/nMitupzApdvT18bu+YeDQwY9Xl4aG9/d/URiMBhQq/dvZMeVghtT17lSZW9/rAKsvPa/r9Fc2dw+Pe0/xI6kM9mT5vtXy+Nw2kU/5zOGRpvuMIu0YAAAAABJRU5ErkJggg==">variables
  2401. <?php
  2402. return;case'errors':if(!Debug::$errors)return;?>
  2403. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAIsSURBVDjLpVNLSJQBEP7+h6uu62vLVAJDW1KQTMrINQ1vPQzq1GOpa9EppGOHLh0kCEKL7JBEhVCHihAsESyJiE4FWShGRmauu7KYiv6Pma+DGoFrBQ7MzGFmPr5vmDFIYj1mr1WYfrHPovA9VVOqbC7e/1rS9ZlrAVDYHig5WB0oPtBI0TNrUiC5yhP9jeF4X8NPcWfopoY48XT39PjjXeF0vWkZqOjd7LJYrmGasHPCCJbHwhS9/F8M4s8baid764Xi0Ilfp5voorpJfn2wwx/r3l77TwZUvR+qajXVn8PnvocYfXYH6k2ioOaCpaIdf11ivDcayyiMVudsOYqFb60gARJYHG9DbqQFmSVNjaO3K2NpAeK90ZCqtgcrjkP9aUCXp0moetDFEeRXnYCKXhm+uTW0CkBFu4JlxzZkFlbASz4CQGQVBFeEwZm8geyiMuRVntzsL3oXV+YMkvjRsydC1U+lhwZsWXgHb+oWVAEzIwvzyVlk5igsi7DymmHlHsFQR50rjl+981Jy1Fw6Gu0ObTtnU+cgs28AKgDiy+Awpj5OACBAhZ/qh2HOo6i+NeA73jUAML4/qWux8mt6NjW1w599CS9xb0mSEqQBEDAtwqALUmBaG5FV3oYPnTHMjAwetlWksyByaukxQg2wQ9FlccaK/OXA3/uAEUDp3rNIDQ1ctSk6kHh1/jRFoaL4M4snEMeD73gQx4M4PsT1IZ5AfYH68tZY7zv/ApRMY9mnuVMvAAAAAElFTkSuQmCC"
  2404. ><span class="nette-warning"><?php echo
  2405. count(self::$errors)?> errors</span>
  2406. <?php }}static
  2407. function
  2408. renderPanel($id){switch($id){case'dumps':if(!function_exists('_netteDumpCb2')){function
  2409. _netteDumpCb2($m){return"$m[1]<a href='#' class='nette-toggler'>$m[2]($m[3]) ".($m[3]<7?'<abbr>&#x25bc;</abbr> </a><code>':'<abbr>&#x25ba;</abbr> </a><code class="nette-hidden">');}}?>
  2410. <style>#nette-debug-dumps h2{font:11pt/1.5 sans-serif;margin:0;padding:2px 8px;background:#3484d2;color:white}#nette-debug-dumps table{width:100%}#nette-debug #nette-debug-dumps a{color:#333;background:transparent}#nette-debug-dumps a abbr{font-family:sans-serif;color:#999}#nette-debug-dumps pre.nette-dump span{color:#c16549}</style>
  2411. <h1>Dumped variables</h1>
  2412. <div class="nette-inner">
  2413. <?php foreach(self::$dumps
  2414. as$item):?>
  2415. <?php if($item['title']):?>
  2416. <h2><?php echo
  2417. htmlspecialchars($item['title'])?></h2>
  2418. <?php endif?>
  2419. <table>
  2420. <?php $i=0?>
  2421. <?php foreach($item['dump']as$key=>$dump):?>
  2422. <tr class="<?php echo$i++%
  2423. 2?'nette-alt':''?>">
  2424. <th><?php echo
  2425. htmlspecialchars($key)?></th>
  2426. <td><?php echo
  2427. preg_replace_callback('#(<pre class="nette-dump">|\s+)?(.*)\((\d+)\) <code>#','_netteDumpCb2',$dump)?></td>
  2428. </tr>
  2429. <?php endforeach?>
  2430. </table>
  2431. <?php endforeach?>
  2432. </div>
  2433. <?php
  2434. return;case'errors':?>
  2435. <h1>Errors</h1>
  2436. <?php $relative=isset($_SERVER['SCRIPT_FILENAME'])?strtr(dirname(dirname($_SERVER['SCRIPT_FILENAME'])),'/',DIRECTORY_SEPARATOR):NULL?>
  2437. <div class="nette-inner">
  2438. <table>
  2439. <?php foreach(self::$errors
  2440. as$i=>$item):?>
  2441. <tr class="<?php echo$i++%
  2442. 2?'nette-alt':''?>">
  2443. <td><pre><?php echo$relative?str_replace($relative,"...",$item):$item?></pre></td>
  2444. </tr>
  2445. <?php endforeach?>
  2446. </table>
  2447. </div><?php }}static
  2448. function
  2449. addColophon(){}static
  2450. function
  2451. consoleDump(){}static
  2452. function
  2453. fireLog($message,$priority=self::LOG,$label=NULL){if($message
  2454. instanceof
  2455. Exception){if($priority!==self::EXCEPTION&&$priority!==self::TRACE){$priority=self::TRACE;}$message=array('Class'=>get_class($message),'Message'=>$message->getMessage(),'File'=>$message->getFile(),'Line'=>$message->getLine(),'Trace'=>$message->getTrace(),'Type'=>'','Function'=>'');foreach($message['Trace']as&$row){if(empty($row['file']))$row['file']='?';if(empty($row['line']))$row['line']='?';}}elseif($priority===self::GROUP_START){$label=$message;$message=NULL;}return
  2456. self::fireSend('FirebugConsole/0.1',self::replaceObjects(array(array('Type'=>$priority,'Label'=>$label),$message)));}private
  2457. static
  2458. function
  2459. fireSend($struct,$payload){if(self::$productionMode)return
  2460. NULL;if(headers_sent())return
  2461. FALSE;header('X-Wf-Protocol-nette: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');header('X-Wf-nette-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');static$structures;$index=isset($structures[$struct])?$structures[$struct]:($structures[$struct]=count($structures)+1);header("X-Wf-nette-Structure-$index: http://meta.firephp.org/Wildfire/Structure/FirePHP/$struct");$payload=json_encode($payload);static$counter;foreach(str_split($payload,4990)as$s){$num=++$counter;header("X-Wf-nette-$index-1-n$num: |$s|\\");}header("X-Wf-nette-$index-1-n$num: |$s|");return
  2462. TRUE;}static
  2463. private
  2464. function
  2465. replaceObjects($val){if(is_object($val)){return'object '.get_class($val).'';}elseif(is_string($val)){return@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$val));}elseif(is_array($val)){foreach($val
  2466. as$k=>$v){unset($val[$k]);$k=@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$k));$val[$k]=self::replaceObjects($v);}}return$val;}}Debug::_init();class
  2467. Configurator
  2468. extends
  2469. Object{public$defaultConfigFile='%appDir%/config.ini';public$defaultServices=array('Nette\\Application\\Application'=>'Application','Nette\\Web\\HttpContext'=>'HttpContext','Nette\\Web\\IHttpRequest'=>'HttpRequest','Nette\\Web\\IHttpResponse'=>'HttpResponse','Nette\\Web\\IUser'=>'User','Nette\\Caching\\ICacheStorage'=>array(__CLASS__,'createCacheStorage'),'Nette\\Web\\Session'=>'Session','Nette\\Loaders\\RobotLoader'=>array(__CLASS__,'createRobotLoader'));function
  2470. detect($name){switch($name){case'environment':if($this->detect('console')){return
  2471. Environment::CONSOLE;}else{return
  2472. Environment::getMode('production')?Environment::PRODUCTION:Environment::DEVELOPMENT;}case'production':if(PHP_SAPI==='cli'){return
  2473. FALSE;}elseif(isset($_SERVER['SERVER_ADDR'])||isset($_SERVER['LOCAL_ADDR'])){$addr=isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:$_SERVER['LOCAL_ADDR'];$oct=explode('.',$addr);return$addr!=='::1'&&(count($oct)!==4||($oct[0]!=='10'&&$oct[0]!=='127'&&($oct[0]!=='172'||$oct[1]<16||$oct[1]>31)&&($oct[0]!=='169'||$oct[1]!=='254')&&($oct[0]!=='192'||$oct[1]!=='168')));}else{return
  2474. TRUE;}case'console':return
  2475. PHP_SAPI==='cli';default:return
  2476. NULL;}}function
  2477. loadConfig($file){$name=Environment::getName();if($file
  2478. instanceof
  2479. Config){$config=$file;$file=NULL;}else{if($file===NULL){$file=$this->defaultConfigFile;}$file=Environment::expand($file);$config=Config::fromFile($file,$name);}if($config->variable
  2480. instanceof
  2481. Config){foreach($config->variable
  2482. as$key=>$value){Environment::setVariable($key,$value);}}$iterator=new
  2483. RecursiveIteratorIterator($config);foreach($iterator
  2484. as$key=>$value){$tmp=$iterator->getDepth()?$iterator->getSubIterator($iterator->getDepth()-1)->current():$config;$tmp[$key]=Environment::expand($value);}$runServices=array();$locator=Environment::getServiceLocator();if($config->service
  2485. instanceof
  2486. Config){foreach($config->service
  2487. as$key=>$value){$key=strtr($key,'-','\\');if(is_string($value)){$locator->removeService($key);$locator->addService($key,$value);}else{if($value->factory){$locator->removeService($key);$locator->addService($key,$value->factory,isset($value->singleton)?$value->singleton:TRUE,(array)$value->option);}if($value->run){$runServices[]=$key;}}}}if(!$config->php){$config->php=$config->set;unset($config->set);}if($config->php
  2488. instanceof
  2489. Config){if(PATH_SEPARATOR!==';'&&isset($config->php->include_path)){$config->php->include_path=str_replace(';',PATH_SEPARATOR,$config->php->include_path);}foreach(clone$config->php
  2490. as$key=>$value){if($value
  2491. instanceof
  2492. Config){unset($config->php->$key);foreach($value
  2493. as$k=>$v){$config->php->{"$key.$k"}=$v;}}}foreach($config->php
  2494. as$key=>$value){$key=strtr($key,'-','.');if(!is_scalar($value)){throw
  2495. new
  2496. InvalidStateException("Configuration value for directive '$key' is not scalar.");}if($key==='date.timezone'){date_default_timezone_set($value);}if(function_exists('ini_set')){ini_set($key,$value);}else{switch($key){case'include_path':set_include_path($value);break;case'iconv.internal_encoding':iconv_set_encoding('internal_encoding',$value);break;case'mbstring.internal_encoding':mb_internal_encoding($value);break;case'date.timezone':date_default_timezone_set($value);break;case'error_reporting':error_reporting($value);break;case'ignore_user_abort':ignore_user_abort($value);break;case'max_execution_time':set_time_limit($value);break;default:if(ini_get($key)!=$value){throw
  2497. new
  2498. NotSupportedException('Required function ini_set() is disabled.');}}}}}if($config->const
  2499. instanceof
  2500. Config){foreach($config->const
  2501. as$key=>$value){define($key,$value);}}if(isset($config->mode)){foreach($config->mode
  2502. as$mode=>$state){Environment::setMode($mode,$state);}}foreach($runServices
  2503. as$name){$locator->getService($name);}return$config;}function
  2504. createServiceLocator(){$locator=new
  2505. ServiceLocator;foreach($this->defaultServices
  2506. as$name=>$service){$locator->addService($name,$service);}return$locator;}static
  2507. function
  2508. createCacheStorage(){return
  2509. new
  2510. FileStorage(Environment::getVariable('tempDir'));}static
  2511. function
  2512. createRobotLoader($options){$loader=new
  2513. RobotLoader;$loader->autoRebuild=!Environment::isProduction();$dirs=isset($options['directory'])?$options['directory']:array(Environment::getVariable('appDir'),Environment::getVariable('libsDir'));$loader->addDirectory($dirs);$loader->register();return$loader;}}final
  2514. class
  2515. Environment{const
  2516. DEVELOPMENT='development';const
  2517. PRODUCTION='production';const
  2518. CONSOLE='console';const
  2519. LAB='lab';const
  2520. DEBUG='debug';const
  2521. PERFORMANCE='performance';private
  2522. static$configurator;private
  2523. static$modes=array();private
  2524. static$config;private
  2525. static$serviceLocator;private
  2526. static$vars=array('encoding'=>array('UTF-8',FALSE),'lang'=>array('en',FALSE),'cacheBase'=>array('%tempDir%',TRUE),'tempDir'=>array('%appDir%/temp',TRUE),'logDir'=>array('%appDir%/log',TRUE));private
  2527. static$aliases=array('getHttpContext'=>'Nette\\Web\\HttpContext','getHttpRequest'=>'Nette\\Web\\IHttpRequest','getHttpResponse'=>'Nette\\Web\\IHttpResponse','getApplication'=>'Nette\\Application\\Application','getUser'=>'Nette\\Web\\IUser');private
  2528. static$criticalSections;final
  2529. function
  2530. __construct(){throw
  2531. new
  2532. LogicException("Cannot instantiate static class ".get_class($this));}static
  2533. function
  2534. setConfigurator(Configurator$configurator){self::$configurator=$configurator;}static
  2535. function
  2536. getConfigurator(){if(self::$configurator===NULL){self::$configurator=new
  2537. Configurator;}return
  2538. self::$configurator;}static
  2539. function
  2540. setName($name){if(!isset(self::$vars['environment'])){self::setVariable('environment',$name,FALSE);}else{throw
  2541. new
  2542. InvalidStateException('Environment name has been already set.');}}static
  2543. function
  2544. getName(){$name=self::getVariable('environment');if($name===NULL){$name=self::getConfigurator()->detect('environment');self::setVariable('environment',$name,FALSE);}return$name;}static
  2545. function
  2546. setMode($mode,$value=TRUE){self::$modes[$mode]=(bool)$value;}static
  2547. function
  2548. getMode($mode){if(isset(self::$modes[$mode])){return
  2549. self::$modes[$mode];}else{return
  2550. self::$modes[$mode]=self::getConfigurator()->detect($mode);}}static
  2551. function
  2552. isConsole(){return
  2553. self::getMode('console');}static
  2554. function
  2555. isProduction(){return
  2556. self::getMode('production');}static
  2557. function
  2558. setVariable($name,$value,$expand=TRUE){if(!is_string($value)){$expand=FALSE;}self::$vars[$name]=array($value,(bool)$expand);}static
  2559. function
  2560. getVariable($name,$default=NULL){if(isset(self::$vars[$name])){list($var,$exp)=self::$vars[$name];if($exp){$var=self::expand($var);self::$vars[$name]=array($var,FALSE);}return$var;}else{$const=strtoupper(preg_replace('#(.)([A-Z]+)#','$1_$2',$name));$list=get_defined_constants(TRUE);if(isset($list['user'][$const])){self::$vars[$name]=array($list['user'][$const],FALSE);return$list['user'][$const];}else{return$default;}}}static
  2561. function
  2562. getVariables(){$res=array();foreach(self::$vars
  2563. as$name=>$foo){$res[$name]=self::getVariable($name);}return$res;}static
  2564. function
  2565. expand($var){if(is_string($var)&&strpos($var,'%')!==FALSE){return@preg_replace_callback('#%([a-z0-9_-]*)%#i',array(__CLASS__,'expandCb'),$var);}return$var;}private
  2566. static
  2567. function
  2568. expandCb($m){list(,$var)=$m;if($var==='')return'%';static$livelock;if(isset($livelock[$var])){throw
  2569. new
  2570. InvalidStateException("Circular reference detected for variables: ".implode(', ',array_keys($livelock)).".");}try{$livelock[$var]=TRUE;$val=self::getVariable($var);unset($livelock[$var]);}catch(Exception$e){$livelock=array();throw$e;}if($val===NULL){throw
  2571. new
  2572. InvalidStateException("Unknown environment variable '$var'.");}elseif(!is_scalar($val)){throw
  2573. new
  2574. InvalidStateException("Environment variable '$var' is not scalar.");}return$val;}static
  2575. function
  2576. getServiceLocator(){if(self::$serviceLocator===NULL){self::$serviceLocator=self::getConfigurator()->createServiceLocator();}return
  2577. self::$serviceLocator;}static
  2578. function
  2579. getService($name,array$options=NULL){return
  2580. self::getServiceLocator()->getService($name,$options);}static
  2581. function
  2582. setServiceAlias($service,$alias){self::$aliases['get'.ucfirst($alias)]=$service;}static
  2583. function
  2584. __callStatic($name,$args){if(isset(self::$aliases[$name])){return
  2585. self::getServiceLocator()->getService(self::$aliases[$name],$args);}else{throw
  2586. new
  2587. MemberAccessException("Call to undefined static method Nette\\Environment::$name().");}}static
  2588. function
  2589. getHttpRequest(){return
  2590. self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);}static
  2591. function
  2592. getHttpContext(){return
  2593. self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);}static
  2594. function
  2595. getHttpResponse(){return
  2596. self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);}static
  2597. function
  2598. getApplication(){return
  2599. self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);}static
  2600. function
  2601. getUser(){return
  2602. self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);}static
  2603. function
  2604. getCache($namespace=''){return
  2605. new
  2606. Cache(self::getService('Nette\\Caching\\ICacheStorage'),$namespace);}static
  2607. function
  2608. getSession($namespace=NULL){$handler=self::getService('Nette\\Web\\Session');return$namespace===NULL?$handler:$handler->getNamespace($namespace);}static
  2609. function
  2610. loadConfig($file=NULL){return
  2611. self::$config=self::getConfigurator()->loadConfig($file);}static
  2612. function
  2613. getConfig($key=NULL,$default=NULL){if(func_num_args()){return
  2614. isset(self::$config[$key])?self::$config[$key]:$default;}else{return
  2615. self::$config;}}static
  2616. function
  2617. enterCriticalSection($key){$file=self::getVariable('tempDir')."/criticalSection-".md5($key);$handle=fopen($file,'w');flock($handle,LOCK_EX);self::$criticalSections[$key]=array($file,$handle);}static
  2618. function
  2619. leaveCriticalSection($key){if(!isset(self::$criticalSections[$key])){throw
  2620. new
  2621. InvalidStateException('Critical section has not been initialized.');}list($file,$handle)=self::$criticalSections[$key];@unlink($file);fclose($handle);unset(self::$criticalSections[$key]);}}class
  2622. ServiceLocator
  2623. extends
  2624. Object
  2625. implements
  2626. IServiceLocator{private$parent;private$registry=array();private$factories=array();function
  2627. __construct(IServiceLocator$parent=NULL){$this->parent=$parent;}function
  2628. addService($name,$service,$singleton=TRUE,array$options=NULL){if(!is_string($name)||$name===''){throw
  2629. new
  2630. InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}$lower=strtolower($name);if(isset($this->registry[$lower])){throw
  2631. new
  2632. AmbiguousServiceException("Service named '$name' has been already registered.");}if(is_object($service)){if(!$singleton||$options){throw
  2633. new
  2634. InvalidArgumentException("Service named '$name' is an instantiated object and must therefore be singleton without options.");}$this->registry[$lower]=$service;}else{if(!$service){throw
  2635. new
  2636. InvalidArgumentException("Service named '$name' is empty.");}$this->factories[$lower]=array($service,$singleton,$options);}}function
  2637. removeService($name){if(!is_string($name)||$name===''){throw
  2638. new
  2639. InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}$lower=strtolower($name);unset($this->registry[$lower],$this->factories[$lower]);}function
  2640. getService($name,array$options=NULL){if(!is_string($name)||$name===''){throw
  2641. new
  2642. InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}$lower=strtolower($name);if(isset($this->registry[$lower])){if($options){throw
  2643. new
  2644. InvalidArgumentException("Service named '$name' is singleton and therefore can not have options.");}return$this->registry[$lower];}elseif(isset($this->factories[$lower])){list($factory,$singleton,$defOptions)=$this->factories[$lower];if($singleton&&$options){throw
  2645. new
  2646. InvalidArgumentException("Service named '$name' is singleton and therefore can not have options.");}elseif($defOptions){$options=$options?$options+$defOptions:$defOptions;}if(is_string($factory)&&strpos($factory,':')===FALSE){if($a=strrpos($factory,'\\'))$factory=substr($factory,$a+1);if(!class_exists($factory)){throw
  2647. new
  2648. AmbiguousServiceException("Cannot instantiate service '$name', class '$factory' not found.");}$service=new$factory;if($options&&method_exists($service,'setOptions')){$service->setOptions($options);}}else{$factory=callback($factory);if(!$factory->isCallable()){throw
  2649. new
  2650. InvalidStateException("Cannot instantiate service '$name', handler '$factory' is not callable.");}$service=$factory->invoke($options);if(!is_object($service)){throw
  2651. new
  2652. AmbiguousServiceException("Cannot instantiate service '$name', value returned by '$factory' is not object.");}}if($singleton){$this->registry[$lower]=$service;unset($this->factories[$lower]);}return$service;}if($this->parent!==NULL){return$this->parent->getService($name,$options);}else{throw
  2653. new
  2654. InvalidStateException("Service '$name' not found.");}}function
  2655. hasService($name,$created=FALSE){if(!is_string($name)||$name===''){throw
  2656. new
  2657. InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}$lower=strtolower($name);return
  2658. isset($this->registry[$lower])||(!$created&&isset($this->factories[$lower]))||($this->parent!==NULL&&$this->parent->hasService($name,$created));}function
  2659. getParent(){return$this->parent;}}class
  2660. AmbiguousServiceException
  2661. extends
  2662. Exception{}abstract
  2663. class
  2664. FormControl
  2665. extends
  2666. Component
  2667. implements
  2668. IFormControl{public
  2669. static$idMask='frm%s-%s';public$caption;protected$value;protected$control;protected$label;private$errors=array();private$disabled=FALSE;private$htmlId;private$htmlName;private$rules;private$translator=TRUE;private$options=array();function
  2670. __construct($caption=NULL){$this->monitor('Form');parent::__construct();$this->control=Html::el('input');$this->label=Html::el('label');$this->caption=$caption;$this->rules=new
  2671. Rules($this);}protected
  2672. function
  2673. attached($form){if(!$this->disabled&&$form
  2674. instanceof
  2675. Form&&$form->isAnchored()&&$form->isSubmitted()){$this->htmlName=NULL;$this->loadHttpData();}}function
  2676. getForm($need=TRUE){return$this->lookup('Form',$need);}function
  2677. getHtmlName(){if($this->htmlName===NULL){$s='';$name=$this->getName();$obj=$this->lookup('INamingContainer',TRUE);while(!($obj
  2678. instanceof
  2679. Form)){$s="[$name]$s";$name=$obj->getName();$obj=$obj->lookup('INamingContainer',TRUE);}$name.=$s;if($name==='submit'){throw
  2680. new
  2681. InvalidArgumentException("Form control name 'submit' is not allowed due to JavaScript limitations.");}$this->htmlName=$name;}return$this->htmlName;}function
  2682. setHtmlId($id){$this->htmlId=$id;return$this;}function
  2683. getHtmlId(){if($this->htmlId===FALSE){return
  2684. NULL;}elseif($this->htmlId===NULL){$this->htmlId=sprintf(self::$idMask,$this->getForm()->getName(),$this->getHtmlName());$this->htmlId=str_replace(array('[]','[',']'),array('','-',''),$this->htmlId);}return$this->htmlId;}function
  2685. setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}final
  2686. function
  2687. getOption($key,$default=NULL){return
  2688. isset($this->options[$key])?$this->options[$key]:$default;}final
  2689. function
  2690. getOptions(){return$this->options;}function
  2691. setTranslator(ITranslator$translator=NULL){$this->translator=$translator;return$this;}final
  2692. function
  2693. getTranslator(){if($this->translator===TRUE){return$this->getForm(FALSE)?$this->getForm()->getTranslator():NULL;}return$this->translator;}function
  2694. translate($s,$count=NULL){$translator=$this->getTranslator();return$translator===NULL?$s:$translator->translate($s,$count);}function
  2695. setValue($value){$this->value=$value;return$this;}function
  2696. getValue(){return$this->value;}function
  2697. setDefaultValue($value){$form=$this->getForm(FALSE);if(!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValue($value);}return$this;}function
  2698. loadHttpData(){$path=explode('[',strtr(str_replace(array('[]',']'),'',$this->getHtmlName()),'.','_'));$this->setValue(ArrayTools::get($this->getForm()->getHttpData(),$path));}function
  2699. setDisabled($value=TRUE){$this->disabled=(bool)$value;return$this;}function
  2700. isDisabled(){return$this->disabled;}function
  2701. getControl(){$this->setOption('rendered',TRUE);$control=clone$this->control;$control->name=$this->getHtmlName();$control->disabled=$this->disabled;$control->id=$this->getHtmlId();return$control;}function
  2702. getLabel($caption=NULL){$label=clone$this->label;$label->for=$this->getHtmlId();if($caption!==NULL){$label->setText($this->translate($caption));}elseif($this->caption
  2703. instanceof
  2704. Html){$label->add($this->caption);}else{$label->setText($this->translate($this->caption));}return$label;}final
  2705. function
  2706. getControlPrototype(){return$this->control;}final
  2707. function
  2708. getLabelPrototype(){return$this->label;}function
  2709. setRendered($value=TRUE){$this->setOption('rendered',$value);return$this;}function
  2710. isRendered(){return!empty($this->options['rendered']);}function
  2711. addRule($operation,$message=NULL,$arg=NULL){$this->rules->addRule($operation,$message,$arg);return$this;}function
  2712. addCondition($operation,$value=NULL){return$this->rules->addCondition($operation,$value);}function
  2713. addConditionOn(IFormControl$control,$operation,$value=NULL){return$this->rules->addConditionOn($control,$operation,$value);}final
  2714. function
  2715. getRules(){return$this->rules;}final
  2716. function
  2717. setRequired($message=NULL){$this->rules->addRule(':Filled',$message);return$this;}final
  2718. function
  2719. isRequired(){return!empty($this->options['required']);}function
  2720. notifyRule(Rule$rule){if(is_string($rule->operation)&&strcasecmp($rule->operation,':filled')===0){$this->setOption('required',TRUE);}}static
  2721. function
  2722. validateEqual(IFormControl$control,$arg){$value=$control->getValue();foreach((is_array($value)?$value:array($value))as$val){foreach((is_array($arg)?$arg:array($arg))as$item){if((string)$val===(string)($item
  2723. instanceof
  2724. IFormControl?$item->value:$item)){return
  2725. TRUE;}}}return
  2726. FALSE;}static
  2727. function
  2728. validateFilled(IFormControl$control){return(string)$control->getValue()!=='';}static
  2729. function
  2730. validateValid(IFormControl$control){return$control->rules->validate(TRUE);}function
  2731. addError($message){if(!in_array($message,$this->errors,TRUE)){$this->errors[]=$message;}$this->getForm()->addError($message);}function
  2732. getErrors(){return$this->errors;}function
  2733. hasErrors(){return(bool)$this->errors;}function
  2734. cleanErrors(){$this->errors=array();}}class
  2735. Button
  2736. extends
  2737. FormControl{function
  2738. __construct($caption=NULL){parent::__construct($caption);$this->control->type='button';}function
  2739. getLabel($caption=NULL){return
  2740. NULL;}function
  2741. getControl($caption=NULL){$control=parent::getControl();$control->value=$this->translate($caption===NULL?$this->caption:$caption);return$control;}}class
  2742. Checkbox
  2743. extends
  2744. FormControl{function
  2745. __construct($label=NULL){parent::__construct($label);$this->control->type='checkbox';$this->value=FALSE;}function
  2746. setValue($value){$this->value=is_scalar($value)?(bool)$value:FALSE;return$this;}function
  2747. getControl(){return
  2748. parent::getControl()->checked($this->value);}}class
  2749. FileUpload
  2750. extends
  2751. FormControl{function
  2752. __construct($label=NULL){parent::__construct($label);$this->control->type='file';}protected
  2753. function
  2754. attached($form){if($form
  2755. instanceof
  2756. Form){if($form->getMethod()!==Form::POST){throw
  2757. new
  2758. InvalidStateException('File upload requires method POST.');}$form->getElementPrototype()->enctype='multipart/form-data';}parent::attached($form);}function
  2759. setValue($value){if(is_array($value)){$this->value=new
  2760. HttpUploadedFile($value);}elseif($value
  2761. instanceof
  2762. HttpUploadedFile){$this->value=$value;}else{$this->value=new
  2763. HttpUploadedFile(NULL);}return$this;}static
  2764. function
  2765. validateFilled(IFormControl$control){$file=$control->getValue();return$file
  2766. instanceof
  2767. HttpUploadedFile&&$file->isOK();}static
  2768. function
  2769. validateFileSize(FileUpload$control,$limit){$file=$control->getValue();return$file
  2770. instanceof
  2771. HttpUploadedFile&&$file->getSize()<=$limit;}static
  2772. function
  2773. validateMimeType(FileUpload$control,$mimeType){$file=$control->getValue();if($file
  2774. instanceof
  2775. HttpUploadedFile){$type=strtolower($file->getContentType());$mimeTypes=is_array($mimeType)?$mimeType:explode(',',$mimeType);if(in_array($type,$mimeTypes,TRUE)){return
  2776. TRUE;}if(in_array(preg_replace('#/.*#','/*',$type),$mimeTypes,TRUE)){return
  2777. TRUE;}}return
  2778. FALSE;}static
  2779. function
  2780. validateImage(FileUpload$control){$file=$control->getValue();return$file
  2781. instanceof
  2782. HttpUploadedFile&&$file->isImage();}}class
  2783. HiddenField
  2784. extends
  2785. FormControl{private$forcedValue;function
  2786. __construct($forcedValue=NULL){parent::__construct();$this->control->type='hidden';$this->value=(string)$forcedValue;$this->forcedValue=$forcedValue;}function
  2787. getLabel($caption=NULL){return
  2788. NULL;}function
  2789. setValue($value){$this->value=is_scalar($value)?(string)$value:'';return$this;}function
  2790. getControl(){return
  2791. parent::getControl()->value($this->forcedValue===NULL?$this->value:$this->forcedValue);}}class
  2792. SubmitButton
  2793. extends
  2794. Button
  2795. implements
  2796. ISubmitterControl{public$onClick;public$onInvalidClick;private$validationScope=TRUE;function
  2797. __construct($caption=NULL){parent::__construct($caption);$this->control->type='submit';}function
  2798. setValue($value){$this->value=is_scalar($value)&&(bool)$value;$form=$this->getForm();if($this->value||!is_object($form->isSubmitted())){$this->value=TRUE;$form->setSubmittedBy($this);}return$this;}function
  2799. isSubmittedBy(){return$this->getForm()->isSubmitted()===$this;}function
  2800. setValidationScope($scope){$this->validationScope=(bool)$scope;return$this;}final
  2801. function
  2802. getValidationScope(){return$this->validationScope;}function
  2803. click(){$this->onClick($this);}static
  2804. function
  2805. validateSubmitted(ISubmitterControl$control){return$control->isSubmittedBy();}}class
  2806. ImageButton
  2807. extends
  2808. SubmitButton{function
  2809. __construct($src=NULL,$alt=NULL){parent::__construct();$this->control->type='image';$this->control->src=$src;$this->control->alt=$alt;}function
  2810. getHtmlName(){$name=parent::getHtmlName();return
  2811. strpos($name,'[')===FALSE?$name:$name.'[]';}function
  2812. loadHttpData(){$path=$this->getHtmlName();$path=explode('[',strtr(str_replace(']','',strpos($path,'[')===FALSE?$path.'.x':substr($path,0,-2)),'.','_'));$this->setValue(ArrayTools::get($this->getForm()->getHttpData(),$path)!==NULL);}}class
  2813. SelectBox
  2814. extends
  2815. FormControl{private$items=array();protected$allowed=array();private$skipFirst=FALSE;private$useKeys=TRUE;function
  2816. __construct($label=NULL,array$items=NULL,$size=NULL){parent::__construct($label);$this->control->setName('select');$this->control->size=$size>1?(int)$size:NULL;$this->control->onfocus='this.onmousewheel=function(){return false}';$this->label->onclick='document.getElementById(this.htmlFor).focus();return false';if($items!==NULL){$this->setItems($items);}}function
  2817. getValue(){$allowed=$this->allowed;if($this->skipFirst){$allowed=array_slice($allowed,1,count($allowed),TRUE);}return
  2818. is_scalar($this->value)&&isset($allowed[$this->value])?$this->value:NULL;}function
  2819. getRawValue(){return
  2820. is_scalar($this->value)?$this->value:NULL;}function
  2821. skipFirst($item=NULL){if(is_bool($item)){$this->skipFirst=$item;}else{$this->skipFirst=TRUE;if($item!==NULL){$this->items=array(''=>$item)+$this->items;$this->allowed=array(''=>'')+$this->allowed;}}return$this;}final
  2822. function
  2823. isFirstSkipped(){return$this->skipFirst;}final
  2824. function
  2825. areKeysUsed(){return$this->useKeys;}function
  2826. setItems(array$items,$useKeys=TRUE){$this->items=$items;$this->allowed=array();$this->useKeys=(bool)$useKeys;foreach($items
  2827. as$key=>$value){if(!is_array($value)){$value=array($key=>$value);}foreach($value
  2828. as$key2=>$value2){if(!$this->useKeys){if(!is_scalar($value2)){throw
  2829. new
  2830. InvalidArgumentException("All items must be scalars.");}$key2=$value2;}if(isset($this->allowed[$key2])){throw
  2831. new
  2832. InvalidArgumentException("Items contain duplication for key '$key2'.");}$this->allowed[$key2]=$value2;}}return$this;}final
  2833. function
  2834. getItems(){return$this->items;}function
  2835. getSelectedItem(){if(!$this->useKeys){return$this->getValue();}else{$value=$this->getValue();return$value===NULL?NULL:$this->allowed[$value];}}function
  2836. getControl(){$control=parent::getControl();$selected=$this->getValue();$selected=is_array($selected)?array_flip($selected):array($selected=>TRUE);$option=Html::el('option');foreach($this->items
  2837. as$key=>$value){if(!is_array($value)){$value=array($key=>$value);$dest=$control;}else{$dest=$control->create('optgroup')->label($key);}foreach($value
  2838. as$key2=>$value2){if($value2
  2839. instanceof
  2840. Html){$dest->add((string)$value2->selected(isset($selected[$key2])));}elseif($this->useKeys){$dest->add((string)$option->value($key2)->selected(isset($selected[$key2]))->setText($this->translate($value2)));}else{$dest->add((string)$option->selected(isset($selected[$value2]))->setText($this->translate($value2)));}}}return$control;}static
  2841. function
  2842. validateFilled(IFormControl$control){$value=$control->getValue();return
  2843. is_array($value)?count($value)>0:$value!==NULL;}}class
  2844. MultiSelectBox
  2845. extends
  2846. SelectBox{function
  2847. getValue(){$allowed=array_keys($this->allowed);if($this->isFirstSkipped()){unset($allowed[0]);}return
  2848. array_intersect($this->getRawValue(),$allowed);}function
  2849. getRawValue(){if(is_scalar($this->value)){$value=array($this->value);}elseif(!is_array($this->value)){$value=array();}else{$value=$this->value;}$res=array();foreach($value
  2850. as$val){if(is_scalar($val)){$res[]=$val;}}return$res;}function
  2851. getSelectedItem(){if(!$this->areKeysUsed()){return$this->getValue();}else{$res=array();foreach($this->getValue()as$value){$res[$value]=$this->allowed[$value];}return$res;}}function
  2852. getHtmlName(){return
  2853. parent::getHtmlName().'[]';}function
  2854. getControl(){$control=parent::getControl();$control->multiple=TRUE;return$control;}}class
  2855. RadioList
  2856. extends
  2857. FormControl{protected$separator;protected$container;protected$items=array();function
  2858. __construct($label=NULL,array$items=NULL){parent::__construct($label);$this->control->type='radio';$this->container=Html::el();$this->separator=Html::el('br');if($items!==NULL)$this->setItems($items);}function
  2859. getValue($raw=FALSE){return
  2860. is_scalar($this->value)&&($raw||isset($this->items[$this->value]))?$this->value:NULL;}function
  2861. setItems(array$items){$this->items=$items;return$this;}final
  2862. function
  2863. getItems(){return$this->items;}final
  2864. function
  2865. getSeparatorPrototype(){return$this->separator;}final
  2866. function
  2867. getContainerPrototype(){return$this->container;}function
  2868. getControl($key=NULL){if($key===NULL){$container=clone$this->container;$separator=(string)$this->separator;}elseif(!isset($this->items[$key])){return
  2869. NULL;}$control=parent::getControl();$id=$control->id;$counter=-1;$value=$this->value===NULL?NULL:(string)$this->getValue();$label=Html::el('label');foreach($this->items
  2870. as$k=>$val){$counter++;if($key!==NULL&&$key!=$k)continue;$control->id=$label->for=$id.'-'.$counter;$control->checked=(string)$k===$value;$control->value=$k;if($val
  2871. instanceof
  2872. Html){$label->setHtml($val);}else{$label->setText($this->translate($val));}if($key!==NULL){return(string)$control.(string)$label;}$container->add((string)$control.(string)$label.$separator);}return$container;}function
  2873. getLabel($caption=NULL){$label=parent::getLabel($caption);$label->for=NULL;return$label;}static
  2874. function
  2875. validateFilled(IFormControl$control){return$control->getValue()!==NULL;}}abstract
  2876. class
  2877. TextBase
  2878. extends
  2879. FormControl{protected$emptyValue='';protected$filters=array();function
  2880. setValue($value){$this->value=is_scalar($value)?(string)$value:'';return$this;}function
  2881. getValue(){$value=$this->value;foreach($this->filters
  2882. as$filter){$value=(string)$filter->invoke($value);}return$value===$this->translate($this->emptyValue)?'':$value;}function
  2883. setEmptyValue($value){$this->emptyValue=$value;return$this;}final
  2884. function
  2885. getEmptyValue(){return$this->emptyValue;}function
  2886. addFilter($filter){$this->filters[]=callback($filter);return$this;}function
  2887. notifyRule(Rule$rule){if(is_string($rule->operation)&&strcasecmp($rule->operation,':float')===0){$this->addFilter(callback(__CLASS__,'filterFloat'));}parent::notifyRule($rule);}static
  2888. function
  2889. validateMinLength(TextBase$control,$length){return
  2890. String::length($control->getValue())>=$length;}static
  2891. function
  2892. validateMaxLength(TextBase$control,$length){return
  2893. String::length($control->getValue())<=$length;}static
  2894. function
  2895. validateLength(TextBase$control,$range){if(!is_array($range)){$range=array($range,$range);}$len=String::length($control->getValue());return($range[0]===NULL||$len>=$range[0])&&($range[1]===NULL||$len<=$range[1]);}static
  2896. function
  2897. validateEmail(TextBase$control){$atom="[-a-z0-9!#$%&'*+/=?^_`{|}~]";$localPart="(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)";$chars="a-z0-9\x80-\xFF";$domain="[$chars](?:[-$chars]{0,61}[$chars])";return(bool)String::match($control->getValue(),"(^$localPart@(?:$domain?\\.)+[-$chars]{2,19}\\z)i");}static
  2898. function
  2899. validateUrl(TextBase$control){return(bool)String::match($control->getValue(),'/^.+\.[a-z]{2,6}(?:\\/.*)?$/i');}static
  2900. function
  2901. validateRegexp(TextBase$control,$regexp){return(bool)String::match($control->getValue(),$regexp);}static
  2902. function
  2903. validateInteger(TextBase$control){return(bool)String::match($control->getValue(),'/^-?[0-9]+$/');}static
  2904. function
  2905. validateFloat(TextBase$control){return(bool)String::match($control->getValue(),'/^-?[0-9]*[.,]?[0-9]+$/');}static
  2906. function
  2907. validateRange(TextBase$control,$range){return($range[0]===NULL||$control->getValue()>=$range[0])&&($range[1]===NULL||$control->getValue()<=$range[1]);}static
  2908. function
  2909. filterFloat($s){return
  2910. str_replace(array(' ',','),array('','.'),$s);}}class
  2911. TextArea
  2912. extends
  2913. TextBase{function
  2914. __construct($label=NULL,$cols=NULL,$rows=NULL){parent::__construct($label);$this->control->setName('textarea');$this->control->cols=$cols;$this->control->rows=$rows;$this->value='';}function
  2915. getControl(){$control=parent::getControl();$control->setText($this->getValue()===''?$this->translate($this->emptyValue):$this->value);return$control;}}class
  2916. TextInput
  2917. extends
  2918. TextBase{function
  2919. __construct($label=NULL,$cols=NULL,$maxLength=NULL){parent::__construct($label);$this->control->type='text';$this->control->size=$cols;$this->control->maxlength=$maxLength;$this->filters[]=callback('String','trim');$this->filters[]=callback($this,'checkMaxLength');$this->value='';}function
  2920. checkMaxLength($value){if($this->control->maxlength&&String::length($value)>$this->control->maxlength){$value=iconv_substr($value,0,$this->control->maxlength,'UTF-8');}return$value;}function
  2921. setPasswordMode($mode=TRUE){$this->control->type=$mode?'password':'text';return$this;}function
  2922. getControl(){$control=parent::getControl();if($this->control->type!=='password'){$control->value=$this->getValue()===''?$this->translate($this->emptyValue):$this->value;}return$control;}function
  2923. notifyRule(Rule$rule){if(is_string($rule->operation)&&strcasecmp($rule->operation,':length')===0&&!$rule->isNegative){$this->control->maxlength=is_array($rule->arg)?$rule->arg[1]:$rule->arg;}elseif(is_string($rule->operation)&&strcasecmp($rule->operation,':maxLength')===0&&!$rule->isNegative){$this->control->maxlength=$rule->arg;}parent::notifyRule($rule);}}class
  2924. FormGroup
  2925. extends
  2926. Object{protected$controls;private$options=array();function
  2927. __construct(){$this->controls=new
  2928. SplObjectStorage;}function
  2929. add(){foreach(func_get_args()as$num=>$item){if($item
  2930. instanceof
  2931. IFormControl){$this->controls->attach($item);}elseif($item
  2932. instanceof
  2933. Traversable||is_array($item)){foreach($item
  2934. as$control){$this->controls->attach($control);}}else{throw
  2935. new
  2936. InvalidArgumentException("Only IFormControl items are allowed, the #$num parameter is invalid.");}}return$this;}function
  2937. getControls(){return
  2938. iterator_to_array($this->controls);}function
  2939. setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}final
  2940. function
  2941. getOption($key,$default=NULL){return
  2942. isset($this->options[$key])?$this->options[$key]:$default;}final
  2943. function
  2944. getOptions(){return$this->options;}}class
  2945. ConventionalRenderer
  2946. extends
  2947. Object
  2948. implements
  2949. IFormRenderer{public$wrappers=array('form'=>array('container'=>NULL,'errors'=>TRUE),'error'=>array('container'=>'ul class=error','item'=>'li'),'group'=>array('container'=>'fieldset','label'=>'legend','description'=>'p'),'controls'=>array('container'=>'table'),'pair'=>array('container'=>'tr','.required'=>'required','.optional'=>NULL,'.odd'=>NULL),'control'=>array('container'=>'td','.odd'=>NULL,'errors'=>FALSE,'description'=>'small','requiredsuffix'=>'','.required'=>'required','.text'=>'text','.password'=>'text','.file'=>'text','.submit'=>'button','.image'=>'imagebutton','.button'=>'button'),'label'=>array('container'=>'th','suffix'=>NULL,'requiredsuffix'=>''),'hidden'=>array('container'=>'div'));protected$form;protected$clientScript=TRUE;protected$counter;function
  2950. render(Form$form,$mode=NULL){if($this->form!==$form){$this->form=$form;$this->init();}$s='';if(!$mode||$mode==='begin'){$s.=$this->renderBegin();}if((!$mode&&$this->getValue('form errors'))||$mode==='errors'){$s.=$this->renderErrors();}if(!$mode||$mode==='body'){$s.=$this->renderBody();}if(!$mode||$mode==='end'){$s.=$this->renderEnd();}return$s;}function
  2951. setClientScript($clientScript=NULL){$this->clientScript=$clientScript;return$this;}function
  2952. getClientScript(){if($this->clientScript===TRUE){$this->clientScript=new
  2953. InstantClientScript($this->form);}return$this->clientScript;}protected
  2954. function
  2955. init(){$clientScript=$this->getClientScript();if($clientScript!==NULL){$clientScript->enable();}$wrapper=&$this->wrappers['control'];foreach($this->form->getControls()as$control){if($control->getOption('required')&&isset($wrapper['.required'])){$control->getLabelPrototype()->class($wrapper['.required'],TRUE);}$el=$control->getControlPrototype();if($el->getName()==='input'&&isset($wrapper['.'.$el->type])){$el->class($wrapper['.'.$el->type],TRUE);}}}function
  2956. renderBegin(){$this->counter=0;foreach($this->form->getControls()as$control){$control->setOption('rendered',FALSE);}if(strcasecmp($this->form->getMethod(),'get')===0){$el=clone$this->form->getElementPrototype();$uri=explode('?',(string)$el->action,2);$el->action=$uri[0];$s='';if(isset($uri[1])){foreach(preg_split('#[;&]#',$uri[1])as$param){$parts=explode('=',$param,2);$name=urldecode($parts[0]);if(!isset($this->form[$name])){$s.=Html::el('input',array('type'=>'hidden','name'=>$name,'value'=>urldecode($parts[1])));}}$s="\n\t".$this->getWrapper('hidden container')->setHtml($s);}return$el->startTag().$s;}else{return$this->form->getElementPrototype()->startTag();}}function
  2957. renderEnd(){$s='';foreach($this->form->getControls()as$control){if($control
  2958. instanceof
  2959. HiddenField&&!$control->getOption('rendered')){$s.=(string)$control->getControl();}}if($s){$s=$this->getWrapper('hidden container')->setHtml($s)."\n";}$s.=$this->form->getElementPrototype()->endTag()."\n";$clientScript=$this->getClientScript();if($clientScript!==NULL){$s.=$clientScript->renderClientScript()."\n";}return$s;}function
  2960. renderErrors(IFormControl$control=NULL){$errors=$control===NULL?$this->form->getErrors():$control->getErrors();if(count($errors)){$ul=$this->getWrapper('error container');$li=$this->getWrapper('error item');foreach($errors
  2961. as$error){$item=clone$li;if($error
  2962. instanceof
  2963. Html){$item->add($error);}else{$item->setText($error);}$ul->add($item);}return"\n".$ul->render(0);}}function
  2964. renderBody(){$s=$remains='';$defaultContainer=$this->getWrapper('group container');$translator=$this->form->getTranslator();foreach($this->form->getGroups()as$group){if(!$group->getControls()||!$group->getOption('visual'))continue;$container=$group->getOption('container',$defaultContainer);$container=$container
  2965. instanceof
  2966. Html?clone$container:Html::el($container);$s.="\n".$container->startTag();$text=$group->getOption('label');if($text
  2967. instanceof
  2968. Html){$s.=$text;}elseif(is_string($text)){if($translator!==NULL){$text=$translator->translate($text);}$s.="\n".$this->getWrapper('group label')->setText($text)."\n";}$text=$group->getOption('description');if($text
  2969. instanceof
  2970. Html){$s.=$text;}elseif(is_string($text)){if($translator!==NULL){$text=$translator->translate($text);}$s.=$this->getWrapper('group description')->setText($text)."\n";}$s.=$this->renderControls($group);$remains=$container->endTag()."\n".$remains;if(!$group->getOption('embedNext')){$s.=$remains;$remains='';}}$s.=$remains.$this->renderControls($this->form);$container=$this->getWrapper('form container');$container->setHtml($s);return$container->render(0);}function
  2971. renderControls($parent){if(!($parent
  2972. instanceof
  2973. FormContainer||$parent
  2974. instanceof
  2975. FormGroup)){throw
  2976. new
  2977. InvalidArgumentException("Argument must be FormContainer or FormGroup instance.");}$container=$this->getWrapper('controls container');$buttons=NULL;foreach($parent->getControls()as$control){if($control->getOption('rendered')||$control
  2978. instanceof
  2979. HiddenField||$control->getForm(FALSE)!==$this->form){}elseif($control
  2980. instanceof
  2981. Button){$buttons[]=$control;}else{if($buttons){$container->add($this->renderPairMulti($buttons));$buttons=NULL;}$container->add($this->renderPair($control));}}if($buttons){$container->add($this->renderPairMulti($buttons));}$s='';if(count($container)){$s.="\n".$container."\n";}return$s;}function
  2982. renderPair(IFormControl$control){$pair=$this->getWrapper('pair container');$pair->add($this->renderLabel($control));$pair->add($this->renderControl($control));$pair->class($this->getValue($control->getOption('required')?'pair .required':'pair .optional'),TRUE);$pair->class($control->getOption('class'),TRUE);if(++$this->counter
  2983. %
  2984. 2)$pair->class($this->getValue('pair .odd'),TRUE);$pair->id=$control->getOption('id');return$pair->render(0);}function
  2985. renderPairMulti(array$controls){$s=array();foreach($controls
  2986. as$control){if(!($control
  2987. instanceof
  2988. IFormControl)){throw
  2989. new
  2990. InvalidArgumentException("Argument must be array of IFormControl instances.");}$s[]=(string)$control->getControl();}$pair=$this->getWrapper('pair container');$pair->add($this->renderLabel($control));$pair->add($this->getWrapper('control container')->setHtml(implode(" ",$s)));return$pair->render(0);}function
  2991. renderLabel(IFormControl$control){$head=$this->getWrapper('label container');if($control
  2992. instanceof
  2993. Checkbox||$control
  2994. instanceof
  2995. Button){return$head->setHtml(($head->getName()==='td'||$head->getName()==='th')?'&nbsp;':'');}else{$label=$control->getLabel();$suffix=$this->getValue('label suffix').($control->getOption('required')?$this->getValue('label requiredsuffix'):'');if($label
  2996. instanceof
  2997. Html){$label->setHtml($label->getHtml().$suffix);$suffix='';}return$head->setHtml((string)$label.$suffix);}}function
  2998. renderControl(IFormControl$control){$body=$this->getWrapper('control container');if($this->counter
  2999. %
  3000. 2)$body->class($this->getValue('control .odd'),TRUE);$description=$control->getOption('description');if($description
  3001. instanceof
  3002. Html){$description=' '.$control->getOption('description');}elseif(is_string($description)){$description=' '.$this->getWrapper('control description')->setText($control->translate($description));}else{$description='';}if($control->getOption('required')){$description=$this->getValue('control requiredsuffix').$description;}if($this->getValue('control errors')){$description.=$this->renderErrors($control);}if($control
  3003. instanceof
  3004. Checkbox||$control
  3005. instanceof
  3006. Button){return$body->setHtml((string)$control->getControl().(string)$control->getLabel().$description);}else{return$body->setHtml((string)$control->getControl().$description);}}protected
  3007. function
  3008. getWrapper($name){$data=$this->getValue($name);return$data
  3009. instanceof
  3010. Html?clone$data:Html::el($data);}protected
  3011. function
  3012. getValue($name){$name=explode(' ',$name);$data=&$this->wrappers[$name[0]][$name[1]];return$data;}}final
  3013. class
  3014. InstantClientScript
  3015. extends
  3016. Object{private$validateScripts;private$toggleScript;private$central;private$form;function
  3017. __construct(Form$form){$this->form=$form;}function
  3018. enable(){$this->validateScripts=array();$this->toggleScript='';$this->central=TRUE;foreach($this->form->getControls()as$control){$script=$this->getValidateScript($control->getRules());if($script){$this->validateScripts[$control->getHtmlName()]=$script;}$this->toggleScript.=$this->getToggleScript($control->getRules());if($control
  3019. instanceof
  3020. ISubmitterControl&&$control->getValidationScope()!==TRUE){$this->central=FALSE;}}if($this->validateScripts||$this->toggleScript){if($this->central){$this->form->getElementPrototype()->onsubmit("return nette.validateForm(this)",TRUE);}else{foreach($this->form->getComponents(TRUE,'ISubmitterControl')as$control){if($control->getValidationScope()){$control->getControlPrototype()->onclick("return nette.validateForm(this)",TRUE);}}}}}function
  3021. renderClientScript(){if(!$this->validateScripts&&!$this->toggleScript){return;}$formName=json_encode((string)$this->form->getElementPrototype()->id);ob_start();?>
  3022. <!-- Nette Form validator -->
  3023. <script type="text/javascript">/*<![CDATA[*/var nette=nette||{};nette.getValue=function(a){if(a){if(!a.nodeName){for(var b=0,d=a.length;b<d;b++)if(a[b].checked)return a[b].value;return null}if(a.nodeName.toLowerCase()==="select"){b=a.selectedIndex;var c=a.options;if(b<0)return null;else if(a.type==="select-one")return c[b].value;b=0;a=[];for(d=c.length;b<d;b++)c[b].selected&&a.push(c[b].value);return a}if(a.type==="checkbox")return a.checked;return a.value.replace(/^\s+|\s+$/g,"")}};
  3024. nette.getFormValidators=function(a){a=a.getAttributeNode("id").nodeValue;return this.forms[a]?this.forms[a].validators:[]};nette.validateControl=function(a){var b=this.getFormValidators(a.form)[a.name];return b?b(a):null};nette.validateForm=function(a){var b=a.form||a,d=this.getFormValidators(b);for(var c in d){var e=d[c](a);if(e){b[c].focus&&b[c].focus();alert(e);return false}}return true};nette.toggle=function(a,b){if(a=document.getElementById(a))a.style.display=b?"":"none"};/*]]>*/</script>
  3025. <script type="text/javascript">
  3026. /* <![CDATA[ */
  3027. nette.forms = nette.forms || { };
  3028. nette.forms[<?php echo$formName?>] = {
  3029. validators: {
  3030. <?php $count=count($this->validateScripts);?>
  3031. <?php foreach($this->validateScripts
  3032. as$name=>$validateScript):?>
  3033. <?php echo
  3034. json_encode((string)$name)?>: function(sender) {
  3035. var res, val, form = sender.form || sender;
  3036. <?php echo
  3037. String::indent($validateScript,3)?>
  3038. }<?php echo--$count?',':''?>
  3039. <?php endforeach?>
  3040. },
  3041. toggle: function(sender) {
  3042. var visible, res, form = sender.form || sender;
  3043. <?php echo
  3044. String::indent($this->toggleScript,2)?>
  3045. }
  3046. }
  3047. <?php if($this->toggleScript):?>
  3048. nette.forms[<?php echo$formName?>].toggle(document.getElementById(<?php echo$formName?>));
  3049. <?php endif?>
  3050. /* ]]> */
  3051. </script>
  3052. <!-- /Nette Form validator -->
  3053. <?php
  3054. return
  3055. ob_get_clean();}private
  3056. function
  3057. getValidateScript(Rules$rules){$res='';foreach($rules
  3058. as$rule){if(!is_string($rule->operation))continue;if(strcasecmp($rule->operation,'Nette\\Forms\\InstantClientScript::javascript')===0){$res.="$rule->arg\n";continue;}$script=$this->getClientScript($rule->control,$rule->operation,$rule->arg);if(!$script)continue;if(!empty($rule->message)){$message=Rules::formatMessage($rule,FALSE);$res.="$script\n"."if (".($rule->isNegative?'':'!')."res) "."return ".json_encode((string)$message).(strpos($message,'%value')===FALSE?'':".replace('%value', val);\n").";\n";}if($rule->type===Rule::CONDITION){$innerScript=$this->getValidateScript($rule->subRules);if($innerScript){$res.="$script\nif (".($rule->isNegative?'!':'')."res) {\n".String::indent($innerScript)."}\n";if($rule->control
  3059. instanceof
  3060. ISubmitterControl){$this->central=FALSE;}}}}return$res;}private
  3061. function
  3062. getToggleScript(Rules$rules,$cond=NULL){$s='';foreach($rules->getToggles()as$id=>$visible){$s.="visible = true; {$cond}\n"."nette.toggle(".json_encode((string)$id).", ".($visible?'':'!')."visible);\n";}$formName=json_encode((string)$this->form->getElementPrototype()->id);foreach($rules
  3063. as$rule){if($rule->type===Rule::CONDITION&&is_string($rule->operation)){$script=$this->getClientScript($rule->control,$rule->operation,$rule->arg);if($script){$res=$this->getToggleScript($rule->subRules,$cond."$script visible = visible && ".($rule->isNegative?'!':'')."res;\n");if($res){$el=$rule->control->getControlPrototype();if($el->getName()==='select'){$el->onchange("nette.forms[$formName].toggle(this)",TRUE);}else{$el->onclick("nette.forms[$formName].toggle(this)",TRUE);}$s.=$res;}}}}return$s;}private
  3064. function
  3065. getClientScript(IFormControl$control,$operation,$arg){$operation=strtolower($operation);$elem='form['.json_encode($control->getHtmlName()).']';switch(TRUE){case$control
  3066. instanceof
  3067. HiddenField||$control->isDisabled():return
  3068. NULL;case$operation===':filled'&&$control
  3069. instanceof
  3070. RadioList:return"res = (val = nette.getValue($elem)) !== null;";case$operation===':submitted'&&$control
  3071. instanceof
  3072. SubmitButton:return"res = sender && sender.name==".json_encode($control->getHtmlName()).";";case$operation===':equal'&&$control
  3073. instanceof
  3074. MultiSelectBox:$tmp=array();foreach((is_array($arg)?$arg:array($arg))as$item){$tmp[]="options[i].value==".json_encode((string)$item);}$first=$control->isFirstSkipped()?1:0;return"var options = $elem.options; res = false;\n"."for (var i=$first, len=options.length; i<len; i++)\n\t"."if (options[i].selected && (".implode(' || ',$tmp).")) { res = true; break; }";case$operation===':filled'&&$control
  3075. instanceof
  3076. SelectBox:return"res = $elem.selectedIndex >= ".($control->isFirstSkipped()?1:0).";";case$operation===':filled'&&$control
  3077. instanceof
  3078. TextBase:return"val = nette.getValue($elem); res = val!='' && val!=".json_encode((string)$control->getEmptyValue()).";";case$operation===':minlength'&&$control
  3079. instanceof
  3080. TextBase:return"res = (val = nette.getValue($elem)).length>=".(int)$arg.";";case$operation===':maxlength'&&$control
  3081. instanceof
  3082. TextBase:return"res = (val = nette.getValue($elem)).length<=".(int)$arg.";";case$operation===':length'&&$control
  3083. instanceof
  3084. TextBase:if(!is_array($arg)){$arg=array($arg,$arg);}return"val = nette.getValue($elem); res = ".($arg[0]===NULL?"true":"val.length>=".(int)$arg[0])." && ".($arg[1]===NULL?"true":"val.length<=".(int)$arg[1]).";";case$operation===':email'&&$control
  3085. instanceof
  3086. TextBase:return'res = /^[^@\s]+@[^@\s]+\.[a-z]{2,10}$/i.test(val = nette.getValue('.$elem.'));';case$operation===':url'&&$control
  3087. instanceof
  3088. TextBase:return'res = /^.+\.[a-z]{2,6}(\\/.*)?$/i.test(val = nette.getValue('.$elem.'));';case$operation===':regexp'&&$control
  3089. instanceof
  3090. TextBase:if(!preg_match('#^(/.*/)([imu]*)$#',$arg,$matches)){return
  3091. NULL;}$arg=$matches[1].str_replace('u','',$matches[2]);return"res = $arg.test(val = nette.getValue($elem));";case$operation===':integer'&&$control
  3092. instanceof
  3093. TextBase:return"res = /^-?[0-9]+$/.test(val = nette.getValue($elem));";case$operation===':float'&&$control
  3094. instanceof
  3095. TextBase:return"res = /^-?[0-9]*[.,]?[0-9]+$/.test(val = nette.getValue($elem));";case$operation===':range'&&$control
  3096. instanceof
  3097. TextBase:return"val = nette.getValue($elem); res = ".($arg[0]===NULL?"true":"parseFloat(val)>=".json_encode((float)$arg[0]))." && ".($arg[1]===NULL?"true":"parseFloat(val)<=".json_encode((float)$arg[1])).";";case$operation===':filled'&&$control
  3098. instanceof
  3099. FormControl:return"res = (val = nette.getValue($elem)) != '';";case$operation===':valid'&&$control
  3100. instanceof
  3101. FormControl:return"res = !this[".json_encode($control->getHtmlName())."](sender);";case$operation===':equal'&&$control
  3102. instanceof
  3103. FormControl:if($control
  3104. instanceof
  3105. Checkbox)$arg=(bool)$arg;$tmp=array();foreach((is_array($arg)?$arg:array($arg))as$item){if($item
  3106. instanceof
  3107. IFormControl){$tmp[]="val==nette.getValue(form[".json_encode($item->getHtmlName())."])";}else{$tmp[]="val==".json_encode($item);}}return"val = nette.getValue($elem); res = (".implode(' || ',$tmp).");";}}static
  3108. function
  3109. javascript(){return
  3110. TRUE;}}final
  3111. class
  3112. Rule
  3113. extends
  3114. Object{const
  3115. CONDITION=1;const
  3116. VALIDATOR=2;const
  3117. FILTER=3;const
  3118. TERMINATOR=4;public$control;public$operation;public$arg;public$type;public$isNegative=FALSE;public$message;public$breakOnFailure=TRUE;public$subRules;}final
  3119. class
  3120. Rules
  3121. extends
  3122. Object
  3123. implements
  3124. IteratorAggregate{const
  3125. VALIDATE_PREFIX='validate';public
  3126. static$defaultMessages=array();private$rules=array();private$parent;private$toggles=array();private$control;function
  3127. __construct(IFormControl$control){$this->control=$control;}function
  3128. addRule($operation,$message=NULL,$arg=NULL){$rule=new
  3129. Rule;$rule->control=$this->control;$rule->operation=$operation;$this->adjustOperation($rule);$rule->arg=$arg;$rule->type=Rule::VALIDATOR;if($message===NULL&&isset(self::$defaultMessages[$rule->operation])){$rule->message=self::$defaultMessages[$rule->operation];}else{$rule->message=$message;}if($this->parent===NULL){$this->control->notifyRule($rule);}$this->rules[]=$rule;return$this;}function
  3130. addCondition($operation,$arg=NULL){return$this->addConditionOn($this->control,$operation,$arg);}function
  3131. addConditionOn(IFormControl$control,$operation,$arg=NULL){$rule=new
  3132. Rule;$rule->control=$control;$rule->operation=$operation;$this->adjustOperation($rule);$rule->arg=$arg;$rule->type=Rule::CONDITION;$rule->subRules=new
  3133. self($this->control);$rule->subRules->parent=$this;$this->rules[]=$rule;return$rule->subRules;}function
  3134. elseCondition(){$rule=clone
  3135. end($this->parent->rules);$rule->isNegative=!$rule->isNegative;$rule->subRules=new
  3136. self($this->parent->control);$rule->subRules->parent=$this->parent;$this->parent->rules[]=$rule;return$rule->subRules;}function
  3137. endCondition(){return$this->parent;}function
  3138. toggle($id,$hide=TRUE){$this->toggles[$id]=$hide;return$this;}function
  3139. validate($onlyCheck=FALSE){$valid=TRUE;foreach($this->rules
  3140. as$rule){if($rule->control->isDisabled())continue;$success=($rule->isNegative
  3141. xor$this->getCallback($rule)->invoke($rule->control,$rule->arg));if($rule->type===Rule::CONDITION&&$success){$success=$rule->subRules->validate($onlyCheck);$valid=$valid&&$success;}elseif($rule->type===Rule::VALIDATOR&&!$success){if($onlyCheck){return
  3142. FALSE;}$rule->control->addError(self::formatMessage($rule,TRUE));$valid=FALSE;if($rule->breakOnFailure){break;}}}return$valid;}final
  3143. function
  3144. getIterator(){return
  3145. new
  3146. ArrayIterator($this->rules);}final
  3147. function
  3148. getToggles(){return$this->toggles;}private
  3149. function
  3150. adjustOperation($rule){if(is_string($rule->operation)&&ord($rule->operation[0])>127){$rule->isNegative=TRUE;$rule->operation=~$rule->operation;}if(!$this->getCallback($rule)->isCallable()){$operation=is_scalar($rule->operation)?" '$rule->operation'":'';throw
  3151. new
  3152. InvalidArgumentException("Unknown operation$operation for control '{$rule->control->name}'.");}}private
  3153. function
  3154. getCallback($rule){$op=$rule->operation;if(is_string($op)&&strncmp($op,':',1)===0){return
  3155. callback(get_class($rule->control),self::VALIDATE_PREFIX.ltrim($op,':'));}else{return
  3156. callback($op);}}static
  3157. function
  3158. formatMessage($rule,$withValue){$message=$rule->message;if($translator=$rule->control->getForm()->getTranslator()){$message=$translator->translate($message,is_int($rule->arg)?$rule->arg:NULL);}$message=str_replace('%name',$rule->control->getName(),$message);$message=str_replace('%label',$rule->control->translate($rule->control->caption),$message);if(strpos($message,'%value')!==FALSE){$message=str_replace('%value',$withValue?(string)$rule->control->getValue():'%%value',$message);}$message=vsprintf($message,(array)$rule->arg);return$message;}}class
  3159. RobotLoader
  3160. extends
  3161. AutoLoader{public$scanDirs;public$ignoreDirs='.*, *.old, *.bak, *.tmp, temp';public$acceptFiles='*.php, *.php5';public$autoRebuild;private$list=array();private$files;private$rebuilded=FALSE;private$acceptMask;private$ignoreMask;function
  3162. __construct(){if(!extension_loaded('tokenizer')){throw
  3163. new
  3164. Exception("PHP extension Tokenizer is not loaded.");}}function
  3165. register(){$cache=$this->getCache();$key=$this->getKey();if(isset($cache[$key])){$this->list=$cache[$key];}else{$this->rebuild();}if(isset($this->list[strtolower(__CLASS__)])&&class_exists('NetteLoader',FALSE)){NetteLoader::getInstance()->unregister();}parent::register();}function
  3166. tryLoad($type){$type=ltrim(strtolower($type),'\\');if(isset($this->list[$type])){if($this->list[$type]!==FALSE){LimitedScope::load($this->list[$type][0]);self::$count++;}}else{$this->list[$type]=FALSE;if($this->autoRebuild===NULL){$this->autoRebuild=!$this->isProduction();}if($this->autoRebuild){if($this->rebuilded){$this->getCache()->save($this->getKey(),$this->list);}else{$this->rebuild();}}if($this->list[$type]!==FALSE){LimitedScope::load($this->list[$type][0]);self::$count++;}}}function
  3167. rebuild(){$this->getCache()->save($this->getKey(),callback($this,'_rebuildCallback'));$this->rebuilded=TRUE;}function
  3168. _rebuildCallback(){$this->acceptMask=self::wildcards2re($this->acceptFiles);$this->ignoreMask=self::wildcards2re($this->ignoreDirs);foreach($this->list
  3169. as$pair){if($pair)$this->files[$pair[0]]=$pair[1];}foreach(array_unique($this->scanDirs)as$dir){$this->scanDirectory($dir);}$this->files=NULL;return$this->list;}function
  3170. getIndexedClasses(){$res=array();foreach($this->list
  3171. as$class=>$pair){if($pair)$res[$class]=$pair[0];}return$res;}function
  3172. addDirectory($path){foreach((array)$path
  3173. as$val){$real=realpath($val);if($real===FALSE){throw
  3174. new
  3175. DirectoryNotFoundException("Directory '$val' not found.");}$this->scanDirs[]=$real;}}private
  3176. function
  3177. addClass($class,$file,$time){$class=strtolower($class);if(!empty($this->list[$class])&&$this->list[$class][0]!==$file){spl_autoload_call($class);throw
  3178. new
  3179. InvalidStateException("Ambiguous class '$class' resolution; defined in $file and in ".$this->list[$class][0].".");}$this->list[$class]=array($file,$time);}private
  3180. function
  3181. scanDirectory($dir){if(is_file($dir)){if(!isset($this->files[$dir])||$this->files[$dir]!==filemtime($dir)){$this->scanScript($dir);}return;}$iterator=dir($dir);if(!$iterator)return;$disallow=array();if(is_file($dir.'/netterobots.txt')){foreach(file($dir.'/netterobots.txt')as$s){if($matches=String::match($s,'#^disallow\\s*:\\s*(\\S+)#i')){$disallow[trim($matches[1],'/')]=TRUE;}}if(isset($disallow['']))return;}while(FALSE!==($entry=$iterator->read())){if($entry=='.'||$entry=='..'||isset($disallow[$entry]))continue;$path=$dir.DIRECTORY_SEPARATOR.$entry;if(is_dir($path)){if(!String::match($entry,$this->ignoreMask)){$this->scanDirectory($path);}continue;}if(is_file($path)&&String::match($entry,$this->acceptMask)){if(!isset($this->files[$path])||$this->files[$path]!==filemtime($path)){$this->scanScript($path);}}}$iterator->close();}private
  3182. function
  3183. scanScript($file){$T_NAMESPACE=PHP_VERSION_ID<50300?-1:T_NAMESPACE;$T_NS_SEPARATOR=PHP_VERSION_ID<50300?-1:T_NS_SEPARATOR;$expected=FALSE;$namespace='';$level=0;$time=filemtime($file);$s=file_get_contents($file);if($matches=String::match($s,'#//nette'.'loader=(\S*)#')){foreach(explode(',',$matches[1])as$name){$this->addClass($name,$file,$time);}return;}foreach(token_get_all($s)as$token){if(is_array($token)){switch($token[0]){case
  3184. T_COMMENT:case
  3185. T_DOC_COMMENT:case
  3186. T_WHITESPACE:continue
  3187. 2;case$T_NS_SEPARATOR:case
  3188. T_STRING:if($expected){$name.=$token[1];}continue
  3189. 2;case$T_NAMESPACE:case
  3190. T_CLASS:case
  3191. T_INTERFACE:$expected=$token[0];$name='';continue
  3192. 2;case
  3193. T_CURLY_OPEN:case
  3194. T_DOLLAR_OPEN_CURLY_BRACES:$level++;}}if($expected){switch($expected){case
  3195. T_CLASS:case
  3196. T_INTERFACE:if($level===0){$this->addClass($namespace.$name,$file,$time);}break;case$T_NAMESPACE:$namespace=$name.'\\';}$expected=NULL;}if($token==='{'){$level++;}elseif($token==='}'){$level--;}}}private
  3197. static
  3198. function
  3199. wildcards2re($wildcards){$mask=array();foreach(explode(',',$wildcards)as$wildcard){$wildcard=trim($wildcard);$wildcard=addcslashes($wildcard,'.\\+[^]$(){}=!><|:#');$wildcard=strtr($wildcard,array('*'=>'.*','?'=>'.'));$mask[]=$wildcard;}return'#^('.implode('|',$mask).')$#i';}protected
  3200. function
  3201. getCache(){return
  3202. Environment::getCache('Nette.RobotLoader');}protected
  3203. function
  3204. getKey(){return
  3205. md5("v2|$this->ignoreDirs|$this->acceptFiles|".implode('|',$this->scanDirs));}protected
  3206. function
  3207. isProduction(){return
  3208. Environment::isProduction();}}class
  3209. MailMimePart
  3210. extends
  3211. Object{const
  3212. ENCODING_BASE64='base64';const
  3213. ENCODING_7BIT='7bit';const
  3214. ENCODING_8BIT='8bit';const
  3215. ENCODING_QUOTED_PRINTABLE='quoted-printable';const
  3216. EOL="\r\n";const
  3217. LINE_LENGTH=76;private$headers=array();private$parts=array();private$body;function
  3218. setHeader($name,$value,$append=FALSE){if(!$name||preg_match('#[^a-z0-9-]#i',$name)){throw
  3219. new
  3220. InvalidArgumentException("Header name must be non-empty alphanumeric string, '$name' given.");}if($value==NULL){if(!$append){unset($this->headers[$name]);}}elseif(is_array($value)){$tmp=&$this->headers[$name];if(!$append||!is_array($tmp)){$tmp=array();}foreach($value
  3221. as$email=>$name){if($name!==NULL&&!String::checkEncoding($name)){throw
  3222. new
  3223. InvalidArgumentException("Name is not valid UTF-8 string.");}if(!preg_match('#^[^@",\s]+@[^@",\s]+\.[a-z]{2,10}$#i',$email)){throw
  3224. new
  3225. InvalidArgumentException("Email address '$email' is not valid.");}if(preg_match('#[\r\n]#',$name)){throw
  3226. new
  3227. InvalidArgumentException("Name cannot contain the line separator.");}$tmp[$email]=$name;}}else{$value=(string)$value;if(!String::checkEncoding($value)){throw
  3228. new
  3229. InvalidArgumentException("Header is not valid UTF-8 string.");}$this->headers[$name]=preg_replace('#[\r\n]+#',' ',$value);}return$this;}function
  3230. getHeader($name){return
  3231. isset($this->headers[$name])?$this->headers[$name]:NULL;}function
  3232. clearHeader($name){unset($this->headers[$name]);return$this;}function
  3233. getEncodedHeader($name){$offset=strlen($name)+2;if(!isset($this->headers[$name])){return
  3234. NULL;}elseif(is_array($this->headers[$name])){$s='';foreach($this->headers[$name]as$email=>$name){if($name!=NULL){$s.=self::encodeHeader(strspn($name,'.,;<@>()[]"=?')?'"'.addcslashes($name,'"\\').'"':$name,$offset);$email=" <$email>";}$email.=',';if($s!==''&&$offset+strlen($email)>self::LINE_LENGTH){$s.=self::EOL."\t";$offset=1;}$s.=$email;$offset+=strlen($email);}return
  3235. substr($s,0,-1);}else{return
  3236. self::encodeHeader($this->headers[$name],$offset);}}function
  3237. getHeaders(){return$this->headers;}function
  3238. setContentType($contentType,$charset=NULL){$this->setHeader('Content-Type',$contentType.($charset?"; charset=$charset":''));return$this;}function
  3239. setEncoding($encoding){$this->setHeader('Content-Transfer-Encoding',$encoding);return$this;}function
  3240. getEncoding(){return$this->getHeader('Content-Transfer-Encoding');}function
  3241. addPart(MailMimePart$part=NULL){return$this->parts[]=$part===NULL?new
  3242. self:$part;}function
  3243. setBody($body){$this->body=$body;return$this;}function
  3244. getBody(){return$this->body;}function
  3245. generateMessage(){$output='';$boundary='--------'.md5(uniqid('',TRUE));foreach($this->headers
  3246. as$name=>$value){$output.=$name.': '.$this->getEncodedHeader($name);if($this->parts&&$name==='Content-Type'){$output.=';'.self::EOL."\tboundary=\"$boundary\"";}$output.=self::EOL;}$output.=self::EOL;$body=(string)$this->body;if($body!==''){switch($this->getEncoding()){case
  3247. self::ENCODING_QUOTED_PRINTABLE:$output.=function_exists('quoted_printable_encode')?quoted_printable_encode($body):self::encodeQuotedPrintable($body);break;case
  3248. self::ENCODING_BASE64:$output.=rtrim(chunk_split(base64_encode($body),self::LINE_LENGTH,self::EOL));break;case
  3249. self::ENCODING_7BIT:$body=preg_replace('#[\x80-\xFF]+#','',$body);case
  3250. self::ENCODING_8BIT:$body=str_replace(array("\x00","\r"),'',$body);$body=str_replace("\n",self::EOL,$body);$output.=$body;break;default:throw
  3251. new
  3252. InvalidStateException('Unknown encoding');}}if($this->parts){if(substr($output,-strlen(self::EOL))!==self::EOL)$output.=self::EOL;foreach($this->parts
  3253. as$part){$output.='--'.$boundary.self::EOL.$part->generateMessage().self::EOL;}$output.='--'.$boundary.'--';}return$output;}private
  3254. static
  3255. function
  3256. encodeHeader($s,&$offset=0){if(strspn($s,"!\"#$%&\'()*+,-./0123456789:;<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz{|}=? _\r\n\t")===strlen($s)&&($offset+strlen($s)<=self::LINE_LENGTH)){$offset+=strlen($s);return$s;}$o=str_replace("\n ","\n\t",substr(iconv_mime_encode(str_repeat(' ',$offset),$s,array('scheme'=>'B','input-charset'=>'UTF-8','output-charset'=>'UTF-8')),$offset+2));$offset=strlen($o)-strrpos($o,"\n");return$o;}static
  3257. function
  3258. encodeQuotedPrintable($s){$range='!"#$%&\'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}';$pos=0;$len=0;$o='';$size=strlen($s);while($pos<$size){if($l=strspn($s,$range,$pos)){while($len+$l>self::LINE_LENGTH-1){$lx=self::LINE_LENGTH-$len-1;$o.=substr($s,$pos,$lx).'='.self::EOL;$pos+=$lx;$l-=$lx;$len=0;}$o.=substr($s,$pos,$l);$len+=$l;$pos+=$l;}else{$len+=3;if($len>self::LINE_LENGTH-1){$o.='='.self::EOL;$len=3;}$o.='='.strtoupper(bin2hex($s[$pos]));$pos++;}}return
  3259. rtrim($o,'='.self::EOL);}}class
  3260. Mail
  3261. extends
  3262. MailMimePart{const
  3263. HIGH=1;const
  3264. NORMAL=3;const
  3265. LOW=5;public
  3266. static$defaultMailer='SendmailMailer';public
  3267. static$defaultHeaders=array('MIME-Version'=>'1.0','X-Mailer'=>'Nette Framework');private$mailer;private$attachments=array();private$inlines=array();private$html;private$basePath;function
  3268. __construct(){foreach(self::$defaultHeaders
  3269. as$name=>$value){$this->setHeader($name,$value);}$this->setHeader('Date',date('r'));}function
  3270. setFrom($email,$name=NULL){$this->setHeader('From',$this->formatEmail($email,$name));return$this;}function
  3271. getFrom(){return$this->getHeader('From');}function
  3272. addReplyTo($email,$name=NULL){$this->setHeader('Reply-To',$this->formatEmail($email,$name),TRUE);return$this;}function
  3273. setSubject($subject){$this->setHeader('Subject',$subject);return$this;}function
  3274. getSubject(){return$this->getHeader('Subject');}function
  3275. addTo($email,$name=NULL){$this->setHeader('To',$this->formatEmail($email,$name),TRUE);return$this;}function
  3276. addCc($email,$name=NULL){$this->setHeader('Cc',$this->formatEmail($email,$name),TRUE);return$this;}function
  3277. addBcc($email,$name=NULL){$this->setHeader('Bcc',$this->formatEmail($email,$name),TRUE);return$this;}private
  3278. function
  3279. formatEmail($email,$name){if(!$name&&preg_match('#^(.+) +<(.*)>$#',$email,$matches)){return
  3280. array($matches[2]=>$matches[1]);}else{return
  3281. array($email=>$name);}}function
  3282. setReturnPath($email){$this->setHeader('Return-Path',$email);return$this;}function
  3283. getReturnPath(){return$this->getHeader('From');}function
  3284. setPriority($priority){$this->setHeader('X-Priority',(int)$priority);return$this;}function
  3285. getPriority(){return$this->getHeader('X-Priority');}function
  3286. setHtmlBody($html,$basePath=NULL){$this->html=$html;$this->basePath=$basePath;return$this;}function
  3287. getHtmlBody(){return$this->html;}function
  3288. addEmbeddedFile($file,$content=NULL,$contentType=NULL){$part=new
  3289. MailMimePart;$part->setBody($content===NULL?$this->readFile($file,$contentType):(string)$content);$part->setContentType($contentType?$contentType:'application/octet-stream');$part->setEncoding(self::ENCODING_BASE64);$part->setHeader('Content-Disposition','inline; filename="'.String::fixEncoding(basename($file)).'"');$part->setHeader('Content-ID','<'.md5(uniqid('',TRUE)).'>');return$this->inlines[$file]=$part;}function
  3290. addAttachment($file,$content=NULL,$contentType=NULL){$part=new
  3291. MailMimePart;$part->setBody($content===NULL?$this->readFile($file,$contentType):(string)$content);$part->setContentType($contentType?$contentType:'application/octet-stream');$part->setEncoding(self::ENCODING_BASE64);$part->setHeader('Content-Disposition','attachment; filename="'.String::fixEncoding(basename($file)).'"');return$this->attachments[]=$part;}private
  3292. function
  3293. readFile($file,&$contentType){if(!is_file($file)){throw
  3294. new
  3295. FileNotFoundException("File '$file' not found.");}if(!$contentType&&$info=getimagesize($file)){$contentType=$info['mime'];}return
  3296. file_get_contents($file);}function
  3297. send(){$this->getMailer()->send($this->build());}function
  3298. setMailer(IMailer$mailer){$this->mailer=$mailer;return$this;}function
  3299. getMailer(){if($this->mailer===NULL){if($a=strrpos(self::$defaultMailer,'\\'))self::$defaultMailer=substr(self::$defaultMailer,$a+1);$this->mailer=is_object(self::$defaultMailer)?self::$defaultMailer:new
  3300. self::$defaultMailer;}return$this->mailer;}protected
  3301. function
  3302. build(){$mail=clone$this;$hostname=isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost');$mail->setHeader('Message-ID','<'.md5(uniqid('',TRUE))."@$hostname>");$mail->buildHtml();$mail->buildText();$cursor=$mail;if($mail->attachments){$tmp=$cursor->setContentType('multipart/mixed');$cursor=$cursor->addPart();foreach($mail->attachments
  3303. as$value){$tmp->addPart($value);}}if($mail->html!=NULL){$tmp=$cursor->setContentType('multipart/alternative');$cursor=$cursor->addPart();$alt=$tmp->addPart();if($mail->inlines){$tmp=$alt->setContentType('multipart/related');$alt=$alt->addPart();foreach($mail->inlines
  3304. as$name=>$value){$tmp->addPart($value);}}$alt->setContentType('text/html','UTF-8')->setEncoding(preg_match('#[\x80-\xFF]#',$mail->html)?self::ENCODING_8BIT:self::ENCODING_7BIT)->setBody($mail->html);}$text=$mail->getBody();$mail->setBody(NULL);$cursor->setContentType('text/plain','UTF-8')->setEncoding(preg_match('#[\x80-\xFF]#',$text)?self::ENCODING_8BIT:self::ENCODING_7BIT)->setBody($text);return$mail;}protected
  3305. function
  3306. buildHtml(){if($this->html
  3307. instanceof
  3308. ITemplate){$this->html->mail=$this;if($this->basePath===NULL&&$this->html
  3309. instanceof
  3310. IFileTemplate){$this->basePath=dirname($this->html->getFile());}$this->html=$this->html->__toString(TRUE);}if($this->basePath!==FALSE){$cids=array();$matches=String::matchAll($this->html,'#(src\s*=\s*|background\s*=\s*|url\()(["\'])(?![a-z]+:|[/\\#])(.+?)\\2#i',PREG_OFFSET_CAPTURE);foreach(array_reverse($matches)as$m){$file=rtrim($this->basePath,'/\\').'/'.$m[3][0];$cid=isset($cids[$file])?$cids[$file]:$cids[$file]=substr($this->addEmbeddedFile($file)->getHeader("Content-ID"),1,-1);$this->html=substr_replace($this->html,"{$m[1][0]}{$m[2][0]}cid:$cid{$m[2][0]}",$m[0][1],strlen($m[0][0]));}}if(!$this->getSubject()&&$matches=String::match($this->html,'#<title>(.+?)</title>#is')){$this->setSubject(html_entity_decode($matches[1],ENT_QUOTES,'UTF-8'));}}protected
  3311. function
  3312. buildText(){$text=$this->getBody();if($text
  3313. instanceof
  3314. ITemplate){$text->mail=$this;$this->setBody($text->__toString(TRUE));}elseif($text==NULL&&$this->html!=NULL){$text=String::replace($this->html,array('#<(style|script|head).*</\\1>#Uis'=>'','#<t[dh][ >]#i'=>" $0",'#[ \t\r\n]+#'=>' ','#<(/?p|/?h\d|li|br|/tr)[ >]#i'=>"\n$0"));$text=html_entity_decode(strip_tags($text),ENT_QUOTES,'UTF-8');$this->setBody(trim($text));}}}class
  3315. SendmailMailer
  3316. extends
  3317. Object
  3318. implements
  3319. IMailer{function
  3320. send(Mail$mail){$tmp=clone$mail;$tmp->setHeader('Subject',NULL);$tmp->setHeader('To',NULL);$parts=explode(Mail::EOL.Mail::EOL,$tmp->generateMessage(),2);Tools::tryError();$res=mail(str_replace(Mail::EOL,PHP_EOL,$mail->getEncodedHeader('To')),str_replace(Mail::EOL,PHP_EOL,$mail->getEncodedHeader('Subject')),str_replace(Mail::EOL,PHP_EOL,$parts[1]),str_replace(Mail::EOL,PHP_EOL,$parts[0]));if(Tools::catchError($msg)){throw
  3321. new
  3322. InvalidStateException($msg);}elseif(!$res){throw
  3323. new
  3324. InvalidStateException('Unable to send email.');}}}class
  3325. Annotation
  3326. extends
  3327. Object
  3328. implements
  3329. IAnnotation{function
  3330. __construct(array$values){foreach($values
  3331. as$k=>$v){$this->$k=$v;}}function
  3332. __toString(){return$this->value;}}/**
  3333. * Annotations support for PHP.
  3334. *
  3335. * @copyright Copyright (c) 2004, 2010 David Grudl
  3336. * @package Nette\Reflection
  3337. * @Annotation
  3338. */final
  3339. class
  3340. AnnotationsParser{const
  3341. RE_STRING='\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';const
  3342. RE_IDENTIFIER='[_a-zA-Z\x7F-\xFF][_a-zA-Z0-9\x7F-\xFF]*';public
  3343. static$useReflection;private
  3344. static$cache;private
  3345. static$timestamps;final
  3346. function
  3347. __construct(){throw
  3348. new
  3349. LogicException("Cannot instantiate static class ".get_class($this));}static
  3350. function
  3351. getAll(Reflector$r){if($r
  3352. instanceof
  3353. ReflectionClass){$type=$r->getName();$member='';}elseif($r
  3354. instanceof
  3355. ReflectionMethod){$type=$r->getDeclaringClass()->getName();$member=$r->getName();}else{$type=$r->getDeclaringClass()->getName();$member='$'.$r->getName();}if(!self::$useReflection){$file=$r
  3356. instanceof
  3357. ReflectionClass?$r->getFileName():$r->getDeclaringClass()->getFileName();if($file&&isset(self::$timestamps[$file])&&self::$timestamps[$file]!==filemtime($file)){unset(self::$cache[$type]);}unset(self::$timestamps[$file]);}if(isset(self::$cache[$type][$member])){return
  3358. self::$cache[$type][$member];}if(self::$useReflection===NULL){self::$useReflection=(bool)ClassReflection::from(__CLASS__)->getDocComment();}if(self::$useReflection){return
  3359. self::$cache[$type][$member]=self::parseComment($r->getDocComment());}else{if(self::$cache===NULL){self::$cache=(array)self::getCache()->offsetGet('list');self::$timestamps=isset(self::$cache['*'])?self::$cache['*']:array();}if(!isset(self::$cache[$type])&&$file){self::$cache['*'][$file]=filemtime($file);self::parseScript($file);self::getCache()->save('list',self::$cache);}if(isset(self::$cache[$type][$member])){return
  3360. self::$cache[$type][$member];}else{return
  3361. self::$cache[$type][$member]=array();}}}private
  3362. static
  3363. function
  3364. parseComment($comment){static$tokens=array('true'=>TRUE,'false'=>FALSE,'null'=>NULL,''=>TRUE);$matches=String::matchAll(trim($comment,'/*'),'~
  3365. @('.self::RE_IDENTIFIER.')[ \t]* ## annotation
  3366. (
  3367. \((?>'.self::RE_STRING.'|[^\'")@]+)+\)| ## (value)
  3368. [^(@\r\n][^@\r\n]*|) ## value
  3369. ~xi');$res=array();foreach($matches
  3370. as$match){list(,$name,$value)=$match;if(substr($value,0,1)==='('){$items=array();$key='';$val=TRUE;$value[0]=',';while($m=String::match($value,'#\s*,\s*(?>('.self::RE_IDENTIFIER.')\s*=\s*)?('.self::RE_STRING.'|[^\'"),\s][^\'"),]*)#A')){$value=substr($value,strlen($m[0]));list(,$key,$val)=$m;if($val[0]==="'"||$val[0]==='"'){$val=substr($val,1,-1);}elseif(is_numeric($val)){$val=1*$val;}else{$lval=strtolower($val);$val=array_key_exists($lval,$tokens)?$tokens[$lval]:$val;}if($key===''){$items[]=$val;}else{$items[$key]=$val;}}$value=count($items)<2&&$key===''?$val:$items;}else{$value=trim($value);if(is_numeric($value)){$value=1*$value;}else{$lval=strtolower($value);$value=array_key_exists($lval,$tokens)?$tokens[$lval]:$value;}}$class=$name.'Annotation';if(class_exists($class)){$res[$name][]=new$class(is_array($value)?$value:array('value'=>$value));}else{$res[$name][]=is_array($value)?new
  3371. ArrayObject($value,ArrayObject::ARRAY_AS_PROPS):$value;}}return$res;}private
  3372. static
  3373. function
  3374. parseScript($file){$T_NAMESPACE=PHP_VERSION_ID<50300?-1:T_NAMESPACE;$T_NS_SEPARATOR=PHP_VERSION_ID<50300?-1:T_NS_SEPARATOR;$s=file_get_contents($file);if(String::match($s,'#//nette'.'loader=(\S*)#')){return;}$expected=$namespace=$class=$docComment=NULL;$level=$classLevel=0;foreach(token_get_all($s)as$token){if(is_array($token)){switch($token[0]){case
  3375. T_DOC_COMMENT:$docComment=$token[1];case
  3376. T_WHITESPACE:case
  3377. T_COMMENT:continue
  3378. 2;case
  3379. T_STRING:case$T_NS_SEPARATOR:case
  3380. T_VARIABLE:if($expected){$name.=$token[1];}continue
  3381. 2;case
  3382. T_FUNCTION:case
  3383. T_VAR:case
  3384. T_PUBLIC:case
  3385. T_PROTECTED:case$T_NAMESPACE:case
  3386. T_CLASS:case
  3387. T_INTERFACE:$expected=$token[0];$name=NULL;continue
  3388. 2;case
  3389. T_STATIC:case
  3390. T_ABSTRACT:case
  3391. T_FINAL:continue
  3392. 2;case
  3393. T_CURLY_OPEN:case
  3394. T_DOLLAR_OPEN_CURLY_BRACES:$level++;}}if($expected){switch($expected){case
  3395. T_CLASS:case
  3396. T_INTERFACE:$class=$namespace.$name;$classLevel=$level;$name='';case
  3397. T_FUNCTION:if($token==='&')continue
  3398. 2;case
  3399. T_VAR:case
  3400. T_PUBLIC:case
  3401. T_PROTECTED:if($class&&$name!==NULL&&$docComment){self::$cache[$class][$name]=self::parseComment($docComment);}break;case$T_NAMESPACE:$namespace=$name.'\\';}$expected=$docComment=NULL;}if($token===';'){$docComment=NULL;}elseif($token==='{'){$docComment=NULL;$level++;}elseif($token==='}'){$level--;if($level===$classLevel){$class=NULL;}}}}protected
  3402. static
  3403. function
  3404. getCache(){return
  3405. Environment::getCache('Nette.Annotations');}}class
  3406. ExtensionReflection
  3407. extends
  3408. ReflectionExtension{function
  3409. __toString(){return'Extension '.$this->getName();}static
  3410. function
  3411. import(ReflectionExtension$ref){return
  3412. new
  3413. self($ref->getName());}function
  3414. getClasses(){return
  3415. array_map(array('ClassReflection','import'),parent::getClasses());}function
  3416. getFunctions(){return
  3417. array_map(array('FunctionReflection','import'),parent::getFunctions());}function
  3418. getReflection(){return
  3419. new
  3420. ClassReflection($this);}function
  3421. __call($name,$args){return
  3422. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3423. ObjectMixin::get($this,$name);}function
  3424. __set($name,$value){return
  3425. ObjectMixin::set($this,$name,$value);}function
  3426. __isset($name){return
  3427. ObjectMixin::has($this,$name);}function
  3428. __unset($name){throw
  3429. new
  3430. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3431. FunctionReflection
  3432. extends
  3433. ReflectionFunction{function
  3434. __toString(){return'Function '.$this->getName().'()';}static
  3435. function
  3436. import(ReflectionFunction$ref){return
  3437. new
  3438. self($ref->getName());}function
  3439. getExtension(){return($ref=parent::getExtension())?ExtensionReflection::import($ref):NULL;}function
  3440. getParameters(){return
  3441. array_map(array('MethodParameterReflection','import'),parent::getParameters());}function
  3442. getReflection(){return
  3443. new
  3444. ClassReflection($this);}function
  3445. __call($name,$args){return
  3446. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3447. ObjectMixin::get($this,$name);}function
  3448. __set($name,$value){return
  3449. ObjectMixin::set($this,$name,$value);}function
  3450. __isset($name){return
  3451. ObjectMixin::has($this,$name);}function
  3452. __unset($name){throw
  3453. new
  3454. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3455. MethodParameterReflection
  3456. extends
  3457. ReflectionParameter{static
  3458. function
  3459. import(ReflectionParameter$ref){$method=$ref->getDeclaringFunction();return
  3460. new
  3461. self($method
  3462. instanceof
  3463. ReflectionMethod?array($ref->getDeclaringClass()->getName(),$method->getName()):$method->getName(),$ref->getName());}function
  3464. getClass(){return($ref=parent::getClass())?ClassReflection::import($ref):NULL;}function
  3465. getDeclaringClass(){return($ref=parent::getDeclaringClass())?ClassReflection::import($ref):NULL;}function
  3466. getDeclaringFunction(){return($ref=parent::getDeclaringFunction())instanceof
  3467. ReflectionMethod?MethodReflection::import($ref):FunctionReflection::import($ref);}function
  3468. getReflection(){return
  3469. new
  3470. ClassReflection($this);}function
  3471. __call($name,$args){return
  3472. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3473. ObjectMixin::get($this,$name);}function
  3474. __set($name,$value){return
  3475. ObjectMixin::set($this,$name,$value);}function
  3476. __isset($name){return
  3477. ObjectMixin::has($this,$name);}function
  3478. __unset($name){throw
  3479. new
  3480. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3481. MethodReflection
  3482. extends
  3483. ReflectionMethod{static
  3484. function
  3485. from($class,$method){return
  3486. new
  3487. self(is_object($class)?get_class($class):$class,$method);}function
  3488. getDefaultParameters(){$res=array();foreach(parent::getParameters()as$param){$res[$param->getName()]=$param->isDefaultValueAvailable()?$param->getDefaultValue():NULL;if($param->isArray()){settype($res[$param->getName()],'array');}}return$res;}function
  3489. invokeNamedArgs($object,$args){$res=array();$i=0;foreach($this->getDefaultParameters()as$name=>$def){if(isset($args[$name])){$val=$args[$name];if($def!==NULL){settype($val,gettype($def));}$res[$i++]=$val;}else{$res[$i++]=$def;}}return$this->invokeArgs($object,$res);}function
  3490. getCallback(){return
  3491. new
  3492. Callback(parent::getDeclaringClass()->getName(),$this->getName());}function
  3493. __toString(){return'Method '.parent::getDeclaringClass()->getName().'::'.$this->getName().'()';}static
  3494. function
  3495. import(ReflectionMethod$ref){return
  3496. new
  3497. self($ref->getDeclaringClass()->getName(),$ref->getName());}function
  3498. getDeclaringClass(){return
  3499. ClassReflection::import(parent::getDeclaringClass());}function
  3500. getExtension(){return($ref=parent::getExtension())?ExtensionReflection::import($ref):NULL;}function
  3501. getParameters(){return
  3502. array_map(array('MethodParameterReflection','import'),parent::getParameters());}function
  3503. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  3504. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  3505. isset($res[$name])?end($res[$name]):NULL;}function
  3506. getAnnotations(){return
  3507. AnnotationsParser::getAll($this);}function
  3508. getReflection(){return
  3509. new
  3510. ClassReflection($this);}function
  3511. __call($name,$args){return
  3512. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3513. ObjectMixin::get($this,$name);}function
  3514. __set($name,$value){return
  3515. ObjectMixin::set($this,$name,$value);}function
  3516. __isset($name){return
  3517. ObjectMixin::has($this,$name);}function
  3518. __unset($name){throw
  3519. new
  3520. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3521. PropertyReflection
  3522. extends
  3523. ReflectionProperty{function
  3524. __toString(){return'Property '.parent::getDeclaringClass()->getName().'::$'.$this->getName();}static
  3525. function
  3526. import(ReflectionProperty$ref){return
  3527. new
  3528. self($ref->getDeclaringClass()->getName(),$ref->getName());}function
  3529. getDeclaringClass(){return
  3530. ClassReflection::import(parent::getDeclaringClass());}function
  3531. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  3532. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  3533. isset($res[$name])?end($res[$name]):NULL;}function
  3534. getAnnotations(){return
  3535. AnnotationsParser::getAll($this);}function
  3536. getReflection(){return
  3537. new
  3538. ClassReflection($this);}function
  3539. __call($name,$args){return
  3540. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3541. ObjectMixin::get($this,$name);}function
  3542. __set($name,$value){return
  3543. ObjectMixin::set($this,$name,$value);}function
  3544. __isset($name){return
  3545. ObjectMixin::has($this,$name);}function
  3546. __unset($name){throw
  3547. new
  3548. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3549. AuthenticationException
  3550. extends
  3551. Exception{}class
  3552. Identity
  3553. extends
  3554. FreezableObject
  3555. implements
  3556. IIdentity{private$id;private$roles;private$data;function
  3557. __construct($id,$roles=NULL,$data=NULL){$this->setId($id);$this->setRoles((array)$roles);$this->data=$data
  3558. instanceof
  3559. Traversable?iterator_to_array($data):(array)$data;}function
  3560. setId($id){$this->updating();$this->id=is_numeric($id)?1*$id:$id;return$this;}function
  3561. getId(){return$this->id;}function
  3562. setRoles(array$roles){$this->updating();$this->roles=$roles;return$this;}function
  3563. getRoles(){return$this->roles;}function
  3564. getData(){return$this->data;}function
  3565. __set($key,$value){$this->updating();if(parent::__isset($key)){parent::__set($key,$value);}else{$this->data[$key]=$value;}}function&__get($key){if(parent::__isset($key)){return
  3566. parent::__get($key);}else{return$this->data[$key];}}function
  3567. __isset($key){return
  3568. isset($this->data[$key])||parent::__isset($key);}function
  3569. __unset($name){throw
  3570. new
  3571. MemberAccessException("Cannot unset the property {$this->reflection->name}::\$$name.");}}class
  3572. Permission
  3573. extends
  3574. Object
  3575. implements
  3576. IAuthorizator{private$roles=array();private$resources=array();private$rules=array('allResources'=>array('allRoles'=>array('allPrivileges'=>array('type'=>self::DENY,'assert'=>NULL),'byPrivilege'=>array()),'byRole'=>array()),'byResource'=>array());private$queriedRole,$queriedResource;function
  3577. addRole($role,$parents=NULL){$this->checkRole($role,FALSE);if(isset($this->roles[$role])){throw
  3578. new
  3579. InvalidStateException("Role '$role' already exists in the list.");}$roleParents=array();if($parents!==NULL){if(!is_array($parents)){$parents=array($parents);}foreach($parents
  3580. as$parent){$this->checkRole($parent);$roleParents[$parent]=TRUE;$this->roles[$parent]['children'][$role]=TRUE;}}$this->roles[$role]=array('parents'=>$roleParents,'children'=>array());return$this;}function
  3581. hasRole($role){$this->checkRole($role,FALSE);return
  3582. isset($this->roles[$role]);}private
  3583. function
  3584. checkRole($role,$need=TRUE){if(!is_string($role)||$role===''){throw
  3585. new
  3586. InvalidArgumentException("Role must be a non-empty string.");}elseif($need&&!isset($this->roles[$role])){throw
  3587. new
  3588. InvalidStateException("Role '$role' does not exist.");}}function
  3589. getRoleParents($role){$this->checkRole($role);return
  3590. array_keys($this->roles[$role]['parents']);}function
  3591. roleInheritsFrom($role,$inherit,$onlyParents=FALSE){$this->checkRole($role);$this->checkRole($inherit);$inherits=isset($this->roles[$role]['parents'][$inherit]);if($inherits||$onlyParents){return$inherits;}foreach($this->roles[$role]['parents']as$parent=>$foo){if($this->roleInheritsFrom($parent,$inherit)){return
  3592. TRUE;}}return
  3593. FALSE;}function
  3594. removeRole($role){$this->checkRole($role);foreach($this->roles[$role]['children']as$child=>$foo)unset($this->roles[$child]['parents'][$role]);foreach($this->roles[$role]['parents']as$parent=>$foo)unset($this->roles[$parent]['children'][$role]);unset($this->roles[$role]);foreach($this->rules['allResources']['byRole']as$roleCurrent=>$rules){if($role===$roleCurrent){unset($this->rules['allResources']['byRole'][$roleCurrent]);}}foreach($this->rules['byResource']as$resourceCurrent=>$visitor){if(isset($visitor['byRole'])){foreach($visitor['byRole']as$roleCurrent=>$rules){if($role===$roleCurrent){unset($this->rules['byResource'][$resourceCurrent]['byRole'][$roleCurrent]);}}}}return$this;}function
  3595. removeAllRoles(){$this->roles=array();foreach($this->rules['allResources']['byRole']as$roleCurrent=>$rules)unset($this->rules['allResources']['byRole'][$roleCurrent]);foreach($this->rules['byResource']as$resourceCurrent=>$visitor){foreach($visitor['byRole']as$roleCurrent=>$rules){unset($this->rules['byResource'][$resourceCurrent]['byRole'][$roleCurrent]);}}return$this;}function
  3596. addResource($resource,$parent=NULL){$this->checkResource($resource,FALSE);if(isset($this->resources[$resource])){throw
  3597. new
  3598. InvalidStateException("Resource '$resource' already exists in the list.");}if($parent!==NULL){$this->checkResource($parent);$this->resources[$parent]['children'][$resource]=TRUE;}$this->resources[$resource]=array('parent'=>$parent,'children'=>array());return$this;}function
  3599. hasResource($resource){$this->checkResource($resource,FALSE);return
  3600. isset($this->resources[$resource]);}private
  3601. function
  3602. checkResource($resource,$need=TRUE){if(!is_string($resource)||$resource===''){throw
  3603. new
  3604. InvalidArgumentException("Resource must be a non-empty string.");}elseif($need&&!isset($this->resources[$resource])){throw
  3605. new
  3606. InvalidStateException("Resource '$resource' does not exist.");}}function
  3607. resourceInheritsFrom($resource,$inherit,$onlyParent=FALSE){$this->checkResource($resource);$this->checkResource($inherit);if($this->resources[$resource]['parent']===NULL){return
  3608. FALSE;}$parent=$this->resources[$resource]['parent'];if($inherit===$parent){return
  3609. TRUE;}elseif($onlyParent){return
  3610. FALSE;}while($this->resources[$parent]['parent']!==NULL){$parent=$this->resources[$parent]['parent'];if($inherit===$parent){return
  3611. TRUE;}}return
  3612. FALSE;}function
  3613. removeResource($resource){$this->checkResource($resource);$parent=$this->resources[$resource]['parent'];if($parent!==NULL){unset($this->resources[$parent]['children'][$resource]);}$removed=array($resource);foreach($this->resources[$resource]['children']as$child=>$foo){$this->removeResource($child);$removed[]=$child;}foreach($removed
  3614. as$resourceRemoved){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resourceRemoved===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}unset($this->resources[$resource]);return$this;}function
  3615. removeAllResources(){foreach($this->resources
  3616. as$resource=>$foo){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resource===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}$this->resources=array();return$this;}function
  3617. allow($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=NULL){$this->setRule(TRUE,self::ALLOW,$roles,$resources,$privileges,$assertion);return$this;}function
  3618. deny($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=NULL){$this->setRule(TRUE,self::DENY,$roles,$resources,$privileges,$assertion);return$this;}function
  3619. removeAllow($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL){$this->setRule(FALSE,self::ALLOW,$roles,$resources,$privileges);return$this;}function
  3620. removeDeny($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL){$this->setRule(FALSE,self::DENY,$roles,$resources,$privileges);return$this;}protected
  3621. function
  3622. setRule($toAdd,$type,$roles,$resources,$privileges,$assertion=NULL){if($roles===self::ALL){$roles=array(self::ALL);}else{if(!is_array($roles)){$roles=array($roles);}foreach($roles
  3623. as$role){$this->checkRole($role);}}if($resources===self::ALL){$resources=array(self::ALL);}else{if(!is_array($resources)){$resources=array($resources);}foreach($resources
  3624. as$resource){$this->checkResource($resource);}}if($privileges===self::ALL){$privileges=array();}elseif(!is_array($privileges)){$privileges=array($privileges);}$assertion=$assertion?callback($assertion):NULL;if($toAdd){foreach($resources
  3625. as$resource){foreach($roles
  3626. as$role){$rules=&$this->getRules($resource,$role,TRUE);if(count($privileges)===0){$rules['allPrivileges']['type']=$type;$rules['allPrivileges']['assert']=$assertion;if(!isset($rules['byPrivilege'])){$rules['byPrivilege']=array();}}else{foreach($privileges
  3627. as$privilege){$rules['byPrivilege'][$privilege]['type']=$type;$rules['byPrivilege'][$privilege]['assert']=$assertion;}}}}}else{foreach($resources
  3628. as$resource){foreach($roles
  3629. as$role){$rules=&$this->getRules($resource,$role);if($rules===NULL){continue;}if(count($privileges)===0){if($resource===self::ALL&&$role===self::ALL){if($type===$rules['allPrivileges']['type']){$rules=array('allPrivileges'=>array('type'=>self::DENY,'assert'=>NULL),'byPrivilege'=>array());}continue;}if($type===$rules['allPrivileges']['type']){unset($rules['allPrivileges']);}}else{foreach($privileges
  3630. as$privilege){if(isset($rules['byPrivilege'][$privilege])&&$type===$rules['byPrivilege'][$privilege]['type']){unset($rules['byPrivilege'][$privilege]);}}}}}}return$this;}function
  3631. isAllowed($role=self::ALL,$resource=self::ALL,$privilege=self::ALL){$this->queriedRole=$role;if($role!==self::ALL){if($role
  3632. instanceof
  3633. IRole){$role=$role->getRoleId();}$this->checkRole($role);}$this->queriedResource=$resource;if($resource!==self::ALL){if($resource
  3634. instanceof
  3635. IResource){$resource=$resource->getResourceId();}$this->checkResource($resource);}if($privilege===self::ALL){do{if($role!==NULL&&NULL!==($result=$this->roleDFSAllPrivileges($role,$resource))){break;}if(NULL!==($rules=$this->getRules($resource,self::ALL))){foreach($rules['byPrivilege']as$privilege=>$rule){if(self::DENY===($ruleTypeOnePrivilege=$this->getRuleType($resource,NULL,$privilege))){$result=self::DENY;break
  3636. 2;}}if(NULL!==($ruleTypeAllPrivileges=$this->getRuleType($resource,NULL,NULL))){$result=self::ALLOW===$ruleTypeAllPrivileges;break;}}$resource=$this->resources[$resource]['parent'];}while(TRUE);}else{do{if($role!==NULL&&NULL!==($result=$this->roleDFSOnePrivilege($role,$resource,$privilege))){break;}if(NULL!==($ruleType=$this->getRuleType($resource,NULL,$privilege))){$result=self::ALLOW===$ruleType;break;}elseif(NULL!==($ruleTypeAllPrivileges=$this->getRuleType($resource,NULL,NULL))){$result=self::ALLOW===$ruleTypeAllPrivileges;break;}$resource=$this->resources[$resource]['parent'];}while(TRUE);}$this->queriedRole=$this->queriedResource=NULL;return$result;}function
  3637. getQueriedRole(){return$this->queriedRole;}function
  3638. getQueriedResource(){return$this->queriedResource;}private
  3639. function
  3640. roleDFSAllPrivileges($role,$resource){$dfs=array('visited'=>array(),'stack'=>array($role));while(NULL!==($role=array_pop($dfs['stack']))){if(!isset($dfs['visited'][$role])){if(NULL!==($result=$this->roleDFSVisitAllPrivileges($role,$resource,$dfs))){return$result;}}}return
  3641. NULL;}private
  3642. function
  3643. roleDFSVisitAllPrivileges($role,$resource,&$dfs){if(NULL!==($rules=$this->getRules($resource,$role))){foreach($rules['byPrivilege']as$privilege=>$rule){if(self::DENY===$this->getRuleType($resource,$role,$privilege)){return
  3644. self::DENY;}}if(NULL!==($type=$this->getRuleType($resource,$role,NULL))){return
  3645. self::ALLOW===$type;}}$dfs['visited'][$role]=TRUE;foreach($this->roles[$role]['parents']as$roleParent=>$foo){$dfs['stack'][]=$roleParent;}return
  3646. NULL;}private
  3647. function
  3648. roleDFSOnePrivilege($role,$resource,$privilege){$dfs=array('visited'=>array(),'stack'=>array($role));while(NULL!==($role=array_pop($dfs['stack']))){if(!isset($dfs['visited'][$role])){if(NULL!==($result=$this->roleDFSVisitOnePrivilege($role,$resource,$privilege,$dfs))){return$result;}}}return
  3649. NULL;}private
  3650. function
  3651. roleDFSVisitOnePrivilege($role,$resource,$privilege,&$dfs){if(NULL!==($type=$this->getRuleType($resource,$role,$privilege))){return
  3652. self::ALLOW===$type;}if(NULL!==($type=$this->getRuleType($resource,$role,NULL))){return
  3653. self::ALLOW===$type;}$dfs['visited'][$role]=TRUE;foreach($this->roles[$role]['parents']as$roleParent=>$foo)$dfs['stack'][]=$roleParent;return
  3654. NULL;}private
  3655. function
  3656. getRuleType($resource,$role,$privilege){if(NULL===($rules=$this->getRules($resource,$role))){return
  3657. NULL;}if($privilege===self::ALL){if(isset($rules['allPrivileges'])){$rule=$rules['allPrivileges'];}else{return
  3658. NULL;}}elseif(!isset($rules['byPrivilege'][$privilege])){return
  3659. NULL;}else{$rule=$rules['byPrivilege'][$privilege];}if($rule['assert']===NULL||$rule['assert']->__invoke($this,$role,$resource,$privilege)){return$rule['type'];}elseif($resource!==self::ALL||$role!==self::ALL||$privilege!==self::ALL){return
  3660. NULL;}elseif(self::ALLOW===$rule['type']){return
  3661. self::DENY;}else{return
  3662. self::ALLOW;}}private
  3663. function&getRules($resource,$role,$create=FALSE){if($resource===self::ALL){$visitor=&$this->rules['allResources'];}else{if(!isset($this->rules['byResource'][$resource])){if(!$create){$null=NULL;return$null;}$this->rules['byResource'][$resource]=array();}$visitor=&$this->rules['byResource'][$resource];}if($role===self::ALL){if(!isset($visitor['allRoles'])){if(!$create){$null=NULL;return$null;}$visitor['allRoles']['byPrivilege']=array();}return$visitor['allRoles'];}if(!isset($visitor['byRole'][$role])){if(!$create){$null=NULL;return$null;}$visitor['byRole'][$role]['byPrivilege']=array();}return$visitor['byRole'][$role];}}class
  3664. SimpleAuthenticator
  3665. extends
  3666. Object
  3667. implements
  3668. IAuthenticator{private$userlist;function
  3669. __construct(array$userlist){$this->userlist=$userlist;}function
  3670. authenticate(array$credentials){$username=$credentials[self::USERNAME];foreach($this->userlist
  3671. as$name=>$pass){if(strcasecmp($name,$credentials[self::USERNAME])===0){if(strcasecmp($pass,$credentials[self::PASSWORD])===0){return
  3672. new
  3673. Identity($name);}throw
  3674. new
  3675. AuthenticationException("Invalid password.",self::INVALID_CREDENTIAL);}}throw
  3676. new
  3677. AuthenticationException("User '$username' not found.",self::IDENTITY_NOT_FOUND);}}abstract
  3678. class
  3679. BaseTemplate
  3680. extends
  3681. Object
  3682. implements
  3683. ITemplate{public$warnOnUndefined=TRUE;public$onPrepareFilters=array();private$params=array();private$filters=array();private$helpers=array();private$helperLoaders=array();function
  3684. registerFilter($callback){$callback=callback($callback);if(in_array($callback,$this->filters)){throw
  3685. new
  3686. InvalidStateException("Filter '$callback' was registered twice.");}$this->filters[]=$callback;}final
  3687. function
  3688. getFilters(){return$this->filters;}function
  3689. render(){}function
  3690. __toString(){ob_start();try{$this->render();return
  3691. ob_get_clean();}catch(Exception$e){ob_end_clean();if(func_num_args()&&func_get_arg(0)){throw$e;}else{Debug::toStringException($e);}}}protected
  3692. function
  3693. compile($content,$label=NULL){if(!$this->filters){$this->onPrepareFilters($this);}try{foreach($this->filters
  3694. as$filter){$content=self::extractPhp($content,$blocks);$content=$filter->invoke($content);$content=strtr($content,$blocks);}}catch(Exception$e){throw
  3695. new
  3696. InvalidStateException("Filter $filter: ".$e->getMessage().($label?" (in $label)":''),0,$e);}if($label){$content="<?php\n// $label\n//\n?>$content";}return
  3697. self::optimizePhp($content);}function
  3698. registerHelper($name,$callback){$this->helpers[strtolower($name)]=callback($callback);}function
  3699. registerHelperLoader($callback){$this->helperLoaders[]=callback($callback);}final
  3700. function
  3701. getHelpers(){return$this->helpers;}function
  3702. __call($name,$args){$lname=strtolower($name);if(!isset($this->helpers[$lname])){foreach($this->helperLoaders
  3703. as$loader){$helper=$loader->invoke($lname);if($helper){$this->registerHelper($lname,$helper);return$this->helpers[$lname]->invokeArgs($args);}}return
  3704. parent::__call($name,$args);}return$this->helpers[$lname]->invokeArgs($args);}function
  3705. setTranslator(ITranslator$translator=NULL){$this->registerHelper('translate',$translator===NULL?NULL:array($translator,'translate'));return$this;}function
  3706. add($name,$value){if(array_key_exists($name,$this->params)){throw
  3707. new
  3708. InvalidStateException("The variable '$name' exists yet.");}$this->params[$name]=$value;}function
  3709. setParams(array$params){$this->params=$params;return$this;}function
  3710. getParams(){return$this->params;}function
  3711. __set($name,$value){$this->params[$name]=$value;}function&__get($name){if($this->warnOnUndefined&&!array_key_exists($name,$this->params)){trigger_error("The variable '$name' does not exist in template.",E_USER_NOTICE);}return$this->params[$name];}function
  3712. __isset($name){return
  3713. isset($this->params[$name]);}function
  3714. __unset($name){unset($this->params[$name]);}private
  3715. static
  3716. function
  3717. extractPhp($source,&$blocks){$res='';$blocks=array();$tokens=token_get_all($source);foreach($tokens
  3718. as$n=>$token){if(is_array($token)){if($token[0]===T_INLINE_HTML){$res.=$token[1];continue;}elseif($token[0]===T_OPEN_TAG&&$token[1]==='<?'&&isset($tokens[$n+1][1])&&$tokens[$n+1][1]==='xml'){$php=&$res;$token[1]='<<?php ?>?';}elseif($token[0]===T_OPEN_TAG||$token[0]===T_OPEN_TAG_WITH_ECHO){$res.=$id="\x01@php:p".count($blocks)."@\x02";$php=&$blocks[$id];}$php.=$token[1];}else{$php.=$token;}}return$res;}static
  3719. function
  3720. optimizePhp($source){$res=$php='';$lastChar=';';$tokens=new
  3721. ArrayIterator(token_get_all($source));foreach($tokens
  3722. as$key=>$token){if(is_array($token)){if($token[0]===T_INLINE_HTML){$lastChar='';$res.=$token[1];}elseif($token[0]===T_CLOSE_TAG){$next=isset($tokens[$key+1])?$tokens[$key+1]:NULL;if(substr($res,-1)!=='<'&&preg_match('#^<\?php\s*$#',$php)){$php='';}elseif(is_array($next)&&$next[0]===T_OPEN_TAG){if($lastChar!==';'&&$lastChar!=='{'&&$lastChar!=='}'&&$lastChar!==':'&&$lastChar!=='/')$php.=$lastChar=';';if(substr($next[1],-1)==="\n")$php.="\n";$tokens->next();}elseif($next){$res.=preg_replace('#;?(\s)*$#','$1',$php).$token[1];$php='';}else{if($lastChar!=='}'&&$lastChar!==';')$php.=';';}}elseif($token[0]===T_ELSE||$token[0]===T_ELSEIF){if($tokens[$key+1]===':'&&$lastChar==='}')$php.=';';$lastChar='';$php.=$token[1];}else{if(!in_array($token[0],array(T_WHITESPACE,T_COMMENT,T_DOC_COMMENT,T_OPEN_TAG)))$lastChar='';$php.=$token[1];}}else{$php.=$lastChar=$token;}}return$res.$php;}}class
  3723. CachingHelper
  3724. extends
  3725. Object{private$frame;private$key;static
  3726. function
  3727. create($key,$file,$tags){$cache=self::getCache();if(isset($cache[$key])){echo$cache[$key];return
  3728. FALSE;}else{$obj=new
  3729. self;$obj->key=$key;$obj->frame=array(Cache::FILES=>array($file),Cache::TAGS=>$tags,Cache::EXPIRE=>rand(86400*4,86400*7));ob_start();return$obj;}}function
  3730. save(){$this->getCache()->save($this->key,ob_get_flush(),$this->frame);$this->key=$this->frame=NULL;}function
  3731. addFile($file){$this->frame[Cache::FILES][]=$file;}function
  3732. addItem($item){$this->frame[Cache::ITEMS][]=$item;}protected
  3733. static
  3734. function
  3735. getCache(){return
  3736. Environment::getCache('Nette.Template.Curly');}}class
  3737. LatteFilter
  3738. extends
  3739. Object{const
  3740. RE_STRING='\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';const
  3741. RE_IDENTIFIER='[_a-zA-Z\x7F-\xFF][_a-zA-Z0-9\x7F-\xFF]*';const
  3742. HTML_PREFIX='n:';private$handler;private$macroRe;private$input,$output;private$offset;private$quote;private$tags;public$context,$escape;const
  3743. CONTEXT_TEXT='text';const
  3744. CONTEXT_CDATA='cdata';const
  3745. CONTEXT_TAG='tag';const
  3746. CONTEXT_ATTRIBUTE='attribute';const
  3747. CONTEXT_NONE='none';const
  3748. CONTEXT_COMMENT='comment';function
  3749. setHandler($handler){$this->handler=$handler;return$this;}function
  3750. getHandler(){if($this->handler===NULL){$this->handler=new
  3751. LatteMacros;}return$this->handler;}function
  3752. __invoke($s){if(!$this->macroRe){$this->setDelimiters('\\{(?![\\s\'"{}])','\\}');}$this->context=LatteFilter::CONTEXT_NONE;$this->escape='$template->escape';$this->getHandler()->initialize($this,$s);$s=$this->parse("\n".$s);$this->getHandler()->finalize($s);return$s;}private
  3753. function
  3754. parse($s){$this->input=&$s;$this->offset=0;$this->output='';$this->tags=array();$len=strlen($s);while($this->offset<$len){$matches=$this->{"context$this->context"}();if(!$matches){break;}elseif(!empty($matches['macro'])){list(,$macro,$value,$modifiers)=String::match($matches['macro'],'#^(/?[a-z]+)?(.*?)(\\|[a-z](?:'.self::RE_STRING.'|[^\'"]+)*)?$()#is');$code=$this->handler->macro($macro,trim($value),isset($modifiers)?$modifiers:'');if($code===NULL){throw
  3755. new
  3756. InvalidStateException("Unknown macro {{$matches['macro']}} on line $this->line.");}$nl=isset($matches['newline'])?"\n":'';if($nl&&$matches['indent']&&strncmp($code,'<?php echo ',11)){$this->output.="\n".$code;}else{$this->output.=$matches['indent'].$code.(substr($code,-2)==='?>'?$nl:'');}}else{$this->output.=$matches[0];}}foreach($this->tags
  3757. as$tag){if(!$tag->isMacro&&!empty($tag->attrs)){throw
  3758. new
  3759. InvalidStateException("Missing end tag </$tag->name> for macro-attribute ".self::HTML_PREFIX.implode(' and '.self::HTML_PREFIX,array_keys($tag->attrs)).".");}}return$this->output.substr($this->input,$this->offset);}private
  3760. function
  3761. contextText(){$matches=$this->match('~
  3762. (?:\n[ \t]*)?<(?P<closing>/?)(?P<tag>[a-z0-9:]+)| ## begin of HTML tag <tag </tag - ignores <!DOCTYPE
  3763. <(?P<comment>!--)| ## begin of HTML comment <!--
  3764. '.$this->macroRe.' ## curly tag
  3765. ~xsi');if(!$matches||!empty($matches['macro'])){}elseif(!empty($matches['comment'])){$this->context=self::CONTEXT_COMMENT;$this->escape='TemplateHelpers::escapeHtmlComment';}elseif(empty($matches['closing'])){$tag=$this->tags[]=(object)NULL;$tag->name=$matches['tag'];$tag->closing=FALSE;$tag->isMacro=String::startsWith($tag->name,self::HTML_PREFIX);$tag->attrs=array();$tag->pos=strlen($this->output);$this->context=self::CONTEXT_TAG;$this->escape='TemplateHelpers::escapeHtml';}else{do{$tag=array_pop($this->tags);if(!$tag){$tag=(object)NULL;$tag->name=$matches['tag'];$tag->isMacro=String::startsWith($tag->name,self::HTML_PREFIX);}}while(strcasecmp($tag->name,$matches['tag']));$this->tags[]=$tag;$tag->closing=TRUE;$tag->pos=strlen($this->output);$this->context=self::CONTEXT_TAG;$this->escape='TemplateHelpers::escapeHtml';}return$matches;}private
  3766. function
  3767. contextCData(){$tag=end($this->tags);$matches=$this->match('~
  3768. </'.$tag->name.'(?![a-z0-9:])| ## end HTML tag </tag
  3769. '.$this->macroRe.' ## curly tag
  3770. ~xsi');if($matches&&empty($matches['macro'])){$tag->closing=TRUE;$tag->pos=strlen($this->output);$this->context=self::CONTEXT_TAG;$this->escape='TemplateHelpers::escapeHtml';}return$matches;}private
  3771. function
  3772. contextTag(){$matches=$this->match('~
  3773. (?P<end>\ ?/?>)(?P<tagnewline>[\ \t]*(?=\r|\n))?| ## end of HTML tag
  3774. '.$this->macroRe.'| ## curly tag
  3775. \s*(?P<attr>[^\s/>={]+)(?:\s*=\s*(?P<value>["\']|[^\s/>{]+))? ## begin of HTML attribute
  3776. ~xsi');if(!$matches||!empty($matches['macro'])){}elseif(!empty($matches['end'])){$tag=end($this->tags);$isEmpty=!$tag->closing&&(strpos($matches['end'],'/')!==FALSE||isset(Html::$emptyElements[strtolower($tag->name)]));if($isEmpty){$matches[0]=(Html::$xhtml?' />':'>').(isset($matches['tagnewline'])?$matches['tagnewline']:'');}if($tag->isMacro||!empty($tag->attrs)){if($tag->isMacro){$code=$this->handler->tagMacro(substr($tag->name,strlen(self::HTML_PREFIX)),$tag->attrs,$tag->closing);if($code===NULL){throw
  3777. new
  3778. InvalidStateException("Unknown tag-macro <$tag->name> on line $this->line.");}if($isEmpty){$code.=$this->handler->tagMacro(substr($tag->name,strlen(self::HTML_PREFIX)),$tag->attrs,TRUE);}}else{$code=substr($this->output,$tag->pos).$matches[0].(isset($matches['tagnewline'])?"\n":'');$code=$this->handler->attrsMacro($code,$tag->attrs,$tag->closing);if($code===NULL){throw
  3779. new
  3780. InvalidStateException("Unknown macro-attribute ".self::HTML_PREFIX.implode(' or '.self::HTML_PREFIX,array_keys($tag->attrs))." on line $this->line.");}if($isEmpty){$code=$this->handler->attrsMacro($code,$tag->attrs,TRUE);}}$this->output=substr_replace($this->output,$code,$tag->pos);$matches[0]='';}if($isEmpty){$tag->closing=TRUE;}if(!$tag->closing&&(strcasecmp($tag->name,'script')===0||strcasecmp($tag->name,'style')===0)){$this->context=self::CONTEXT_CDATA;$this->escape=strcasecmp($tag->name,'style')?'TemplateHelpers::escapeJs':'TemplateHelpers::escapeCss';}else{$this->context=self::CONTEXT_TEXT;$this->escape='TemplateHelpers::escapeHtml';if($tag->closing)array_pop($this->tags);}}else{$name=$matches['attr'];$value=empty($matches['value'])?TRUE:$matches['value'];if($isSpecial=String::startsWith($name,self::HTML_PREFIX)){$name=substr($name,strlen(self::HTML_PREFIX));}$tag=end($this->tags);if($isSpecial||$tag->isMacro){if($value==='"'||$value==="'"){if($matches=$this->match('~(.*?)'.$value.'~xsi')){$value=$matches[1];}}$tag->attrs[$name]=$value;$matches[0]='';}elseif($value==='"'||$value==="'"){$this->context=self::CONTEXT_ATTRIBUTE;$this->quote=$value;$this->escape=strncasecmp($name,'on',2)?(strcasecmp($name,'style')?'TemplateHelpers::escapeHtml':'TemplateHelpers::escapeHtmlCss'):'TemplateHelpers::escapeHtmlJs';}}return$matches;}private
  3781. function
  3782. contextAttribute(){$matches=$this->match('~
  3783. ('.$this->quote.')| ## 1) end of HTML attribute
  3784. '.$this->macroRe.' ## curly tag
  3785. ~xsi');if($matches&&empty($matches['macro'])){$this->context=self::CONTEXT_TAG;$this->escape='TemplateHelpers::escapeHtml';}return$matches;}private
  3786. function
  3787. contextComment(){$matches=$this->match('~
  3788. (--\s*>)| ## 1) end of HTML comment
  3789. '.$this->macroRe.' ## curly tag
  3790. ~xsi');if($matches&&empty($matches['macro'])){$this->context=self::CONTEXT_TEXT;$this->escape='TemplateHelpers::escapeHtml';}return$matches;}private
  3791. function
  3792. contextNone(){$matches=$this->match('~
  3793. '.$this->macroRe.' ## curly tag
  3794. ~xsi');return$matches;}private
  3795. function
  3796. match($re){if($matches=String::match($this->input,$re,PREG_OFFSET_CAPTURE,$this->offset)){$this->output.=substr($this->input,$this->offset,$matches[0][1]-$this->offset);$this->offset=$matches[0][1]+strlen($matches[0][0]);foreach($matches
  3797. as$k=>$v)$matches[$k]=$v[0];}return$matches;}function
  3798. getLine(){return
  3799. substr_count($this->input,"\n",0,$this->offset);}function
  3800. setDelimiters($left,$right){$this->macroRe='
  3801. (?P<indent>\n[\ \t]*)?
  3802. '.$left.'
  3803. (?P<macro>(?:'.self::RE_STRING.'|[^\'"]+?)*?)
  3804. '.$right.'
  3805. (?P<newline>[\ \t]*(?=\r|\n))?
  3806. ';return$this;}static
  3807. function
  3808. formatModifiers($var,$modifiers){if(!$modifiers)return$var;$tokens=String::matchAll($modifiers.'|','~
  3809. '.self::RE_STRING.'| ## single or double quoted string
  3810. [^\'"|:,\s]+| ## symbol
  3811. [|:,] ## separator
  3812. ~xs',PREG_PATTERN_ORDER);$inside=FALSE;$prev='';foreach($tokens[0]as$token){if($token==='|'||$token===':'||$token===','){if($prev===''){}elseif(!$inside){if(!String::match($prev,'#^'.self::RE_IDENTIFIER.'$#')){throw
  3813. new
  3814. InvalidStateException("Modifier name must be alphanumeric string, '$prev' given.");}$var="\$template->$prev($var";$prev='';$inside=TRUE;}else{$var.=', '.self::formatString($prev);$prev='';}if($token==='|'&&$inside){$var.=')';$inside=FALSE;}}else{$prev.=$token;}}return$var;}static
  3815. function
  3816. fetchToken(&$s){if($matches=String::match($s,'#^((?>'.self::RE_STRING.'|[^\'"\s,]+)+)\s*,?\s*(.*)$#')){$s=$matches[2];return$matches[1];}return
  3817. NULL;}static
  3818. function
  3819. formatArray($s,$prefix=''){$s=String::replace(trim($s),'~
  3820. '.self::RE_STRING.'| ## single or double quoted string
  3821. (?<=[,=(]|=>|^)\s*([a-z\d_]+)(?=\s*[,=)]|$) ## 1) symbol
  3822. ~xi',callback(__CLASS__,'cbArgs'));$s=String::replace($s,'#\$('.self::RE_IDENTIFIER.')\s*=>#','"$1" =>');return$s===''?'':$prefix."array($s)";}static
  3823. function
  3824. cbArgs($matches){if(!empty($matches[1])){list(,$symbol)=$matches;static$keywords=array('true'=>1,'false'=>1,'null'=>1,'and'=>1,'or'=>1,'xor'=>1,'clone'=>1,'new'=>1);return
  3825. is_numeric($symbol)||isset($keywords[strtolower($symbol)])?$matches[0]:"'$symbol'";}else{return$matches[0];}}static
  3826. function
  3827. formatString($s){static$keywords=array('true'=>1,'false'=>1,'null'=>1);return(is_numeric($s)||strspn($s,'\'"$')||isset($keywords[strtolower($s)]))?$s:'"'.$s.'"';}}class
  3828. LatteMacros
  3829. extends
  3830. Object{public
  3831. static$defaultMacros=array('syntax'=>'%:macroSyntax%','/syntax'=>'%:macroSyntax%','block'=>'<?php %:macroBlock% ?>','/block'=>'<?php %:macroBlockEnd% ?>','capture'=>'<?php %:macroCapture% ?>','/capture'=>'<?php %:macroCaptureEnd% ?>','snippet'=>'<?php %:macroSnippet% ?>','/snippet'=>'<?php %:macroSnippetEnd% ?>','cache'=>'<?php if ($_cb->foo = CachingHelper::create($_cb->key = md5(__FILE__) . __LINE__, $template->getFile(), array(%%))) { $_cb->caches[] = $_cb->foo ?>','/cache'=>'<?php array_pop($_cb->caches)->save(); } if (!empty($_cb->caches)) end($_cb->caches)->addItem($_cb->key) ?>','if'=>'<?php if (%%): ?>','elseif'=>'<?php elseif (%%): ?>','else'=>'<?php else: ?>','/if'=>'<?php endif ?>','ifset'=>'<?php if (isset(%%)): ?>','/ifset'=>'<?php endif ?>','elseifset'=>'<?php elseif (isset(%%)): ?>','foreach'=>'<?php foreach (%:macroForeach%): ?>','/foreach'=>'<?php endforeach; array_pop($_cb->its); $iterator = end($_cb->its) ?>','for'=>'<?php for (%%): ?>','/for'=>'<?php endfor ?>','while'=>'<?php while (%%): ?>','/while'=>'<?php endwhile ?>','continueIf'=>'<?php if (%%) continue ?>','breakIf'=>'<?php if (%%) break ?>','include'=>'<?php %:macroInclude% ?>','extends'=>'<?php %:macroExtends% ?>','layout'=>'<?php %:macroExtends% ?>','plink'=>'<?php echo %:macroEscape%(%:macroPlink%) ?>','link'=>'<?php echo %:macroEscape%(%:macroLink%) ?>','ifCurrent'=>'<?php %:macroIfCurrent%; if ($presenter->getLastCreatedRequestFlag("current")): ?>','widget'=>'<?php %:macroWidget% ?>','control'=>'<?php %:macroWidget% ?>','attr'=>'<?php echo Html::el(NULL)->%:macroAttr%attributes() ?>','contentType'=>'<?php %:macroContentType% ?>','status'=>'<?php Environment::getHttpResponse()->setCode(%%) ?>','var'=>'<?php %:macroAssign% ?>','assign'=>'<?php %:macroAssign% ?>','default'=>'<?php %:macroDefault% ?>','dump'=>'<?php Debug::barDump(%:macroDump%, "Template " . str_replace(Environment::getVariable("appDir"), "\xE2\x80\xA6", $template->getFile())) ?>','debugbreak'=>'<?php if (function_exists("debugbreak")) debugbreak(); elseif (function_exists("xdebug_break")) xdebug_break() ?>','!_'=>'<?php echo %:macroTranslate% ?>','_'=>'<?php echo %:macroEscape%(%:macroTranslate%) ?>','!='=>'<?php echo %:macroModifiers% ?>','='=>'<?php echo %:macroEscape%(%:macroModifiers%) ?>','!$'=>'<?php echo %:macroVar% ?>','$'=>'<?php echo %:macroEscape%(%:macroVar%) ?>','?'=>'<?php %:macroModifiers% ?>');public$macros;private$filter;private$current;private$blocks=array();private$namedBlocks=array();private$extends;private$uniq;private$oldSnippetMode=TRUE;const
  3832. BLOCK_NAMED=1;const
  3833. BLOCK_CAPTURE=2;const
  3834. BLOCK_ANONYMOUS=3;function
  3835. __construct(){$this->macros=self::$defaultMacros;}function
  3836. initialize($filter,&$s){$this->filter=$filter;$this->blocks=array();$this->namedBlocks=array();$this->extends=NULL;$this->uniq=substr(md5(uniqid('',TRUE)),0,10);$filter->context=LatteFilter::CONTEXT_TEXT;$filter->escape='TemplateHelpers::escapeHtml';$s=String::replace($s,'#\\{\\*.*?\\*\\}[\r\n]*#s','');$s=String::replace($s,'#@(\\{[^}]+?\\})#s','<?php } ?>$1<?php if (SnippetHelper::$outputAllowed) { ?>');}function
  3837. finalize(&$s){if(count($this->blocks)===1){$s.=$this->macro('/block','','');}elseif($this->blocks){throw
  3838. new
  3839. InvalidStateException("There are some unclosed blocks.");}$s="<?php\nif (".'SnippetHelper::$outputAllowed'.") {\n?>$s<?php\n}\n?>";if($this->namedBlocks||$this->extends){$s="<?php\n".'if ($_cb->extends) { ob_start(); }'."\n".'elseif (isset($presenter, $control) && $presenter->isAjax()) { LatteMacros::renderSnippets($control, $_cb, get_defined_vars()); }'."\n".'?>'.$s."<?php\n".'if ($_cb->extends) { ob_end_clean(); LatteMacros::includeTemplate($_cb->extends, get_defined_vars(), $template)->render(); }'."\n";}else{$s="<?php\n".'if (isset($presenter, $control) && $presenter->isAjax()) { LatteMacros::renderSnippets($control, $_cb, get_defined_vars()); }'."\n".'?>'.$s;}if($this->namedBlocks){foreach(array_reverse($this->namedBlocks,TRUE)as$name=>$foo){$name=preg_quote($name,'#');$s=String::replace($s,"#{block ($name)} \?>(.*)<\?php {/block $name}#sU",callback($this,'cbNamedBlocks'));}$s="<?php\n\n".implode("\n\n\n",$this->namedBlocks)."\n\n//\n// end of blocks\n//\n?>".$s;}$s="<?php\n".'$_cb = LatteMacros::initRuntime($template, '.var_export($this->extends,TRUE).', '.var_export($this->uniq,TRUE)."); unset(\$_extends);\n".'?>'.$s;}function
  3840. macro($macro,$content,$modifiers){if($macro===''){$macro=substr($content,0,2);if(!isset($this->macros[$macro])){$macro=substr($content,0,1);if(!isset($this->macros[$macro])){return
  3841. NULL;}}$content=substr($content,strlen($macro));}elseif(!isset($this->macros[$macro])){return
  3842. NULL;}$this->current=array($content,$modifiers);return
  3843. String::replace($this->macros[$macro],'#%(.*?)%#',callback($this,'cbMacro'));}function
  3844. cbMacro($m){list($content,$modifiers)=$this->current;if($m[1]){return
  3845. callback($m[1][0]===':'?array($this,substr($m[1],1)):$m[1])->invoke($content,$modifiers);}else{return$content;}}function
  3846. tagMacro($name,$attrs,$closing){$knownTags=array('include'=>'block','for'=>'each','block'=>'name','if'=>'cond','elseif'=>'cond');return$this->macro($closing?"/$name":$name,isset($knownTags[$name],$attrs[$knownTags[$name]])?$attrs[$knownTags[$name]]:substr(var_export($attrs,TRUE),8,-1),isset($attrs['modifiers'])?$attrs['modifiers']:'');}function
  3847. attrsMacro($code,$attrs,$closing){$left=$right='';foreach($this->macros
  3848. as$name=>$foo){if(!isset($this->macros["/$name"])){continue;}$macro=$closing?"/$name":$name;if(isset($attrs[$name])){if($closing){$right.=$this->macro($macro,'','');}else{$left=$this->macro($macro,$attrs[$name],'').$left;}}$innerName="inner-$name";if(isset($attrs[$innerName])){if($closing){$left.=$this->macro($macro,'','');}else{$right=$this->macro($macro,$attrs[$innerName],'').$right;}}$tagName="tag-$name";if(isset($attrs[$tagName])){$left=$this->macro($name,$attrs[$tagName],'').$left;$right.=$this->macro("/$name",'','');}unset($attrs[$name],$attrs[$innerName],$attrs[$tagName]);}return$attrs?NULL:$left.$code.$right;}function
  3849. macroVar($var,$modifiers){return
  3850. LatteFilter::formatModifiers('$'.$var,$modifiers);}function
  3851. macroTranslate($var,$modifiers){return
  3852. LatteFilter::formatModifiers($var,'translate|'.$modifiers);}function
  3853. macroSyntax($var){switch($var){case'':case'latte':$this->filter->setDelimiters('\\{(?![\\s\'"{}])','\\}');break;case'double':$this->filter->setDelimiters('\\{\\{(?![\\s\'"{}])','\\}\\}');break;case'asp':$this->filter->setDelimiters('<%\s*','\s*%>');break;case'python':$this->filter->setDelimiters('\\{[{%]\s*','\s*[%}]\\}');break;case'off':$this->filter->setDelimiters('[^\x00-\xFF]','');break;default:throw
  3854. new
  3855. InvalidStateException("Unknown macro syntax '$var' on line {$this->filter->line}.");}}function
  3856. macroInclude($content,$modifiers,$isDefinition=FALSE){$destination=LatteFilter::fetchToken($content);$params=LatteFilter::formatArray($content).($content?' + ':'');if($destination===NULL){throw
  3857. new
  3858. InvalidStateException("Missing destination in {include} on line {$this->filter->line}.");}elseif($destination[0]==='#'){$destination=ltrim($destination,'#');if(!String::match($destination,'#^'.LatteFilter::RE_IDENTIFIER.'$#')){throw
  3859. new
  3860. InvalidStateException("Included block name must be alphanumeric string, '$destination' given on line {$this->filter->line}.");}$parent=$destination==='parent';if($destination==='parent'||$destination==='this'){$item=end($this->blocks);while($item&&$item[0]!==self::BLOCK_NAMED)$item=prev($this->blocks);if(!$item){throw
  3861. new
  3862. InvalidStateException("Cannot include $destination block outside of any block on line {$this->filter->line}.");}$destination=$item[1];}$name=var_export($destination,TRUE);$params.=$isDefinition?'get_defined_vars()':'$template->getParams()';$cmd=isset($this->namedBlocks[$destination])&&!$parent?"call_user_func(reset(\$_cb->blocks[$name]), \$_cb, $params)":'LatteMacros::callBlock'.($parent?'Parent':'')."(\$_cb, $name, $params)";return$modifiers?"ob_start(); $cmd; echo ".LatteFilter::formatModifiers('ob_get_clean()',$modifiers):$cmd;}else{$destination=LatteFilter::formatString($destination);$params.='$template->getParams()';return$modifiers?'echo '.LatteFilter::formatModifiers('LatteMacros::includeTemplate'."($destination, $params, \$_cb->templates[".var_export($this->uniq,TRUE).'])->__toString(TRUE)',$modifiers):'LatteMacros::includeTemplate'."($destination, $params, \$_cb->templates[".var_export($this->uniq,TRUE).'])->render()';}}function
  3863. macroExtends($content){$destination=LatteFilter::fetchToken($content);if($destination===NULL){throw
  3864. new
  3865. InvalidStateException("Missing destination in {extends} on line {$this->filter->line}.");}if(!empty($this->blocks)){throw
  3866. new
  3867. InvalidStateException("{extends} must be placed outside any block; on line {$this->filter->line}.");}if($this->extends!==NULL){throw
  3868. new
  3869. InvalidStateException("Multiple {extends} declarations are not allowed; on line {$this->filter->line}.");}$this->extends=$destination!=='none';return$this->extends?'$_cb->extends = '.LatteFilter::formatString($destination):'';}function
  3870. macroBlock($content,$modifiers){$name=LatteFilter::fetchToken($content);if($name===NULL){$this->blocks[]=array(self::BLOCK_ANONYMOUS,NULL,$modifiers);return$modifiers===''?'':'ob_start()';}else{$name=ltrim($name,'#');if(!String::match($name,'#^'.LatteFilter::RE_IDENTIFIER.'$#')){throw
  3871. new
  3872. InvalidStateException("Block name must be alphanumeric string, '$name' given on line {$this->filter->line}.");}elseif(isset($this->namedBlocks[$name])){throw
  3873. new
  3874. InvalidStateException("Cannot redeclare block '$name'; on line {$this->filter->line}.");}$top=empty($this->blocks);$this->namedBlocks[$name]=$name;$this->blocks[]=array(self::BLOCK_NAMED,$name,'');if($name[0]==='_'){$tag=LatteFilter::fetchToken($content);$tag=trim($tag,'<>');$namePhp=var_export(substr($name,1),TRUE);if(!$tag)$tag='div';return"?><$tag id=\"<?php echo \$control->getSnippetId($namePhp) ?>\"><?php ".$this->macroInclude('#'.$name,$modifiers)." ?></$tag><?php {block $name}";}elseif(!$top){return$this->macroInclude('#'.$name,$modifiers,TRUE)."{block $name}";}elseif($this->extends){return"{block $name}";}else{return'if (!$_cb->extends) { '.$this->macroInclude('#'.$name,$modifiers,TRUE)."; } {block $name}";}}}function
  3875. macroBlockEnd($content){list($type,$name,$modifiers)=array_pop($this->blocks);if($type===self::BLOCK_CAPTURE){$this->blocks[]=array($type,$name,$modifiers);return$this->macroCaptureEnd($content);}if(($type!==self::BLOCK_NAMED&&$type!==self::BLOCK_ANONYMOUS)||($content&&$content!==$name)){throw
  3876. new
  3877. InvalidStateException("Tag {/block $content} was not expected here on line {$this->filter->line}.");}elseif($type===self::BLOCK_NAMED){return"{/block $name}";}else{return$modifiers===''?'':'echo '.LatteFilter::formatModifiers('ob_get_clean()',$modifiers);}}function
  3878. macroSnippet($content){if(substr($content,0,1)===':'||!$this->oldSnippetMode){$this->oldSnippetMode=FALSE;return$this->macroBlock('_'.ltrim($content,':'),'');}$args=array('');if($snippet=LatteFilter::fetchToken($content)){$args[]=LatteFilter::formatString($snippet);}if($content){$args[]=LatteFilter::formatString($content);}return'} if ($_cb->foo = SnippetHelper::create($control'.implode(', ',$args).')) { $_cb->snippets[] = $_cb->foo';}function
  3879. macroSnippetEnd($content){if(!$this->oldSnippetMode){return$this->macroBlockEnd('','');}return'array_pop($_cb->snippets)->finish(); } if (SnippetHelper::$outputAllowed) {';}function
  3880. macroCapture($content,$modifiers){$name=LatteFilter::fetchToken($content);if(substr($name,0,1)!=='$'){throw
  3881. new
  3882. InvalidStateException("Invalid capture block parameter '$name' on line {$this->filter->line}.");}$this->blocks[]=array(self::BLOCK_CAPTURE,$name,$modifiers);return'ob_start()';}function
  3883. macroCaptureEnd($content){list($type,$name,$modifiers)=array_pop($this->blocks);if($type!==self::BLOCK_CAPTURE||($content&&$content!==$name)){throw
  3884. new
  3885. InvalidStateException("Tag {/capture $content} was not expected here on line {$this->filter->line}.");}return$name.'='.LatteFilter::formatModifiers('ob_get_clean()',$modifiers);}function
  3886. cbNamedBlocks($matches){list(,$name,$content)=$matches;$func='_cbb'.substr(md5($this->uniq.$name),0,10).'_'.preg_replace('#[^a-z0-9_]#i','_',$name);$this->namedBlocks[$name]="//\n// block $name\n//\n"."if (!function_exists(\$_cb->blocks[".var_export($name,TRUE)."][] = '$func')) { function $func(\$_cb, \$_args) { extract(\$_args)\n?>$content<?php\n}}";return'';}function
  3887. macroForeach($content){return'$iterator = $_cb->its[] = new SmartCachingIterator('.preg_replace('# +as +#i',') as ',$content,1);}function
  3888. macroAttr($content){return
  3889. String::replace($content.' ','#\)\s+#',')->');}function
  3890. macroContentType($content){if(strpos($content,'html')!==FALSE){$this->filter->escape='TemplateHelpers::escapeHtml';$this->filter->context=LatteFilter::CONTEXT_TEXT;}elseif(strpos($content,'xml')!==FALSE){$this->filter->escape='TemplateHelpers::escapeXml';$this->filter->context=LatteFilter::CONTEXT_NONE;}elseif(strpos($content,'javascript')!==FALSE){$this->filter->escape='TemplateHelpers::escapeJs';$this->filter->context=LatteFilter::CONTEXT_NONE;}elseif(strpos($content,'css')!==FALSE){$this->filter->escape='TemplateHelpers::escapeCss';$this->filter->context=LatteFilter::CONTEXT_NONE;}elseif(strpos($content,'plain')!==FALSE){$this->filter->escape='';$this->filter->context=LatteFilter::CONTEXT_NONE;}else{$this->filter->escape='$template->escape';$this->filter->context=LatteFilter::CONTEXT_NONE;}return
  3891. strpos($content,'/')?'Environment::getHttpResponse()->setHeader("Content-Type", "'.$content.'")':'';}function
  3892. macroDump($content){return$content?"array(".var_export($content,TRUE)." => $content)":'get_defined_vars()';}function
  3893. macroWidget($content){$pair=LatteFilter::fetchToken($content);if($pair===NULL){throw
  3894. new
  3895. InvalidStateException("Missing widget name in {widget} on line {$this->filter->line}.");}$pair=explode(':',$pair,2);$widget=LatteFilter::formatString($pair[0]);$method=isset($pair[1])?ucfirst($pair[1]):'';$method=String::match($method,'#^('.LatteFilter::RE_IDENTIFIER.'|)$#')?"render$method":"{\"render$method\"}";$param=LatteFilter::formatArray($content);if(strpos($content,'=>')===FALSE)$param=substr($param,6,-1);return($widget[0]==='$'?"if (is_object($widget)) {$widget}->$method($param); else ":'')."\$control->getWidget($widget)->$method($param)";}function
  3896. macroLink($content,$modifiers){return
  3897. LatteFilter::formatModifiers('$control->link('.$this->formatLink($content).')',$modifiers);}function
  3898. macroPlink($content,$modifiers){return
  3899. LatteFilter::formatModifiers('$presenter->link('.$this->formatLink($content).')',$modifiers);}function
  3900. macroIfCurrent($content){return$content?'try { $presenter->link('.$this->formatLink($content).'); } catch (InvalidLinkException $e) {}':'';}private
  3901. function
  3902. formatLink($content){return
  3903. LatteFilter::formatString(LatteFilter::fetchToken($content)).LatteFilter::formatArray($content,', ');}function
  3904. macroAssign($content,$modifiers){if(!$content){throw
  3905. new
  3906. InvalidStateException("Missing arguments in {var} or {assign} on line {$this->filter->line}.");}if(strpos($content,'=>')===FALSE){return'$'.ltrim(LatteFilter::fetchToken($content),'$').' = '.LatteFilter::formatModifiers($content===''?'NULL':$content,$modifiers);}return'extract('.LatteFilter::formatArray($content).')';}function
  3907. macroDefault($content){if(!$content){throw
  3908. new
  3909. InvalidStateException("Missing arguments in {default} on line {$this->filter->line}.");}return'extract('.LatteFilter::formatArray($content).', EXTR_SKIP)';}function
  3910. macroEscape($content){return$this->filter->escape;}function
  3911. macroModifiers($content,$modifiers){return
  3912. LatteFilter::formatModifiers($content,$modifiers);}static
  3913. function
  3914. callBlock($context,$name,$params){if(empty($context->blocks[$name])){throw
  3915. new
  3916. InvalidStateException("Call to undefined block '$name'.");}$block=reset($context->blocks[$name]);$block($context,$params);}static
  3917. function
  3918. callBlockParent($context,$name,$params){if(empty($context->blocks[$name])||($block=next($context->blocks[$name]))===FALSE){throw
  3919. new
  3920. InvalidStateException("Call to undefined parent block '$name'.");}$block($context,$params);}static
  3921. function
  3922. includeTemplate($destination,$params,$template){if($destination
  3923. instanceof
  3924. ITemplate){$tpl=$destination;}elseif($destination==NULL){throw
  3925. new
  3926. InvalidArgumentException("Template file name was not specified.");}else{$tpl=clone$template;if($template
  3927. instanceof
  3928. IFileTemplate){if(substr($destination,0,1)!=='/'&&substr($destination,1,1)!==':'){$destination=dirname($template->getFile()).'/'.$destination;}$tpl->setFile($destination);}}$tpl->setParams($params);return$tpl;}static
  3929. function
  3930. initRuntime($template,$extends,$realFile){$cb=(object)NULL;if(isset($template->_cb)){$cb->blocks=&$template->_cb->blocks;$cb->templates=&$template->_cb->templates;}$cb->templates[$realFile]=$template;$cb->extends=is_bool($extends)?$extends:(empty($template->_extends)?FALSE:$template->_extends);unset($template->_cb,$template->_extends);if(!empty($cb->caches)){end($cb->caches)->addFile($template->getFile());}return$cb;}static
  3931. function
  3932. renderSnippets($control,$cb,$params){$payload=$control->getPresenter()->getPayload();if(isset($cb->blocks)){foreach($cb->blocks
  3933. as$name=>$function){if($name[0]!=='_'||!$control->isControlInvalid(substr($name,1)))continue;ob_start();$function=reset($function);$function($cb,$params);$payload->snippets[$control->getSnippetId(substr($name,1))]=ob_get_clean();}}}}class
  3934. SnippetHelper
  3935. extends
  3936. Object{public
  3937. static$outputAllowed=TRUE;private$id;private$tag;private$payload;private$level;static
  3938. function
  3939. create(Control$control,$name=NULL,$tag='div'){if(self::$outputAllowed){$obj=new
  3940. self;$obj->tag=trim($tag,'<>');if($obj->tag)echo'<',$obj->tag,' id="',$control->getSnippetId($name),'">';return$obj;}elseif($control->isControlInvalid($name)){$obj=new
  3941. self;$obj->id=$control->getSnippetId($name);$obj->payload=$control->getPresenter()->getPayload();ob_start();$obj->level=ob_get_level();self::$outputAllowed=TRUE;return$obj;}else{return
  3942. FALSE;}}function
  3943. finish(){if($this->tag!==NULL){if($this->tag)echo"</$this->tag>";}else{if($this->level!==ob_get_level()){throw
  3944. new
  3945. InvalidStateException("Snippet '$this->id' cannot be ended here.");}$this->payload->snippets[$this->id]=ob_get_clean();self::$outputAllowed=FALSE;}}}final
  3946. class
  3947. TemplateFilters{final
  3948. function
  3949. __construct(){throw
  3950. new
  3951. LogicException("Cannot instantiate static class ".get_class($this));}static
  3952. function
  3953. removePhp($s){return
  3954. String::replace($s,'#\x01@php:p\d+@\x02#','<?php ?>');}static
  3955. function
  3956. relativeLinks($s){return
  3957. String::replace($s,'#(src|href|action)\s*=\s*(["\'])(?![a-z]+:|[\x01/\\#])#','$1=$2<?php echo \\$baseUri ?>');}static
  3958. function
  3959. netteLinks($s){return
  3960. String::replace($s,'#(src|href|action)\s*=\s*(["\'])(nette:.*?)([\#"\'])#',callback(__CLASS__,'netteLinksCb'));}static
  3961. function
  3962. netteLinksCb($m){list(,$attr,$quote,$uri,$fragment)=$m;$parts=parse_url($uri);if(isset($parts['scheme'])&&$parts['scheme']==='nette'){return$attr.'='.$quote.'<?php echo $template->escape($control->'."link('".(isset($parts['path'])?$parts['path']:'this!').(isset($parts['query'])?'?'.$parts['query']:'').'\'))?>'.$fragment;}else{return$m[0];}}public
  3963. static$texy;static
  3964. function
  3965. texyElements($s){return
  3966. String::replace($s,'#<texy([^>]*)>(.*?)</texy>#s',callback(__CLASS__,'texyCb'));}static
  3967. function
  3968. texyCb($m){list(,$mAttrs,$mContent)=$m;$attrs=array();if($mAttrs){foreach(String::matchAll($mAttrs,'#([a-z0-9:-]+)\s*(?:=\s*(\'[^\']*\'|"[^"]*"|[^\'"\s]+))?()#isu')as$m){$key=strtolower($m[1]);$val=$m[2];if($val==NULL)$attrs[$key]=TRUE;elseif($val{0}==='\''||$val{0}==='"')$attrs[$key]=html_entity_decode(substr($val,1,-1),ENT_QUOTES,'UTF-8');else$attrs[$key]=html_entity_decode($val,ENT_QUOTES,'UTF-8');}}return
  3969. self::$texy->process($m[2]);}}final
  3970. class
  3971. TemplateHelpers{final
  3972. function
  3973. __construct(){throw
  3974. new
  3975. LogicException("Cannot instantiate static class ".get_class($this));}static
  3976. function
  3977. loader($helper){$callback=callback('TemplateHelpers',$helper);if($callback->isCallable()){return$callback;}$callback=callback('String',$helper);if($callback->isCallable()){return$callback;}}static
  3978. function
  3979. escapeHtml($s){if(is_object($s)&&($s
  3980. instanceof
  3981. ITemplate||$s
  3982. instanceof
  3983. Html||$s
  3984. instanceof
  3985. Form)){return$s->__toString(TRUE);}return
  3986. htmlSpecialChars($s,ENT_QUOTES);}static
  3987. function
  3988. escapeHtmlComment($s){return
  3989. str_replace('--','--><!--',$s);}static
  3990. function
  3991. escapeXML($s){return
  3992. htmlSpecialChars(preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]+#','',$s),ENT_QUOTES);}static
  3993. function
  3994. escapeCss($s){return
  3995. addcslashes($s,"\x00..\x2C./:;<=>?@[\\]^`{|}~");}static
  3996. function
  3997. escapeHtmlCss($s){return
  3998. htmlSpecialChars(self::escapeCss($s),ENT_QUOTES);}static
  3999. function
  4000. escapeJs($s){if(is_object($s)&&($s
  4001. instanceof
  4002. ITemplate||$s
  4003. instanceof
  4004. Html||$s
  4005. instanceof
  4006. Form)){$s=$s->__toString(TRUE);}return
  4007. str_replace(']]>',']]\x3E',json_encode($s));}static
  4008. function
  4009. escapeHtmlJs($s){return
  4010. htmlSpecialChars(self::escapeJs($s),ENT_QUOTES);}static
  4011. function
  4012. strip($s){return
  4013. String::replace($s,'#(</textarea|</pre|</script|^).*?(?=<textarea|<pre|<script|$)#si',callback(create_function('$m','return trim(preg_replace("#[ \t\r\n]+#", " ", $m[0]));')));}static
  4014. function
  4015. indent($s,$level=1,$chars="\t"){if($level>=1){$s=String::replace($s,'#<(textarea|pre).*?</\\1#si',callback(create_function('$m','return strtr($m[0], " \t\r\n", "\x1F\x1E\x1D\x1A");')));$s=String::indent($s,$level,$chars);$s=strtr($s,"\x1F\x1E\x1D\x1A"," \t\r\n");}return$s;}static
  4016. function
  4017. date($time,$format="%x"){if($time==NULL){return
  4018. NULL;}$time=Tools::createDateTime($time);return
  4019. strpos($format,'%')===FALSE?$time->format($format):strftime($format,$time->format('U'));}static
  4020. function
  4021. bytes($bytes,$precision=2){$bytes=round($bytes);$units=array('B','kB','MB','GB','TB','PB');foreach($units
  4022. as$unit){if(abs($bytes)<1024||$unit===end($units))break;$bytes=$bytes/1024;}return
  4023. round($bytes,$precision).' '.$unit;}static
  4024. function
  4025. length($var){return
  4026. is_string($var)?String::length($var):count($var);}static
  4027. function
  4028. replace($subject,$search,$replacement=''){return
  4029. str_replace($search,$replacement,$subject);}static
  4030. function
  4031. null($value){return'';}}class
  4032. Template
  4033. extends
  4034. BaseTemplate
  4035. implements
  4036. IFileTemplate{public
  4037. static$cacheExpire=FALSE;private
  4038. static$cacheStorage;private$file;function
  4039. __construct($file=NULL){if($file!==NULL){$this->setFile($file);}}function
  4040. setFile($file){if(!is_file($file)){throw
  4041. new
  4042. FileNotFoundException("Missing template file '$file'.");}$this->file=$file;return$this;}function
  4043. getFile(){return$this->file;}function
  4044. render(){if($this->file==NULL){throw
  4045. new
  4046. InvalidStateException("Template file name was not specified.");}$this->__set('template',$this);$shortName=str_replace(Environment::getVariable('appDir'),'',$this->file);$cache=new
  4047. Cache($this->getCacheStorage(),'Nette.Template');$key=trim(strtr($shortName,'\\/@','.._'),'.').'-'.md5($this->file);$cached=$content=$cache[$key];if($content===NULL){if(!$this->getFilters()){$this->onPrepareFilters($this);}if(!$this->getFilters()){LimitedScope::load($this->file,$this->getParams());return;}$content=$this->compile(file_get_contents($this->file),"file \xE2\x80\xA6$shortName");$cache->save($key,$content,array(Cache::FILES=>$this->file,Cache::EXPIRE=>self::$cacheExpire));$cache->release();$cached=$cache[$key];}if($cached!==NULL&&self::$cacheStorage
  4048. instanceof
  4049. TemplateCacheStorage){LimitedScope::load($cached['file'],$this->getParams());fclose($cached['handle']);}else{LimitedScope::evaluate($content,$this->getParams());}}static
  4050. function
  4051. setCacheStorage(ICacheStorage$storage){self::$cacheStorage=$storage;}static
  4052. function
  4053. getCacheStorage(){if(self::$cacheStorage===NULL){self::$cacheStorage=new
  4054. TemplateCacheStorage(Environment::getVariable('tempDir'));}return
  4055. self::$cacheStorage;}}class
  4056. TemplateCacheStorage
  4057. extends
  4058. FileStorage{protected
  4059. function
  4060. readData($meta){return
  4061. array('file'=>$meta[self::FILE],'handle'=>$meta[self::HANDLE]);}protected
  4062. function
  4063. getCacheFile($key){return
  4064. parent::getCacheFile($key).'.php';}}class
  4065. ArrayList
  4066. implements
  4067. ArrayAccess,Countable,IteratorAggregate{private$list=array();function
  4068. getIterator(){return
  4069. new
  4070. ArrayIterator($this->list);}function
  4071. count(){return
  4072. count($this->list);}function
  4073. offsetSet($index,$value){if($index===NULL){$this->list[]=$value;}elseif($index<0||$index>=count($this->list)){throw
  4074. new
  4075. OutOfRangeException("Offset invalid or out of range");}else{$this->list[(int)$index]=$value;}}function
  4076. offsetGet($index){if($index<0||$index>=count($this->list)){throw
  4077. new
  4078. OutOfRangeException("Offset invalid or out of range");}return$this->list[(int)$index];}function
  4079. offsetExists($index){return$index>=0&&$index<count($this->list);}function
  4080. offsetUnset($index){if($index<0||$index>=count($this->list)){throw
  4081. new
  4082. OutOfRangeException("Offset invalid or out of range");}array_splice($this->list,(int)$index,1);}}final
  4083. class
  4084. ArrayTools{final
  4085. function
  4086. __construct(){throw
  4087. new
  4088. LogicException("Cannot instantiate static class ".get_class($this));}static
  4089. function
  4090. get(array$arr,$key,$default=NULL){foreach(is_array($key)?$key:array($key)as$k){if(is_array($arr)&&array_key_exists($k,$arr)){$arr=$arr[$k];}else{return$default;}}return$arr;}static
  4091. function&getRef(&$arr,$key){foreach(is_array($key)?$key:array($key)as$k){if(is_array($arr)||$arr===NULL){$arr=&$arr[$k];}else{throw
  4092. new
  4093. InvalidArgumentException('Traversed item is not an array.');}}return$arr;}static
  4094. function
  4095. mergeTree($arr1,$arr2){$res=$arr1+$arr2;foreach(array_intersect_key($arr1,$arr2)as$k=>$v){if(is_array($v)&&is_array($arr2[$k])){$res[$k]=self::mergeTree($v,$arr2[$k]);}}return$res;}static
  4096. function
  4097. searchKey($arr,$key){$foo=array($key=>NULL);return
  4098. array_search(key($foo),array_keys($arr),TRUE);}static
  4099. function
  4100. insertBefore(array&$arr,$key,array$inserted){$offset=self::searchKey($arr,$key);$arr=array_slice($arr,0,$offset,TRUE)+$inserted+array_slice($arr,$offset,count($arr),TRUE);}static
  4101. function
  4102. insertAfter(array&$arr,$key,array$inserted){$offset=self::searchKey($arr,$key);$offset=$offset===FALSE?count($arr):$offset+1;$arr=array_slice($arr,0,$offset,TRUE)+$inserted+array_slice($arr,$offset,count($arr),TRUE);}static
  4103. function
  4104. renameKey(array&$arr,$oldKey,$newKey){$offset=self::searchKey($arr,$oldKey);if($offset!==FALSE){$keys=array_keys($arr);$keys[$offset]=$newKey;$arr=array_combine($keys,$arr);}}}class
  4105. DateTime53
  4106. extends
  4107. DateTime{function
  4108. __sleep(){$this->fix=array($this->format('Y-m-d H:i:s'),$this->getTimezone()->getName());return
  4109. array('fix');}function
  4110. __wakeup(){$this->__construct($this->fix[0],new
  4111. DateTimeZone($this->fix[1]));unset($this->fix);}function
  4112. getTimestamp(){return(int)$this->format('U');}function
  4113. setTimestamp($timestamp){return$this->__construct(gmdate('Y-m-d H:i:s',$timestamp),new
  4114. DateTimeZone($this->getTimezone()->getName()));}}class
  4115. Image
  4116. extends
  4117. Object{const
  4118. ENLARGE=1;const
  4119. STRETCH=2;const
  4120. FIT=0;const
  4121. FILL=4;const
  4122. JPEG=IMAGETYPE_JPEG;const
  4123. PNG=IMAGETYPE_PNG;const
  4124. GIF=IMAGETYPE_GIF;const
  4125. EMPTY_GIF="GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";public
  4126. static$useImageMagick=FALSE;private$image;static
  4127. function
  4128. rgb($red,$green,$blue,$transparency=0){return
  4129. array('red'=>max(0,min(255,(int)$red)),'green'=>max(0,min(255,(int)$green)),'blue'=>max(0,min(255,(int)$blue)),'alpha'=>max(0,min(127,(int)$transparency)));}static
  4130. function
  4131. fromFile($file,&$format=NULL){if(!extension_loaded('gd')){throw
  4132. new
  4133. Exception("PHP extension GD is not loaded.");}$info=@getimagesize($file);if(self::$useImageMagick&&(empty($info)||$info[0]*$info[1]>9e5)){return
  4134. new
  4135. ImageMagick($file,$format);}switch($format=$info[2]){case
  4136. self::JPEG:return
  4137. new
  4138. self(imagecreatefromjpeg($file));case
  4139. self::PNG:return
  4140. new
  4141. self(imagecreatefrompng($file));case
  4142. self::GIF:return
  4143. new
  4144. self(imagecreatefromgif($file));default:if(self::$useImageMagick){return
  4145. new
  4146. ImageMagick($file,$format);}throw
  4147. new
  4148. Exception("Unknown image type or file '$file' not found.");}}static
  4149. function
  4150. fromString($s,&$format=NULL){if(!extension_loaded('gd')){throw
  4151. new
  4152. Exception("PHP extension GD is not loaded.");}if(strncmp($s,"\xff\xd8",2)===0){$format=self::JPEG;}elseif(strncmp($s,"\x89PNG",4)===0){$format=self::PNG;}elseif(strncmp($s,"GIF",3)===0){$format=self::GIF;}else{$format=NULL;}return
  4153. new
  4154. self(imagecreatefromstring($s));}static
  4155. function
  4156. fromBlank($width,$height,$color=NULL){if(!extension_loaded('gd')){throw
  4157. new
  4158. Exception("PHP extension GD is not loaded.");}$width=(int)$width;$height=(int)$height;if($width<1||$height<1){throw
  4159. new
  4160. InvalidArgumentException('Image width and height must be greater than zero.');}$image=imagecreatetruecolor($width,$height);if(is_array($color)){$color+=array('alpha'=>0);$color=imagecolorallocatealpha($image,$color['red'],$color['green'],$color['blue'],$color['alpha']);imagealphablending($image,FALSE);imagefilledrectangle($image,0,0,$width-1,$height-1,$color);imagealphablending($image,TRUE);}return
  4161. new
  4162. self($image);}function
  4163. __construct($image){$this->setImageResource($image);}function
  4164. getWidth(){return
  4165. imagesx($this->image);}function
  4166. getHeight(){return
  4167. imagesy($this->image);}protected
  4168. function
  4169. setImageResource($image){if(!is_resource($image)||get_resource_type($image)!=='gd'){throw
  4170. new
  4171. InvalidArgumentException('Image is not valid.');}$this->image=$image;return$this;}function
  4172. getImageResource(){return$this->image;}function
  4173. resize($width,$height,$flags=self::FIT){list($newWidth,$newHeight)=self::calculateSize($this->getWidth(),$this->getHeight(),$width,$height,$flags);if($newWidth!==$this->getWidth()||$newHeight!==$this->getHeight()){$newImage=self::fromBlank($newWidth,$newHeight,self::RGB(0,0,0,127))->getImageResource();imagecopyresampled($newImage,$this->getImageResource(),0,0,0,0,$newWidth,$newHeight,$this->getWidth(),$this->getHeight());$this->image=$newImage;}if($width<0||$height<0){$newImage=self::fromBlank($newWidth,$newHeight,self::RGB(0,0,0,127))->getImageResource();imagecopyresampled($newImage,$this->getImageResource(),0,0,$width<0?$newWidth-1:0,$height<0?$newHeight-1:0,$newWidth,$newHeight,$width<0?-$newWidth:$newWidth,$height<0?-$newHeight:$newHeight);$this->image=$newImage;}return$this;}static
  4174. function
  4175. calculateSize($srcWidth,$srcHeight,$newWidth,$newHeight,$flags=self::FIT){if(substr($newWidth,-1)==='%'){$newWidth=round($srcWidth/100*abs($newWidth));$flags|=self::ENLARGE;$percents=TRUE;}else{$newWidth=(int)abs($newWidth);}if(substr($newHeight,-1)==='%'){$newHeight=round($srcHeight/100*abs($newHeight));$flags|=empty($percents)?self::ENLARGE:self::STRETCH;}else{$newHeight=(int)abs($newHeight);}if($flags&self::STRETCH){if(empty($newWidth)||empty($newHeight)){throw
  4176. new
  4177. InvalidArgumentException('For stretching must be both width and height specified.');}if(($flags&self::ENLARGE)===0){$newWidth=round($srcWidth*min(1,$newWidth/$srcWidth));$newHeight=round($srcHeight*min(1,$newHeight/$srcHeight));}}else{if(empty($newWidth)&&empty($newHeight)){throw
  4178. new
  4179. InvalidArgumentException('At least width or height must be specified.');}$scale=array();if($newWidth>0){$scale[]=$newWidth/$srcWidth;}if($newHeight>0){$scale[]=$newHeight/$srcHeight;}if($flags&self::FILL){$scale=array(max($scale));}if(($flags&self::ENLARGE)===0){$scale[]=1;}$scale=min($scale);$newWidth=round($srcWidth*$scale);$newHeight=round($srcHeight*$scale);}return
  4180. array((int)$newWidth,(int)$newHeight);}function
  4181. crop($left,$top,$width,$height){if(substr($left,-1)==='%'){$left=round(($this->getWidth()-$width)/100*$left);}if(substr($top,-1)==='%'){$top=round(($this->getHeight()-$height)/100*$top);}$left=max(0,(int)$left);$top=max(0,(int)$top);$width=min((int)$width,$this->getWidth()-$left);$height=min((int)$height,$this->getHeight()-$top);$newImage=self::fromBlank($width,$height,self::RGB(0,0,0,127))->getImageResource();imagecopy($newImage,$this->getImageResource(),0,0,$left,$top,$width,$height);$this->image=$newImage;return$this;}function
  4182. sharpen(){imageconvolution($this->getImageResource(),array(array(-1,-1,-1),array(-1,24,-1),array(-1,-1,-1)),16,0);return$this;}function
  4183. place(Image$image,$left=0,$top=0,$opacity=100){$opacity=max(0,min(100,(int)$opacity));if(substr($left,-1)==='%'){$left=round(($this->getWidth()-$image->getWidth())/100*$left);}if(substr($top,-1)==='%'){$top=round(($this->getHeight()-$image->getHeight())/100*$top);}if($opacity===100){imagecopy($this->getImageResource(),$image->getImageResource(),$left,$top,0,0,$image->getWidth(),$image->getHeight());}elseif($opacity<>0){imagecopymerge($this->getImageResource(),$image->getImageResource(),$left,$top,0,0,$image->getWidth(),$image->getHeight(),$opacity);}return$this;}function
  4184. save($file=NULL,$quality=NULL,$type=NULL){if($type===NULL){switch(strtolower(pathinfo($file,PATHINFO_EXTENSION))){case'jpg':case'jpeg':$type=self::JPEG;break;case'png':$type=self::PNG;break;case'gif':$type=self::GIF;}}switch($type){case
  4185. self::JPEG:$quality=$quality===NULL?85:max(0,min(100,(int)$quality));return
  4186. imagejpeg($this->getImageResource(),$file,$quality);case
  4187. self::PNG:$quality=$quality===NULL?9:max(0,min(9,(int)$quality));return
  4188. imagepng($this->getImageResource(),$file,$quality);case
  4189. self::GIF:return$file===NULL?imagegif($this->getImageResource()):imagegif($this->getImageResource(),$file);default:throw
  4190. new
  4191. Exception("Unsupported image type.");}}function
  4192. toString($type=self::JPEG,$quality=NULL){ob_start();$this->save(NULL,$quality,$type);return
  4193. ob_get_clean();}function
  4194. __toString(){try{return$this->toString();}catch(Exception$e){Debug::toStringException($e);}}function
  4195. send($type=self::JPEG,$quality=NULL){if($type!==self::GIF&&$type!==self::PNG&&$type!==self::JPEG){throw
  4196. new
  4197. Exception("Unsupported image type.");}header('Content-Type: '.image_type_to_mime_type($type));return$this->save(NULL,$quality,$type);}function
  4198. __call($name,$args){$function='image'.$name;if(function_exists($function)){foreach($args
  4199. as$key=>$value){if($value
  4200. instanceof
  4201. self){$args[$key]=$value->getImageResource();}elseif(is_array($value)&&isset($value['red'])){$args[$key]=imagecolorallocatealpha($this->getImageResource(),$value['red'],$value['green'],$value['blue'],$value['alpha']);}}array_unshift($args,$this->getImageResource());$res=call_user_func_array($function,$args);return
  4202. is_resource($res)?new
  4203. self($res):$res;}return
  4204. parent::__call($name,$args);}}class
  4205. ImageMagick
  4206. extends
  4207. Image{public
  4208. static$path='';public
  4209. static$tempDir;private$file;private$isTemporary=FALSE;private$width;private$height;function
  4210. __construct($file,&$format=NULL){if(!is_file($file)){throw
  4211. new
  4212. InvalidArgumentException("File '$file' not found.");}$format=$this->setFile(realpath($file));if($format==='JPEG')$format=self::JPEG;elseif($format==='PNG')$format=self::PNG;elseif($format==='GIF')$format=self::GIF;}function
  4213. getWidth(){return$this->file===NULL?parent::getWidth():$this->width;}function
  4214. getHeight(){return$this->file===NULL?parent::getHeight():$this->height;}function
  4215. getImageResource(){if($this->file!==NULL){if(!$this->isTemporary){$this->execute("convert -strip %input %output",self::PNG);}$this->setImageResource(imagecreatefrompng($this->file));if($this->isTemporary){unlink($this->file);}$this->file=NULL;}return
  4216. parent::getImageResource();}function
  4217. resize($width,$height,$flags=self::FIT){if($this->file===NULL){return
  4218. parent::resize($width,$height,$flags);}$mirror='';if($width<0)$mirror.=' -flop';if($height<0)$mirror.=' -flip';list($newWidth,$newHeight)=self::calculateSize($this->getWidth(),$this->getHeight(),$width,$height,$flags);$this->execute("convert -resize {$newWidth}x{$newHeight}! {$mirror} -strip %input %output",self::PNG);return$this;}function
  4219. crop($left,$top,$width,$height){if($this->file===NULL){return
  4220. parent::crop($left,$top,$width,$height);}$left=max(0,(int)$left);$top=max(0,(int)$top);$width=min((int)$width,$this->getWidth()-$left);$height=min((int)$height,$this->getHeight()-$top);$this->execute("convert -crop {$width}x{$height}+{$left}+{$top} -strip %input %output",self::PNG);return$this;}function
  4221. save($file=NULL,$quality=NULL,$type=NULL){if($this->file===NULL){return
  4222. parent::save($file,$quality,$type);}$quality=$quality===NULL?'':'-quality '.max(0,min(100,(int)$quality));if($file===NULL){$this->execute("convert $quality -strip %input %output",$type===NULL?self::PNG:$type);readfile($this->file);}else{$this->execute("convert $quality -strip %input %output",(string)$file);}return
  4223. TRUE;}private
  4224. function
  4225. setFile($file){$this->file=$file;$res=$this->execute('identify -format "%w,%h,%m" '.escapeshellarg($this->file));if(!$res){throw
  4226. new
  4227. Exception("Unknown image type in file '$file' or ImageMagick not available.");}list($this->width,$this->height,$format)=explode(',',$res,3);return$format;}private
  4228. function
  4229. execute($command,$output=NULL){$command=str_replace('%input',escapeshellarg($this->file),$command);if($output){$newFile=is_string($output)?$output:(self::$tempDir?self::$tempDir:dirname($this->file)).'/'.uniqid('_tempimage',TRUE).image_type_to_extension($output);$command=str_replace('%output',escapeshellarg($newFile),$command);}$lines=array();exec(self::$path.$command,$lines,$status);if($output){if($status!=0){throw
  4230. new
  4231. Exception("Unknown error while calling ImageMagick.");}if($this->isTemporary){unlink($this->file);}$this->setFile($newFile);$this->isTemporary=!is_string($output);}return$lines?$lines[0]:FALSE;}function
  4232. __destruct(){if($this->file!==NULL&&$this->isTemporary){unlink($this->file);}}}class
  4233. GenericRecursiveIterator
  4234. extends
  4235. IteratorIterator
  4236. implements
  4237. RecursiveIterator,Countable{function
  4238. hasChildren(){$obj=$this->current();return($obj
  4239. instanceof
  4240. IteratorAggregate&&$obj->getIterator()instanceof
  4241. RecursiveIterator)||$obj
  4242. instanceof
  4243. RecursiveIterator;}function
  4244. getChildren(){$obj=$this->current();return$obj
  4245. instanceof
  4246. IteratorAggregate?$obj->getIterator():$obj;}function
  4247. count(){return
  4248. iterator_count($this);}}class
  4249. InstanceFilterIterator
  4250. extends
  4251. FilterIterator
  4252. implements
  4253. Countable{private$type;function
  4254. __construct(Iterator$iterator,$type){$this->type=$type;parent::__construct($iterator);}function
  4255. accept(){return$this->current()instanceof$this->type;}function
  4256. count(){return
  4257. iterator_count($this);}}class
  4258. SmartCachingIterator
  4259. extends
  4260. CachingIterator
  4261. implements
  4262. Countable{private$counter=0;function
  4263. __construct($iterator){if(is_array($iterator)||$iterator
  4264. instanceof
  4265. stdClass){$iterator=new
  4266. ArrayIterator($iterator);}elseif($iterator
  4267. instanceof
  4268. Traversable){if($iterator
  4269. instanceof
  4270. IteratorAggregate){$iterator=$iterator->getIterator();}elseif(!($iterator
  4271. instanceof
  4272. Iterator)){$iterator=new
  4273. IteratorIterator($iterator);}}else{throw
  4274. new
  4275. InvalidArgumentException("Invalid argument passed to foreach resp. ".__CLASS__."; array or Traversable expected, ".(is_object($iterator)?get_class($iterator):gettype($iterator))." given.");}parent::__construct($iterator,0);}function
  4276. isFirst($width=NULL){return$width===NULL?$this->counter===1:($this->counter
  4277. %$width)===1;}function
  4278. isLast($width=NULL){return!$this->hasNext()||($width!==NULL&&($this->counter
  4279. %$width)===0);}function
  4280. isEmpty(){return$this->counter===0;}function
  4281. isOdd(){return$this->counter
  4282. %
  4283. 2===1;}function
  4284. isEven(){return$this->counter
  4285. %
  4286. 2===0;}function
  4287. getCounter(){return$this->counter;}function
  4288. count(){$inner=$this->getInnerIterator();if($inner
  4289. instanceof
  4290. Countable){return$inner->count();}else{throw
  4291. new
  4292. NotSupportedException('Iterator is not countable.');}}function
  4293. next(){parent::next();if(parent::valid()){$this->counter++;}}function
  4294. rewind(){parent::rewind();$this->counter=parent::valid()?1:0;}function
  4295. getNextKey(){return$this->getInnerIterator()->key();}function
  4296. getNextValue(){return$this->getInnerIterator()->current();}function
  4297. __call($name,$args){return
  4298. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  4299. ObjectMixin::get($this,$name);}function
  4300. __set($name,$value){return
  4301. ObjectMixin::set($this,$name,$value);}function
  4302. __isset($name){return
  4303. ObjectMixin::has($this,$name);}function
  4304. __unset($name){$class=get_class($this);throw
  4305. new
  4306. MemberAccessException("Cannot unset the property $class::\$$name.");}}class
  4307. NeonParser
  4308. extends
  4309. Object{private
  4310. static$patterns=array('(\'[^\'\n]*\'|"(?:\\\\.|[^"\\\\\n])*")','(@[a-zA-Z_0-9\\\\]+)','([:-](?=\s|$)|[,=[\]{}()])','#.*','(\n *)','literal'=>'([^#"\',:=@[\]{}()<>\s](?:[^#,:=\]})>\n]+|:(?!\s)|(?<!\s)#)*)(?<!\s)',' +');private
  4311. static$regexp;private
  4312. static$brackets=array('['=>']','{'=>'}','('=>')');private$input;private$tokens;private$n;function
  4313. parse($s){$this->tokenize($s);$this->n=0;$res=$this->_parse();while(isset($this->tokens[$this->n])){if($this->tokens[$this->n][0]==="\n")$this->n++;else$this->error();}return$res;}private
  4314. function
  4315. _parse($indent=NULL,$endBracket=NULL){$inlineParser=$endBracket!==NULL;$result=$inlineParser||$indent?array():NULL;$value=$key=$object=NULL;$hasValue=$hasKey=FALSE;$tokens=$this->tokens;$n=&$this->n;$count=count($tokens);for(;$n<$count;$n++){$t=$tokens[$n];if($t===','){if(!$hasValue||!$inlineParser){$this->error();}if($hasKey)$result[$key]=$value;else$result[]=$value;$hasKey=$hasValue=FALSE;}elseif($t===':'||$t==='='){if($hasKey||!$hasValue){$this->error();}$key=(string)$value;$hasKey=TRUE;$hasValue=FALSE;}elseif($t==='-'){if($hasKey||$hasValue||$inlineParser){$this->error();}$key=NULL;$hasKey=TRUE;}elseif(isset(self::$brackets[$t])){if($hasValue){$this->error();}$hasValue=TRUE;$value=$this->_parse(NULL,self::$brackets[$tokens[$n++]]);}elseif($t===']'||$t==='}'||$t===')'){if($t!==$endBracket){$this->error();}if($hasValue){if($hasKey)$result[$key]=$value;else$result[]=$value;}elseif($hasKey){$this->error();}return$result;}elseif($t[0]==='@'){$object=$t;}elseif($t[0]==="\n"){if($inlineParser){if($hasValue){if($hasKey)$result[$key]=$value;else$result[]=$value;$hasKey=$hasValue=FALSE;}}else{while(isset($tokens[$n+1])&&$tokens[$n+1][0]==="\n")$n++;$newIndent=strlen($tokens[$n])-1;if($indent===NULL){$indent=$newIndent;}if($newIndent>$indent){if($hasValue||!$hasKey){$this->error();}elseif($key===NULL){$result[]=$this->_parse($newIndent);}else{$result[$key]=$this->_parse($newIndent);}$newIndent=strlen($tokens[$n])-1;$hasKey=FALSE;}else{if($hasValue&&!$hasKey){if($result===NULL)return$value;$this->error();}elseif($hasKey){$value=$hasValue?$value:NULL;if($key===NULL)$result[]=$value;else$result[$key]=$value;$hasKey=$hasValue=FALSE;}}if($newIndent<$indent||!isset($tokens[$n+1])){return$result;}}}else{if($hasValue){$this->error();}if($t[0]==='"'){$value=json_decode($t);if($value===NULL){$this->error();}}elseif($t[0]==="'"){$value=substr($t,1,-1);}elseif($t==='true'||$t==='yes'||$t==='TRUE'||$t==='YES'){$value=TRUE;}elseif($t==='false'||$t==='no'||$t==='FALSE'||$t==='NO'){$value=FALSE;}elseif($t==='null'||$t==='NULL'){$value=NULL;}elseif(is_numeric($t)){$value=$t*1;}else{$value=$t;}$hasValue=TRUE;}}throw
  4316. new
  4317. Exception('NEON parse error: unexpected end of file.');}private
  4318. function
  4319. tokenize($s){if(!self::$regexp){self::$regexp='~'.implode('|',self::$patterns).'~mA';}$s=str_replace("\r",'',$s);$s=strtr($s,"\t",' ');$s="\n".$s."\n";$this->input=$s;$this->tokens=String::split($s,self::$regexp,PREG_SPLIT_NO_EMPTY);if(end($this->tokens)!=="\n"){$this->n=key($this->tokens);$this->error();}}private
  4320. function
  4321. error(){$tokens=String::split($this->input,self::$regexp,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE);list($token,$offset)=$tokens[$this->n];$line=substr_count($this->input,"\n",0,$offset)+1;$col=$offset-strrpos(substr($this->input,0,$offset),"\n");throw
  4322. new
  4323. Exception('NEON parse error: unexpected '.str_replace("\n",'\n',substr($token,0,10))." on line $line, column $col.");}}class
  4324. Paginator
  4325. extends
  4326. Object{private$base=1;private$itemsPerPage=1;private$page;private$itemCount=0;function
  4327. setPage($page){$this->page=(int)$page;return$this;}function
  4328. getPage(){return$this->base+$this->getPageIndex();}function
  4329. getFirstPage(){return$this->base;}function
  4330. getLastPage(){return$this->base+max(0,$this->getPageCount()-1);}function
  4331. setBase($base){$this->base=(int)$base;return$this;}function
  4332. getBase(){return$this->base;}protected
  4333. function
  4334. getPageIndex(){return
  4335. min(max(0,$this->page-$this->base),max(0,$this->getPageCount()-1));}function
  4336. isFirst(){return$this->getPageIndex()===0;}function
  4337. isLast(){return$this->getPageIndex()>=$this->getPageCount()-1;}function
  4338. getPageCount(){return(int)ceil($this->itemCount/$this->itemsPerPage);}function
  4339. setItemsPerPage($itemsPerPage){$this->itemsPerPage=max(1,(int)$itemsPerPage);return$this;}function
  4340. getItemsPerPage(){return$this->itemsPerPage;}function
  4341. setItemCount($itemCount){$this->itemCount=$itemCount===FALSE?PHP_INT_MAX:max(0,(int)$itemCount);return$this;}function
  4342. getItemCount(){return$this->itemCount;}function
  4343. getOffset(){return$this->getPageIndex()*$this->itemsPerPage;}function
  4344. getCountdownOffset(){return
  4345. max(0,$this->itemCount-($this->getPageIndex()+1)*$this->itemsPerPage);}function
  4346. getLength(){return
  4347. min($this->itemsPerPage,$this->itemCount-$this->getPageIndex()*$this->itemsPerPage);}}final
  4348. class
  4349. SafeStream{const
  4350. PROTOCOL='safe';private$handle;private$filePath;private$tempFile;private$startPos=0;private$writeError=FALSE;static
  4351. function
  4352. register(){return
  4353. stream_wrapper_register(self::PROTOCOL,__CLASS__);}function
  4354. stream_open($path,$mode,$options,&$opened_path){$path=substr($path,strlen(self::PROTOCOL)+3);$flag=trim($mode,'rwax+');$mode=trim($mode,'tb');$use_path=(bool)(STREAM_USE_PATH&$options);$append=FALSE;switch($mode){case'r':case'r+':$handle=@fopen($path,$mode.$flag,$use_path);if(!$handle)return
  4355. FALSE;if(flock($handle,$mode=='r'?LOCK_SH:LOCK_EX)){$this->handle=$handle;return
  4356. TRUE;}fclose($handle);return
  4357. FALSE;case'a':case'a+':$append=TRUE;case'w':case'w+':$handle=@fopen($path,'r+'.$flag,$use_path);if($handle){if(flock($handle,LOCK_EX)){if($append){fseek($handle,0,SEEK_END);$this->startPos=ftell($handle);}else{ftruncate($handle,0);}$this->handle=$handle;return
  4358. TRUE;}fclose($handle);}$mode{0}='x';case'x':case'x+':if(file_exists($path))return
  4359. FALSE;$tmp='~~'.time().'.tmp';$handle=@fopen($path.$tmp,$mode.$flag,$use_path);if($handle){if(flock($handle,LOCK_EX)){$this->handle=$handle;if(!@rename($path.$tmp,$path)){$this->tempFile=realpath($path.$tmp);$this->filePath=substr($this->tempFile,0,-strlen($tmp));}return
  4360. TRUE;}fclose($handle);unlink($path.$tmp);}return
  4361. FALSE;default:trigger_error("Unsupported mode $mode",E_USER_WARNING);return
  4362. FALSE;}}function
  4363. stream_close(){if($this->writeError){ftruncate($this->handle,$this->startPos);}fclose($this->handle);if($this->tempFile){if(!@rename($this->tempFile,$this->filePath)){unlink($this->tempFile);}}}function
  4364. stream_read($length){return
  4365. fread($this->handle,$length);}function
  4366. stream_write($data){$len=strlen($data);$res=fwrite($this->handle,$data,$len);if($res!==$len){$this->writeError=TRUE;}return$res;}function
  4367. stream_tell(){return
  4368. ftell($this->handle);}function
  4369. stream_eof(){return
  4370. feof($this->handle);}function
  4371. stream_seek($offset,$whence){return
  4372. fseek($this->handle,$offset,$whence)===0;}function
  4373. stream_stat(){return
  4374. fstat($this->handle);}function
  4375. url_stat($path,$flags){$path=substr($path,strlen(self::PROTOCOL)+3);return($flags&STREAM_URL_STAT_LINK)?@lstat($path):@stat($path);}function
  4376. unlink($path){$path=substr($path,strlen(self::PROTOCOL)+3);return
  4377. unlink($path);}}final
  4378. class
  4379. String{final
  4380. function
  4381. __construct(){throw
  4382. new
  4383. LogicException("Cannot instantiate static class ".get_class($this));}static
  4384. function
  4385. checkEncoding($s,$encoding='UTF-8'){return$s===self::fixEncoding($s,$encoding);}static
  4386. function
  4387. fixEncoding($s,$encoding='UTF-8'){return@iconv('UTF-16',$encoding.'//IGNORE',iconv($encoding,'UTF-16//IGNORE',$s));}static
  4388. function
  4389. chr($code,$encoding='UTF-8'){return
  4390. iconv('UTF-32BE',$encoding.'//IGNORE',pack('N',$code));}static
  4391. function
  4392. startsWith($haystack,$needle){return
  4393. strncmp($haystack,$needle,strlen($needle))===0;}static
  4394. function
  4395. endsWith($haystack,$needle){return
  4396. strlen($needle)===0||substr($haystack,-strlen($needle))===$needle;}static
  4397. function
  4398. normalize($s){$s=str_replace("\r\n","\n",$s);$s=strtr($s,"\r","\n");$s=preg_replace('#[\x00-\x08\x0B-\x1F]+#','',$s);$s=preg_replace("#[\t ]+$#m",'',$s);$s=trim($s,"\n");return$s;}static
  4399. function
  4400. webalize($s,$charlist=NULL,$lower=TRUE){$s=strtr($s,'`\'"^~','-----');if(ICONV_IMPL==='glibc'){setlocale(LC_CTYPE,'en_US.UTF-8');}$s=@iconv('UTF-8','ASCII//TRANSLIT',$s);$s=str_replace(array('`',"'",'"','^','~'),'',$s);if($lower)$s=strtolower($s);$s=preg_replace('#[^a-z0-9'.preg_quote($charlist,'#').']+#i','-',$s);$s=trim($s,'-');return$s;}static
  4401. function
  4402. truncate($s,$maxLen,$append="\xE2\x80\xA6"){if(self::length($s)>$maxLen){$maxLen=$maxLen-self::length($append);if($maxLen<1){return$append;}elseif($matches=self::match($s,'#^.{1,'.$maxLen.'}(?=[\s\x00-@\[-`{-~])#us')){return$matches[0].$append;}else{return
  4403. iconv_substr($s,0,$maxLen,'UTF-8').$append;}}return$s;}static
  4404. function
  4405. indent($s,$level=1,$chars="\t"){return$level<1?$s:self::replace($s,'#(?:^|[\r\n]+)(?=[^\r\n])#','$0'.str_repeat($chars,$level));}static
  4406. function
  4407. lower($s){return
  4408. mb_strtolower($s,'UTF-8');}static
  4409. function
  4410. upper($s){return
  4411. mb_strtoupper($s,'UTF-8');}static
  4412. function
  4413. capitalize($s){return
  4414. mb_convert_case($s,MB_CASE_TITLE,'UTF-8');}static
  4415. function
  4416. compare($left,$right,$len=NULL){if($len<0){$left=iconv_substr($left,$len,-$len,'UTF-8');$right=iconv_substr($right,$len,-$len,'UTF-8');}elseif($len!==NULL){$left=iconv_substr($left,0,$len,'UTF-8');$right=iconv_substr($right,0,$len,'UTF-8');}return
  4417. self::lower($left)===self::lower($right);}static
  4418. function
  4419. length($s){return
  4420. function_exists('mb_strlen')?mb_strlen($s,'UTF-8'):strlen(utf8_decode($s));}static
  4421. function
  4422. trim($s,$charlist=" \t\n\r\0\x0B\xC2\xA0"){$charlist=preg_quote($charlist,'#');return
  4423. self::replace($s,'#^['.$charlist.']+|['.$charlist.']+$#u','');}static
  4424. function
  4425. padLeft($s,$length,$pad=' '){$length=max(0,$length-self::length($s));$padLen=self::length($pad);return
  4426. str_repeat($pad,$length/$padLen).iconv_substr($pad,0,$length
  4427. %$padLen,'UTF-8').$s;}static
  4428. function
  4429. padRight($s,$length,$pad=' '){$length=max(0,$length-self::length($s));$padLen=self::length($pad);return$s.str_repeat($pad,$length/$padLen).iconv_substr($pad,0,$length
  4430. %$padLen,'UTF-8');}static
  4431. function
  4432. split($subject,$pattern,$flags=0){$res=preg_split($pattern,$subject,-1,$flags|PREG_SPLIT_DELIM_CAPTURE);self::checkPreg($res,$pattern);return$res;}static
  4433. function
  4434. match($subject,$pattern,$flags=0,$offset=0){$res=preg_match($pattern,$subject,$m,$flags,$offset);self::checkPreg($res,$pattern);if($res){return$m;}}static
  4435. function
  4436. matchAll($subject,$pattern,$flags=0,$offset=0){$res=preg_match_all($pattern,$subject,$m,($flags&PREG_PATTERN_ORDER)?$flags:($flags|PREG_SET_ORDER),$offset);self::checkPreg($res,$pattern);return$m;}static
  4437. function
  4438. replace($subject,$pattern,$replacement=NULL,$limit=-1){preg_match('##','');if(is_object($replacement)||is_array($replacement)){if($replacement
  4439. instanceof
  4440. Callback){$replacement=$replacement->getNative();}if(!is_callable($replacement,FALSE,$textual)){throw
  4441. new
  4442. InvalidStateException("Callback '$textual' is not callable.");}$res=preg_replace_callback($pattern,$replacement,$subject,$limit);}elseif(is_array($pattern)){$res=preg_replace(array_keys($pattern),array_values($pattern),$subject,$limit);}else{$res=preg_replace($pattern,$replacement,$subject,$limit);}if(preg_last_error()){self::checkPreg(TRUE,$pattern);}elseif($res===NULL){self::checkPreg(FALSE,$pattern);}else{return$res;}}private
  4443. static
  4444. function
  4445. checkPreg($res,$pattern){if($res===FALSE){$error=error_get_last();throw
  4446. new
  4447. RegexpException("$error[message] in pattern: $pattern");}elseif(preg_last_error()){static$messages=array(PREG_INTERNAL_ERROR=>'Internal error',PREG_BACKTRACK_LIMIT_ERROR=>'Backtrack limit was exhausted',PREG_RECURSION_LIMIT_ERROR=>'Recursion limit was exhausted',PREG_BAD_UTF8_ERROR=>'Malformed UTF-8 data',5=>'Offset didn\'t correspond to the begin of a valid UTF-8 code point');$code=preg_last_error();throw
  4448. new
  4449. RegexpException((isset($messages[$code])?$messages[$code]:'Unknown error')." (pattern: $pattern)",$code);}}}class
  4450. RegexpException
  4451. extends
  4452. Exception{}final
  4453. class
  4454. Tools{const
  4455. MINUTE=60;const
  4456. HOUR=3600;const
  4457. DAY=86400;const
  4458. WEEK=604800;const
  4459. MONTH=2629800;const
  4460. YEAR=31557600;final
  4461. function
  4462. __construct(){throw
  4463. new
  4464. LogicException("Cannot instantiate static class ".get_class($this));}static
  4465. function
  4466. createDateTime($time){if($time
  4467. instanceof
  4468. DateTime){return
  4469. clone$time;}elseif(is_numeric($time)){if($time<=self::YEAR){$time+=time();}return
  4470. new
  4471. DateTime53(date('Y-m-d H:i:s',$time));}else{return
  4472. new
  4473. DateTime53($time);}}static
  4474. function
  4475. iniFlag($var){$status=strtolower(ini_get($var));return$status==='on'||$status==='true'||$status==='yes'||(int)$status;}static
  4476. function
  4477. defaultize(&$var,$default){if($var===NULL)$var=$default;}static
  4478. function
  4479. glob($pattern,$flags=0){$files=glob($pattern,$flags);if(!is_array($files)){$files=array();}$dirs=glob(dirname($pattern).'/*',$flags|GLOB_ONLYDIR);if(is_array($dirs)){$mask=basename($pattern);foreach($dirs
  4480. as$dir){$files=array_merge($files,self::glob($dir.'/'.$mask,$flags));}}return$files;}private
  4481. static$errorMsg;static
  4482. function
  4483. tryError($level=E_ALL){set_error_handler(array(__CLASS__,'_errorHandler'),$level);self::$errorMsg=NULL;}static
  4484. function
  4485. catchError(&$message){restore_error_handler();$message=self::$errorMsg;self::$errorMsg=NULL;return$message!==NULL;}static
  4486. function
  4487. _errorHandler($severity,$message){if(($severity&error_reporting())!==$severity){return
  4488. NULL;}if(ini_get('html_errors')){$message=html_entity_decode(strip_tags($message),ENT_QUOTES,'UTF-8');}if(($a=strpos($message,': '))!==FALSE){$message=substr($message,$a+2);}self::$errorMsg=$message;}}class
  4489. Html
  4490. extends
  4491. Object
  4492. implements
  4493. ArrayAccess,Countable,IteratorAggregate{private$name;private$isEmpty;public$attrs=array();protected$children=array();public
  4494. static$xhtml=TRUE;public
  4495. static$emptyElements=array('img'=>1,'hr'=>1,'br'=>1,'input'=>1,'meta'=>1,'area'=>1,'command'=>1,'keygen'=>1,'source'=>1,'base'=>1,'col'=>1,'link'=>1,'param'=>1,'basefont'=>1,'frame'=>1,'isindex'=>1,'wbr'=>1,'embed'=>1);static
  4496. function
  4497. el($name=NULL,$attrs=NULL){$el=new
  4498. self;$parts=explode(' ',$name,2);$el->setName($parts[0]);if(is_array($attrs)){$el->attrs=$attrs;}elseif($attrs!==NULL){$el->setText($attrs);}if(isset($parts[1])){foreach(String::matchAll($parts[1].' ','#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i')as$m){$el->attrs[$m[1]]=isset($m[3])?$m[3]:TRUE;}}return$el;}final
  4499. function
  4500. setName($name,$isEmpty=NULL){if($name!==NULL&&!is_string($name)){throw
  4501. new
  4502. InvalidArgumentException("Name must be string or NULL, ".gettype($name)." given.");}$this->name=$name;$this->isEmpty=$isEmpty===NULL?isset(self::$emptyElements[$name]):(bool)$isEmpty;return$this;}final
  4503. function
  4504. getName(){return$this->name;}final
  4505. function
  4506. isEmpty(){return$this->isEmpty;}final
  4507. function
  4508. __set($name,$value){$this->attrs[$name]=$value;}final
  4509. function&__get($name){return$this->attrs[$name];}final
  4510. function
  4511. __unset($name){unset($this->attrs[$name]);}final
  4512. function
  4513. __call($m,$args){$p=substr($m,0,3);if($p==='get'||$p==='set'||$p==='add'){$m=substr($m,3);$m[0]=$m[0]|"\x20";if($p==='get'){return
  4514. isset($this->attrs[$m])?$this->attrs[$m]:NULL;}elseif($p==='add'){$args[]=TRUE;}}if(count($args)===1){$this->attrs[$m]=$args[0];}elseif($args[0]==NULL){$tmp=&$this->attrs[$m];}elseif(!isset($this->attrs[$m])||is_array($this->attrs[$m])){$this->attrs[$m][$args[0]]=$args[1];}else{$this->attrs[$m]=array($this->attrs[$m],$args[0]=>$args[1]);}return$this;}final
  4515. function
  4516. href($path,$query=NULL){if($query){$query=http_build_query($query,NULL,'&');if($query!=='')$path.='?'.$query;}$this->attrs['href']=$path;return$this;}final
  4517. function
  4518. setHtml($html){if($html===NULL){$html='';}elseif(is_array($html)){throw
  4519. new
  4520. InvalidArgumentException("Textual content must be a scalar, ".gettype($html)." given.");}else{$html=(string)$html;}$this->removeChildren();$this->children[]=$html;return$this;}final
  4521. function
  4522. getHtml(){$s='';foreach($this->children
  4523. as$child){if(is_object($child)){$s.=$child->render();}else{$s.=$child;}}return$s;}final
  4524. function
  4525. setText($text){if(!is_array($text)){$text=str_replace(array('&','<','>'),array('&amp;','&lt;','&gt;'),(string)$text);}return$this->setHtml($text);}final
  4526. function
  4527. getText(){return
  4528. html_entity_decode(strip_tags($this->getHtml()),ENT_QUOTES,'UTF-8');}final
  4529. function
  4530. add($child){return$this->insert(NULL,$child);}final
  4531. function
  4532. create($name,$attrs=NULL){$this->insert(NULL,$child=self::el($name,$attrs));return$child;}function
  4533. insert($index,$child,$replace=FALSE){if($child
  4534. instanceof
  4535. Html||is_scalar($child)){if($index===NULL){$this->children[]=$child;}else{array_splice($this->children,(int)$index,$replace?1:0,array($child));}}else{throw
  4536. new
  4537. InvalidArgumentException("Child node must be scalar or Html object, ".(is_object($child)?get_class($child):gettype($child))." given.");}return$this;}final
  4538. function
  4539. offsetSet($index,$child){$this->insert($index,$child,TRUE);}final
  4540. function
  4541. offsetGet($index){return$this->children[$index];}final
  4542. function
  4543. offsetExists($index){return
  4544. isset($this->children[$index]);}function
  4545. offsetUnset($index){if(isset($this->children[$index])){array_splice($this->children,(int)$index,1);}}final
  4546. function
  4547. count(){return
  4548. count($this->children);}function
  4549. removeChildren(){$this->children=array();}final
  4550. function
  4551. getIterator($deep=FALSE){if($deep){$deep=$deep>0?RecursiveIteratorIterator::SELF_FIRST:RecursiveIteratorIterator::CHILD_FIRST;return
  4552. new
  4553. RecursiveIteratorIterator(new
  4554. GenericRecursiveIterator(new
  4555. ArrayIterator($this->children)),$deep);}else{return
  4556. new
  4557. GenericRecursiveIterator(new
  4558. ArrayIterator($this->children));}}final
  4559. function
  4560. getChildren(){return$this->children;}final
  4561. function
  4562. render($indent=NULL){$s=$this->startTag();if(!$this->isEmpty){if($indent!==NULL){$indent++;}foreach($this->children
  4563. as$child){if(is_object($child)){$s.=$child->render($indent);}else{$s.=$child;}}$s.=$this->endTag();}if($indent!==NULL){return"\n".str_repeat("\t",$indent-1).$s."\n".str_repeat("\t",max(0,$indent-2));}return$s;}final
  4564. function
  4565. __toString(){return$this->render();}final
  4566. function
  4567. startTag(){if($this->name){return'<'.$this->name.$this->attributes().(self::$xhtml&&$this->isEmpty?' />':'>');}else{return'';}}final
  4568. function
  4569. endTag(){return$this->name&&!$this->isEmpty?'</'.$this->name.'>':'';}final
  4570. function
  4571. attributes(){if(!is_array($this->attrs)){return'';}$s='';foreach($this->attrs
  4572. as$key=>$value){if($value===NULL||$value===FALSE)continue;if($value===TRUE){if(self::$xhtml)$s.=' '.$key.'="'.$key.'"';else$s.=' '.$key;continue;}elseif(is_array($value)){$tmp=NULL;foreach($value
  4573. as$k=>$v){if($v==NULL)continue;$tmp[]=is_string($k)?($v===TRUE?$k:$k.':'.$v):$v;}if($tmp===NULL)continue;$value=implode($key==='style'||!strncmp($key,'on',2)?';':' ',$tmp);}else{$value=(string)$value;}$s.=' '.$key.'="'.str_replace(array('&','"','<','>','@'),array('&amp;','&quot;','&lt;','&gt;','&#64;'),$value).'"';}return$s;}function
  4574. __clone(){foreach($this->children
  4575. as$key=>$value){if(is_object($value)){$this->children[$key]=clone$value;}}}}class
  4576. HttpContext
  4577. extends
  4578. Object{function
  4579. isModified($lastModified=NULL,$etag=NULL){$response=$this->getResponse();$request=$this->getRequest();if($lastModified){$response->setHeader('Last-Modified',$response->date($lastModified));}if($etag){$response->setHeader('ETag','"'.addslashes($etag).'"');}$ifNoneMatch=$request->getHeader('If-None-Match');if($ifNoneMatch==='*'){$match=TRUE;}elseif($ifNoneMatch!==NULL){$etag=$response->getHeader('ETag');if($etag==NULL||strpos(' '.strtr($ifNoneMatch,",\t",' '),' '.$etag)===FALSE){return
  4580. TRUE;}else{$match=TRUE;}}$ifModifiedSince=$request->getHeader('If-Modified-Since');if($ifModifiedSince!==NULL){$lastModified=$response->getHeader('Last-Modified');if($lastModified!=NULL&&strtotime($lastModified)<=strtotime($ifModifiedSince)){$match=TRUE;}else{return
  4581. TRUE;}}if(empty($match)){return
  4582. TRUE;}$response->setCode(IHttpResponse::S304_NOT_MODIFIED);return
  4583. FALSE;}function
  4584. getRequest(){return
  4585. Environment::getHttpRequest();}function
  4586. getResponse(){return
  4587. Environment::getHttpResponse();}}class
  4588. HttpRequest
  4589. extends
  4590. Object
  4591. implements
  4592. IHttpRequest{protected$query;protected$post;protected$files;protected$cookies;protected$uri;protected$originalUri;protected$headers;protected$uriFilter=array(PHP_URL_PATH=>array('#/{2,}#'=>'/'),0=>array());protected$encoding;final
  4593. function
  4594. getUri(){if($this->uri===NULL){$this->detectUri();}return$this->uri;}function
  4595. setUri(UriScript$uri){$this->uri=clone$uri;$this->query=NULL;$this->uri->canonicalize();$this->uri->freeze();return$this;}final
  4596. function
  4597. getOriginalUri(){if($this->originalUri===NULL){$this->detectUri();}return$this->originalUri;}function
  4598. addUriFilter($pattern,$replacement='',$component=NULL){$pattern='#'.$pattern.'#';$component=$component===PHP_URL_PATH?PHP_URL_PATH:0;if($replacement===NULL){unset($this->uriFilter[$component][$pattern]);}else{$this->uriFilter[$component][$pattern]=$replacement;}$this->uri=NULL;}final
  4599. function
  4600. getUriFilters(){return$this->uriFilter;}protected
  4601. function
  4602. detectUri(){$uri=$this->uri=new
  4603. UriScript;$uri->scheme=$this->isSecured()?'https':'http';$uri->user=isset($_SERVER['PHP_AUTH_USER'])?$_SERVER['PHP_AUTH_USER']:'';$uri->password=isset($_SERVER['PHP_AUTH_PW'])?$_SERVER['PHP_AUTH_PW']:'';if(isset($_SERVER['HTTP_HOST'])){$pair=explode(':',$_SERVER['HTTP_HOST']);}elseif(isset($_SERVER['SERVER_NAME'])){$pair=explode(':',$_SERVER['SERVER_NAME']);}else{$pair=array('');}$uri->host=$pair[0];if(isset($pair[1])){$uri->port=(int)$pair[1];}elseif(isset($_SERVER['SERVER_PORT'])){$uri->port=(int)$_SERVER['SERVER_PORT'];}if(isset($_SERVER['REQUEST_URI'])){$requestUri=$_SERVER['REQUEST_URI'];}elseif(isset($_SERVER['ORIG_PATH_INFO'])){$requestUri=$_SERVER['ORIG_PATH_INFO'];if(isset($_SERVER['QUERY_STRING'])&&$_SERVER['QUERY_STRING']!=''){$requestUri.='?'.$_SERVER['QUERY_STRING'];}}else{$requestUri='';}$tmp=explode('?',$requestUri,2);$this->originalUri=new
  4604. Uri($uri);$this->originalUri->path=$tmp[0];$this->originalUri->query=isset($tmp[1])?$tmp[1]:'';$this->originalUri->freeze();$requestUri=String::replace($requestUri,$this->uriFilter[0]);$tmp=explode('?',$requestUri,2);$uri->path=String::replace($tmp[0],$this->uriFilter[PHP_URL_PATH]);$uri->path=String::fixEncoding($uri->path);$uri->query=isset($tmp[1])?$tmp[1]:'';$uri->canonicalize();$filename=isset($_SERVER['SCRIPT_FILENAME'])?basename($_SERVER['SCRIPT_FILENAME']):NULL;$scriptPath='';if(isset($_SERVER['SCRIPT_NAME'])&&basename($_SERVER['SCRIPT_NAME'])===$filename){$scriptPath=rtrim($_SERVER['SCRIPT_NAME'],'/');}elseif(isset($_SERVER['PHP_SELF'])&&basename($_SERVER['PHP_SELF'])===$filename){$scriptPath=$_SERVER['PHP_SELF'];}elseif(isset($_SERVER['ORIG_SCRIPT_NAME'])&&basename($_SERVER['ORIG_SCRIPT_NAME'])===$filename){$scriptPath=$_SERVER['ORIG_SCRIPT_NAME'];}elseif(isset($_SERVER['PHP_SELF'],$_SERVER['SCRIPT_FILENAME'])){$path=$_SERVER['PHP_SELF'];$segs=explode('/',trim($_SERVER['SCRIPT_FILENAME'],'/'));$segs=array_reverse($segs);$index=0;$last=count($segs);do{$seg=$segs[$index];$scriptPath='/'.$seg.$scriptPath;$index++;}while(($last>$index)&&(FALSE!==($pos=strpos($path,$scriptPath)))&&(0!=$pos));}if(strncmp($uri->path,$scriptPath,strlen($scriptPath))===0){$uri->scriptPath=$scriptPath;}elseif(strncmp($uri->path,$scriptPath,strrpos($scriptPath,'/')+1)===0){$uri->scriptPath=substr($scriptPath,0,strrpos($scriptPath,'/')+1);}elseif(strpos($uri->path,basename($scriptPath))===FALSE){$uri->scriptPath='/';}elseif((strlen($uri->path)>=strlen($scriptPath))&&((FALSE!==($pos=strpos($uri->path,$scriptPath)))&&($pos!==0))){$uri->scriptPath=substr($uri->path,0,$pos+strlen($scriptPath));}else{$uri->scriptPath=$scriptPath;}$uri->freeze();}final
  4605. function
  4606. getQuery($key=NULL,$default=NULL){if($this->query===NULL){$this->initialize();}if(func_num_args()===0){return$this->query;}elseif(isset($this->query[$key])){return$this->query[$key];}else{return$default;}}final
  4607. function
  4608. getPost($key=NULL,$default=NULL){if($this->post===NULL){$this->initialize();}if(func_num_args()===0){return$this->post;}elseif(isset($this->post[$key])){return$this->post[$key];}else{return$default;}}function
  4609. getPostRaw(){return
  4610. file_get_contents('php://input');}final
  4611. function
  4612. getFile($key){if($this->files===NULL){$this->initialize();}$args=func_get_args();return
  4613. ArrayTools::get($this->files,$args);}final
  4614. function
  4615. getFiles(){if($this->files===NULL){$this->initialize();}return$this->files;}final
  4616. function
  4617. getCookie($key,$default=NULL){if($this->cookies===NULL){$this->initialize();}if(func_num_args()===0){return$this->cookies;}elseif(isset($this->cookies[$key])){return$this->cookies[$key];}else{return$default;}}final
  4618. function
  4619. getCookies(){if($this->cookies===NULL){$this->initialize();}return$this->cookies;}function
  4620. setEncoding($encoding){if(strcasecmp($encoding,$this->encoding)){$this->encoding=$encoding;$this->query=$this->post=$this->cookies=$this->files=NULL;}return$this;}function
  4621. initialize(){$filter=(!in_array(ini_get("filter.default"),array("","unsafe_raw"))||ini_get("filter.default_flags"));parse_str($this->getUri()->query,$this->query);if(!$this->query){$this->query=$filter?filter_input_array(INPUT_GET,FILTER_UNSAFE_RAW):(empty($_GET)?array():$_GET);}$this->post=$filter?filter_input_array(INPUT_POST,FILTER_UNSAFE_RAW):(empty($_POST)?array():$_POST);$this->cookies=$filter?filter_input_array(INPUT_COOKIE,FILTER_UNSAFE_RAW):(empty($_COOKIE)?array():$_COOKIE);$gpc=(bool)get_magic_quotes_gpc();$enc=(bool)$this->encoding;$old=error_reporting(error_reporting()^E_NOTICE);$nonChars='#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';if($gpc||$enc){$utf=strcasecmp($this->encoding,'UTF-8')===0;$list=array(&$this->query,&$this->post,&$this->cookies);while(list($key,$val)=each($list)){foreach($val
  4622. as$k=>$v){unset($list[$key][$k]);if($gpc){$k=stripslashes($k);}if($enc&&is_string($k)&&(preg_match($nonChars,$k)||preg_last_error())){}elseif(is_array($v)){$list[$key][$k]=$v;$list[]=&$list[$key][$k];}else{if($gpc&&!$filter){$v=stripSlashes($v);}if($enc){if($utf){$v=String::fixEncoding($v);}else{if(!String::checkEncoding($v)){$v=iconv($this->encoding,'UTF-8//IGNORE',$v);}$v=html_entity_decode($v,ENT_QUOTES,'UTF-8');}$v=preg_replace($nonChars,'',$v);}$list[$key][$k]=$v;}}}unset($list,$key,$val,$k,$v);}$this->files=array();$list=array();if(!empty($_FILES)){foreach($_FILES
  4623. as$k=>$v){if($enc&&is_string($k)&&(preg_match($nonChars,$k)||preg_last_error()))continue;$v['@']=&$this->files[$k];$list[]=$v;}}while(list(,$v)=each($list)){if(!isset($v['name'])){continue;}elseif(!is_array($v['name'])){if($gpc){$v['name']=stripSlashes($v['name']);}if($enc){$v['name']=preg_replace($nonChars,'',String::fixEncoding($v['name']));}$v['@']=new
  4624. HttpUploadedFile($v);continue;}foreach($v['name']as$k=>$foo){if($enc&&is_string($k)&&(preg_match($nonChars,$k)||preg_last_error()))continue;$list[]=array('name'=>$v['name'][$k],'type'=>$v['type'][$k],'size'=>$v['size'][$k],'tmp_name'=>$v['tmp_name'][$k],'error'=>$v['error'][$k],'@'=>&$v['@'][$k]);}}error_reporting($old);}function
  4625. getMethod(){return
  4626. isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:NULL;}function
  4627. isMethod($method){return
  4628. isset($_SERVER['REQUEST_METHOD'])?strcasecmp($_SERVER['REQUEST_METHOD'],$method)===0:FALSE;}function
  4629. isPost(){return$this->isMethod('POST');}final
  4630. function
  4631. getHeader($header,$default=NULL){$header=strtolower($header);$headers=$this->getHeaders();if(isset($headers[$header])){return$headers[$header];}else{return$default;}}function
  4632. getHeaders(){if($this->headers===NULL){if(function_exists('apache_request_headers')){$this->headers=array_change_key_case(apache_request_headers(),CASE_LOWER);}else{$this->headers=array();foreach($_SERVER
  4633. as$k=>$v){if(strncmp($k,'HTTP_',5)==0){$k=substr($k,5);}elseif(strncmp($k,'CONTENT_',8)){continue;}$this->headers[strtr(strtolower($k),'_','-')]=$v;}}}return$this->headers;}final
  4634. function
  4635. getReferer(){$uri=self::getHeader('referer');return$uri?new
  4636. Uri($uri):NULL;}function
  4637. isSecured(){return
  4638. isset($_SERVER['HTTPS'])&&strcasecmp($_SERVER['HTTPS'],'off');}function
  4639. isAjax(){return$this->getHeader('X-Requested-With')==='XMLHttpRequest';}function
  4640. getRemoteAddress(){return
  4641. isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:NULL;}function
  4642. getRemoteHost(){if(!isset($_SERVER['REMOTE_HOST'])){if(!isset($_SERVER['REMOTE_ADDR'])){return
  4643. NULL;}$_SERVER['REMOTE_HOST']=getHostByAddr($_SERVER['REMOTE_ADDR']);}return$_SERVER['REMOTE_HOST'];}function
  4644. detectLanguage(array$langs){$header=$this->getHeader('accept-language');if(!$header)return
  4645. NULL;$s=strtolower($header);$s=strtr($s,'_','-');rsort($langs);preg_match_all('#('.implode('|',$langs).')(?:-[^\s,;=]+)?\s*(?:;\s*q=([0-9.]+))?#',$s,$matches);if(!$matches[0]){return
  4646. NULL;}$max=0;$lang=NULL;foreach($matches[1]as$key=>$value){$q=$matches[2][$key]===''?1.0:(float)$matches[2][$key];if($q>$max){$max=$q;$lang=$value;}}return$lang;}}final
  4647. class
  4648. HttpResponse
  4649. extends
  4650. Object
  4651. implements
  4652. IHttpResponse{private
  4653. static$fixIE=TRUE;public$cookieDomain='';public$cookiePath='/';public$cookieSecure=FALSE;private$code=self::S200_OK;function
  4654. setCode($code){$code=(int)$code;static$allowed=array(200=>1,201=>1,202=>1,203=>1,204=>1,205=>1,206=>1,300=>1,301=>1,302=>1,303=>1,304=>1,307=>1,400=>1,401=>1,403=>1,404=>1,406=>1,408=>1,410=>1,412=>1,415=>1,416=>1,500=>1,501=>1,503=>1,505=>1);if(!isset($allowed[$code])){throw
  4655. new
  4656. InvalidArgumentException("Bad HTTP response '$code'.");}elseif(headers_sent($file,$line)){throw
  4657. new
  4658. InvalidStateException("Cannot set HTTP code after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}else{$this->code=$code;$protocol=isset($_SERVER['SERVER_PROTOCOL'])?$_SERVER['SERVER_PROTOCOL']:'HTTP/1.1';header($protocol.' '.$code,TRUE,$code);}return$this;}function
  4659. getCode(){return$this->code;}function
  4660. setHeader($name,$value){if(headers_sent($file,$line)){throw
  4661. new
  4662. InvalidStateException("Cannot send header after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}if($value===NULL&&function_exists('header_remove')){header_remove($name);}else{header($name.': '.$value,TRUE,$this->code);}return$this;}function
  4663. addHeader($name,$value){if(headers_sent($file,$line)){throw
  4664. new
  4665. InvalidStateException("Cannot send header after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}header($name.': '.$value,FALSE,$this->code);}function
  4666. setContentType($type,$charset=NULL){$this->setHeader('Content-Type',$type.($charset?'; charset='.$charset:''));return$this;}function
  4667. redirect($url,$code=self::S302_FOUND){if(isset($_SERVER['SERVER_SOFTWARE'])&&preg_match('#^Microsoft-IIS/[1-5]#',$_SERVER['SERVER_SOFTWARE'])&&$this->getHeader('Set-Cookie')!==NULL){$this->setHeader('Refresh',"0;url=$url");return;}$this->setCode($code);$this->setHeader('Location',$url);echo"<h1>Redirect</h1>\n\n<p><a href=\"".htmlSpecialChars($url)."\">Please click here to continue</a>.</p>";}function
  4668. setExpiration($time){if(!$time){$this->setHeader('Cache-Control','s-maxage=0, max-age=0, must-revalidate');$this->setHeader('Expires','Mon, 23 Jan 1978 10:00:00 GMT');return$this;}$time=Tools::createDateTime($time);$this->setHeader('Cache-Control','max-age='.($time->format('U')-time()));$this->setHeader('Expires',self::date($time));return$this;}function
  4669. isSent(){return
  4670. headers_sent();}function
  4671. getHeader($header,$default=NULL){$header.=':';$len=strlen($header);foreach(headers_list()as$item){if(strncasecmp($item,$header,$len)===0){return
  4672. ltrim(substr($item,$len));}}return$default;}function
  4673. getHeaders(){$headers=array();foreach(headers_list()as$header){$a=strpos($header,':');$headers[substr($header,0,$a)]=(string)substr($header,$a+2);}return$headers;}static
  4674. function
  4675. date($time=NULL){$time=Tools::createDateTime($time);$time->setTimezone(new
  4676. DateTimeZone('GMT'));return$time->format('D, d M Y H:i:s \G\M\T');}function
  4677. enableCompression(){if(headers_sent()){return
  4678. FALSE;}if($this->getHeader('Content-Encoding')!==NULL){return
  4679. FALSE;}$ok=ob_gzhandler('',PHP_OUTPUT_HANDLER_START);if($ok===FALSE){return
  4680. FALSE;}if(function_exists('ini_set')){ini_set('zlib.output_compression','Off');ini_set('zlib.output_compression_level','6');}ob_start('ob_gzhandler',1);return
  4681. TRUE;}function
  4682. __destruct(){if(self::$fixIE){if(!isset($_SERVER['HTTP_USER_AGENT'])||strpos($_SERVER['HTTP_USER_AGENT'],'MSIE ')===FALSE)return;if(!in_array($this->code,array(400,403,404,405,406,408,409,410,500,501,505),TRUE))return;if($this->getHeader('Content-Type','text/html')!=='text/html')return;$s=" \t\r\n";for($i=2e3;$i;$i--)echo$s{rand(0,3)};self::$fixIE=FALSE;}}function
  4683. setCookie($name,$value,$time,$path=NULL,$domain=NULL,$secure=NULL){if(headers_sent($file,$line)){throw
  4684. new
  4685. InvalidStateException("Cannot set cookie after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}setcookie($name,$value,$time?Tools::createDateTime($time)->format('U'):0,$path===NULL?$this->cookiePath:(string)$path,$domain===NULL?$this->cookieDomain:(string)$domain,$secure===NULL?$this->cookieSecure:(bool)$secure,TRUE);return$this;}function
  4686. deleteCookie($name,$path=NULL,$domain=NULL,$secure=NULL){if(headers_sent($file,$line)){throw
  4687. new
  4688. InvalidStateException("Cannot delete cookie after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}setcookie($name,FALSE,254400000,$path===NULL?$this->cookiePath:(string)$path,$domain===NULL?$this->cookieDomain:(string)$domain,$secure===NULL?$this->cookieSecure:(bool)$secure,TRUE);}}class
  4689. HttpUploadedFile
  4690. extends
  4691. Object{private$name;private$type;private$size;private$tmpName;private$error;function
  4692. __construct($value){foreach(array('name','type','size','tmp_name','error')as$key){if(!isset($value[$key])||!is_scalar($value[$key])){$this->error=UPLOAD_ERR_NO_FILE;return;}}$this->name=$value['name'];$this->size=$value['size'];$this->tmpName=$value['tmp_name'];$this->error=$value['error'];}function
  4693. getName(){return$this->name;}function
  4694. getContentType(){if($this->isOk()&&$this->type===NULL){$info=getimagesize($this->tmpName);if(isset($info['mime'])){$this->type=$info['mime'];}elseif(extension_loaded('fileinfo')){$this->type=finfo_file(finfo_open(FILEINFO_MIME),$this->tmpName);}elseif(function_exists('mime_content_type')){$this->type=mime_content_type($this->tmpName);}if(!$this->type){$this->type='application/octet-stream';}else{$this->type=preg_replace('#[\s;].*$#','',$this->type);}}return$this->type;}function
  4695. getSize(){return$this->size;}function
  4696. getTemporaryFile(){return$this->tmpName;}function
  4697. __toString(){return$this->tmpName;}function
  4698. getError(){return$this->error;}function
  4699. isOk(){return$this->error===UPLOAD_ERR_OK;}function
  4700. move($dest){$dir=dirname($dest);if(@mkdir($dir,0755,TRUE)){chmod($dir,0755);}$func=is_uploaded_file($this->tmpName)?'move_uploaded_file':'rename';if(!$func($this->tmpName,$dest)){throw
  4701. new
  4702. InvalidStateException("Unable to move uploaded file '$this->tmpName' to '$dest'.");}chmod($dest,0644);$this->tmpName=$dest;return$this;}function
  4703. isImage(){return
  4704. in_array($this->getContentType(),array('image/gif','image/png','image/jpeg'),TRUE);}function
  4705. toImage(){return
  4706. Image::fromFile($this->tmpName);}function
  4707. getImage(){trigger_error(__METHOD__.'() is deprecated; use toImage() instead.',E_USER_WARNING);return$this->toImage();}function
  4708. getImageSize(){return$this->isOk()?getimagesize($this->tmpName):NULL;}}class
  4709. Session
  4710. extends
  4711. Object{const
  4712. DEFAULT_FILE_LIFETIME=10800;private$regenerationNeeded;private
  4713. static$started;private$options=array('referer_check'=>'','use_cookies'=>1,'use_only_cookies'=>1,'use_trans_sid'=>0,'cookie_lifetime'=>0,'cookie_path'=>'/','cookie_domain'=>'','cookie_secure'=>FALSE,'cookie_httponly'=>TRUE,'gc_maxlifetime'=>self::DEFAULT_FILE_LIFETIME,'cache_limiter'=>NULL,'cache_expire'=>NULL,'hash_function'=>NULL,'hash_bits_per_character'=>NULL);function
  4714. start(){if(self::$started){throw
  4715. new
  4716. InvalidStateException('Session has already been started.');}elseif(self::$started===NULL&&defined('SID')){throw
  4717. new
  4718. InvalidStateException('A session had already been started by session.auto-start or session_start().');}try{$this->configure($this->options);}catch(NotSupportedException$e){}Tools::tryError();session_start();if(Tools::catchError($msg)){@session_write_close();throw
  4719. new
  4720. InvalidStateException($msg);}self::$started=TRUE;if($this->regenerationNeeded){session_regenerate_id(TRUE);$this->regenerationNeeded=FALSE;}unset($_SESSION['__NT'],$_SESSION['__NS'],$_SESSION['__NM']);$nf=&$_SESSION['__NF'];if(empty($nf)){$nf=array('C'=>0);}else{$nf['C']++;}$browserKey=$this->getHttpRequest()->getCookie('nette-browser');if(!$browserKey){$browserKey=(string)lcg_value();}$browserClosed=!isset($nf['B'])||$nf['B']!==$browserKey;$nf['B']=$browserKey;$this->sendCookie();if(isset($nf['META'])){$now=time();foreach($nf['META']as$namespace=>$metadata){if(is_array($metadata)){foreach($metadata
  4721. as$variable=>$value){if((!empty($value['B'])&&$browserClosed)||(!empty($value['T'])&&$now>$value['T'])||($variable!==''&&is_object($nf['DATA'][$namespace][$variable])&&(isset($value['V'])?$value['V']:NULL)!==ClassReflection::from($nf['DATA'][$namespace][$variable])->getAnnotation('serializationVersion'))){if($variable===''){unset($nf['META'][$namespace],$nf['DATA'][$namespace]);continue
  4722. 2;}unset($nf['META'][$namespace][$variable],$nf['DATA'][$namespace][$variable]);}}}}}register_shutdown_function(array($this,'clean'));}function
  4723. isStarted(){return(bool)self::$started;}function
  4724. close(){if(self::$started){$this->clean();session_write_close();self::$started=FALSE;}}function
  4725. destroy(){if(!self::$started){throw
  4726. new
  4727. InvalidStateException('Session is not started.');}session_destroy();$_SESSION=NULL;self::$started=FALSE;if(!$this->getHttpResponse()->isSent()){$params=session_get_cookie_params();$this->getHttpResponse()->deleteCookie(session_name(),$params['path'],$params['domain'],$params['secure']);}}function
  4728. exists(){return
  4729. self::$started||$this->getHttpRequest()->getCookie(session_name())!==NULL;}function
  4730. regenerateId(){if(self::$started){if(headers_sent($file,$line)){throw
  4731. new
  4732. InvalidStateException("Cannot regenerate session ID after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}session_regenerate_id(TRUE);}else{$this->regenerationNeeded=TRUE;}}function
  4733. getId(){return
  4734. session_id();}function
  4735. setName($name){if(!is_string($name)||!preg_match('#[^0-9.][^.]*$#A',$name)){throw
  4736. new
  4737. InvalidArgumentException('Session name must be a string and cannot contain dot.');}session_name($name);return$this->setOptions(array('name'=>$name));}function
  4738. getName(){return
  4739. session_name();}function
  4740. getNamespace($namespace,$class='SessionNamespace'){if(!is_string($namespace)||$namespace===''){throw
  4741. new
  4742. InvalidArgumentException('Session namespace must be a non-empty string.');}if(!self::$started){$this->start();}return
  4743. new$class($_SESSION['__NF']['DATA'][$namespace],$_SESSION['__NF']['META'][$namespace]);}function
  4744. hasNamespace($namespace){if($this->exists()&&!self::$started){$this->start();}return!empty($_SESSION['__NF']['DATA'][$namespace]);}function
  4745. getIterator(){if($this->exists()&&!self::$started){$this->start();}if(isset($_SESSION['__NF']['DATA'])){return
  4746. new
  4747. ArrayIterator(array_keys($_SESSION['__NF']['DATA']));}else{return
  4748. new
  4749. ArrayIterator;}}function
  4750. clean(){if(!self::$started||empty($_SESSION)){return;}$nf=&$_SESSION['__NF'];if(isset($nf['META'])&&is_array($nf['META'])){foreach($nf['META']as$name=>$foo){if(empty($nf['META'][$name])){unset($nf['META'][$name]);}}}if(empty($nf['META'])){unset($nf['META']);}if(empty($nf['DATA'])){unset($nf['DATA']);}if(empty($_SESSION)){}}function
  4751. setOptions(array$options){if(self::$started){$this->configure($options);}$this->options=$options+$this->options;return$this;}function
  4752. getOptions(){return$this->options;}private
  4753. function
  4754. configure(array$config){$special=array('cache_expire'=>1,'cache_limiter'=>1,'save_path'=>1,'name'=>1);foreach($config
  4755. as$key=>$value){if(!strncmp($key,'session.',8)){$key=substr($key,8);}if($value===NULL){continue;}elseif(isset($special[$key])){if(self::$started){throw
  4756. new
  4757. InvalidStateException("Unable to set '$key' when session has been started.");}$key="session_$key";$key($value);}elseif(strncmp($key,'cookie_',7)===0){if(!isset($cookie)){$cookie=session_get_cookie_params();}$cookie[substr($key,7)]=$value;}elseif(!function_exists('ini_set')){if(ini_get($key)!=$value){throw
  4758. new
  4759. NotSupportedException('Required function ini_set() is disabled.');}}else{if(self::$started){throw
  4760. new
  4761. InvalidStateException("Unable to set '$key' when session has been started.");}ini_set("session.$key",$value);}}if(isset($cookie)){session_set_cookie_params($cookie['lifetime'],$cookie['path'],$cookie['domain'],$cookie['secure'],$cookie['httponly']);if(self::$started){$this->sendCookie();}}}function
  4762. setExpiration($time){if(empty($time)){return$this->setOptions(array('gc_maxlifetime'=>self::DEFAULT_FILE_LIFETIME,'cookie_lifetime'=>0));}else{$time=Tools::createDateTime($time)->format('U');return$this->setOptions(array('gc_maxlifetime'=>$time,'cookie_lifetime'=>$time));}}function
  4763. setCookieParams($path,$domain=NULL,$secure=NULL){return$this->setOptions(array('cookie_path'=>$path,'cookie_domain'=>$domain,'cookie_secure'=>$secure));}function
  4764. getCookieParams(){return
  4765. session_get_cookie_params();}function
  4766. setSavePath($path){return$this->setOptions(array('save_path'=>$path));}private
  4767. function
  4768. sendCookie(){$cookie=$this->getCookieParams();$this->getHttpResponse()->setCookie(session_name(),session_id(),$cookie['lifetime'],$cookie['path'],$cookie['domain'],$cookie['secure'],$cookie['httponly']);$this->getHttpResponse()->setCookie('nette-browser',$_SESSION['__NF']['B'],HttpResponse::BROWSER,$cookie['path'],$cookie['domain'],$cookie['secure'],$cookie['httponly']);}protected
  4769. function
  4770. getHttpRequest(){return
  4771. Environment::getHttpRequest();}protected
  4772. function
  4773. getHttpResponse(){return
  4774. Environment::getHttpResponse();}}final
  4775. class
  4776. SessionNamespace
  4777. extends
  4778. Object
  4779. implements
  4780. IteratorAggregate,ArrayAccess{private$data;private$meta;public$warnOnUndefined=FALSE;function
  4781. __construct(&$data,&$meta){$this->data=&$data;$this->meta=&$meta;}function
  4782. getIterator(){if(isset($this->data)){return
  4783. new
  4784. ArrayIterator($this->data);}else{return
  4785. new
  4786. ArrayIterator;}}function
  4787. __set($name,$value){$this->data[$name]=$value;if(is_object($value)){$this->meta[$name]['V']=ClassReflection::from($value)->getAnnotation('serializationVersion');}}function&__get($name){if($this->warnOnUndefined&&!array_key_exists($name,$this->data)){trigger_error("The variable '$name' does not exist in session namespace",E_USER_NOTICE);}return$this->data[$name];}function
  4788. __isset($name){return
  4789. isset($this->data[$name]);}function
  4790. __unset($name){unset($this->data[$name],$this->meta[$name]);}function
  4791. offsetSet($name,$value){$this->__set($name,$value);}function
  4792. offsetGet($name){return$this->__get($name);}function
  4793. offsetExists($name){return$this->__isset($name);}function
  4794. offsetUnset($name){$this->__unset($name);}function
  4795. setExpiration($time,$variables=NULL){if(empty($time)){$time=NULL;$whenBrowserIsClosed=TRUE;}else{$time=Tools::createDateTime($time)->format('U');$whenBrowserIsClosed=FALSE;}if($variables===NULL){$this->meta['']['T']=$time;$this->meta['']['B']=$whenBrowserIsClosed;}elseif(is_array($variables)){foreach($variables
  4796. as$variable){$this->meta[$variable]['T']=$time;$this->meta[$variable]['B']=$whenBrowserIsClosed;}}else{$this->meta[$variables]['T']=$time;$this->meta[$variables]['B']=$whenBrowserIsClosed;}return$this;}function
  4797. removeExpiration($variables=NULL){if($variables===NULL){unset($this->meta['']['T'],$this->meta['']['B']);}elseif(is_array($variables)){foreach($variables
  4798. as$variable){unset($this->meta[$variable]['T'],$this->meta[$variable]['B']);}}else{unset($this->meta[$variables]['T'],$this->meta[$variable]['B']);}}function
  4799. remove(){$this->data=NULL;$this->meta=NULL;}}class
  4800. Uri
  4801. extends
  4802. FreezableObject{public
  4803. static$defaultPorts=array('http'=>80,'https'=>443,'ftp'=>21,'news'=>119,'nntp'=>119);private$scheme='';private$user='';private$pass='';private$host='';private$port=NULL;private$path='';private$query='';private$fragment='';function
  4804. __construct($uri=NULL){if(is_string($uri)){$parts=@parse_url($uri);if($parts===FALSE){throw
  4805. new
  4806. InvalidArgumentException("Malformed or unsupported URI '$uri'.");}foreach($parts
  4807. as$key=>$val){$this->$key=$val;}if(!$this->port&&isset(self::$defaultPorts[$this->scheme])){$this->port=self::$defaultPorts[$this->scheme];}}elseif($uri
  4808. instanceof
  4809. self){foreach($this
  4810. as$key=>$val){$this->$key=$uri->$key;}}}function
  4811. setScheme($value){$this->updating();$this->scheme=(string)$value;return$this;}function
  4812. getScheme(){return$this->scheme;}function
  4813. setUser($value){$this->updating();$this->user=(string)$value;return$this;}function
  4814. getUser(){return$this->user;}function
  4815. setPassword($value){$this->updating();$this->pass=(string)$value;return$this;}function
  4816. getPassword(){return$this->pass;}function
  4817. setHost($value){$this->updating();$this->host=(string)$value;return$this;}function
  4818. getHost(){return$this->host;}function
  4819. setPort($value){$this->updating();$this->port=(int)$value;return$this;}function
  4820. getPort(){return$this->port;}function
  4821. setPath($value){$this->updating();$this->path=(string)$value;return$this;}function
  4822. getPath(){return$this->path;}function
  4823. setQuery($value){$this->updating();$this->query=(string)(is_array($value)?http_build_query($value,'','&'):$value);return$this;}function
  4824. appendQuery($value){$this->updating();$value=(string)(is_array($value)?http_build_query($value,'','&'):$value);$this->query.=($this->query===''||$value==='')?$value:'&'.$value;}function
  4825. getQuery(){return$this->query;}function
  4826. setFragment($value){$this->updating();$this->fragment=(string)$value;return$this;}function
  4827. getFragment(){return$this->fragment;}function
  4828. getAbsoluteUri(){return$this->scheme.'://'.$this->getAuthority().$this->path.($this->query===''?'':'?'.$this->query).($this->fragment===''?'':'#'.$this->fragment);}function
  4829. getAuthority(){$authority=$this->host;if($this->port&&isset(self::$defaultPorts[$this->scheme])&&$this->port!==self::$defaultPorts[$this->scheme]){$authority.=':'.$this->port;}if($this->user!==''&&$this->scheme!=='http'&&$this->scheme!=='https'){$authority=$this->user.($this->pass===''?'':':'.$this->pass).'@'.$authority;}return$authority;}function
  4830. getHostUri(){return$this->scheme.'://'.$this->getAuthority();}function
  4831. isEqual($uri){$part=self::unescape(strtok($uri,'?#'),'%/');if(strncmp($part,'//',2)===0){if($part!=='//'.$this->getAuthority().$this->path)return
  4832. FALSE;}elseif(strncmp($part,'/',1)===0){if($part!==$this->path)return
  4833. FALSE;}else{if($part!==$this->scheme.'://'.$this->getAuthority().$this->path)return
  4834. FALSE;}$part=self::unescape(strtr((string)strtok('?#'),'+',' '),'%&;=+');return$part===$this->query;}function
  4835. canonicalize(){$this->updating();$this->path=$this->path===''?'/':self::unescape($this->path,'%/');$this->host=strtolower(rawurldecode($this->host));$this->query=self::unescape(strtr($this->query,'+',' '),'%&;=+');}function
  4836. __toString(){return$this->getAbsoluteUri();}static
  4837. function
  4838. unescape($s,$reserved='%;/?:@&=+$,'){preg_match_all('#(?<=%)[a-f0-9][a-f0-9]#i',$s,$matches,PREG_OFFSET_CAPTURE|PREG_SET_ORDER);foreach(array_reverse($matches)as$match){$ch=chr(hexdec($match[0][0]));if(strpos($reserved,$ch)===FALSE){$s=substr_replace($s,$ch,$match[0][1]-1,3);}}return$s;}}class
  4839. UriScript
  4840. extends
  4841. Uri{private$scriptPath='';function
  4842. setScriptPath($value){$this->updating();$this->scriptPath=(string)$value;return$this;}function
  4843. getScriptPath(){return$this->scriptPath;}function
  4844. getBasePath(){return(string)substr($this->scriptPath,0,strrpos($this->scriptPath,'/')+1);}function
  4845. getBaseUri(){return$this->scheme.'://'.$this->getAuthority().$this->getBasePath();}function
  4846. getRelativeUri(){return(string)substr($this->path,strrpos($this->scriptPath,'/')+1);}function
  4847. getPathInfo(){return(string)substr($this->path,strlen($this->scriptPath));}}class
  4848. User
  4849. extends
  4850. Object
  4851. implements
  4852. IUser{const
  4853. MANUAL=1;const
  4854. INACTIVITY=2;const
  4855. BROWSER_CLOSED=3;public$guestRole='guest';public$authenticatedRole='authenticated';public$onLoggedIn;public$onLoggedOut;private$authenticationHandler;private$authorizationHandler;private$namespace='';private$session;function
  4856. login($username,$password,$extra=NULL){$handler=$this->getAuthenticationHandler();if($handler===NULL){throw
  4857. new
  4858. InvalidStateException('Authentication handler has not been set.');}$this->logout(TRUE);$credentials=array(IAuthenticator::USERNAME=>$username,IAuthenticator::PASSWORD=>$password,'extra'=>$extra);$this->setIdentity($handler->authenticate($credentials));$this->setAuthenticated(TRUE);$this->onLoggedIn($this);}final
  4859. function
  4860. logout($clearIdentity=FALSE){if($this->isLoggedIn()){$this->setAuthenticated(FALSE);$this->onLoggedOut($this);}if($clearIdentity){$this->setIdentity(NULL);}}final
  4861. function
  4862. isLoggedIn(){$session=$this->getSessionNamespace(FALSE);return$session&&$session->authenticated;}final
  4863. function
  4864. getIdentity(){$session=$this->getSessionNamespace(FALSE);return$session?$session->identity:NULL;}function
  4865. getId(){$identity=$this->getIdentity();return$identity?$identity->getId():NULL;}function
  4866. setAuthenticationHandler(IAuthenticator$handler){$this->authenticationHandler=$handler;return$this;}final
  4867. function
  4868. getAuthenticationHandler(){if($this->authenticationHandler===NULL){$this->authenticationHandler=Environment::getService('Nette\\Security\\IAuthenticator');}return$this->authenticationHandler;}function
  4869. setNamespace($namespace){if($this->namespace!==$namespace){$this->namespace=(string)$namespace;$this->session=NULL;}return$this;}final
  4870. function
  4871. getNamespace(){return$this->namespace;}function
  4872. setExpiration($time,$whenBrowserIsClosed=TRUE,$clearIdentity=FALSE){$session=$this->getSessionNamespace(TRUE);if($time){$time=Tools::createDateTime($time)->format('U');$session->expireTime=$time;$session->expireDelta=$time-time();}else{unset($session->expireTime,$session->expireDelta);}$session->expireIdentity=(bool)$clearIdentity;$session->expireBrowser=(bool)$whenBrowserIsClosed;$session->browserCheck=TRUE;$session->setExpiration(0,'browserCheck');return$this;}final
  4873. function
  4874. getLogoutReason(){$session=$this->getSessionNamespace(FALSE);return$session?$session->reason:NULL;}protected
  4875. function
  4876. getSessionNamespace($need){if($this->session!==NULL){return$this->session;}$sessionHandler=$this->getSession();if(!$need&&!$sessionHandler->exists()){return
  4877. NULL;}$this->session=$session=$sessionHandler->getNamespace('Nette.Web.User/'.$this->namespace);if(!($session->identity
  4878. instanceof
  4879. IIdentity)||!is_bool($session->authenticated)){$session->remove();}if($session->authenticated&&$session->expireBrowser&&!$session->browserCheck){$session->reason=self::BROWSER_CLOSED;$session->authenticated=FALSE;$this->onLoggedOut($this);if($session->expireIdentity){unset($session->identity);}}if($session->authenticated&&$session->expireDelta>0){if($session->expireTime<time()){$session->reason=self::INACTIVITY;$session->authenticated=FALSE;$this->onLoggedOut($this);if($session->expireIdentity){unset($session->identity);}}$session->expireTime=time()+$session->expireDelta;}if(!$session->authenticated){unset($session->expireTime,$session->expireDelta,$session->expireIdentity,$session->expireBrowser,$session->browserCheck,$session->authTime);}return$this->session;}protected
  4880. function
  4881. setAuthenticated($state){$session=$this->getSessionNamespace(TRUE);$session->authenticated=(bool)$state;$this->getSession()->regenerateId();if($state){$session->reason=NULL;$session->authTime=time();}else{$session->reason=self::MANUAL;$session->authTime=NULL;}return$this;}protected
  4882. function
  4883. setIdentity(IIdentity$identity=NULL){$this->getSessionNamespace(TRUE)->identity=$identity;return$this;}function
  4884. getRoles(){if(!$this->isLoggedIn()){return
  4885. array($this->guestRole);}$identity=$this->getIdentity();return$identity?$identity->getRoles():array($this->authenticatedRole);}final
  4886. function
  4887. isInRole($role){return
  4888. in_array($role,$this->getRoles(),TRUE);}function
  4889. isAllowed($resource=NULL,$privilege=NULL){$handler=$this->getAuthorizationHandler();if(!$handler){throw
  4890. new
  4891. InvalidStateException("Authorization handler has not been set.");}foreach($this->getRoles()as$role){if($handler->isAllowed($role,$resource,$privilege))return
  4892. TRUE;}return
  4893. FALSE;}function
  4894. setAuthorizationHandler(IAuthorizator$handler){$this->authorizationHandler=$handler;return$this;}final
  4895. function
  4896. getAuthorizationHandler(){if($this->authorizationHandler===NULL){$this->authorizationHandler=Environment::getService('Nette\\Security\\IAuthorizator');}return$this->authorizationHandler;}protected
  4897. function
  4898. getSession(){return
  4899. Environment::getSession();}function
  4900. authenticate($username,$password,$extra=NULL){trigger_error(__METHOD__.'() is deprecated; use login() instead.',E_USER_WARNING);return$this->login($username,$password,$extra);}function
  4901. signOut($clearIdentity=FALSE){trigger_error(__METHOD__.'() is deprecated; use logout() instead.',E_USER_WARNING);return$this->logout($clearIdentity);}function
  4902. isAuthenticated(){trigger_error(__METHOD__.'() is deprecated; use isLoggedIn() instead.',E_USER_WARNING);return$this->isLoggedIn();}function
  4903. getSignOutReason(){trigger_error(__METHOD__.'() is deprecated; use getLogoutReason() instead.',E_USER_WARNING);return$this->getLogoutReason();}}