PageRenderTime 157ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 3ms

/app/libs/nette.min.php

https://bitbucket.org/thoracek/rdprstice
PHP | 5617 lines | 5475 code | 134 blank | 8 comment | 61 complexity | 5b4618b87e2daa7fce18c578cb0d4f10 MD5 | raw file
  1. <?php //netteloader=Nette\Framework
  2. namespace {/**
  3. * Nette Framework (version 2.0.3 released on 2012-04-04, http://nette.org)
  4. *
  5. * Copyright (c) 2004, 2012 David Grudl (http://davidgrudl.com)
  6. *
  7. * For the full copyright and license information, please view
  8. * the file license.txt that was distributed with this source code.
  9. */
  10. 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');umask(0);@header('X-Powered-By: Nette Framework');@header('Content-Type: text/html; charset=utf-8');define('NETTE',TRUE);define('NETTE_DIR',__DIR__);define('NETTE_VERSION_ID',20003);define('NETTE_PACKAGE','5.3');}namespace Nette\Diagnostics{use
  11. Nette;interface
  12. IBarPanel{function
  13. getTab();function
  14. getPanel();}}namespace Nette\Application{use
  15. Nette;interface
  16. IPresenter{function
  17. run(Request$request);}interface
  18. IPresenterFactory{function
  19. getPresenterClass(&$name);function
  20. createPresenter($name);}interface
  21. IResponse{function
  22. send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse);}interface
  23. IRouter{const
  24. ONE_WAY=1;const
  25. SECURED=2;function
  26. match(Nette\Http\IRequest$httpRequest);function
  27. constructUrl(Request$appRequest,Nette\Http\Url$refUrl);}}namespace Nette{use
  28. Nette;interface
  29. IFreezable{function
  30. freeze();function
  31. isFrozen();}}namespace Nette\ComponentModel{use
  32. Nette;interface
  33. IComponent{const
  34. NAME_SEPARATOR='-';function
  35. getName();function
  36. getParent();function
  37. setParent(IContainer$parent=NULL,$name=NULL);}interface
  38. IContainer
  39. extends
  40. IComponent{function
  41. addComponent(IComponent$component,$name);function
  42. removeComponent(IComponent$component);function
  43. getComponent($name);function
  44. getComponents($deep=FALSE,$filterType=NULL);}}namespace Nette\Application\UI{use
  45. Nette;interface
  46. ISignalReceiver{function
  47. signalReceived($signal);}interface
  48. IStatePersistent{function
  49. loadState(array$params);function
  50. saveState(array&$params);}interface
  51. IRenderable{function
  52. invalidateControl();function
  53. isControlInvalid();}}namespace Nette\Caching{use
  54. Nette;interface
  55. IStorage{function
  56. read($key);function
  57. lock($key);function
  58. write($key,$data,array$dependencies);function
  59. remove($key);function
  60. clean(array$conds);}}namespace Nette\Caching\Storages{use
  61. Nette;interface
  62. IJournal{function
  63. write($key,array$dependencies);function
  64. clean(array$conditions);}}namespace Nette\Config{use
  65. Nette;interface
  66. IAdapter{function
  67. load($file);function
  68. dump(array$data);}}namespace Nette\Database{use
  69. Nette;interface
  70. ISupplementalDriver{const
  71. META='meta';function
  72. delimite($name);function
  73. formatDateTime(\DateTime$value);function
  74. formatLike($value,$pos);function
  75. applyLimit(&$sql,$limit,$offset);function
  76. normalizeRow($row,$statement);function
  77. getTables();function
  78. getColumns($table);function
  79. getIndexes($table);function
  80. getForeignKeys($table);}interface
  81. IReflection{const
  82. FIELD_TEXT='string',FIELD_BINARY='bin',FIELD_BOOL='bool',FIELD_INTEGER='int',FIELD_FLOAT='float',FIELD_DATE='date',FIELD_TIME='time',FIELD_DATETIME='datetime';function
  83. getPrimary($table);function
  84. getHasManyReference($table,$key);function
  85. getBelongsToReference($table,$key);function
  86. setConnection(Connection$connection);}}namespace Nette\DI{use
  87. Nette;interface
  88. IContainer{function
  89. addService($name,$service);function
  90. getService($name);function
  91. removeService($name);function
  92. hasService($name);}}namespace Nette\Forms{use
  93. Nette;interface
  94. IControl{function
  95. loadHttpData();function
  96. setValue($value);function
  97. getValue();function
  98. getRules();function
  99. getErrors();function
  100. isDisabled();function
  101. translate($s,$count=NULL);}interface
  102. ISubmitterControl
  103. extends
  104. IControl{function
  105. isSubmittedBy();function
  106. getValidationScope();}interface
  107. IFormRenderer{function
  108. render(Form$form);}}namespace Nette\Http{use
  109. Nette;interface
  110. IRequest{const
  111. GET='GET',POST='POST',HEAD='HEAD',PUT='PUT',DELETE='DELETE';function
  112. getUrl();function
  113. getQuery($key=NULL,$default=NULL);function
  114. getPost($key=NULL,$default=NULL);function
  115. getFile($key);function
  116. getFiles();function
  117. getCookie($key,$default=NULL);function
  118. getCookies();function
  119. getMethod();function
  120. isMethod($method);function
  121. getHeader($header,$default=NULL);function
  122. getHeaders();function
  123. isSecured();function
  124. isAjax();function
  125. getRemoteAddress();function
  126. getRemoteHost();}interface
  127. IResponse{const
  128. PERMANENT=2116333333;const
  129. BROWSER=0;const
  130. 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
  131. setCode($code);function
  132. getCode();function
  133. setHeader($name,$value);function
  134. addHeader($name,$value);function
  135. setContentType($type,$charset=NULL);function
  136. redirect($url,$code=self::S302_FOUND);function
  137. setExpiration($seconds);function
  138. isSent();function
  139. getHeaders();function
  140. setCookie($name,$value,$expire,$path=NULL,$domain=NULL,$secure=NULL,$httpOnly=NULL);function
  141. deleteCookie($name,$path=NULL,$domain=NULL,$secure=NULL);}interface
  142. ISessionStorage{function
  143. open($savePath,$sessionName);function
  144. close();function
  145. read($id);function
  146. write($id,$data);function
  147. remove($id);function
  148. clean($maxlifetime);}}namespace Nette\Security{use
  149. Nette;interface
  150. IUserStorage{const
  151. MANUAL=1,INACTIVITY=2,BROWSER_CLOSED=4;const
  152. CLEAR_IDENTITY=8;function
  153. setAuthenticated($state);function
  154. isAuthenticated();function
  155. setIdentity(IIdentity$identity=NULL);function
  156. getIdentity();function
  157. setExpiration($time,$flags=0);function
  158. getLogoutReason();}}namespace Nette\Latte{use
  159. Nette;interface
  160. IMacro{function
  161. initialize();function
  162. finalize();function
  163. nodeOpened(MacroNode$node);function
  164. nodeClosed(MacroNode$node);}}namespace Nette\Localization{use
  165. Nette;interface
  166. ITranslator{function
  167. translate($message,$count=NULL);}}namespace Nette\Mail{use
  168. Nette;interface
  169. IMailer{function
  170. send(Message$mail);}}namespace Nette\Reflection{use
  171. Nette;interface
  172. IAnnotation{function
  173. __construct(array$values);}}namespace Nette\Security{use
  174. Nette;interface
  175. IAuthenticator{const
  176. USERNAME=0,PASSWORD=1;const
  177. IDENTITY_NOT_FOUND=1,INVALID_CREDENTIAL=2,FAILURE=3,NOT_APPROVED=4;function
  178. authenticate(array$credentials);}interface
  179. IAuthorizator{const
  180. ALL=NULL;const
  181. ALLOW=TRUE;const
  182. DENY=FALSE;function
  183. isAllowed($role,$resource,$privilege);}interface
  184. IIdentity{function
  185. getId();function
  186. getRoles();}interface
  187. IResource{function
  188. getResourceId();}interface
  189. IRole{function
  190. getRoleId();}}namespace Nette\Templating{use
  191. Nette;interface
  192. ITemplate{function
  193. render();}interface
  194. IFileTemplate
  195. extends
  196. ITemplate{function
  197. setFile($file);function
  198. getFile();}}namespace Nette{use
  199. Nette;class
  200. ArgumentOutOfRangeException
  201. extends\InvalidArgumentException{}class
  202. InvalidStateException
  203. extends\RuntimeException{}class
  204. NotImplementedException
  205. extends\LogicException{}class
  206. NotSupportedException
  207. extends\LogicException{}class
  208. DeprecatedException
  209. extends
  210. NotSupportedException{}class
  211. MemberAccessException
  212. extends\LogicException{}class
  213. IOException
  214. extends\RuntimeException{}class
  215. FileNotFoundException
  216. extends
  217. IOException{}class
  218. DirectoryNotFoundException
  219. extends
  220. IOException{}class
  221. InvalidArgumentException
  222. extends\InvalidArgumentException{}class
  223. OutOfRangeException
  224. extends\OutOfRangeException{}class
  225. UnexpectedValueException
  226. extends\UnexpectedValueException{}class
  227. StaticClassException
  228. extends\LogicException{}class
  229. FatalErrorException
  230. extends\ErrorException{function
  231. __construct($message,$code,$severity,$file,$line,$context){parent::__construct($message,$code,$severity,$file,$line);$this->context=$context;}}abstract
  232. class
  233. Object{static
  234. function
  235. getReflection(){return
  236. new
  237. Reflection\ClassType(get_called_class());}function
  238. __call($name,$args){return
  239. ObjectMixin::call($this,$name,$args);}static
  240. function
  241. __callStatic($name,$args){return
  242. ObjectMixin::callStatic(get_called_class(),$name,$args);}static
  243. function
  244. extensionMethod($name,$callback=NULL){if(strpos($name,'::')===FALSE){$class=get_called_class();}else{list($class,$name)=explode('::',$name);}$class=new
  245. Reflection\ClassType($class);if($callback===NULL){return$class->getExtensionMethod($name);}else{$class->setExtensionMethod($name,$callback);}}function&__get($name){return
  246. ObjectMixin::get($this,$name);}function
  247. __set($name,$value){return
  248. ObjectMixin::set($this,$name,$value);}function
  249. __isset($name){return
  250. ObjectMixin::has($this,$name);}function
  251. __unset($name){ObjectMixin::remove($this,$name);}}}namespace Nette\Utils{use
  252. Nette;final
  253. class
  254. LimitedScope{private
  255. static$vars;final
  256. function
  257. __construct(){throw
  258. new
  259. Nette\StaticClassException;}static
  260. function
  261. evaluate(){if(func_num_args()>1){self::$vars=func_get_arg(1);extract(self::$vars);}$res=eval('?>'.func_get_arg(0));if($res===FALSE&&($error=error_get_last())&&$error['type']===E_PARSE){throw
  262. new
  263. Nette\FatalErrorException($error['message'],0,$error['type'],$error['file'],$error['line'],NULL);}return$res;}static
  264. function
  265. load(){if(func_num_args()>1){self::$vars=func_get_arg(1);if(self::$vars===TRUE){return include_once func_get_arg(0);}extract(self::$vars);}return include func_get_arg(0);}}}namespace Nette\Loaders{use
  266. Nette;abstract
  267. class
  268. AutoLoader
  269. extends
  270. Nette\Object{static
  271. private$loaders=array();public
  272. static$count=0;final
  273. static
  274. function
  275. load($type){foreach(func_get_args()as$type){if(!class_exists($type)){throw
  276. new
  277. Nette\InvalidStateException("Unable to load class or interface '$type'.");}}}final
  278. static
  279. function
  280. getLoaders(){return
  281. array_values(self::$loaders);}function
  282. register(){if(!function_exists('spl_autoload_register')){throw
  283. new
  284. Nette\NotSupportedException('spl_autoload does not exist in this PHP installation.');}spl_autoload_register(array($this,'tryLoad'));self::$loaders[spl_object_hash($this)]=$this;}function
  285. unregister(){unset(self::$loaders[spl_object_hash($this)]);return
  286. spl_autoload_unregister(array($this,'tryLoad'));}abstract
  287. function
  288. tryLoad($type);}}namespace Nette\Diagnostics{use
  289. Nette;final
  290. class
  291. Helpers{static
  292. function
  293. editorLink($file,$line){if(Debugger::$editor&&is_file($file)){$dir=dirname(strtr($file,'/',DIRECTORY_SEPARATOR));$base=isset($_SERVER['SCRIPT_FILENAME'])?dirname(dirname(strtr($_SERVER['SCRIPT_FILENAME'],'/',DIRECTORY_SEPARATOR))):dirname($dir);if(substr($dir,0,strlen($base))===$base){$dir='...'.substr($dir,strlen($base));}return
  294. Nette\Utils\Html::el('a')->href(strtr(Debugger::$editor,array('%file'=>rawurlencode($file),'%line'=>$line)))->title("$file:$line")->setHtml(htmlSpecialChars(rtrim($dir,DIRECTORY_SEPARATOR)).DIRECTORY_SEPARATOR.'<b>'.htmlSpecialChars(basename($file)).'</b>');}else{return
  295. Nette\Utils\Html::el('span')->setText($file);}}static
  296. function
  297. htmlDump(&$var,$level=0){static$tableUtf,$tableBin,$reBinary='#[^\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));}}$tableBin["\\"]='\\\\';$tableBin["\r"]='\\r';$tableBin["\n"]='\\n';$tableBin["\t"]='\\t';$tableUtf['\\x']=$tableBin['\\x']='\\\\x';}if(is_bool($var)){return'<span class="php-bool">'.($var?'TRUE':'FALSE')."</span>\n";}elseif($var===NULL){return"<span class=\"php-null\">NULL</span>\n";}elseif(is_int($var)){return"<span class=\"php-int\">$var</span>\n";}elseif(is_float($var)){$var=var_export($var,TRUE);if(strpos($var,'.')===FALSE){$var.='.0';}return"<span class=\"php-float\">$var</span>\n";}elseif(is_string($var)){if(Debugger::$maxLen&&strlen($var)>Debugger::$maxLen){$s=htmlSpecialChars(substr($var,0,Debugger::$maxLen),ENT_NOQUOTES,'ISO-8859-1').' ... ';}else{$s=htmlSpecialChars($var,ENT_NOQUOTES,'ISO-8859-1');}$s=strtr($s,preg_match($reBinary,$s)||preg_last_error()?$tableBin:$tableUtf);$len=strlen($var);return"<span class=\"php-string\">\"$s\"</span>".($len>1?" ($len)":"")."\n";}elseif(is_array($var)){$s='<span class="php-array">array</span>('.count($var).") ";$space=str_repeat($space1=' ',$level);$brackets=range(0,count($var)-1)===array_keys($var)?"[]":"{}";static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(empty($var)){}elseif(isset($var[$marker])){$brackets=$var[$marker];$s.="$brackets[0] *RECURSION* $brackets[1]";}elseif($level<Debugger::$maxDepth||!Debugger::$maxDepth){$s.="<code>$brackets[0]\n";$var[$marker]=$brackets;foreach($var
  298. as$k=>&$v){if($k===$marker){continue;}$k=strtr($k,preg_match($reBinary,$k)||preg_last_error()?$tableBin:$tableUtf);$k=htmlSpecialChars(preg_match('#^\w+$#',$k)?$k:"\"$k\"");$s.="$space$space1<span class=\"php-key\">$k</span> => ".self::htmlDump($v,$level+1);}unset($var[$marker]);$s.="$space$brackets[1]</code>";}else{$s.="$brackets[0] ... $brackets[1]";}return$s."\n";}elseif(is_object($var)){if($var
  299. instanceof\Closure){$rc=new\ReflectionFunction($var);$arr=array();foreach($rc->getParameters()as$param){$arr[]='$'.$param->getName();}$arr=array('file'=>$rc->getFileName(),'line'=>$rc->getStartLine(),'parameters'=>implode(', ',$arr));}else{$arr=(array)$var;}$s='<span class="php-object">'.get_class($var)."</span>(".count($arr).") ";$space=str_repeat($space1=' ',$level);static$list=array();if(empty($arr)){}elseif(in_array($var,$list,TRUE)){$s.="{ *RECURSION* }";}elseif($level<Debugger::$maxDepth||!Debugger::$maxDepth||$var
  300. instanceof\Closure){$s.="<code>{\n";$list[]=$var;foreach($arr
  301. as$k=>&$v){$m='';if($k[0]==="\x00"){$m=' <span class="php-visibility">'.($k[1]==='*'?'protected':'private').'</span>';$k=substr($k,strrpos($k,"\x00")+1);}$k=strtr($k,preg_match($reBinary,$k)||preg_last_error()?$tableBin:$tableUtf);$k=htmlSpecialChars(preg_match('#^\w+$#',$k)?$k:"\"$k\"");$s.="$space$space1<span class=\"php-key\">$k</span>$m => ".self::htmlDump($v,$level+1);}array_pop($list);$s.="$space}</code>";}else{$s.="{ ... }";}return$s."\n";}elseif(is_resource($var)){return'<span class="php-resource">'.htmlSpecialChars(get_resource_type($var))." resource</span>\n";}else{return"<span>unknown type</span>\n";}}static
  302. function
  303. clickableDump($dump,$collapsed=FALSE){return'<pre class="nette-dump">'.preg_replace_callback('#^( *)((?>[^(\r\n]{1,200}))\((\d+)\) <code>#m',function($m)use($collapsed){return"$m[1]<a href='#' rel='next'>$m[2]($m[3]) ".(($m[1]||!$collapsed)&&($m[3]<7)?'<abbr>&#x25bc;</abbr> </a><code>':'<abbr>&#x25ba;</abbr> </a><code class="nette-collapsed">');},self::htmlDump($dump)).'</pre>';}static
  304. function
  305. findTrace(array$trace,$method,&$index=NULL){$m=explode('::',$method);foreach($trace
  306. as$i=>$item){if(isset($item['function'])&&$item['function']===end($m)&&isset($item['class'])===isset($m[1])&&(!isset($item['class'])||$item['class']===$m[0]||is_subclass_of($item['class'],$m[0]))){$index=$i;return$item;}}}}}namespace Nette\Utils{use
  307. Nette;class
  308. Html
  309. extends
  310. Nette\Object
  311. implements\ArrayAccess,\Countable,\IteratorAggregate{private$name;private$isEmpty;public$attrs=array();protected$children=array();public
  312. static$xhtml=TRUE;public
  313. static$emptyElements=array('img'=>1,'hr'=>1,'br'=>1,'input'=>1,'meta'=>1,'area'=>1,'embed'=>1,'keygen'=>1,'source'=>1,'base'=>1,'col'=>1,'link'=>1,'param'=>1,'basefont'=>1,'frame'=>1,'isindex'=>1,'wbr'=>1,'command'=>1);static
  314. function
  315. el($name=NULL,$attrs=NULL){$el=new
  316. static;$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(Strings::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
  317. function
  318. setName($name,$isEmpty=NULL){if($name!==NULL&&!is_string($name)){throw
  319. new
  320. Nette\InvalidArgumentException("Name must be string or NULL, ".gettype($name)." given.");}$this->name=$name;$this->isEmpty=$isEmpty===NULL?isset(static::$emptyElements[$name]):(bool)$isEmpty;return$this;}final
  321. function
  322. getName(){return$this->name;}final
  323. function
  324. isEmpty(){return$this->isEmpty;}function
  325. addAttributes(array$attrs){$this->attrs=$attrs+$this->attrs;return$this;}final
  326. function
  327. __set($name,$value){$this->attrs[$name]=$value;}final
  328. function&__get($name){return$this->attrs[$name];}final
  329. function
  330. __isset($name){return
  331. isset($this->attrs[$name]);}final
  332. function
  333. __unset($name){unset($this->attrs[$name]);}final
  334. function
  335. __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
  336. isset($this->attrs[$m])?$this->attrs[$m]:NULL;}elseif($p==='add'){$args[]=TRUE;}}if(count($args)===0){}elseif(count($args)===1){$this->attrs[$m]=$args[0];}elseif((string)$args[0]===''){$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
  337. function
  338. href($path,$query=NULL){if($query){$query=http_build_query($query,NULL,'&');if($query!==''){$path.='?'.$query;}}$this->attrs['href']=$path;return$this;}final
  339. function
  340. setHtml($html){if($html===NULL){$html='';}elseif(is_array($html)){throw
  341. new
  342. Nette\InvalidArgumentException("Textual content must be a scalar, ".gettype($html)." given.");}else{$html=(string)$html;}$this->removeChildren();$this->children[]=$html;return$this;}final
  343. function
  344. getHtml(){$s='';foreach($this->children
  345. as$child){if(is_object($child)){$s.=$child->render();}else{$s.=$child;}}return$s;}final
  346. function
  347. setText($text){if(!is_array($text)){$text=htmlspecialchars((string)$text,ENT_NOQUOTES);}return$this->setHtml($text);}final
  348. function
  349. getText(){return
  350. html_entity_decode(strip_tags($this->getHtml()),ENT_QUOTES,'UTF-8');}final
  351. function
  352. add($child){return$this->insert(NULL,$child);}final
  353. function
  354. create($name,$attrs=NULL){$this->insert(NULL,$child=static::el($name,$attrs));return$child;}function
  355. insert($index,$child,$replace=FALSE){if($child
  356. instanceof
  357. Html||is_scalar($child)){if($index===NULL){$this->children[]=$child;}else{array_splice($this->children,(int)$index,$replace?1:0,array($child));}}else{throw
  358. new
  359. Nette\InvalidArgumentException("Child node must be scalar or Html object, ".(is_object($child)?get_class($child):gettype($child))." given.");}return$this;}final
  360. function
  361. offsetSet($index,$child){$this->insert($index,$child,TRUE);}final
  362. function
  363. offsetGet($index){return$this->children[$index];}final
  364. function
  365. offsetExists($index){return
  366. isset($this->children[$index]);}function
  367. offsetUnset($index){if(isset($this->children[$index])){array_splice($this->children,(int)$index,1);}}final
  368. function
  369. count(){return
  370. count($this->children);}function
  371. removeChildren(){$this->children=array();}final
  372. function
  373. getIterator($deep=FALSE){if($deep){$deep=$deep>0?\RecursiveIteratorIterator::SELF_FIRST:\RecursiveIteratorIterator::CHILD_FIRST;return
  374. new\RecursiveIteratorIterator(new
  375. Nette\Iterators\Recursor(new\ArrayIterator($this->children)),$deep);}else{return
  376. new
  377. Nette\Iterators\Recursor(new\ArrayIterator($this->children));}}final
  378. function
  379. getChildren(){return$this->children;}final
  380. function
  381. render($indent=NULL){$s=$this->startTag();if(!$this->isEmpty){if($indent!==NULL){$indent++;}foreach($this->children
  382. 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
  383. function
  384. __toString(){return$this->render();}final
  385. function
  386. startTag(){if($this->name){return'<'.$this->name.$this->attributes().(static::$xhtml&&$this->isEmpty?' />':'>');}else{return'';}}final
  387. function
  388. endTag(){return$this->name&&!$this->isEmpty?'</'.$this->name.'>':'';}final
  389. function
  390. attributes(){if(!is_array($this->attrs)){return'';}$s='';foreach($this->attrs
  391. as$key=>$value){if($value===NULL||$value===FALSE){continue;}elseif($value===TRUE){if(static::$xhtml){$s.=' '.$key.'="'.$key.'"';}else{$s.=' '.$key;}continue;}elseif(is_array($value)){if($key==='data'){foreach($value
  392. as$k=>$v){if($v!==NULL&&$v!==FALSE){$s.=' data-'.$k.'="'.htmlspecialchars((string)$v).'"';}}continue;}$tmp=NULL;foreach($value
  393. as$k=>$v){if($v!=NULL){$tmp[]=$v===TRUE?$k:(is_string($k)?$k.':'.$v:$v);}}if($tmp===NULL){continue;}$value=implode($key==='style'||!strncmp($key,'on',2)?';':' ',$tmp);}else{$value=(string)$value;}$s.=' '.$key.'="'.htmlspecialchars($value).'"';}$s=str_replace('@','&#64;',$s);return$s;}function
  394. __clone(){foreach($this->children
  395. as$key=>$value){if(is_object($value)){$this->children[$key]=clone$value;}}}}}namespace Nette\Diagnostics{use
  396. Nette;final
  397. class
  398. Debugger{public
  399. static$productionMode;public
  400. static$consoleMode;public
  401. static$time;private
  402. static$ajaxDetected;public
  403. static$source;public
  404. static$editor='editor://open/?file=%file&line=%line';public
  405. static$browser;public
  406. static$maxDepth=3;public
  407. static$maxLen=150;public
  408. static$showLocation=FALSE;public
  409. static$consoleColors=array('bool'=>'1;33','null'=>'1;33','int'=>'1;36','float'=>'1;36','string'=>'1;32','array'=>'1;31','key'=>'1;37','object'=>'1;31','visibility'=>'1;30','resource'=>'1;37');const
  410. DEVELOPMENT=FALSE,PRODUCTION=TRUE,DETECT=NULL;public
  411. static$blueScreen;public
  412. static$strictMode=FALSE;public
  413. static$scream=FALSE;public
  414. static$onFatalError=array();private
  415. static$enabled=FALSE;private
  416. static$lastError=FALSE;public
  417. static$logger;public
  418. static$fireLogger;public
  419. static$logDirectory;public
  420. static$email;public
  421. static$mailer;public
  422. static$emailSnooze;public
  423. static$bar;private
  424. static$errorPanel;private
  425. static$dumpPanel;const
  426. DEBUG='debug',INFO='info',WARNING='warning',ERROR='error',CRITICAL='critical';final
  427. function
  428. __construct(){throw
  429. new
  430. Nette\StaticClassException;}static
  431. function
  432. _init(){self::$time=microtime(TRUE);self::$consoleMode=PHP_SAPI==='cli';self::$productionMode=self::DETECT;if(self::$consoleMode){self::$source=empty($_SERVER['argv'])?'cli':'cli: '.implode(' ',$_SERVER['argv']);}else{self::$ajaxDetected=isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';if(isset($_SERVER['REQUEST_URI'])){self::$source=(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'];}}self::$logger=new
  433. Logger;self::$logDirectory=&self::$logger->directory;self::$email=&self::$logger->email;self::$mailer=&self::$logger->mailer;self::$emailSnooze=&Logger::$emailSnooze;self::$fireLogger=new
  434. FireLogger;self::$blueScreen=new
  435. BlueScreen;self::$blueScreen->addPanel(function($e){if($e
  436. instanceof
  437. Nette\Templating\FilterException){return
  438. array('tab'=>'Template','panel'=>'<p><b>File:</b> '.Helpers::editorLink($e->sourceFile,$e->sourceLine).'&nbsp; <b>Line:</b> '.($e->sourceLine?$e->sourceLine:'n/a').'</p>'.($e->sourceLine?BlueScreen::highlightFile($e->sourceFile,$e->sourceLine):''));}elseif($e
  439. instanceof
  440. Nette\Utils\NeonException&&preg_match('#line (\d+)#',$e->getMessage(),$m)){if($item=Helpers::findTrace($e->getTrace(),'Nette\Config\Adapters\NeonAdapter::load')){return
  441. array('tab'=>'NEON','panel'=>'<p><b>File:</b> '.Helpers::editorLink($item['args'][0],$m[1]).'&nbsp; <b>Line:</b> '.$m[1].'</p>'.BlueScreen::highlightFile($item['args'][0],$m[1]));}elseif($item=Helpers::findTrace($e->getTrace(),'Nette\Utils\Neon::decode')){return
  442. array('tab'=>'NEON','panel'=>BlueScreen::highlightPhp($item['args'][0],$m[1]));}}});self::$bar=new
  443. Bar;self::$bar->addPanel(new
  444. DefaultBarPanel('time'));self::$bar->addPanel(new
  445. DefaultBarPanel('memory'));self::$bar->addPanel(self::$errorPanel=new
  446. DefaultBarPanel('errors'));self::$bar->addPanel(self::$dumpPanel=new
  447. DefaultBarPanel('dumps'));}static
  448. function
  449. enable($mode=NULL,$logDirectory=NULL,$email=NULL){error_reporting(E_ALL|E_STRICT);if(is_bool($mode)){self::$productionMode=$mode;}elseif($mode!==self::DETECT||self::$productionMode===NULL){$mode=is_string($mode)?preg_split('#[,\s]+#',$mode):(array)$mode;$mode[]='127.0.0.1';$mode[]='::1';self::$productionMode=!in_array(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:php_uname('n'),$mode,TRUE);}if(is_string($logDirectory)){self::$logDirectory=realpath($logDirectory);if(self::$logDirectory===FALSE){throw
  450. new
  451. Nette\DirectoryNotFoundException("Directory '$logDirectory' is not found.");}}elseif($logDirectory===FALSE){self::$logDirectory=FALSE;}elseif(self::$logDirectory===NULL){self::$logDirectory=defined('APP_DIR')?APP_DIR.'/../log':getcwd().'/log';}if(self::$logDirectory){ini_set('error_log',self::$logDirectory.'/php_error.log');}if(function_exists('ini_set')){ini_set('display_errors',!self::$productionMode);ini_set('html_errors',FALSE);ini_set('log_errors',FALSE);}elseif(ini_get('display_errors')!=!self::$productionMode&&ini_get('display_errors')!==(self::$productionMode?'stderr':'stdout')){throw
  452. new
  453. Nette\NotSupportedException('Function ini_set() must be enabled.');}if($email){if(!is_string($email)){throw
  454. new
  455. Nette\InvalidArgumentException('Email address must be a string.');}self::$email=$email;}if(!defined('E_DEPRECATED')){define('E_DEPRECATED',8192);}if(!defined('E_USER_DEPRECATED')){define('E_USER_DEPRECATED',16384);}if(!self::$enabled){register_shutdown_function(array(__CLASS__,'_shutdownHandler'));set_exception_handler(array(__CLASS__,'_exceptionHandler'));set_error_handler(array(__CLASS__,'_errorHandler'));self::$enabled=TRUE;}}static
  456. function
  457. isEnabled(){return
  458. self::$enabled;}static
  459. function
  460. log($message,$priority=self::INFO){if(self::$logDirectory===FALSE){return;}elseif(!self::$logDirectory){throw
  461. new
  462. Nette\InvalidStateException('Logging directory is not specified in Nette\Diagnostics\Debugger::$logDirectory.');}if($message
  463. instanceof\Exception){$exception=$message;$message=($message
  464. instanceof
  465. Nette\FatalErrorException?'Fatal error: '.$exception->getMessage():get_class($exception).": ".$exception->getMessage())." in ".$exception->getFile().":".$exception->getLine();$hash=md5($exception);$exceptionFilename="exception-".@date('Y-m-d-H-i-s')."-$hash.html";foreach(new\DirectoryIterator(self::$logDirectory)as$entry){if(strpos($entry,$hash)){$exceptionFilename=$entry;$saved=TRUE;break;}}}self::$logger->log(array(@date('[Y-m-d H-i-s]'),trim($message),self::$source?' @ '.self::$source:NULL,!empty($exceptionFilename)?' @@ '.$exceptionFilename:NULL),$priority);if(!empty($exceptionFilename)){$exceptionFilename=self::$logDirectory.'/'.$exceptionFilename;if(empty($saved)&&$logHandle=@fopen($exceptionFilename,'w')){ob_start();ob_start(function($buffer)use($logHandle){fwrite($logHandle,$buffer);},4096);self::$blueScreen->render($exception);ob_end_flush();ob_end_clean();fclose($logHandle);}return
  466. strtr($exceptionFilename,'\\/',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);}}static
  467. function
  468. _shutdownHandler(){if(!self::$enabled){return;}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']])){self::_exceptionHandler(new
  469. Nette\FatalErrorException($error['message'],0,$error['type'],$error['file'],$error['line'],NULL));}if(self::$bar&&!self::$productionMode&&self::isHtmlMode()){self::$bar->render();}}static
  470. function
  471. _exceptionHandler(\Exception$exception){if(!headers_sent()){$protocol=isset($_SERVER['SERVER_PROTOCOL'])?$_SERVER['SERVER_PROTOCOL']:'HTTP/1.1';header($protocol.' 500',TRUE,500);}try{if(self::$productionMode){try{self::log($exception,self::ERROR);}catch(\Exception$e){echo'FATAL ERROR: unable to log error';}if(self::$consoleMode){echo"ERROR: the server encountered an internal error and was unable to complete your request.\n";}elseif(self::isHtmlMode()){?>
  472. <!DOCTYPE html>
  473. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  474. <meta name=robots content=noindex><meta name=generator content="Nette Framework">
  475. <style>body{color:#333;background:white;width:500px;margin:100px auto}h1{font:bold 47px/1.5 sans-serif;margin:.6em 0}p{font:21px/1.5 Georgia,serif;margin:1.5em 0}small{font-size:70%;color:gray}</style>
  476. <title>Server Error</title>
  477. <h1>Server Error</h1>
  478. <p>We're sorry! The server encountered an internal error and was unable to complete your request. Please try again later.</p>
  479. <p><small>error 500</small></p>
  480. <?php }}else{if(self::$consoleMode){echo"$exception\n";if($file=self::log($exception)){echo"(stored in $file)\n";if(self::$browser){exec(self::$browser.' '.escapeshellarg($file));}}}elseif(self::isHtmlMode()){self::$blueScreen->render($exception);if(self::$bar){self::$bar->render();}}elseif(!self::fireLog($exception,self::ERROR)){$file=self::log($exception);if(!headers_sent()){header("X-Nette-Error-Log: $file");}}}foreach(self::$onFatalError
  481. as$handler){call_user_func($handler,$exception);}}catch(\Exception$e){if(self::$productionMode){echo
  482. self::isHtmlMode()?'<meta name=robots content=noindex>FATAL ERROR':'FATAL ERROR';}else{echo"FATAL ERROR: thrown ",get_class($e),': ',$e->getMessage(),"\nwhile processing ",get_class($exception),': ',$exception->getMessage(),"\n";}}self::$enabled=FALSE;exit(255);}static
  483. function
  484. _errorHandler($severity,$message,$file,$line,$context){if(self::$scream){error_reporting(E_ALL|E_STRICT);}if(self::$lastError!==FALSE&&($severity&error_reporting())===$severity){self::$lastError=new\ErrorException($message,0,$severity,$file,$line);return
  485. NULL;}if($severity===E_RECOVERABLE_ERROR||$severity===E_USER_ERROR){throw
  486. new
  487. Nette\FatalErrorException($message,0,$severity,$file,$line,$context);}elseif(($severity&error_reporting())!==$severity){return
  488. FALSE;}elseif(!self::$productionMode&&(is_bool(self::$strictMode)?self::$strictMode:((self::$strictMode&$severity)===$severity))){self::_exceptionHandler(new
  489. Nette\FatalErrorException($message,0,$severity,$file,$line,$context));}static$types=array(E_WARNING=>'Warning',E_COMPILE_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";$count=&self::$errorPanel->data["$message|$file|$line"];if($count++){return
  490. NULL;}elseif(self::$productionMode){self::log("$message in $file:$line",self::ERROR);return
  491. NULL;}else{$ok=self::fireLog(new\ErrorException($message,0,$severity,$file,$line),self::WARNING);return!self::isHtmlMode()||(!self::$bar&&!$ok)?FALSE:NULL;}return
  492. FALSE;}static
  493. function
  494. toStringException(\Exception$exception){if(self::$enabled){self::_exceptionHandler($exception);}else{trigger_error($exception->getMessage(),E_USER_ERROR);}}static
  495. function
  496. tryError(){if(!self::$enabled&&self::$lastError===FALSE){set_error_handler(array(__CLASS__,'_errorHandler'));}self::$lastError=NULL;}static
  497. function
  498. catchError(&$error){if(!self::$enabled&&self::$lastError!==FALSE){restore_error_handler();}$error=self::$lastError;self::$lastError=FALSE;return(bool)$error;}static
  499. function
  500. dump($var,$return=FALSE){if(!$return&&self::$productionMode){return$var;}$output="<pre class=\"nette-dump\">".Helpers::htmlDump($var)."</pre>\n";if(!$return){$trace=debug_backtrace(FALSE);$i=Helpers::findTrace($trace,'dump')?1:0;if(isset($trace[$i]['file'],$trace[$i]['line'])&&is_file($trace[$i]['file'])){$lines=file($trace[$i]['file']);preg_match('#dump\((.*)\)#',$lines[$trace[$i]['line']-1],$m);$output=substr_replace($output,' title="'.htmlspecialchars((isset($m[0])?"$m[0] \n":'')."in file {$trace[$i]['file']} on line {$trace[$i]['line']}").'"',4,0);if(self::$showLocation){$output=substr_replace($output,' <small>in '.Helpers::editorLink($trace[$i]['file'],$trace[$i]['line']).":{$trace[$i]['line']}</small>",-8,0);}}}if(self::$consoleMode){if(self::$consoleColors&&substr(PHP_OS,0,3)!=='WIN'){$output=preg_replace_callback('#<span class="php-(\w+)">|</span>#',function($m){return"\033[".(isset($m[1],Debugger::$consoleColors[$m[1]])?Debugger::$consoleColors[$m[1]]:'0')."m";},$output);}$output=htmlspecialchars_decode(strip_tags($output),ENT_QUOTES);}if($return){return$output;}else{echo$output;return$var;}}static
  501. function
  502. timer($name=NULL){static$time=array();$now=microtime(TRUE);$delta=isset($time[$name])?$now-$time[$name]:0;$time[$name]=$now;return$delta;}static
  503. function
  504. barDump($var,$title=NULL){if(!self::$productionMode){$dump=array();foreach((is_array($var)?$var:array(''=>$var))as$key=>$val){$dump[$key]=Helpers::clickableDump($val);}self::$dumpPanel->data[]=array('title'=>$title,'dump'=>$dump);}return$var;}static
  505. function
  506. fireLog($message){if(!self::$productionMode){return
  507. self::$fireLogger->log($message);}}private
  508. static
  509. function
  510. isHtmlMode(){return!self::$ajaxDetected&&!self::$consoleMode&&!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list()));}static
  511. function
  512. addPanel(IBarPanel$panel,$id=NULL){return
  513. self::$bar->addPanel($panel,$id);}}class
  514. Logger
  515. extends
  516. Nette\Object{const
  517. DEBUG='debug',INFO='info',WARNING='warning',ERROR='error',CRITICAL='critical';public
  518. static$emailSnooze=172800;public$mailer=array(__CLASS__,'defaultMailer');public$directory;public$email;function
  519. log($message,$priority=self::INFO){if(!is_dir($this->directory)){throw
  520. new
  521. Nette\DirectoryNotFoundException("Directory '$this->directory' is not found or is not directory.");}if(is_array($message)){$message=implode(' ',$message);}$res=error_log(trim($message).PHP_EOL,3,$this->directory.'/'.strtolower($priority).'.log');if(($priority===self::ERROR||$priority===self::CRITICAL)&&$this->email&&$this->mailer&&@filemtime($this->directory.'/email-sent')+self::$emailSnooze<time()&&@file_put_contents($this->directory.'/email-sent','sent')){callback($this->mailer)->invoke($message,$this->email);}return$res;}static
  522. function
  523. defaultMailer($message,$email){$host='';foreach(array('HTTP_HOST','SERVER_NAME','HOSTNAME')as$item){if(isset($_SERVER[$item])){$host=$_SERVER[$item];break;}}$parts=str_replace(array("\r\n","\n"),array("\n",PHP_EOL),array('headers'=>"From: noreply@$host\nX-Mailer: Nette Framework\n",'subject'=>"PHP: An error occurred on the server $host",'body'=>"[".@date('Y-m-d H:i:s')."] $message"));mail($email,$parts['subject'],$parts['body'],$parts['headers']);}}class
  524. FireLogger
  525. extends
  526. Nette\Object{const
  527. DEBUG='debug',INFO='info',WARNING='warning',ERROR='error',CRITICAL='critical';private
  528. static$payload=array('logs'=>array());static
  529. function
  530. log($message,$priority=self::DEBUG){if(!isset($_SERVER['HTTP_X_FIRELOGGER'])||headers_sent()){return
  531. FALSE;}$item=array('name'=>'PHP','level'=>$priority,'order'=>count(self::$payload['logs']),'time'=>str_pad(number_format((microtime(TRUE)-Debugger::$time)*1000,1,'.',' '),8,'0',STR_PAD_LEFT).' ms','template'=>'','message'=>'','style'=>'background:#767ab6');$args=func_get_args();if(isset($args[0])&&is_string($args[0])){$item['template']=array_shift($args);}if(isset($args[0])&&$args[0]instanceof\Exception){$e=array_shift($args);$trace=$e->getTrace();if(isset($trace[0]['class'])&&$trace[0]['class']==='Nette\Diagnostics\Debugger'&&($trace[0]['function']==='_shutdownHandler'||$trace[0]['function']==='_errorHandler')){unset($trace[0]);}$file=str_replace(dirname(dirname(dirname($e->getFile()))),"\xE2\x80\xA6",$e->getFile());$item['template']=($e
  532. instanceof\ErrorException?'':get_class($e).': ').$e->getMessage().($e->getCode()?' #'.$e->getCode():'').' in '.$file.':'.$e->getLine();$item['pathname']=$e->getFile();$item['lineno']=$e->getLine();}else{$trace=debug_backtrace();if(isset($trace[1]['class'])&&$trace[1]['class']==='Nette\Diagnostics\Debugger'&&($trace[1]['function']==='fireLog')){unset($trace[0]);}foreach($trace
  533. as$frame){if(isset($frame['file'])&&is_file($frame['file'])){$item['pathname']=$frame['file'];$item['lineno']=$frame['line'];break;}}}$item['exc_info']=array('','',array());$item['exc_frames']=array();foreach($trace
  534. as$frame){$frame+=array('file'=>NULL,'line'=>NULL,'class'=>NULL,'type'=>NULL,'function'=>NULL,'object'=>NULL,'args'=>NULL);$item['exc_info'][2][]=array($frame['file'],$frame['line'],"$frame[class]$frame[type]$frame[function]",$frame['object']);$item['exc_frames'][]=$frame['args'];}if(isset($args[0])&&in_array($args[0],array(self::DEBUG,self::INFO,self::WARNING,self::ERROR,self::CRITICAL),TRUE)){$item['level']=array_shift($args);}$item['args']=$args;self::$payload['logs'][]=self::jsonDump($item,-1);foreach(str_split(base64_encode(@json_encode(self::$payload)),4990)as$k=>$v){header("FireLogger-de11e-$k:$v");}return
  535. TRUE;}private
  536. static
  537. function
  538. jsonDump(&$var,$level=0){if(is_bool($var)||is_null($var)||is_int($var)||is_float($var)){return$var;}elseif(is_string($var)){if(Debugger::$maxLen&&strlen($var)>Debugger::$maxLen){$var=substr($var,0,Debugger::$maxLen)." \xE2\x80\xA6 ";}return
  539. Nette\Utils\Strings::fixEncoding($var);}elseif(is_array($var)){static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}if(isset($var[$marker])){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level<Debugger::$maxDepth||!Debugger::$maxDepth){$var[$marker]=TRUE;$res=array();foreach($var
  540. as$k=>&$v){if($k!==$marker){$res[self::jsonDump($k)]=self::jsonDump($v,$level+1);}}unset($var[$marker]);return$res;}else{return" \xE2\x80\xA6 ";}}elseif(is_object($var)){$arr=(array)$var;static$list=array();if(in_array($var,$list,TRUE)){return"\xE2\x80\xA6RECURSION\xE2\x80\xA6";}elseif($level<Debugger::$maxDepth||!Debugger::$maxDepth){$list[]=$var;$res=array("\x00"=>'(object) '.get_class($var));foreach($arr
  541. as$k=>&$v){if($k[0]==="\x00"){$k=substr($k,strrpos($k,"\x00")+1);}$res[self::jsonDump($k)]=self::jsonDump($v,$level+1);}array_pop($list);return$res;}else{return" \xE2\x80\xA6 ";}}elseif(is_resource($var)){return"resource ".get_resource_type($var);}else{return"unknown type";}}}class
  542. BlueScreen
  543. extends
  544. Nette\Object{private$panels=array();function
  545. addPanel($panel){if(!in_array($panel,$this->panels,TRUE)){$this->panels[]=$panel;}return$this;}function
  546. render(\Exception$exception){$panels=$this->panels;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
  547. instanceof
  548. Nette\FatalErrorException&&isset($errorTypes[$exception->getSeverity()]))?$errorTypes[$exception->getSeverity()]:get_class($exception);$expandPath=NETTE_DIR.DIRECTORY_SEPARATOR;$counter=0;?><!DOCTYPE html><!-- "' --></script></style></pre></xmp></table>
  549. <html>
  550. <head>
  551. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  552. <meta name="robots" content="noindex,noarchive">
  553. <meta name="generator" content="Nette Framework">
  554. <title><?php echo
  555. htmlspecialchars($title)?></title><!-- <?php
  556. $ex=$exception;echo
  557. htmlspecialchars($ex->getMessage().($ex->getCode()?' #'.$ex->getCode():''));while((method_exists($ex,'getPrevious')&&$ex=$ex->getPrevious())||(isset($ex->previous)&&$ex=$ex->previous))echo
  558. htmlspecialchars('; caused by '.get_class($ex).' '.$ex->getMessage().($ex->getCode()?' #'.$ex->getCode():''));?> -->
  559. <style type="text/css" class="nette">html{overflow-y:scroll}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 *{font:inherit;color:inherit;background:transparent;border:none;margin:0;padding:0;text-align:inherit;text-indent:0}#netteBluescreen b{font-weight:bold}#netteBluescreen i{font-style:italic}#netteBluescreen a{text-decoration:none;color:#328ADC;padding:2px 4px;margin:-2px -4px}#netteBluescreen a:hover,#netteBluescreen a:active,#netteBluescreen a:focus{color:#085AA3}#netteBluescreen a abbr{font-family:sans-serif;color:#BBB}#netteBluescreenIcon{position:absolute;right:.5em;top:.5em;z-index:23179;text-decoration:none;background:#CD1818;padding:3px}#netteBluescreenError{background:#CD1818;color:white;font:13pt/1.5 Verdana,sans-serif!important;display:block}#netteBluescreenError #netteBsSearch{color:#CD1818;font-size:.7em}#netteBluescreenError:hover #netteBsSearch{color:#ED8383}#netteBluescreen h1{font-size:18pt;font-weight:normal;text-shadow:1px 1px 0 rgba(0,0,0,.4);margin:.7em 0}#netteBluescreen h2{font:14pt/1.5 sans-serif!important;color:#888;margin:.6em 0}#netteBluescreen h3{font:bold 10pt/1.5 Verdana,sans-serif!important;margin:1em 0;padding:0}#netteBluescreen p,#netteBluescreen pre{margin:.8em 0}#netteBluescreen pre,#netteBluescreen code,#netteBluescreen table{font:9pt/1.5 Consolas,monospace!important}#netteBluescreen pre,#netteBluescreen table{background:#FDF5CE;padding:.4em .7em;border:1px dotted silver;overflow:auto}#netteBluescreen pre div{min-width:100%;float:left;_float:none;white-space:pre}#netteBluescreen table pre{padding:0;margin:0;border:none}#netteBluescreen pre .php-array,#netteBluescreen pre .php-object{color:#C22}#netteBluescreen pre .php-string{color:#080}#netteBluescreen pre .php-int,#netteBluescreen pre .php-float,#netteBluescreen pre .php-null,#netteBluescreen pre .php-bool{color:#328ADC}#netteBluescreen pre .php-visibility{font-size:85%;color:#998}#netteBluescreen pre.nette-dump a{color:#333}#netteBluescreen div.panel{padding:1px 25px}#netteBluescreen div.inner{background:#F4F3F1;padding:.1em 1em 1em;border-radius:8px;-moz-border-radius:8px;-webkit-border-radius:8px}#netteBluescreen table{border-collapse:collapse;width:100%}#netteBluescreen .outer{overflow:auto}#netteBluescreen td,#netteBluescreen th{vertical-align:top;text-align:left;padding:2px 6px;border:1px solid #e6dfbf}#netteBluescreen th{font-weight:bold}#netteBluescreen tr>:first-child{width:20%}#netteBluescreen tr:nth-child(2n),#netteBluescreen tr:nth-child(2n) pre{background-color:#F7F0CB}#netteBluescreen ol{margin:1em 0;padding-left:2.5em}#netteBluescreen ul{font:7pt/1.5 Verdana,sans-serif!important;padding:2em 4em;margin:1em 0 0;color:#777;background:#F6F5F3 url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFEAAAAjCAMAAADbuxbOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADBQTFRF/fz24d7Y7Onj5uLd9vPu3drUzMvG09LN39zW8e7o2NbQ3NnT29jS0M7J1tXQAAAApvmsFgAAABB0Uk5T////////////////////AOAjXRkAAAKlSURBVHja7FbbsqQgDAwENEgc//9vN+SCWDtbtXPmZR/Wc6o02mlC58LA9ckFAOszvMV8xNgyUjyXhojfMVKvRL0ZHavxXYy5JrmchMdzou8YlTClxajtK8ZGGpWRoBr1+gFjKfHkJPbizabLgzE3pH7Iu4K980xgFvlrVzMZoVBWhtvouCDdcTDmTgMCJdVxJ9MKO6XxnliM7hxi5lbj2ZVM4l8DqYyKoNLYcfqBB1/LpHYxEcfVG6ZpMDgyFUVWY/Q1sSYPpIdSAKWqLWL0XqWiMWc4hpH0OQOMOAgdycY4N9Sb7wWANQs3rsDSdLAYiuxi5siVfOhBWIrtH0G3kNaF/8Q4kCPE1kMucG/ZMUBUCOgiKJkPuWWTLGVgLGpwns1DraUayCtoBqERyaYtVsm85NActRooezvSLO/sKZP/nq8n4+xcyjNsRu8zW6KWpdb7wjiQd4WrtFZYFiKHENSmWp6xshh96c2RQ+c7Lt+qbijyEjHWUJ/pZsy8MGIUuzNiPySK2Gqoh6ZTRF6ko6q3nVTkaA//itIrDpW6l3SLo8juOmqMXkYknu5FdQxWbhCfKHEGDhxxyTVaXJF3ZjSl3jMksjSOOKmne9pI+mcG5QvaUJhI9HpkmRo2NpCrDJvsktRhRE2MM6F2n7dt4OaMUq8bCctk0+PoMRzL+1l5PZ2eyM/Owr86gf8z/tOM53lom5+nVcFuB+eJVzlXwAYy9TZ9s537tfqcsJWbEU4nBngZo6FfO9T9CdhfBtmk2dLiAy8uS4zwOpMx2HqYbTC+amNeAYTpsP4SIgvWfUBWXxn3CMHW3ffd7k3+YIkx7w0t/CVGvcPejoeOlzOWzeGbawOHqXQGUTMZRcfj4XPCgW9y/fuvVn8zD9P1QHzv80uAAQA0i3Jer7Jr7gAAAABJRU5ErkJggg==') 99% 10px no-repeat;border-top:1px solid #DDD}#netteBluescreen .highlight{background:#CD1818;color:white;font-weight:bold;font-style:normal;display:block;padding:0 .4em;margin:0 -.4em}#netteBluescreen .line{color:#9F9C7F;font-weight:normal;font-style:normal}#netteBluescreen a[href^=editor\:]{color:inherit;border-bottom:1px dotted #C1D2E1}</style>
  560. </head>
  561. <body>
  562. <div id="netteBluescreen">
  563. <a id="netteBluescreenIcon" href="#" rel="next"><abbr>&#x25bc;</abbr></a
  564. ><div>
  565. <div id="netteBluescreenError" class="panel">
  566. <h1><?php echo
  567. htmlspecialchars($title),($exception->getCode()?' #'.$exception->getCode():'')?></h1>
  568. <p><?php echo
  569. htmlspecialchars($exception->getMessage())?> <a href="http://www.google.cz/search?sourceid=nette&amp;q=<?php echo
  570. urlencode($title.' '.preg_replace('#\'.*\'|".*"#Us','',$exception->getMessage()))?>" id="netteBsSearch">search&#x25ba;</a></p>
  571. </div>
  572. <?php $ex=$exception;$level=0;?>
  573. <?php do{?>
  574. <?php if($level++):?>
  575. <div class="panel">
  576. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">Caused by <abbr><?php echo($collapsed=$level>2)?'&#x25ba;':'&#x25bc;'?></abbr></a></h2>
  577. <div id="netteBsPnl<?php echo$counter?>" class="<?php echo$collapsed?'nette-collapsed ':''?>inner">
  578. <div class="panel">
  579. <h1><?php echo
  580. htmlspecialchars(get_class($ex).($ex->getCode()?' #'.$ex->getCode():''))?></h1>
  581. <p><b><?php echo
  582. htmlspecialchars($ex->getMessage())?></b></p>
  583. </div>
  584. <?php endif?>
  585. <?php foreach($panels
  586. as$panel):?>
  587. <?php $panel=call_user_func($panel,$ex);if(empty($panel['tab'])||empty($panel['panel']))continue;?>
  588. <?php if(!empty($panel['bottom'])){continue;}?>
  589. <div class="panel">
  590. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>"><?php echo
  591. htmlSpecialChars($panel['tab'])?> <abbr>&#x25bc;</abbr></a></h2>
  592. <div id="netteBsPnl<?php echo$counter?>" class="inner">
  593. <?php echo$panel['panel']?>
  594. </div></div>
  595. <?php endforeach?>
  596. <?php $stack=$ex->getTrace();$expanded=NULL?>
  597. <?php if(strpos($ex->getFile(),$expandPath)===0){foreach($stack
  598. as$key=>$row){if(isset($row['file'])&&strpos($row['file'],$expandPath)!==0){$expanded=$key;break;}}}?>
  599. <div class="panel">
  600. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">Source file <abbr><?php echo($collapsed=$expanded!==NULL)?'&#x25ba;':'&#x25bc;'?></abbr></a></h2>
  601. <div id="netteBsPnl<?php echo$counter?>" class="<?php echo$collapsed?'nette-collapsed ':''?>inner">
  602. <p><b>File:</b> <?php echo
  603. Helpers::editorLink($ex->getFile(),$ex->getLine())?> &nbsp; <b>Line:</b> <?php echo$ex->getLine()?></p>
  604. <?php if(is_file($ex->getFile())):?><?php echo
  605. self::highlightFile($ex->getFile(),$ex->getLine(),15,isset($ex->context)?$ex->context:NULL)?><?php endif?>
  606. </div></div>
  607. <?php if(isset($stack[0]['class'])&&$stack[0]['class']==='Nette\Diagnostics\Debugger'&&($stack[0]['function']==='_shutdownHandler'||$stack[0]['function']==='_errorHandler'))unset($stack[0])?>
  608. <?php if($stack):?>
  609. <div class="panel">
  610. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">Call stack <abbr>&#x25bc;</abbr></a></h2>
  611. <div id="netteBsPnl<?php echo$counter?>" class="inner">
  612. <ol>
  613. <?php foreach($stack
  614. as$key=>$row):?>
  615. <li><p>
  616. <?php if(isset($row['file'])&&is_file($row['file'])):?>
  617. <?php echo
  618. Helpers::editorLink($row['file'],$row['line']),':',$row['line']?>
  619. <?php else:?>
  620. <i>inner-code</i><?php if(isset($row['line']))echo':',$row['line']?>
  621. <?php endif?>
  622. <?php if(isset($row['file'])&&is_file($row['file'])):?><a href="#" rel="netteBsSrc<?php echo"$level-$key"?>">source <abbr>&#x25ba;</abbr></a>&nbsp; <?php endif?>
  623. <?php if(isset($row['class']))echo
  624. htmlspecialchars($row['class'].$row['type'])?>
  625. <?php echo
  626. htmlspecialchars($row['function'])?>
  627. (<?php if(!empty($row['args'])):?><a href="#" rel="netteBsArgs<?php echo"$level-$key"?>">arguments <abbr>&#x25ba;</abbr></a><?php endif?>)
  628. </p>
  629. <?php if(!empty($row['args'])):?>
  630. <div class="nette-collapsed outer" id="netteBsArgs<?php echo"$level-$key"?>">
  631. <table>
  632. <?php
  633. try{$r=isset($row['class'])?new\ReflectionMethod($row['class'],$row['function']):new\ReflectionFunction($row['function']);$params=$r->getParameters();}catch(\Exception$e){$params=array();}foreach($row['args']as$k=>$v){echo'<tr><th>',htmlspecialchars(isset($params[$k])?'$'.$params[$k]->name:"#$k"),'</th><td>';echo
  634. Helpers::clickableDump($v);echo"</td></tr>\n";}?>
  635. </table>
  636. </div>
  637. <?php endif?>
  638. <?php if(isset($row['file'])&&is_file($row['file'])):?>
  639. <div <?php if($expanded!==$key)echo'class="nette-collapsed"';?> id="netteBsSrc<?php echo"$level-$key"?>"><?php echo
  640. self::highlightFile($row['file'],$row['line'])?></div>
  641. <?php endif?>
  642. </li>
  643. <?php endforeach?>
  644. </ol>
  645. </div></div>
  646. <?php endif?>
  647. <?php if(isset($ex->context)&&is_array($ex->context)):?>
  648. <div class="panel">
  649. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">Variables <abbr>&#x25ba;</abbr></a></h2>
  650. <div id="netteBsPnl<?php echo$counter?>" class="nette-collapsed inner">
  651. <div class="outer">
  652. <table>
  653. <?php
  654. foreach($ex->context
  655. as$k=>$v){echo'<tr><th>$',htmlspecialchars($k),'</th><td>',Helpers::clickableDump($v),"</td></tr>\n";}?>
  656. </table>
  657. </div>
  658. </div></div>
  659. <?php endif?>
  660. <?php }while((method_exists($ex,'getPrevious')&&$ex=$ex->getPrevious())||(isset($ex->previous)&&$ex=$ex->previous));?>
  661. <?php while(--$level)echo'</div></div>'?>
  662. <?php $bottomPanels=array()?>
  663. <?php foreach($panels
  664. as$panel):?>
  665. <?php $panel=call_user_func($panel,NULL);if(empty($panel['tab'])||empty($panel['panel']))continue;?>
  666. <?php if(!empty($panel['bottom'])){$bottomPanels[]=$panel;continue;}?>
  667. <div class="panel">
  668. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>"><?php echo
  669. htmlSpecialChars($panel['tab'])?> <abbr>&#x25ba;</abbr></a></h2>
  670. <div id="netteBsPnl<?php echo$counter?>" class="nette-collapsed inner">
  671. <?php echo$panel['panel']?>
  672. </div></div>
  673. <?php endforeach?>
  674. <div class="panel">
  675. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">Environment <abbr>&#x25ba;</abbr></a></h2>
  676. <div id="netteBsPnl<?php echo$counter?>" class="nette-collapsed inner">
  677. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">$_SERVER <abbr>&#x25bc;</abbr></a></h3>
  678. <div id="netteBsPnl<?php echo$counter?>" class="outer">
  679. <table>
  680. <?php
  681. foreach($_SERVER
  682. as$k=>$v)echo'<tr><th>',htmlspecialchars($k),'</th><td>',Helpers::clickableDump($v),"</td></tr>\n";?>
  683. </table>
  684. </div>
  685. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">$_SESSION <abbr>&#x25bc;</abbr></a></h3>
  686. <div id="netteBsPnl<?php echo$counter?>" class="outer">
  687. <?php if(empty($_SESSION)):?>
  688. <p><i>empty</i></p>
  689. <?php else:?>
  690. <table>
  691. <?php
  692. foreach($_SESSION
  693. as$k=>$v)echo'<tr><th>',htmlspecialchars($k),'</th><td>',$k==='__NF'?'<i>Nette Session</i>':Helpers::clickableDump($v),"</td></tr>\n";?>
  694. </table>
  695. <?php endif?>
  696. </div>
  697. <?php if(!empty($_SESSION['__NF']['DATA'])):?>
  698. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">Nette Session <abbr>&#x25bc;</abbr></a></h3>
  699. <div id="netteBsPnl<?php echo$counter?>" class="outer">
  700. <table>
  701. <?php
  702. foreach($_SESSION['__NF']['DATA']as$k=>$v)echo'<tr><th>',htmlspecialchars($k),'</th><td>',Helpers::clickableDump($v),"</td></tr>\n";?>
  703. </table>
  704. </div>
  705. <?php endif?>
  706. <?php
  707. $list=get_defined_constants(TRUE);if(!empty($list['user'])):?>
  708. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">Constants <abbr>&#x25ba;</abbr></a></h3>
  709. <div id="netteBsPnl<?php echo$counter?>" class="outer nette-collapsed">
  710. <table>
  711. <?php
  712. foreach($list['user']as$k=>$v){echo'<tr><th>',htmlspecialchars($k),'</th>';echo'<td>',Helpers::clickableDump($v),"</td></tr>\n";}?>
  713. </table>
  714. </div>
  715. <?php endif?>
  716. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">Included files <abbr>&#x25ba;</abbr></a> (<?php echo
  717. count(get_included_files())?>)</h3>
  718. <div id="netteBsPnl<?php echo$counter?>" class="outer nette-collapsed">
  719. <table>
  720. <?php
  721. foreach(get_included_files()as$v){echo'<tr><td>',htmlspecialchars($v),"</td></tr>\n";}?>
  722. </table>
  723. </div>
  724. <h3><a href="#" rel="netteBsPnl<?php echo++$counter?>">Configuration options <abbr>&#x25ba;</abbr></a></h3>
  725. <div id="netteBsPnl<?php echo$counter?>" class="outer nette-collapsed">
  726. <?php ob_start();@phpinfo(INFO_CONFIGURATION|INFO_MODULES);echo
  727. preg_replace('#^.+<body>|</body>.+$#s','',ob_get_clean())?>
  728. </div>
  729. </div></div>
  730. <div class="panel">
  731. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">HTTP request <abbr>&#x25ba;</abbr></a></h2>
  732. <div id="netteBsPnl<?php echo$counter?>" class="nette-collapsed inner">
  733. <?php if(function_exists('apache_request_headers')):?>
  734. <h3>Headers</h3>
  735. <div class="outer">
  736. <table>
  737. <?php
  738. foreach(apache_request_headers()as$k=>$v)echo'<tr><th>',htmlspecialchars($k),'</th><td>',htmlspecialchars($v),"</td></tr>\n";?>
  739. </table>
  740. </div>
  741. <?php endif?>
  742. <?php foreach(array('_GET','_POST','_COOKIE')as$name):?>
  743. <h3>$<?php echo
  744. htmlspecialchars($name)?></h3>
  745. <?php if(empty($GLOBALS[$name])):?>
  746. <p><i>empty</i></p>
  747. <?php else:?>
  748. <div class="outer">
  749. <table>
  750. <?php
  751. foreach($GLOBALS[$name]as$k=>$v)echo'<tr><th>',htmlspecialchars($k),'</th><td>',Helpers::clickableDump($v),"</td></tr>\n";?>
  752. </table>
  753. </div>
  754. <?php endif?>
  755. <?php endforeach?>
  756. </div></div>
  757. <div class="panel">
  758. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>">HTTP response <abbr>&#x25ba;</abbr></a></h2>
  759. <div id="netteBsPnl<?php echo$counter?>" class="nette-collapsed inner">
  760. <h3>Headers</h3>
  761. <?php if(headers_list()):?>
  762. <pre><?php
  763. foreach(headers_list()as$s)echo
  764. htmlspecialchars($s),'<br>';?></pre>
  765. <?php else:?>
  766. <p><i>no headers</i></p>
  767. <?php endif?>
  768. </div></div>
  769. <?php foreach($bottomPanels
  770. as$panel):?>
  771. <div class="panel">
  772. <h2><a href="#" rel="netteBsPnl<?php echo++$counter?>"><?php echo
  773. htmlSpecialChars($panel['tab'])?> <abbr>&#x25bc;</abbr></a></h2>
  774. <div id="netteBsPnl<?php echo$counter?>" class="inner">
  775. <?php echo$panel['panel']?>
  776. </div></div>
  777. <?php endforeach?>
  778. <ul>
  779. <li>Report generated at <?php echo@date('Y/m/d H:i:s',Debugger::$time)?></li>
  780. <?php if(preg_match('#^https?://#',Debugger::$source)):?>
  781. <li><a href="<?php echo
  782. htmlSpecialChars(Debugger::$source)?>"><?php echo
  783. htmlSpecialChars(Debugger::$source)?></a></li>
  784. <?php elseif(Debugger::$source):?>
  785. <li><?php echo
  786. htmlSpecialChars(Debugger::$source)?></li>
  787. <?php endif?>
  788. <li>PHP <?php echo
  789. htmlSpecialChars(PHP_VERSION)?></li>
  790. <?php if(isset($_SERVER['SERVER_SOFTWARE'])):?><li><?php echo
  791. htmlSpecialChars($_SERVER['SERVER_SOFTWARE'])?></li><?php endif?>
  792. <?php if(class_exists('Nette\Framework')):?><li><?php echo
  793. htmlSpecialChars('Nette Framework '.Nette\Framework::VERSION)?> <i>(revision <?php echo
  794. htmlSpecialChars(Nette\Framework::REVISION)?>)</i></li><?php endif?>
  795. </ul>
  796. </div>
  797. </div>
  798. <script type="text/javascript">/*<![CDATA[*/var bs=document.getElementById("netteBluescreen");document.body.appendChild(bs);document.onkeyup=function(b){b=b||window.event;if(27==b.keyCode&&!b.shiftKey&&!b.altKey&&!b.ctrlKey&&!b.metaKey)bs.onclick({target:document.getElementById("netteBluescreenIcon")})};
  799. for(var i=0,styles=document.styleSheets;i<styles.length;i++)"nette"!==(styles[i].owningElement||styles[i].ownerNode).className?(styles[i].oldDisabled=styles[i].disabled,styles[i].disabled=!0):styles[i].addRule?styles[i].addRule(".nette-collapsed","display: none"):styles[i].insertRule(".nette-collapsed { display: none }",0);
  800. bs.onclick=function(b){for(var b=b||window.event,a=b.target||b.srcElement;a&&a.tagName&&"a"!==a.tagName.toLowerCase();)a=a.parentNode;if(!a||!a.rel)return!0;for(var d=a.getElementsByTagName("abbr")[0],c="next"===a.rel?a.nextSibling:document.getElementById(a.rel);1!==c.nodeType;)c=c.nextSibling;b=c.currentStyle?"none"==c.currentStyle.display:"none"==getComputedStyle(c,null).display;try{d.innerHTML=String.fromCharCode(b?9660:9658)}catch(e){}c.style.display=b?"code"===c.tagName.toLowerCase()?"inline":
  801. "block":"none";if("netteBluescreenIcon"===a.id){a=0;for(d=document.styleSheets;a<d.length;a++)if("nette"!==(d[a].owningElement||d[a].ownerNode).className)d[a].disabled=b?!0:d[a].oldDisabled}return!1};/*]]>*/</script>
  802. </body>
  803. </html>
  804. <?php }static
  805. function
  806. highlightFile($file,$line,$lines=15,$vars=array()){$source=@file_get_contents($file);if($source){return
  807. static::highlightPhp($source,$line,$lines,$vars);}}static
  808. function
  809. highlightPhp($source,$line,$lines=15,$vars=array()){if(function_exists('ini_set')){ini_set('highlight.comment','#998; 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');}$source=str_replace(array("\r\n","\r"),"\n",$source);$source=explode("\n",highlight_string($source,TRUE));$spans=1;$out=$source[0];$source=explode('<br />',$source[1]);array_unshift($source,NULL);$start=$i=max(1,$line-floor($lines*2/3));while(--$i>=1){if(preg_match('#.*(</?span[^>]*>)#',$source[$i],$m)){if($m[1]!=='</span>'){$spans++;$out.=$m[1];}break;}}$source=array_slice($source,$start,$lines,TRUE);end($source);$numWidth=strlen((string)key($source));foreach($source
  810. as$n=>$s){$spans+=substr_count($s,'<span')-substr_count($s,'</span');$s=str_replace(array("\r","\n"),array('',''),$s);preg_match_all('#<[^>]+>#',$s,$tags);if($n==$line){$out.=sprintf("<span class='highlight'>%{$numWidth}s: %s\n</span>%s",$n,strip_tags($s),implode('',$tags[0]));}else{$out.=sprintf("<span class='line'>%{$numWidth}s:</span> %s\n",$n,$s);}}$out.=str_repeat('</span>',$spans).'</code>';$out=preg_replace_callback('#">\$(\w+)(&nbsp;)?</span>#',function($m)use($vars){return
  811. isset($vars[$m[1]])?'" title="'.str_replace('"','&quot;',strip_tags(Helpers::htmlDump($vars[$m[1]]))).$m[0]:$m[0];},$out);return"<pre><div>$out</div></pre>";}}class
  812. Bar
  813. extends
  814. Nette\Object{private$panels=array();function
  815. addPanel(IBarPanel$panel,$id=NULL){if($id===NULL){$c=0;do{$id=get_class($panel).($c++?"-$c":'');}while(isset($this->panels[$id]));}$this->panels[$id]=$panel;return$this;}function
  816. render(){$obLevel=ob_get_level();$panels=array();foreach($this->panels
  817. as$id=>$panel){try{$panels[]=array('id'=>preg_replace('#[^a-z0-9]+#i','-',$id),'tab'=>$tab=(string)$panel->getTab(),'panel'=>$tab?(string)$panel->getPanel():NULL);}catch(\Exception$e){$panels[]=array('id'=>"error-".preg_replace('#[^a-z0-9]+#i','-',$id),'tab'=>"Error in $id",'panel'=>'<h1>Error: '.$id.'</h1><div class="nette-inner">'.nl2br(htmlSpecialChars($e)).'</div>');while(ob_get_level()>$obLevel){ob_end_clean();}}}?>
  818. <!-- Nette Debug Bar -->
  819. <?php ob_start()?>
  820. &nbsp;
  821. <style id="nette-debug-style" class="nette">#nette-debug{display:none;position:fixed}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;max-width:100%}#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:#FDF5CE}#nette-debug .nette-panel tr:nth-child(2n) td{background:#F7F0CB}#nette-debug .nette-panel td,#nette-debug .nette-panel th{border:1px solid #E6DFBF;padding:2px 5px;vertical-align:top;text-align:left}#nette-debug .nette-panel th{background:#F4F3F1;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-debug table .nette-right{text-align:right}.nette-hidden,.nette-collapsed{display:none}#nette-debug-bar{font:normal normal 12px/21px Tahoma,sans-serif;color:#333;border:1px solid #c9c9c9;background:#EDEAE0 url('data:image/png;base64,R0lGODlhAQAVALMAAOTh1/Px6eHe1fHv5e/s4vLw6Ofk2u3q4PPw6PPx6PDt5PLw5+Dd1OXi2Ojm3Orn3iH5BAAAAAAALAAAAAABABUAAAQPMISEyhpYkfOcaQAgCEwEADs=') top;position:relative;overflow:auto;min-height:21px;_float:left;min-width:50px;white-space:nowrap;z-index:23181;opacity:.9;border-radius:3px;-moz-border-radius:3px;box-shadow:1px 1px 10px rgba(0,0,0,.15);-moz-box-shadow:1px 1px 10px rgba(0,0,0,.15);-webkit-box-shadow:1px 1px 10px rgba(0,0,0,.15)}#nette-debug-bar:hover{opacity:1}#nette-debug-bar ul{list-style:none none;margin-left:4px}#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>span{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 .nette-panel{font:normal normal 12px/1.5 sans-serif;background:white;color:#333;text-align:left}#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;box-shadow:1px 1px 6px #666;-moz-box-shadow:1px 1px 6px rgba(0,0,0,.45);-webkit-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}pre.nette-dump{color:#444;background:white}pre.nette-dump a,#nette-debug pre.nette-dump a{color:inherit;background:inherit}pre.nette-dump .php-array,pre.nette-dump .php-object,#nette-debug pre.nette-dump .php-array,#nette-debug pre.nette-dump .php-object{color:#C22}pre.nette-dump .php-string,#nette-debug pre.nette-dump .php-string{color:#080}pre.nette-dump .php-int,pre.nette-dump .php-float,#nette-debug pre.nette-dump .php-int,#nette-debug pre.nette-dump .php-float{color:#37D}pre.nette-dump .php-null,pre.nette-dump .php-bool,#nette-debug pre.nette-dump .php-null,#nette-debug pre.nette-dump .php-bool{color:black}pre.nette-dump .php-visibility,#nette-debug pre.nette-dump .php-visibility{font-size:85%;color:#999}</style>
  822. <!--[if lt IE 8]><style class="nette">#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]-->
  823. <script id="nette-debug-script">/*<![CDATA[*/var Nette=Nette||{};
  824. (function(){Nette.Class=function(a){var b=a.constructor||function(){},c,f=Object.prototype.hasOwnProperty;delete a.constructor;if(a.Extends){var d=function(){this.constructor=b};d.prototype=a.Extends.prototype;b.prototype=new d;delete a.Extends}if(a.Static){for(c in a.Static)f.call(a.Static,c)&&(b[c]=a.Static[c]);delete a.Static}for(c in a)f.call(a,c)&&(b.prototype[c]=a[c]);return b};Nette.Q=Nette.Class({Static:{factory:function(a){return new Nette.Q(a)},implement:function(a){var b,c=Nette.Q.implement,
  825. f=Nette.Q.prototype,d=Object.prototype.hasOwnProperty;for(b in a)d.call(a,b)&&(c[b]=a[b],f[b]=function(a){return function(){return this.each(c[a],arguments)}}(b))}},constructor:function(a){if("string"===typeof a)a=this._find(document,a);else if(!a||a.nodeType||void 0===a.length||a===window)a=[a];for(var b=0,c=a.length;b<c;b++)a[b]&&(this[this.length++]=a[b])},length:0,find:function(a){return new Nette.Q(this._find(this[0],a))},_find:function(a,b){if(!a||!b)return[];if(document.querySelectorAll)return a.querySelectorAll(b);
  826. if("#"===b.charAt(0))return[document.getElementById(b.substring(1))];var b=b.split("."),c=a.getElementsByTagName(b[0]||"*");if(b[1]){for(var f=[],d=RegExp("(^|\\s)"+b[1]+"(\\s|$)"),e=0,g=c.length;e<g;e++)d.test(c[e].className)&&f.push(c[e]);return f}return c},dom:function(){return this[0]},each:function(a,b){for(var c=0,f;c<this.length;c++)if(void 0!==(f=a.apply(this[c],b||[])))return f;return this}});var e=Nette.Q.factory,d=Nette.Q.implement;d({bind:function(a,b){if(document.addEventListener&&("mouseenter"===
  827. a||"mouseleave"===a))var c=b,a="mouseenter"===a?"mouseover":"mouseout",b=function(a){for(var b=a.relatedTarget;b;b=b.parentNode)if(b===this)return;c.call(this,a)};var f=d.data.call(this),f=f.events=f.events||{};if(!f[a]){var h=this,e=f[a]=[],g=d.bind.genericHandler=function(a){a.target||(a.target=a.srcElement);a.preventDefault||(a.preventDefault=function(){a.returnValue=!1});a.stopPropagation||(a.stopPropagation=function(){a.cancelBubble=!0});a.stopImmediatePropagation=function(){this.stopPropagation();
  828. b=e.length};for(var b=0;b<e.length;b++)e[b].call(h,a)};document.addEventListener?this.addEventListener(a,g,!1):document.attachEvent&&this.attachEvent("on"+a,g)}f[a].push(b)},addClass:function(a){this.className=this.className.replace(/^|\s+|$/g," ").replace(" "+a+" "," ")+" "+a},removeClass:function(a){this.className=this.className.replace(/^|\s+|$/g," ").replace(" "+a+" "," ")},hasClass:function(a){return-1<this.className.replace(/^|\s+|$/g," ").indexOf(" "+a+" ")},show:function(){var a=d.show.display=
  829. d.show.display||{},b=this.tagName;if(!a[b]){var c=document.body.appendChild(document.createElement(b));a[b]=d.css.call(c,"display")}this.style.display=a[b]},hide:function(){this.style.display="none"},css:function(a){return this.currentStyle?this.currentStyle[a]:window.getComputedStyle?document.defaultView.getComputedStyle(this,null).getPropertyValue(a):void 0},data:function(){return this.nette?this.nette:this.nette={}},val:function(){var a;if(!this.nodeName){for(a=0,len=this.length;a<len;a++)if(this[a].checked)return this[a].value;
  830. return null}if("select"===this.nodeName.toLowerCase()){a=this.selectedIndex;var b=this.options;if(0>a)return null;if("select-one"===this.type)return b[a].value;for(a=0,values=[],len=b.length;a<len;a++)b[a].selected&&values.push(b[a].value);return values}return"checkbox"===this.type?this.checked:this.value.replace(/^\s+|\s+$/g,"")},_trav:function(a,b,c){for(b=b.split(".");a&&!(1===a.nodeType&&(!b[0]||a.tagName.toLowerCase()===b[0])&&(!b[1]||d.hasClass.call(a,b[1])));)a=a[c];return e(a)},closest:function(a){return d._trav(this,
  831. a,"parentNode")},prev:function(a){return d._trav(this.previousSibling,a,"previousSibling")},next:function(a){return d._trav(this.nextSibling,a,"nextSibling")},offset:function(a){for(var b=this,c=a?{left:-a.left||0,top:-a.top||0}:d.position.call(b);b=b.offsetParent;)c.left+=b.offsetLeft,c.top+=b.offsetTop;if(a)d.position.call(this,{left:-c.left,top:-c.top});else return c},position:function(a){if(a)this.nette&&this.nette.onmove&&this.nette.onmove.call(this,a),this.style.left=(a.left||0)+"px",this.style.top=
  832. (a.top||0)+"px";else return{left:this.offsetLeft,top:this.offsetTop,width:this.offsetWidth,height:this.offsetHeight}},draggable:function(a){var b=e(this),c=document.documentElement,f,a=a||{};e(a.handle||this).bind("mousedown",function(e){e.preventDefault();e.stopPropagation();if(d.draggable.binded)return c.onmouseup(e);var i=b[0].offsetLeft-e.clientX,g=b[0].offsetTop-e.clientY;d.draggable.binded=!0;f=!1;c.onmousemove=function(c){c=c||event;f||(a.draggedClass&&b.addClass(a.draggedClass),a.start&&a.start(c,
  833. b),f=!0);b.position({left:c.clientX+i,top:c.clientY+g});return!1};c.onmouseup=function(e){f&&(a.draggedClass&&b.removeClass(a.draggedClass),a.stop&&a.stop(e||event,b));d.draggable.binded=c.onmousemove=c.onmouseup=null;return!1}}).bind("click",function(a){f&&(a.stopImmediatePropagation(),preventClick=!1)})}})})();
  834. (function(){Nette.Debug={};var e=Nette.Q.factory,d=Nette.Debug.Panel=Nette.Class({Extends:Nette.Q,Static:{PEEK:"nette-mode-peek",FLOAT:"nette-mode-float",WINDOW:"nette-mode-window",FOCUSED:"nette-focused",factory:function(a){return new d(a)},_toggle:function(a){var b=a.rel,b="#"===b.charAt(0)?e(b):e(a)["prev"===b?"prev":"next"](b.substring(4));"none"===b.css("display")?(b.show(),a.innerHTML=a.innerHTML.replace("?","?")):(b.hide(),a.innerHTML=a.innerHTML.replace("?","?"))}},constructor:function(a){Nette.Q.call(this,
  835. "#nette-debug-panel-"+a.replace("nette-debug-panel-",""))},reposition:function(){this.hasClass(d.WINDOW)?window.resizeBy(document.documentElement.scrollWidth-document.documentElement.clientWidth,document.documentElement.scrollHeight-document.documentElement.clientHeight):(this.position(this.position()),this.position().width&&(document.cookie=this.dom().id+"="+this.position().left+":"+this.position().top+"; path=/"))},focus:function(){this.hasClass(d.WINDOW)?this.data().win.focus():(clearTimeout(this.data().blurTimeout),
  836. this.addClass(d.FOCUSED).show())},blur:function(){this.removeClass(d.FOCUSED);if(this.hasClass(d.PEEK)){var a=this;this.data().blurTimeout=setTimeout(function(){a.hide()},50)}},toFloat:function(){this.removeClass(d.WINDOW).removeClass(d.PEEK).addClass(d.FLOAT).show().reposition();return this},toPeek:function(){this.removeClass(d.WINDOW).removeClass(d.FLOAT).addClass(d.PEEK).hide();document.cookie=this.dom().id+"=; path=/"},toWindow:function(){var a=this,b,c;c=this.offset();var f=this.dom().id;c.left+=
  837. "number"===typeof window.screenLeft?window.screenLeft:window.screenX+10;c.top+="number"===typeof window.screenTop?window.screenTop:window.screenY+50;if(b=window.open("",f.replace(/-/g,"_"),"left="+c.left+",top="+c.top+",width="+c.width+",height="+(c.height+15)+",resizable=yes,scrollbars=yes"))c=b.document,c.write('<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style>'+e("#nette-debug-style").dom().innerHTML+"</style><script>"+e("#nette-debug-script").dom().innerHTML+
  838. '<\/script><body id="nette-debug">'),c.body.innerHTML='<div class="nette-panel nette-mode-window" id="'+f+'">'+this.dom().innerHTML+"</div>",b.Nette.Debug.Panel.factory(f).initToggler().reposition(),c.title=a.find("h1").dom().innerHTML,e([b]).bind("unload",function(){a.toPeek();b.close()}),e(c).bind("keyup",function(a){27===a.keyCode&&!a.shiftKey&&!a.altKey&&!a.ctrlKey&&!a.metaKey&&b.close()}),document.cookie=f+"=window; path=/",this.hide().removeClass(d.FLOAT).removeClass(d.PEEK).addClass(d.WINDOW).data().win=
  839. b},init:function(){var a=this,b;a.data().onmove=function(a){var b=document,d=window.innerWidth||b.documentElement.clientWidth||b.body.clientWidth,b=window.innerHeight||b.documentElement.clientHeight||b.body.clientHeight;a.left=Math.max(Math.min(a.left,0.8*this.offsetWidth),0.2*this.offsetWidth-d);a.top=Math.max(Math.min(a.top,0.8*this.offsetHeight),this.offsetHeight-b)};e(window).bind("resize",function(){a.reposition()});a.draggable({handle:a.find("h1"),stop:function(){a.toFloat()}}).bind("mouseenter",
  840. function(){a.focus()}).bind("mouseleave",function(){a.blur()});this.initToggler();a.find(".nette-icons").find("a").bind("click",function(b){"close"===this.rel?a.toPeek():a.toWindow();b.preventDefault()});(b=document.cookie.match(RegExp(a.dom().id+"=(window|(-?[0-9]+):(-?[0-9]+))")))?b[2]?a.toFloat().position({left:b[2],top:b[3]}):a.toWindow():a.addClass(d.PEEK)},initToggler:function(){var a=this;this.bind("click",function(b){var c=e(b.target).closest("a").dom();c&&c.rel&&(d._toggle(c),b.preventDefault(),
  841. a.reposition())});return this}});Nette.Debug.Bar=Nette.Class({Extends:Nette.Q,constructor:function(){Nette.Q.call(this,"#nette-debug-bar")},init:function(){var a=this,b;a.data().onmove=function(a){var b=document,d=window.innerWidth||b.documentElement.clientWidth||b.body.clientWidth,b=window.innerHeight||b.documentElement.clientHeight||b.body.clientHeight;a.left=Math.max(Math.min(a.left,0),this.offsetWidth-d);a.top=Math.max(Math.min(a.top,0),this.offsetHeight-b)};e(window).bind("resize",function(){a.position(a.position())});
  842. a.draggable({draggedClass:"nette-dragged",stop:function(){document.cookie=a.dom().id+"="+a.position().left+":"+a.position().top+"; path=/"}});a.find("a").bind("click",function(a){if("close"===this.rel)e("#nette-debug").hide(),window.opera&&e("body").show();else if(this.rel){var b=d.factory(this.rel);if(a.shiftKey)b.toFloat().toWindow();else if(b.hasClass(d.FLOAT)){var h=e(this).offset();b.offset({left:h.left-b.position().width+h.width+4,top:h.top-b.position().height-4}).toPeek()}else b.toFloat().position({left:b.position().left-
  843. Math.round(100*Math.random())-20,top:b.position().top-Math.round(100*Math.random())-20}).reposition()}a.preventDefault()}).bind("mouseenter",function(){if(this.rel&&!("close"===this.rel||a.hasClass("nette-dragged"))){var b=d.factory(this.rel);b.focus();if(b.hasClass(d.PEEK)){var f=e(this).offset();b.offset({left:f.left-b.position().width+f.width+4,top:f.top-b.position().height-4})}}}).bind("mouseleave",function(){this.rel&&!("close"===this.rel||a.hasClass("nette-dragged"))&&d.factory(this.rel).blur()});
  844. (b=document.cookie.match(RegExp(a.dom().id+"=(-?[0-9]+):(-?[0-9]+)")))&&a.position({left:b[1],top:b[2]});a.find("a").each(function(){this.rel&&"close"!==this.rel&&d.factory(this.rel).init()})}})})();/*]]>*/</script>
  845. <?php foreach($panels
  846. as$id=>$panel):if(!$panel['panel'])continue;?>
  847. <div class="nette-fixed-coords">
  848. <div class="nette-panel" id="nette-debug-panel-<?php echo$panel['id']?>">
  849. <?php echo$panel['panel']?>
  850. <div class="nette-icons">
  851. <a href="#" title="open in window">&curren;</a>
  852. <a href="#" rel="close" title="close window">&times;</a>
  853. </div>
  854. </div>
  855. </div>
  856. <?php endforeach?>
  857. <div class="nette-fixed-coords">
  858. <div id="nette-debug-bar">
  859. <ul>
  860. <li id="nette-debug-logo" title="PHP <?php echo
  861. htmlSpecialChars(PHP_VERSION." |\n".(isset($_SERVER['SERVER_SOFTWARE'])?$_SERVER['SERVER_SOFTWARE']." |\n":'').(class_exists('Nette\Framework')?'Nette Framework '.Nette\Framework::VERSION.' ('.substr(Nette\Framework::REVISION,8).')':''))?>">&nbsp;<span>Nette Framework</span></li>
  862. <?php foreach($panels
  863. as$panel):if(!$panel['tab'])continue;?>
  864. <li><?php if($panel['panel']):?><a href="#" rel="<?php echo$panel['id']?>"><?php echo
  865. trim($panel['tab'])?></a><?php else:echo'<span>',trim($panel['tab']),'</span>';endif?></li>
  866. <?php endforeach?>
  867. <li><a href="#" rel="close" title="close debug bar">&times;</a></li>
  868. </ul>
  869. </div>
  870. </div>
  871. <?php $output=ob_get_clean();?>
  872. <div id="nette-debug"></div>
  873. <script>
  874. (function (onloadOrig) {
  875. window.onload = function() {
  876. if (typeof onloadOrig === 'function') onloadOrig();
  877. var debug = document.getElementById('nette-debug');
  878. document.body.appendChild(debug);
  879. debug.innerHTML = <?php echo
  880. json_encode(Nette\Utils\Strings::fixEncoding($output))?>;
  881. for (var i = 0, scripts = debug.getElementsByTagName('script'); i < scripts.length; i++) eval(scripts[i].innerHTML);
  882. (new Nette.Debug.Bar).init();
  883. Nette.Q.factory(debug).show();
  884. };
  885. })(window.onload);
  886. </script>
  887. <!-- /Nette Debug Bar -->
  888. <?php }}final
  889. class
  890. DefaultBarPanel
  891. extends
  892. Nette\Object
  893. implements
  894. IBarPanel{private$id;public$data;function
  895. __construct($id){$this->id=$id;}function
  896. getTab(){ob_start();$data=$this->data;if($this->id==='time'){?>
  897. <span title="Execution time"><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"
  898. /><?php echo
  899. number_format((microtime(TRUE)-Debugger::$time)*1000,1,'.',' ')?> ms</span>
  900. <?php }elseif($this->id==='memory'){?>
  901. <span title="The peak of allocated memory"><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=="
  902. /><?php echo
  903. function_exists('memory_get_peak_usage')?number_format(memory_get_peak_usage()/1000000,2,'.',' '):'n/a';?> MB</span>
  904. <?php }elseif($this->id==='dumps'&&$this->data){?>
  905. <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
  906. <?php }elseif($this->id==='errors'&&$this->data){?>
  907. <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"
  908. /><span class="nette-warning"><?php echo
  909. array_sum($data)?> errors</span>
  910. <?php }return
  911. ob_get_clean();}function
  912. getPanel(){ob_start();$data=$this->data;if($this->id==='dumps'){?>
  913. <style>#nette-debug .nette-DumpPanel h2{font:11pt/1.5 sans-serif;margin:0;padding:2px 8px;background:#3484d2;color:white}#nette-debug .nette-DumpPanel table{width:100%}#nette-debug .nette-DumpPanel a{color:#333;background:transparent}#nette-debug .nette-DumpPanel a abbr{font-family:sans-serif;color:#999}#nette-debug .nette-DumpPanel pre .php-array,#nette-debug .nette-DumpPanel pre .php-object{color:#c16549}</style>
  914. <h1>Dumped variables</h1>
  915. <div class="nette-inner nette-DumpPanel">
  916. <?php foreach($data
  917. as$item):?>
  918. <?php if($item['title']):?>
  919. <h2><?php echo
  920. htmlspecialchars($item['title'])?></h2>
  921. <?php endif?>
  922. <table>
  923. <?php $i=0?>
  924. <?php foreach($item['dump']as$key=>$dump):?>
  925. <tr class="<?php echo$i++%
  926. 2?'nette-alt':''?>">
  927. <th><?php echo
  928. htmlspecialchars($key)?></th>
  929. <td><?php echo$dump?></td>
  930. </tr>
  931. <?php endforeach?>
  932. </table>
  933. <?php endforeach?>
  934. </div>
  935. <?php }elseif($this->id==='errors'){?>
  936. <h1>Errors</h1>
  937. <div class="nette-inner">
  938. <table>
  939. <?php $i=0?>
  940. <?php foreach($data
  941. as$item=>$count):list($message,$file,$line)=explode('|',$item)?>
  942. <tr class="<?php echo$i++%
  943. 2?'nette-alt':''?>">
  944. <td class="nette-right"><?php echo$count?"$count\xC3\x97":''?></td>
  945. <td><pre><?php echo
  946. htmlspecialchars($message),' in ',Helpers::editorLink($file,$line),':',$line?></pre></td>
  947. </tr>
  948. <?php endforeach?>
  949. </table>
  950. </div>
  951. <?php }return
  952. ob_get_clean();}}}namespace Nette\Utils{use
  953. Nette;final
  954. class
  955. SafeStream{const
  956. PROTOCOL='safe';private$handle;private$tempHandle;private$file;private$tempFile;private$deleteFile;private$writeError=FALSE;static
  957. function
  958. register(){return
  959. stream_wrapper_register(self::PROTOCOL,__CLASS__);}function
  960. stream_open($path,$mode,$options,&$opened_path){$path=substr($path,strlen(self::PROTOCOL)+3);$flag=trim($mode,'crwax+');$mode=trim($mode,'tb');$use_path=(bool)(STREAM_USE_PATH&$options);if($mode==='r'){return$this->checkAndLock($this->tempHandle=fopen($path,'r'.$flag,$use_path),LOCK_SH);}elseif($mode==='r+'){if(!$this->checkAndLock($this->handle=fopen($path,'r'.$flag,$use_path),LOCK_EX)){return
  961. FALSE;}}elseif($mode[0]==='x'){if(!$this->checkAndLock($this->handle=fopen($path,'x'.$flag,$use_path),LOCK_EX)){return
  962. FALSE;}$this->deleteFile=TRUE;}elseif($mode[0]==='w'||$mode[0]==='a'||$mode[0]==='c'){if($this->checkAndLock($this->handle=@fopen($path,'x'.$flag,$use_path),LOCK_EX)){$this->deleteFile=TRUE;}elseif(!$this->checkAndLock($this->handle=fopen($path,'a+'.$flag,$use_path),LOCK_EX)){return
  963. FALSE;}}else{trigger_error("Unknown mode $mode",E_USER_WARNING);return
  964. FALSE;}$tmp='~~'.lcg_value().'.tmp';if(!$this->tempHandle=fopen($path.$tmp,(strpos($mode,'+')?'x+':'x').$flag,$use_path)){$this->clean();return
  965. FALSE;}$this->tempFile=realpath($path.$tmp);$this->file=substr($this->tempFile,0,-strlen($tmp));if($mode==='r+'||$mode[0]==='a'||$mode[0]==='c'){$stat=fstat($this->handle);fseek($this->handle,0);if($stat['size']!==0&&stream_copy_to_stream($this->handle,$this->tempHandle)!==$stat['size']){$this->clean();return
  966. FALSE;}if($mode[0]==='a'){fseek($this->tempHandle,0,SEEK_END);}}return
  967. TRUE;}private
  968. function
  969. checkAndLock($handle,$lock){if(!$handle){return
  970. FALSE;}elseif(!flock($handle,$lock)){fclose($handle);return
  971. FALSE;}return
  972. TRUE;}private
  973. function
  974. clean(){flock($this->handle,LOCK_UN);fclose($this->handle);if($this->deleteFile){unlink($this->file);}if($this->tempHandle){fclose($this->tempHandle);unlink($this->tempFile);}}function
  975. stream_close(){if(!$this->tempFile){flock($this->tempHandle,LOCK_UN);fclose($this->tempHandle);return;}flock($this->handle,LOCK_UN);fclose($this->handle);fclose($this->tempHandle);if($this->writeError||!rename($this->tempFile,$this->file)){unlink($this->tempFile);if($this->deleteFile){unlink($this->file);}}}function
  976. stream_read($length){return
  977. fread($this->tempHandle,$length);}function
  978. stream_write($data){$len=strlen($data);$res=fwrite($this->tempHandle,$data,$len);if($res!==$len){$this->writeError=TRUE;}return$res;}function
  979. stream_tell(){return
  980. ftell($this->tempHandle);}function
  981. stream_eof(){return
  982. feof($this->tempHandle);}function
  983. stream_seek($offset,$whence){return
  984. fseek($this->tempHandle,$offset,$whence)===0;}function
  985. stream_stat(){return
  986. fstat($this->tempHandle);}function
  987. url_stat($path,$flags){$path=substr($path,strlen(self::PROTOCOL)+3);return($flags&STREAM_URL_STAT_LINK)?@lstat($path):@stat($path);}function
  988. unlink($path){$path=substr($path,strlen(self::PROTOCOL)+3);return
  989. unlink($path);}}}namespace Nette\Application{use
  990. Nette;class
  991. Application
  992. extends
  993. Nette\Object{public
  994. static$maxLoop=20;public$catchExceptions;public$errorPresenter;public$onStartup;public$onShutdown;public$onRequest;public$onResponse;public$onError;public$allowedMethods;private$requests=array();private$presenter;private$httpRequest;private$httpResponse;private$presenterFactory;private$router;function
  995. __construct(IPresenterFactory$presenterFactory,IRouter$router,Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){$this->httpRequest=$httpRequest;$this->httpResponse=$httpResponse;$this->presenterFactory=$presenterFactory;$this->router=$router;}function
  996. run(){$request=NULL;$repeatedError=FALSE;do{try{if(count($this->requests)>self::$maxLoop){throw
  997. new
  998. ApplicationException('Too many loops detected in application life cycle.');}if(!$request){$this->onStartup($this);$request=$this->router->match($this->httpRequest);if(!$request
  999. instanceof
  1000. Request){$request=NULL;throw
  1001. new
  1002. BadRequestException('No route for HTTP request.');}if(strcasecmp($request->getPresenterName(),$this->errorPresenter)===0){throw
  1003. new
  1004. BadRequestException('Invalid request. Presenter is not achievable.');}}$this->requests[]=$request;$this->onRequest($this,$request);$presenterName=$request->getPresenterName();try{$this->presenter=$this->presenterFactory->createPresenter($presenterName);}catch(InvalidPresenterException$e){throw
  1005. new
  1006. BadRequestException($e->getMessage(),404,$e);}$this->presenterFactory->getPresenterClass($presenterName);$request->setPresenterName($presenterName);$request->freeze();$response=$this->presenter->run($request);if($response){$this->onResponse($this,$response);}if($response
  1007. instanceof
  1008. Responses\ForwardResponse){$request=$response->getRequest();continue;}elseif($response
  1009. instanceof
  1010. IResponse){$response->send($this->httpRequest,$this->httpResponse);}break;}catch(\Exception$e){$this->onError($this,$e);if(!$this->catchExceptions){$this->onShutdown($this,$e);throw$e;}if($repeatedError){$e=new
  1011. ApplicationException('An error occurred while executing error-presenter',0,$e);}if(!$this->httpResponse->isSent()){$this->httpResponse->setCode($e
  1012. instanceof
  1013. BadRequestException?$e->getCode():500);}if(!$repeatedError&&$this->errorPresenter){$repeatedError=TRUE;if($this->presenter
  1014. instanceof
  1015. UI\Presenter){try{$this->presenter->forward(":$this->errorPresenter:",array('exception'=>$e));}catch(AbortException$foo){$request=$this->presenter->getLastCreatedRequest();}}else{$request=new
  1016. Request($this->errorPresenter,Request::FORWARD,array('exception'=>$e));}}else{if($e
  1017. instanceof
  1018. BadRequestException){$code=$e->getCode();}else{$code=500;Nette\Diagnostics\Debugger::log($e,Nette\Diagnostics\Debugger::ERROR);}$messages=array(0=>array('Oops...','Your browser sent a request that this server could not understand or process.'),403=>array('Access Denied','You do not have permission to view this page. Please try contact the web site administrator if you believe you should be able to view this page.'),404=>array('Page Not Found','The page you requested could not be found. It is possible that the address is incorrect, or that the page no longer exists. Please use a search engine to find what you are looking for.'),405=>array('Method Not Allowed','The requested method is not allowed for the URL.'),410=>array('Page Not Found','The page you requested has been taken off the site. We apologize for the inconvenience.'),500=>array('Server Error','We\'re sorry! The server encountered an internal error and was unable to complete your request. Please try again later.'));$message=isset($messages[$code])?$messages[$code]:$messages[0];?>
  1019. <!DOCTYPE html>
  1020. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  1021. <meta name=robots content=noindex><meta name=generator content="Nette Framework">
  1022. <style>body{color:#333;background:white;width:500px;margin:100px auto}h1{font:bold 47px/1.5 sans-serif;margin:.6em 0}p{font:21px/1.5 Georgia,serif;margin:1.5em 0}small{font-size:70%;color:gray}</style>
  1023. <title><?php echo$message[0]?></title>
  1024. <h1><?php echo$message[0]?></h1>
  1025. <p><?php echo$message[1]?></p>
  1026. <?php if($code):?><p><small>error <?php echo$code?></small></p><?php endif?>
  1027. <?php
  1028. break;}}}while(1);$this->onShutdown($this,isset($e)?$e:NULL);}final
  1029. function
  1030. getRequests(){return$this->requests;}final
  1031. function
  1032. getPresenter(){return$this->presenter;}function
  1033. getRouter(){return$this->router;}function
  1034. getPresenterFactory(){return$this->presenterFactory;}function
  1035. storeRequest($expiration='+ 10 minutes'){return$this->presenter->storeRequest($expiration);}function
  1036. restoreRequest($key){return$this->presenter->restoreRequest($key);}}}namespace Nette\Application\Diagnostics{use
  1037. Nette;use
  1038. Nette\Application\Routers;use
  1039. Nette\Application\UI\Presenter;use
  1040. Nette\Diagnostics\Debugger;class
  1041. RoutingPanel
  1042. extends
  1043. Nette\Object
  1044. implements
  1045. Nette\Diagnostics\IBarPanel{private$router;private$httpRequest;private$routers=array();private$request;static
  1046. function
  1047. initializePanel(Nette\Application\Application$application){Debugger::$blueScreen->addPanel(function($e)use($application){return$e?NULL:array('tab'=>'Nette Application','panel'=>'<h3>Requests</h3>'.Nette\Diagnostics\Helpers::clickableDump($application->getRequests()).'<h3>Presenter</h3>'.Nette\Diagnostics\Helpers::clickableDump($application->getPresenter()));});}function
  1048. __construct(Nette\Application\IRouter$router,Nette\Http\IRequest$httpRequest){$this->router=$router;$this->httpRequest=$httpRequest;}function
  1049. getTab(){$this->analyse($this->router);ob_start();?>
  1050. <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"
  1051. /><?php if(empty($this->request)):?>no route<?php else:echo
  1052. htmlSpecialChars($this->request->getPresenterName().':'.(isset($this->request->parameters[Presenter::ACTION_KEY])?$this->request->parameters[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION).(isset($this->request->parameters[Presenter::SIGNAL_KEY])?" {$this->request->parameters[Presenter::SIGNAL_KEY]}!":''));endif?>
  1053. <?php
  1054. return
  1055. ob_get_clean();}function
  1056. getPanel(){ob_start();?>
  1057. <style>#nette-debug .nette-RoutingPanel table{font:9pt/1.5 Consolas,monospace}#nette-debug .nette-RoutingPanel .yes td{color:green}#nette-debug .nette-RoutingPanel .may td{color:#67F}#nette-debug .nette-RoutingPanel pre,#nette-debug .nette-RoutingPanel code{display:inline}</style>
  1058. <div class="nette-RoutingPanel">
  1059. <h1>
  1060. <?php if(empty($this->request)):?>
  1061. no route
  1062. <?php else:?>
  1063. <?php echo
  1064. htmlSpecialChars($this->request->getPresenterName().':'.(isset($this->request->parameters[Presenter::ACTION_KEY])?$this->request->parameters[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION).(isset($this->request->parameters[Presenter::SIGNAL_KEY])?" {$this->request->parameters[Presenter::SIGNAL_KEY]}!":''))?>
  1065. <?php endif?>
  1066. </h1>
  1067. <?php if(!empty($this->request)):?>
  1068. <?php $params=$this->request->getParameters()?>
  1069. <?php if(empty($params)):?>
  1070. <p>No parameters.</p>
  1071. <?php else:?>
  1072. <table>
  1073. <thead>
  1074. <tr>
  1075. <th>Parameter</th>
  1076. <th>Value</th>
  1077. </tr>
  1078. </thead>
  1079. <tbody>
  1080. <?php unset($params[Presenter::ACTION_KEY],$params[Presenter::SIGNAL_KEY])?>
  1081. <?php foreach($params
  1082. as$key=>$value):?>
  1083. <tr>
  1084. <td><code><?php echo
  1085. htmlSpecialChars($key)?></code></td>
  1086. <td><?php if(is_string($value)):?><code><?php echo
  1087. htmlSpecialChars($value)?></code><?php else:echo
  1088. Debugger::dump($value,TRUE);endif?></td>
  1089. </tr>
  1090. <?php endforeach?>
  1091. </tbody>
  1092. </table>
  1093. <?php endif?>
  1094. <?php endif?>
  1095. <h2>Routers</h2>
  1096. <?php if(empty($this->routers)):?>
  1097. <p>No routers defined.</p>
  1098. <?php else:?>
  1099. <div class="nette-inner">
  1100. <table>
  1101. <thead>
  1102. <tr>
  1103. <th>Matched?</th>
  1104. <th>Class</th>
  1105. <th>Mask</th>
  1106. <th>Defaults</th>
  1107. <th>Module</th>
  1108. <th>Request</th>
  1109. </tr>
  1110. </thead>
  1111. <tbody>
  1112. <?php foreach($this->routers
  1113. as$router):?>
  1114. <tr class="<?php echo$router['matched']?>">
  1115. <td><?php echo$router['matched']?></td>
  1116. <td><code title="<?php echo
  1117. htmlSpecialChars($router['class'])?>"><?php echo
  1118. preg_replace('#.+\\\\#','',htmlSpecialChars($router['class']))?></code></td>
  1119. <td><code><strong><?php echo
  1120. htmlSpecialChars($router['mask'])?></strong></code></td>
  1121. <td><code>
  1122. <?php foreach($router['defaults']as$key=>$value):?>
  1123. <?php echo
  1124. htmlSpecialChars($key),"&nbsp;=&nbsp;",is_string($value)?htmlSpecialChars($value):str_replace("\n</pre",'</pre',Debugger::dump($value,TRUE))?><br />
  1125. <?php endforeach?>
  1126. </code></td>
  1127. <td><code><?php echo
  1128. htmlSpecialChars($router['module'])?></code></td>
  1129. <td><?php if($router['request']):?><code>
  1130. <?php $params=$router['request']->getParameters();?>
  1131. <strong><?php echo
  1132. htmlSpecialChars($router['request']->getPresenterName().':'.(isset($params[Presenter::ACTION_KEY])?$params[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION))?></strong><br />
  1133. <?php unset($params[Presenter::ACTION_KEY])?>
  1134. <?php foreach($params
  1135. as$key=>$value):?>
  1136. <?php echo
  1137. htmlSpecialChars($key),"&nbsp;=&nbsp;",is_string($value)?htmlSpecialChars($value):str_replace("\n</pre",'</pre',Debugger::dump($value,TRUE))?><br />
  1138. <?php endforeach?>
  1139. </code><?php endif?></td>
  1140. </tr>
  1141. <?php endforeach?>
  1142. </tbody>
  1143. </table>
  1144. </div>
  1145. <?php endif?>
  1146. </div>
  1147. <?php
  1148. return
  1149. ob_get_clean();}private
  1150. function
  1151. analyse($router,$module=''){if($router
  1152. instanceof
  1153. Routers\RouteList){foreach($router
  1154. as$subRouter){$this->analyse($subRouter,$module.$router->getModule());}return;}$matched='no';$request=$router->match($this->httpRequest);if($request){$request->setPresenterName($module.$request->getPresenterName());$matched='may';if(empty($this->request)){$this->request=$request;$matched='yes';}}$this->routers[]=array('matched'=>$matched,'class'=>get_class($router),'defaults'=>$router
  1155. instanceof
  1156. Routers\Route||$router
  1157. instanceof
  1158. Routers\SimpleRouter?$router->getDefaults():array(),'mask'=>$router
  1159. instanceof
  1160. Routers\Route?$router->getMask():NULL,'request'=>$request,'module'=>rtrim($module,':'));}}}namespace Nette\Application{use
  1161. Nette;class
  1162. AbortException
  1163. extends\Exception{}class
  1164. ApplicationException
  1165. extends\Exception{}class
  1166. InvalidPresenterException
  1167. extends\Exception{}class
  1168. BadRequestException
  1169. extends\Exception{protected$defaultCode=404;function
  1170. __construct($message='',$code=0,\Exception$previous=NULL){if($code<200||$code>504){$code=$this->defaultCode;}{parent::__construct($message,$code,$previous);}}}class
  1171. ForbiddenRequestException
  1172. extends
  1173. BadRequestException{protected$defaultCode=403;}}namespace NetteModule{use
  1174. Nette;use
  1175. Nette\Application;use
  1176. Nette\Application\Responses;use
  1177. Nette\Http;class
  1178. MicroPresenter
  1179. extends
  1180. Nette\Object
  1181. implements
  1182. Application\IPresenter{private$context;private$request;function
  1183. __construct(Nette\DI\Container$context){$this->context=$context;}final
  1184. function
  1185. getContext(){return$this->context;}function
  1186. run(Application\Request$request){$this->request=$request;$httpRequest=$this->context->getByType('Nette\Http\IRequest');if(!$httpRequest->isAjax()&&($request->isMethod('get')||$request->isMethod('head'))){$refUrl=clone$httpRequest->getUrl();$url=$this->context->router->constructUrl($request,$refUrl->setPath($refUrl->getScriptPath()));if($url!==NULL&&!$httpRequest->getUrl()->isEqual($url)){return
  1187. new
  1188. Responses\RedirectResponse($url,Http\IResponse::S301_MOVED_PERMANENTLY);}}$params=$request->getParameters();if(!isset($params['callback'])){return;}$params['presenter']=$this;$method=callback($params['callback'])->toReflection();$response=$method->invokeArgs(Application\UI\PresenterComponentReflection::combineArgs($method,$params));if(is_string($response)){$response=array($response,array());}if(is_array($response)){if($response[0]instanceof\SplFileInfo){$response=$this->createTemplate('Nette\Templating\FileTemplate')->setParameters($response[1])->setFile($response[0]);}else{$response=$this->createTemplate('Nette\Templating\Template')->setParameters($response[1])->setSource($response[0]);}}if($response
  1189. instanceof
  1190. Nette\Templating\ITemplate){return
  1191. new
  1192. Responses\TextResponse($response);}else{return$response;}}function
  1193. createTemplate($class=NULL,$latteFactory=NULL){$template=$class?new$class:new
  1194. Nette\Templating\FileTemplate;$template->setParameters($this->request->getParameters());$template->presenter=$this;$template->context=$context=$this->context;$url=$context->getByType('Nette\Http\IRequest')->getUrl();$template->baseUrl=rtrim($url->getBaseUrl(),'/');$template->basePath=rtrim($url->getBasePath(),'/');$template->registerHelperLoader('Nette\Templating\Helpers::loader');$template->setCacheStorage($context->nette->templateCacheStorage);$template->onPrepareFilters[]=function($template)use($latteFactory,$context){$template->registerFilter($latteFactory?$latteFactory():new
  1195. Nette\Latte\Engine);};return$template;}function
  1196. redirectUrl($url,$code=Http\IResponse::S302_FOUND){return
  1197. new
  1198. Responses\RedirectResponse($url,$code);}function
  1199. error($message=NULL,$code=Http\IResponse::S404_NOT_FOUND){throw
  1200. new
  1201. Application\BadRequestException($message,$code);}function
  1202. getRequest(){return$this->request;}}}namespace Nette\Application{use
  1203. Nette;class
  1204. PresenterFactory
  1205. implements
  1206. IPresenterFactory{public$caseSensitive=FALSE;private$baseDir;private$cache=array();private$context;function
  1207. __construct($baseDir,Nette\DI\Container$context){$this->baseDir=$baseDir;$this->context=$context;}function
  1208. createPresenter($name){$presenter=$this->context->createInstance($this->getPresenterClass($name));if(method_exists($presenter,'setContext')){$this->context->callMethod(array($presenter,'setContext'));}return$presenter;}function
  1209. getPresenterClass(&$name){if(isset($this->cache[$name])){list($class,$name)=$this->cache[$name];return$class;}if(!is_string($name)||!Nette\Utils\Strings::match($name,"#^[a-zA-Z\x7f-\xff][a-zA-Z0-9\x7f-\xff:]*$#")){throw
  1210. new
  1211. 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)){Nette\Utils\LimitedScope::load($file,TRUE);}if(!class_exists($class)){throw
  1212. new
  1213. InvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");}}$reflection=new
  1214. Nette\Reflection\ClassType($class);$class=$reflection->getName();if(!$reflection->implementsInterface('Nette\Application\IPresenter')){throw
  1215. new
  1216. InvalidPresenterException("Cannot load presenter '$name', class '$class' is not Nette\\Application\\IPresenter implementor.");}if($reflection->isAbstract()){throw
  1217. new
  1218. InvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");}$realName=$this->unformatPresenterClass($class);if($name!==$realName){if($this->caseSensitive){throw
  1219. new
  1220. 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
  1221. formatPresenterClass($presenter){return
  1222. str_replace(':','Module\\',$presenter).'Presenter';}function
  1223. unformatPresenterClass($class){return
  1224. str_replace('Module\\',':',substr($class,0,-9));}function
  1225. formatPresenterFile($presenter){$path='/'.str_replace(':','Module/',$presenter);return$this->baseDir.substr_replace($path,'/presenters',strrpos($path,'/'),0).'Presenter.php';}}}namespace Nette{use
  1226. Nette;abstract
  1227. class
  1228. FreezableObject
  1229. extends
  1230. Object
  1231. implements
  1232. IFreezable{private$frozen=FALSE;function
  1233. freeze(){$this->frozen=TRUE;}final
  1234. function
  1235. isFrozen(){return$this->frozen;}function
  1236. __clone(){$this->frozen=FALSE;}protected
  1237. function
  1238. updating(){if($this->frozen){$class=get_class($this);throw
  1239. new
  1240. InvalidStateException("Cannot modify a frozen object $class.");}}}}namespace Nette\Application{use
  1241. Nette;final
  1242. class
  1243. Request
  1244. extends
  1245. Nette\FreezableObject{const
  1246. FORWARD='FORWARD';const
  1247. SECURED='secured';const
  1248. RESTORED='restored';private$method;private$flags=array();private$name;private$params;private$post;private$files;function
  1249. __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
  1250. setPresenterName($name){$this->updating();$this->name=$name;return$this;}function
  1251. getPresenterName(){return$this->name;}function
  1252. setParameters(array$params){$this->updating();$this->params=$params;return$this;}function
  1253. getParameters(){return$this->params;}function
  1254. setParams(array$params){trigger_error(__METHOD__.'() is deprecated; use setParameters() instead.',E_USER_WARNING);return$this->setParameters($params);}function
  1255. getParams(){trigger_error(__METHOD__.'() is deprecated; use getParameters() instead.',E_USER_WARNING);return$this->getParameters();}function
  1256. setPost(array$params){$this->updating();$this->post=$params;return$this;}function
  1257. getPost(){return$this->post;}function
  1258. setFiles(array$files){$this->updating();$this->files=$files;return$this;}function
  1259. getFiles(){return$this->files;}function
  1260. setMethod($method){$this->method=$method;return$this;}function
  1261. getMethod(){return$this->method;}function
  1262. isMethod($method){return
  1263. strcasecmp($this->method,$method)===0;}function
  1264. isPost(){return
  1265. strcasecmp($this->method,'post')===0;}function
  1266. setFlag($flag,$value=TRUE){$this->updating();$this->flags[$flag]=(bool)$value;return$this;}function
  1267. hasFlag($flag){return!empty($this->flags[$flag]);}}}namespace Nette\Application\Responses{use
  1268. Nette;class
  1269. FileResponse
  1270. extends
  1271. Nette\Object
  1272. implements
  1273. Nette\Application\IResponse{private$file;private$contentType;private$name;public$resuming=TRUE;function
  1274. __construct($file,$name=NULL,$contentType=NULL){if(!is_file($file)){throw
  1275. new
  1276. Nette\Application\BadRequestException("File '$file' doesn't exist.");}$this->file=$file;$this->name=$name?$name:basename($file);$this->contentType=$contentType?$contentType:'application/octet-stream';}final
  1277. function
  1278. getFile(){return$this->file;}final
  1279. function
  1280. getName(){return$this->name;}final
  1281. function
  1282. getContentType(){return$this->contentType;}function
  1283. send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){$httpResponse->setContentType($this->contentType);$httpResponse->setHeader('Content-Disposition','attachment; filename="'.$this->name.'"');$filesize=$length=filesize($this->file);$handle=fopen($this->file,'r');if($this->resuming){$httpResponse->setHeader('Accept-Ranges','bytes');$range=$httpRequest->getHeader('Range');if($range!==NULL){$range=substr($range,6);list($start,$end)=explode('-',$range);if($start==NULL){$start=0;}if($end==NULL){$end=$filesize-1;}if($start<0||$end<=$start||$end>$filesize-1){$httpResponse->setCode(416);return;}$httpResponse->setCode(206);$httpResponse->setHeader('Content-Range','bytes '.$start.'-'.$end.'/'.$filesize);$length=$end-$start+1;fseek($handle,$start);}else{$httpResponse->setHeader('Content-Range','bytes 0-'.($filesize-1).'/'.$filesize);}}$httpResponse->setHeader('Content-Length',$length);while(!feof($handle)){echo
  1284. fread($handle,4e6);}fclose($handle);}}class
  1285. ForwardResponse
  1286. extends
  1287. Nette\Object
  1288. implements
  1289. Nette\Application\IResponse{private$request;function
  1290. __construct(Nette\Application\Request$request){$this->request=$request;}final
  1291. function
  1292. getRequest(){return$this->request;}function
  1293. send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){}}class
  1294. JsonResponse
  1295. extends
  1296. Nette\Object
  1297. implements
  1298. Nette\Application\IResponse{private$payload;private$contentType;function
  1299. __construct($payload,$contentType=NULL){if(!is_array($payload)&&!is_object($payload)){throw
  1300. new
  1301. Nette\InvalidArgumentException("Payload must be array or object class, ".gettype($payload)." given.");}$this->payload=$payload;$this->contentType=$contentType?$contentType:'application/json';}final
  1302. function
  1303. getPayload(){return$this->payload;}final
  1304. function
  1305. getContentType(){return$this->contentType;}function
  1306. send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){$httpResponse->setContentType($this->contentType);$httpResponse->setExpiration(FALSE);echo
  1307. Nette\Utils\Json::encode($this->payload);}}use
  1308. Nette\Http;class
  1309. RedirectResponse
  1310. extends
  1311. Nette\Object
  1312. implements
  1313. Nette\Application\IResponse{private$url;private$code;function
  1314. __construct($url,$code=Http\IResponse::S302_FOUND){$this->url=(string)$url;$this->code=(int)$code;}final
  1315. function
  1316. getUrl(){return$this->url;}final
  1317. function
  1318. getCode(){return$this->code;}function
  1319. send(Http\IRequest$httpRequest,Http\IResponse$httpResponse){$httpResponse->redirect($this->url,$this->code);}}class
  1320. TextResponse
  1321. extends
  1322. Nette\Object
  1323. implements
  1324. Nette\Application\IResponse{private$source;function
  1325. __construct($source){$this->source=$source;}final
  1326. function
  1327. getSource(){return$this->source;}function
  1328. send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){if($this->source
  1329. instanceof
  1330. Nette\Templating\ITemplate){$this->source->render();}else{echo$this->source;}}}}namespace Nette\Application\Routers{use
  1331. Nette;use
  1332. Nette\Application;class
  1333. CliRouter
  1334. extends
  1335. Nette\Object
  1336. implements
  1337. Application\IRouter{const
  1338. PRESENTER_KEY='action';private$defaults;function
  1339. __construct($defaults=array()){$this->defaults=$defaults;}function
  1340. match(Nette\Http\IRequest$httpRequest){if(empty($_SERVER['argv'])||!is_array($_SERVER['argv'])){return
  1341. NULL;}$names=array(self::PRESENTER_KEY);$params=$this->defaults;$args=$_SERVER['argv'];array_shift($args);$args[]='--';foreach($args
  1342. 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
  1343. new
  1344. Nette\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
  1345. new
  1346. Application\Request($presenter,'CLI',$params);}function
  1347. constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){return
  1348. NULL;}function
  1349. getDefaults(){return$this->defaults;}}use
  1350. Nette\Utils\Strings;class
  1351. Route
  1352. extends
  1353. Nette\Object
  1354. implements
  1355. Application\IRouter{const
  1356. PRESENTER_KEY='presenter';const
  1357. MODULE_KEY='module';const
  1358. CASE_SENSITIVE=256;const
  1359. HOST=1,PATH=2,RELATIVE=3;const
  1360. VALUE='value';const
  1361. PATTERN='pattern';const
  1362. FILTER_IN='filterIn';const
  1363. FILTER_OUT='filterOut';const
  1364. FILTER_TABLE='filterTable';const
  1365. FILTER_STRICT='filterStrict';const
  1366. OPTIONAL=0,PATH_OPTIONAL=1,CONSTANT=2;public
  1367. static$defaultFlags=0;public
  1368. 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
  1369. __construct($mask,$metadata=array(),$flags=0){if(is_string($metadata)){$a=strrpos($metadata,':');if(!$a){throw
  1370. new
  1371. Nette\InvalidArgumentException("Second argument must be array or string in format Presenter:action, '$metadata' given.");}$metadata=array(self::PRESENTER_KEY=>substr($metadata,0,$a),'action'=>$a===strlen($metadata)-1?NULL:substr($metadata,$a+1));}elseif($metadata
  1372. instanceof\Closure||$metadata
  1373. instanceof
  1374. Nette\Callback){$metadata=array(self::PRESENTER_KEY=>'Nette:Micro','callback'=>$metadata);}$this->flags=$flags|static::$defaultFlags;$this->setMask($mask,$metadata);}function
  1375. match(Nette\Http\IRequest$httpRequest){$url=$httpRequest->getUrl();if($this->type===self::HOST){$path='//'.$url->getHost().$url->getPath();}elseif($this->type===self::RELATIVE){$basePath=$url->getBasePath();if(strncmp($url->getPath(),$basePath,strlen($basePath))!==0){return
  1376. NULL;}$path=(string)substr($url->getPath(),strlen($basePath));}else{$path=$url->getPath();}if($path!==''){$path=rtrim($path,'/').'/';}if(!$matches=Strings::match($path,$this->re)){return
  1377. NULL;}$params=array();foreach($matches
  1378. as$k=>$v){if(is_string($k)&&$v!==''){$params[str_replace('___','-',$k)]=$v;}}foreach($this->metadata
  1379. 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
  1380. 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_TABLE])&&!empty($meta[self::FILTER_STRICT])){return
  1381. NULL;}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
  1382. NULL;}}}elseif(isset($meta['fixity'])){$params[$name]=$meta[self::VALUE];}}if(!isset($params[self::PRESENTER_KEY])){throw
  1383. new
  1384. Nette\InvalidStateException('Missing presenter in route definition.');}if(isset($this->metadata[self::MODULE_KEY])){if(!isset($params[self::MODULE_KEY])){throw
  1385. new
  1386. Nette\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
  1387. new
  1388. Application\Request($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(Application\Request::SECURED=>$httpRequest->isSecured()));}function
  1389. constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->flags&self::ONE_WAY){return
  1390. NULL;}$params=$appRequest->getParameters();$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
  1391. as$name=>$meta){if(!isset($params[$name])){continue;}if(isset($meta['fixity'])){if($params[$name]===FALSE){$params[$name]='0';}if(is_scalar($params[$name])?strcasecmp($params[$name],$meta[self::VALUE])===0:$params[$name]===$meta[self::VALUE]){unset($params[$name]);continue;}elseif($meta['fixity']===self::CONSTANT){return
  1392. NULL;}}if(!is_scalar($params[$name])){}elseif(isset($meta['filterTable2'][$params[$name]])){$params[$name]=$meta['filterTable2'][$params[$name]];}elseif(isset($meta['filterTable2'])&&!empty($meta[self::FILTER_STRICT])){return
  1393. NULL;}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
  1394. NULL;}}$sequence=$this->sequence;$brackets=array();$required=NULL;$url='';$i=count($sequence)-1;do{$url=$sequence[$i].$url;if($i===0){break;}$i--;$name=$sequence[$i];$i--;if($name===']'){$brackets[]=$url;}elseif($name[0]==='['){$tmp=array_pop($brackets);if($required<count($brackets)+1){if($name!=='[!'){$url=$tmp;}}else{$required=count($brackets);}}elseif($name[0]==='?'){continue;}elseif(isset($params[$name])&&$params[$name]!=''){$required=count($brackets);$url=$params[$name].$url;unset($params[$name]);}elseif(isset($metadata[$name]['fixity'])){if($required===NULL&&!$brackets){$url='';}else{$url=$metadata[$name]['defOut'].$url;}}else{return
  1395. 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!=''){$url.='?'.$query;}if($this->type===self::RELATIVE){$url='//'.$refUrl->getAuthority().$refUrl->getBasePath().$url;}elseif($this->type===self::PATH){$url='//'.$refUrl->getAuthority().$url;}if(strpos($url,'//',2)!==FALSE){return
  1396. NULL;}$url=($this->flags&self::SECURED?'https:':'http:').$url;return$url;}private
  1397. function
  1398. 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
  1399. 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=Strings::split($mask,'/<([^>#= ]+)(=[^># ]*)? *([^>#]*)(#?[^>\[\]]*)>|(\[!?|\]|\s*\?.*)/');$this->xlat=array();$i=count($parts)-1;if(isset($parts[$i-1])&&substr(ltrim($parts[$i-1]),0,1)==='?'){$matches=Strings::matchAll($parts[$i-1],'/(?:([a-zA-Z0-9_.-]+)=)?<([^># ]+) *([^>#]*)(#?[^>]*)>/');foreach($matches
  1400. as$match){list(,$param,$name,$pattern,$class)=$match;if($class!==''){if(!isset(static::$styles[$class])){throw
  1401. new
  1402. Nette\InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");}$meta=static::$styles[$class];}elseif(isset(static::$styles['?'.$name])){$meta=static::$styles['?'.$name];}else{$meta=static::$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-=6;}$brackets=0;$re='';$sequence=array();$autoOptional=TRUE;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
  1403. new
  1404. Nette\InvalidArgumentException("Unexpected '$part' in mask '$mask'.");}array_unshift($sequence,$part);$re=($part[0]==='['?'(?:':')?').$re;$i-=5;continue;}$class=$parts[$i];$i--;$pattern=trim($parts[$i]);$i--;$default=$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
  1405. new
  1406. Nette\InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '$name' given.");}if($class!==''){if(!isset(static::$styles[$class])){throw
  1407. new
  1408. Nette\InvalidStateException("Parameter '$name' has '$class' flag, but Route::\$styles['$class'] is not set.");}$meta=static::$styles[$class];}elseif(isset(static::$styles[$name])){$meta=static::$styles[$name];}else{$meta=static::$styles['#'];}if(isset($metadata[$name])){$meta=$metadata[$name]+$meta;}if($pattern==''&&isset($meta[self::PATTERN])){$pattern=$meta[self::PATTERN];}if($default!==''){$meta[self::VALUE]=(string)substr($default,1);$meta['fixity']=self::PATH_OPTIONAL;}$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).'>(?U)'.$pattern.')'.$re;if($brackets){if(!isset($meta[self::VALUE])){$meta[self::VALUE]=$meta['defOut']=NULL;}$meta['fixity']=self::PATH_OPTIONAL;}elseif(!$autoOptional){unset($meta['fixity']);}elseif(isset($meta['fixity'])){$re='(?:'.$re.')?';$meta['fixity']=self::PATH_OPTIONAL;}else{$autoOptional=FALSE;}$metadata[$name]=$meta;}while(TRUE);if($brackets){throw
  1409. new
  1410. Nette\InvalidArgumentException("Missing closing ']' in mask '$mask'.");}$this->re='#'.$re.'/?$#A'.($this->flags&self::CASE_SENSITIVE?'':'iu');$this->metadata=$metadata;$this->sequence=$sequence;}function
  1411. getMask(){return$this->mask;}function
  1412. getDefaults(){$defaults=array();foreach($this->metadata
  1413. as$name=>$meta){if(isset($meta['fixity'])){$defaults[$name]=$meta[self::VALUE];}}return$defaults;}function
  1414. getFlags(){return$this->flags;}function
  1415. getTargetPresenter(){if($this->flags&self::ONE_WAY){return
  1416. 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
  1417. NULL;}}if(isset($m[self::PRESENTER_KEY]['fixity'])&&$m[self::PRESENTER_KEY]['fixity']===self::CONSTANT){return$module.$m[self::PRESENTER_KEY][self::VALUE];}return
  1418. NULL;}private
  1419. static
  1420. function
  1421. renameKeys($arr,$xlat){if(empty($xlat)){return$arr;}$res=array();$occupied=array_flip($xlat);foreach($arr
  1422. as$k=>$v){if(isset($xlat[$k])){$res[$xlat[$k]]=$v;}elseif(!isset($occupied[$k])){$res[$k]=$v;}}return$res;}private
  1423. static
  1424. function
  1425. action2path($s){$s=preg_replace('#(.)(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private
  1426. static
  1427. function
  1428. path2action($s){$s=strtolower($s);$s=preg_replace('#-(?=[a-z])#',' ',$s);$s=substr(ucwords('x'.$s),1);$s=str_replace(' ','',$s);return$s;}private
  1429. static
  1430. function
  1431. presenter2path($s){$s=strtr($s,':','.');$s=preg_replace('#([^.])(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private
  1432. static
  1433. function
  1434. 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
  1435. function
  1436. addStyle($style,$parent='#'){if(isset(static::$styles[$style])){throw
  1437. new
  1438. Nette\InvalidArgumentException("Style '$style' already exists.");}if($parent!==NULL){if(!isset(static::$styles[$parent])){throw
  1439. new
  1440. Nette\InvalidArgumentException("Parent style '$parent' doesn't exist.");}static::$styles[$style]=static::$styles[$parent];}else{static::$styles[$style]=array();}}static
  1441. function
  1442. setStyleProperty($style,$key,$value){if(!isset(static::$styles[$style])){throw
  1443. new
  1444. Nette\InvalidArgumentException("Style '$style' doesn't exist.");}static::$styles[$style][$key]=$value;}}}namespace Nette{use
  1445. Nette;class
  1446. ArrayList
  1447. extends
  1448. Object
  1449. implements\ArrayAccess,\Countable,\IteratorAggregate{private$list=array();function
  1450. getIterator(){return
  1451. new\ArrayIterator($this->list);}function
  1452. count(){return
  1453. count($this->list);}function
  1454. offsetSet($index,$value){if($index===NULL){$this->list[]=$value;}elseif($index<0||$index>=count($this->list)){throw
  1455. new
  1456. OutOfRangeException("Offset invalid or out of range");}else{$this->list[(int)$index]=$value;}}function
  1457. offsetGet($index){if($index<0||$index>=count($this->list)){throw
  1458. new
  1459. OutOfRangeException("Offset invalid or out of range");}return$this->list[(int)$index];}function
  1460. offsetExists($index){return$index>=0&&$index<count($this->list);}function
  1461. offsetUnset($index){if($index<0||$index>=count($this->list)){throw
  1462. new
  1463. OutOfRangeException("Offset invalid or out of range");}array_splice($this->list,(int)$index,1);}}}namespace Nette\Application\Routers{use
  1464. Nette;class
  1465. RouteList
  1466. extends
  1467. Nette\ArrayList
  1468. implements
  1469. Nette\Application\IRouter{private$cachedRoutes;private$module;function
  1470. __construct($module=NULL){$this->module=$module?$module.':':'';}function
  1471. match(Nette\Http\IRequest$httpRequest){foreach($this
  1472. as$route){$appRequest=$route->match($httpRequest);if($appRequest!==NULL){$appRequest->setPresenterName($this->module.$appRequest->getPresenterName());return$appRequest;}}return
  1473. NULL;}function
  1474. constructUrl(Nette\Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->cachedRoutes===NULL){$routes=array();$routes['*']=array();foreach($this
  1475. as$route){$presenter=$route
  1476. instanceof
  1477. 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
  1478. as$id=>$foo){$routes[$id][]=$route;}}}$this->cachedRoutes=$routes;}if($this->module){if(strncasecmp($tmp=$appRequest->getPresenterName(),$this->module,strlen($this->module))===0){$appRequest=clone$appRequest;$appRequest->setPresenterName(substr($tmp,strlen($this->module)));}else{return
  1479. NULL;}}$presenter=strtolower($appRequest->getPresenterName());if(!isset($this->cachedRoutes[$presenter])){$presenter='*';}foreach($this->cachedRoutes[$presenter]as$route){$url=$route->constructUrl($appRequest,$refUrl);if($url!==NULL){return$url;}}return
  1480. NULL;}function
  1481. offsetSet($index,$route){if(!$route
  1482. instanceof
  1483. Nette\Application\IRouter){throw
  1484. new
  1485. Nette\InvalidArgumentException("Argument must be IRouter descendant.");}parent::offsetSet($index,$route);}function
  1486. getModule(){return$this->module;}}use
  1487. Nette\Application;class
  1488. SimpleRouter
  1489. extends
  1490. Nette\Object
  1491. implements
  1492. Application\IRouter{const
  1493. PRESENTER_KEY='presenter';const
  1494. MODULE_KEY='module';private$module='';private$defaults;private$flags;function
  1495. __construct($defaults=array(),$flags=0){if(is_string($defaults)){$a=strrpos($defaults,':');if(!$a){throw
  1496. new
  1497. Nette\InvalidArgumentException("Argument must be array or string in format Presenter:action, '$defaults' given.");}$defaults=array(self::PRESENTER_KEY=>substr($defaults,0,$a),'action'=>$a===strlen($defaults)-1?Application\UI\Presenter::DEFAULT_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
  1498. match(Nette\Http\IRequest$httpRequest){if($httpRequest->getUrl()->getPathInfo()!==''){return
  1499. NULL;}$params=$httpRequest->getQuery();$params+=$this->defaults;if(!isset($params[self::PRESENTER_KEY])){throw
  1500. new
  1501. Nette\InvalidStateException('Missing presenter.');}$presenter=$this->module.$params[self::PRESENTER_KEY];unset($params[self::PRESENTER_KEY]);return
  1502. new
  1503. Application\Request($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(Application\Request::SECURED=>$httpRequest->isSecured()));}function
  1504. constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->flags&self::ONE_WAY){return
  1505. NULL;}$params=$appRequest->getParameters();$presenter=$appRequest->getPresenterName();if(strncasecmp($presenter,$this->module,strlen($this->module))===0){$params[self::PRESENTER_KEY]=substr($presenter,strlen($this->module));}else{return
  1506. NULL;}foreach($this->defaults
  1507. as$key=>$value){if(isset($params[$key])&&$params[$key]==$value){unset($params[$key]);}}$url=($this->flags&self::SECURED?'https://':'http://').$refUrl->getAuthority().$refUrl->getPath();$sep=ini_get('arg_separator.input');$query=http_build_query($params,'',$sep?$sep[0]:'&');if($query!=''){$url.='?'.$query;}return$url;}function
  1508. getDefaults(){return$this->defaults;}function
  1509. getFlags(){return$this->flags;}}}namespace Nette\Application\UI{use
  1510. Nette;class
  1511. BadSignalException
  1512. extends
  1513. Nette\Application\BadRequestException{protected$defaultCode=403;}}namespace Nette\ComponentModel{use
  1514. Nette;abstract
  1515. class
  1516. Component
  1517. extends
  1518. Nette\Object
  1519. implements
  1520. IComponent{private$parent;private$name;private$monitors=array();function
  1521. __construct(IContainer$parent=NULL,$name=NULL){if($parent!==NULL){$parent->addComponent($this,$name);}elseif(is_string($name)){$this->name=$name;}}function
  1522. lookup($type,$need=TRUE){if(!isset($this->monitors[$type])){$obj=$this->parent;$path=self::NAME_SEPARATOR.$this->name;$depth=1;while($obj!==NULL){if($obj
  1523. 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
  1524. new
  1525. Nette\InvalidStateException("Component '$this->name' is not attached to '$type'.");}return$this->monitors[$type][0];}function
  1526. lookupPath($type,$need=TRUE){$this->lookup($type,$need);return$this->monitors[$type][2];}function
  1527. monitor($type){if(empty($this->monitors[$type][3])){if($obj=$this->lookup($type,FALSE)){$this->attached($obj);}$this->monitors[$type][3]=TRUE;}}function
  1528. unmonitor($type){unset($this->monitors[$type]);}protected
  1529. function
  1530. attached($obj){}protected
  1531. function
  1532. detached($obj){}final
  1533. function
  1534. getName(){return$this->name;}final
  1535. function
  1536. getParent(){return$this->parent;}function
  1537. setParent(IContainer$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
  1538. new
  1539. Nette\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
  1540. function
  1541. validateParent(IContainer$parent){}private
  1542. function
  1543. refreshMonitors($depth,&$missing=NULL,&$listeners=array()){if($this
  1544. instanceof
  1545. IContainer){foreach($this->getComponents()as$component){if($component
  1546. instanceof
  1547. Component){$component->refreshMonitors($depth+1,$missing,$listeners);}}}if($missing===NULL){foreach($this->monitors
  1548. 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
  1549. 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
  1550. as$item){$item[0]->$method($item[1]);}}}function
  1551. __clone(){if($this->parent===NULL){return;}elseif($this->parent
  1552. instanceof
  1553. Container){$this->parent=$this->parent->_isCloning();if($this->parent===NULL){$this->refreshMonitors(0);}}else{$this->parent=NULL;$this->refreshMonitors(0);}}final
  1554. function
  1555. __sleep(){throw
  1556. new
  1557. Nette\NotImplementedException('Object serialization is not supported by class '.get_class($this));}final
  1558. function
  1559. __wakeup(){throw
  1560. new
  1561. Nette\NotImplementedException('Object unserialization is not supported by class '.get_class($this));}}class
  1562. Container
  1563. extends
  1564. Component
  1565. implements
  1566. IContainer{private$components=array();private$cloning;function
  1567. addComponent(IComponent$component,$name,$insertBefore=NULL){if($name===NULL){$name=$component->getName();}if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw
  1568. new
  1569. Nette\InvalidArgumentException("Component name must be integer or string, ".gettype($name)." given.");}elseif(!preg_match('#^[a-zA-Z0-9_]+$#',$name)){throw
  1570. new
  1571. Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");}if(isset($this->components[$name])){throw
  1572. new
  1573. Nette\InvalidStateException("Component with name '$name' already exists.");}$obj=$this;do{if($obj===$component){throw
  1574. new
  1575. Nette\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
  1576. 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;}return$this;}function
  1577. removeComponent(IComponent$component){$name=$component->getName();if(!isset($this->components[$name])||$this->components[$name]!==$component){throw
  1578. new
  1579. Nette\InvalidArgumentException("Component named '$name' is not located in this container.");}unset($this->components[$name]);$component->setParent(NULL);}final
  1580. function
  1581. getComponent($name,$need=TRUE){if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw
  1582. new
  1583. Nette\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
  1584. new
  1585. Nette\InvalidArgumentException("Component or subcomponent name must not be empty string.");}}if(!isset($this->components[$name])){$component=$this->createComponent($name);if($component
  1586. instanceof
  1587. 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
  1588. IContainer){return$this->components[$name]->getComponent($ext,$need);}elseif($need){throw
  1589. new
  1590. Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$ext' component.");}}elseif($need){throw
  1591. new
  1592. Nette\InvalidArgumentException("Component with name '$name' does not exist.");}}protected
  1593. function
  1594. createComponent($name){$ucname=ucfirst($name);$method='createComponent'.$ucname;if($ucname!==$name&&method_exists($this,$method)&&$this->getReflection()->getMethod($method)->getName()===$method){$component=$this->$method($name);if(!$component
  1595. instanceof
  1596. IComponent&&!isset($this->components[$name])){$class=get_class($this);throw
  1597. new
  1598. Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");}return$component;}}final
  1599. function
  1600. getComponents($deep=FALSE,$filterType=NULL){$iterator=new
  1601. RecursiveComponentIterator($this->components);if($deep){$deep=$deep>0?\RecursiveIteratorIterator::SELF_FIRST:\RecursiveIteratorIterator::CHILD_FIRST;$iterator=new\RecursiveIteratorIterator($iterator,$deep);}if($filterType){$iterator=new
  1602. Nette\Iterators\InstanceFilter($iterator,$filterType);}return$iterator;}protected
  1603. function
  1604. validateChildComponent(IComponent$child){}function
  1605. __clone(){if($this->components){$oldMyself=reset($this->components)->getParent();$oldMyself->cloning=$this;foreach($this->components
  1606. as$name=>$component){$this->components[$name]=clone$component;}$oldMyself->cloning=NULL;}parent::__clone();}function
  1607. _isCloning(){return$this->cloning;}}}namespace Nette\Application\UI{use
  1608. Nette;abstract
  1609. class
  1610. PresenterComponent
  1611. extends
  1612. Nette\ComponentModel\Container
  1613. implements
  1614. ISignalReceiver,IStatePersistent,\ArrayAccess{protected$params=array();function
  1615. __construct(Nette\ComponentModel\IContainer$parent=NULL,$name=NULL){$this->monitor('Nette\Application\UI\Presenter');parent::__construct($parent,$name);}function
  1616. getPresenter($need=TRUE){return$this->lookup('Nette\Application\UI\Presenter',$need);}function
  1617. getUniqueId(){return$this->lookupPath('Nette\Application\UI\Presenter',TRUE);}protected
  1618. function
  1619. attached($presenter){if($presenter
  1620. instanceof
  1621. Presenter){$this->loadState($presenter->popGlobalParameters($this->getUniqueId()));}}protected
  1622. function
  1623. tryCall($method,array$params){$rc=$this->getReflection();if($rc->hasMethod($method)){$rm=$rc->getMethod($method);if($rm->isPublic()&&!$rm->isAbstract()&&!$rm->isStatic()){$this->checkRequirements($rm);$rm->invokeArgs($this,$rc->combineArgs($rm,$params));return
  1624. TRUE;}}return
  1625. FALSE;}function
  1626. checkRequirements($element){}static
  1627. function
  1628. getReflection(){return
  1629. new
  1630. PresenterComponentReflection(get_called_class());}function
  1631. 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];}else{$params[$nm]=&$this->$nm;}}$this->params=$params;}function
  1632. 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
  1633. instanceof$meta['since']){$val=$this->$nm;}else{continue;}if(is_object($val)){$class=get_class($this);throw
  1634. new
  1635. Nette\InvalidStateException("Persistent parameter must be scalar or array, $class::\$$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
  1636. function
  1637. getParameter($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
  1638. function
  1639. getParameterId($name){$uid=$this->getUniqueId();return$uid===''?$name:$uid.self::NAME_SEPARATOR.$name;}function
  1640. 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;}}function
  1641. getParamId($name){trigger_error(__METHOD__.'() is deprecated; use getParameterId() instead.',E_USER_WARNING);return$this->getParameterId($name);}static
  1642. function
  1643. getPersistentParams(){$rc=new
  1644. Nette\Reflection\ClassType(get_called_class());$params=array();foreach($rc->getProperties(\ReflectionProperty::IS_PUBLIC)as$rp){if(!$rp->isStatic()&&$rp->hasAnnotation('persistent')){$params[]=$rp->getName();}}return$params;}function
  1645. signalReceived($signal){if(!$this->tryCall($this->formatSignalMethod($signal),$this->params)){$class=get_class($this);throw
  1646. new
  1647. BadSignalException("There is no handler for signal '$signal' in class $class.");}}function
  1648. formatSignalMethod($signal){return$signal==NULL?NULL:'handle'.$signal;}function
  1649. 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
  1650. lazyLink($destination,$args=array()){if(!is_array($args)){$args=func_get_args();array_shift($args);}return
  1651. new
  1652. Link($this,$destination,$args);}function
  1653. isLinkCurrent($destination=NULL,$args=array()){if($destination!==NULL){if(!is_array($args)){$args=func_get_args();array_shift($args);}$this->link($destination,$args);}return$this->getPresenter()->getLastCreatedRequestFlag('current');}function
  1654. 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->redirectUrl($presenter->createRequest($this,$destination,$args,'redirect'),$code);}final
  1655. function
  1656. offsetSet($name,$component){$this->addComponent($component,$name);}final
  1657. function
  1658. offsetGet($name){return$this->getComponent($name,TRUE);}final
  1659. function
  1660. offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}final
  1661. function
  1662. offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}}abstract
  1663. class
  1664. Control
  1665. extends
  1666. PresenterComponent
  1667. implements
  1668. IRenderable{private$template;private$invalidSnippets=array();public$snippetMode;final
  1669. function
  1670. getTemplate(){if($this->template===NULL){$value=$this->createTemplate();if(!$value
  1671. instanceof
  1672. Nette\Templating\ITemplate&&$value!==NULL){$class2=get_class($value);$class=get_class($this);throw
  1673. new
  1674. Nette\UnexpectedValueException("Object returned by $class::createTemplate() must be instance of Nette\\Templating\\ITemplate, '$class2' given.");}$this->template=$value;}return$this->template;}protected
  1675. function
  1676. createTemplate($class=NULL){$template=$class?new$class:new
  1677. Nette\Templating\FileTemplate;$presenter=$this->getPresenter(FALSE);$template->onPrepareFilters[]=callback($this,'templatePrepareFilters');$template->registerHelperLoader('Nette\Templating\Helpers::loader');$template->control=$template->_control=$this;$template->presenter=$template->_presenter=$presenter;if($presenter
  1678. instanceof
  1679. Presenter){$template->setCacheStorage($presenter->getContext()->nette->templateCacheStorage);$template->user=$presenter->getUser();$template->netteHttpResponse=$presenter->getHttpResponse();$template->netteCacheStorage=$presenter->getContext()->getByType('Nette\Caching\IStorage');$template->baseUri=$template->baseUrl=rtrim($presenter->getHttpRequest()->getUrl()->getBaseUrl(),'/');$template->basePath=preg_replace('#https?://[^/]+#A','',$template->baseUrl);if($presenter->hasFlashSession()){$id=$this->getParameterId('flash');$template->flashes=$presenter->getFlashSession()->$id;}}if(!isset($template->flashes)||!is_array($template->flashes)){$template->flashes=array();}return$template;}function
  1680. templatePrepareFilters($template){$template->registerFilter($this->getPresenter()->getContext()->nette->createLatte());}function
  1681. getWidget($name){trigger_error(__METHOD__.'() is deprecated, use getComponent() instead.',E_USER_WARNING);return$this->getComponent($name);}function
  1682. flashMessage($message,$type='info'){$id=$this->getParameterId('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
  1683. invalidateControl($snippet=NULL){$this->invalidSnippets[$snippet]=TRUE;}function
  1684. validateControl($snippet=NULL){if($snippet===NULL){$this->invalidSnippets=array();}else{unset($this->invalidSnippets[$snippet]);}}function
  1685. isControlInvalid($snippet=NULL){if($snippet===NULL){if(count($this->invalidSnippets)>0){return
  1686. TRUE;}else{$queue=array($this);do{foreach(array_shift($queue)->getComponents()as$component){if($component
  1687. instanceof
  1688. IRenderable){if($component->isControlInvalid()){return
  1689. TRUE;}}elseif($component
  1690. instanceof
  1691. Nette\ComponentModel\IContainer){$queue[]=$component;}}}while($queue);return
  1692. FALSE;}}else{return
  1693. isset($this->invalidSnippets[NULL])||isset($this->invalidSnippets[$snippet]);}}function
  1694. getSnippetId($name=NULL){return'snippet-'.$this->getUniqueId().'-'.$name;}}}namespace Nette\Forms{use
  1695. Nette;class
  1696. Container
  1697. extends
  1698. Nette\ComponentModel\Container
  1699. implements\ArrayAccess{public$onValidate;protected$currentGroup;protected$valid;function
  1700. setDefaults($values,$erase=FALSE){$form=$this->getForm(FALSE);if(!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValues($values,$erase);}return$this;}function
  1701. setValues($values,$erase=FALSE){if($values
  1702. instanceof\Traversable){$values=iterator_to_array($values);}elseif(!is_array($values)){throw
  1703. new
  1704. Nette\InvalidArgumentException("First parameter must be an array, ".gettype($values)." given.");}foreach($this->getComponents()as$name=>$control){if($control
  1705. instanceof
  1706. IControl){if(array_key_exists($name,$values)){$control->setValue($values[$name]);}elseif($erase){$control->setValue(NULL);}}elseif($control
  1707. instanceof
  1708. Container){if(array_key_exists($name,$values)){$control->setValues($values[$name],$erase);}elseif($erase){$control->setValues(array(),$erase);}}}return$this;}function
  1709. getValues($asArray=FALSE){$values=$asArray?array():new
  1710. Nette\ArrayHash;foreach($this->getComponents()as$name=>$control){if($control
  1711. instanceof
  1712. IControl&&!$control->isDisabled()&&!$control
  1713. instanceof
  1714. ISubmitterControl){$values[$name]=$control->getValue();}elseif($control
  1715. instanceof
  1716. Container){$values[$name]=$control->getValues($asArray);}}return$values;}function
  1717. isValid(){if($this->valid===NULL){$this->validate();}return$this->valid;}function
  1718. validate(){$this->valid=TRUE;$this->onValidate($this);foreach($this->getControls()as$control){if(!$control->getRules()->validate()){$this->valid=FALSE;}}}function
  1719. setCurrentGroup(ControlGroup$group=NULL){$this->currentGroup=$group;return$this;}function
  1720. getCurrentGroup(){return$this->currentGroup;}function
  1721. addComponent(Nette\ComponentModel\IComponent$component,$name,$insertBefore=NULL){parent::addComponent($component,$name,$insertBefore);if($this->currentGroup!==NULL&&$component
  1722. instanceof
  1723. IControl){$this->currentGroup->add($component);}return$this;}function
  1724. getControls(){return$this->getComponents(TRUE,'Nette\Forms\IControl');}function
  1725. getForm($need=TRUE){return$this->lookup('Nette\Forms\Form',$need);}function
  1726. addText($name,$label=NULL,$cols=NULL,$maxLength=NULL){return$this[$name]=new
  1727. Controls\TextInput($label,$cols,$maxLength);}function
  1728. addPassword($name,$label=NULL,$cols=NULL,$maxLength=NULL){$control=new
  1729. Controls\TextInput($label,$cols,$maxLength);$control->setType('password');return$this[$name]=$control;}function
  1730. addTextArea($name,$label=NULL,$cols=40,$rows=10){return$this[$name]=new
  1731. Controls\TextArea($label,$cols,$rows);}function
  1732. addUpload($name,$label=NULL){return$this[$name]=new
  1733. Controls\UploadControl($label);}function
  1734. addHidden($name,$default=NULL){$control=new
  1735. Controls\HiddenField;$control->setDefaultValue($default);return$this[$name]=$control;}function
  1736. addCheckbox($name,$caption=NULL){return$this[$name]=new
  1737. Controls\Checkbox($caption);}function
  1738. addRadioList($name,$label=NULL,array$items=NULL){return$this[$name]=new
  1739. Controls\RadioList($label,$items);}function
  1740. addSelect($name,$label=NULL,array$items=NULL,$size=NULL){return$this[$name]=new
  1741. Controls\SelectBox($label,$items,$size);}function
  1742. addMultiSelect($name,$label=NULL,array$items=NULL,$size=NULL){return$this[$name]=new
  1743. Controls\MultiSelectBox($label,$items,$size);}function
  1744. addSubmit($name,$caption=NULL){return$this[$name]=new
  1745. Controls\SubmitButton($caption);}function
  1746. addButton($name,$caption){return$this[$name]=new
  1747. Controls\Button($caption);}function
  1748. addImage($name,$src=NULL,$alt=NULL){return$this[$name]=new
  1749. Controls\ImageButton($src,$alt);}function
  1750. addContainer($name){$control=new
  1751. Container;$control->currentGroup=$this->currentGroup;return$this[$name]=$control;}final
  1752. function
  1753. offsetSet($name,$component){$this->addComponent($component,$name);}final
  1754. function
  1755. offsetGet($name){return$this->getComponent($name,TRUE);}final
  1756. function
  1757. offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}final
  1758. function
  1759. offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}final
  1760. function
  1761. __clone(){throw
  1762. new
  1763. Nette\NotImplementedException('Form cloning is not supported yet.');}function
  1764. addFile($name,$label=NULL){trigger_error(__METHOD__.'() is deprecated; use addUpload() instead.',E_USER_WARNING);return$this->addUpload($name,$label);}}class
  1765. Form
  1766. extends
  1767. Container{const
  1768. EQUAL=':equal',IS_IN=':equal',FILLED=':filled',VALID=':valid';const
  1769. PROTECTION='Nette\Forms\Controls\HiddenField::validateEqual';const
  1770. SUBMITTED=':submitted';const
  1771. MIN_LENGTH=':minLength',MAX_LENGTH=':maxLength',LENGTH=':length',EMAIL=':email',URL=':url',REGEXP=':regexp',PATTERN=':pattern',INTEGER=':integer',NUMERIC=':integer',FLOAT=':float',RANGE=':range';const
  1772. COUNT=':length';const
  1773. MAX_FILE_SIZE=':fileSize',MIME_TYPE=':mimeType',IMAGE=':image';const
  1774. GET='get',POST='post';const
  1775. TRACKER_ID='_form_';const
  1776. PROTECTOR_ID='_token_';public$onSuccess;public$onError;public$onSubmit;public$onInvalidSubmit;private$submittedBy;private$httpData;private$element;private$renderer;private$translator;private$groups=array();private$errors=array();function
  1777. __construct($name=NULL){$this->element=Nette\Utils\Html::el('form');$this->element->action='';$this->element->method=self::POST;$this->element->id=$name===NULL?NULL:'frm-'.$name;$this->monitor(__CLASS__);if($name!==NULL){$tracker=new
  1778. Controls\HiddenField($name);$tracker->unmonitor(__CLASS__);$this[self::TRACKER_ID]=$tracker;}parent::__construct(NULL,$name);}protected
  1779. function
  1780. attached($obj){if($obj
  1781. instanceof
  1782. self){throw
  1783. new
  1784. Nette\InvalidStateException('Nested forms are forbidden.');}}final
  1785. function
  1786. getForm($need=TRUE){return$this;}function
  1787. setAction($url){$this->element->action=$url;return$this;}function
  1788. getAction(){return$this->element->action;}function
  1789. setMethod($method){if($this->httpData!==NULL){throw
  1790. new
  1791. Nette\InvalidStateException(__METHOD__.'() must be called until the form is empty.');}$this->element->method=strtolower($method);return$this;}function
  1792. getMethod(){return$this->element->method;}function
  1793. addProtection($message=NULL,$timeout=NULL){$session=$this->getSession()->getSection('Nette.Forms.Form/CSRF');$key="key$timeout";if(isset($session->$key)){$token=$session->$key;}else{$session->$key=$token=Nette\Utils\Strings::random();}$session->setExpiration($timeout,$key);$this[self::PROTECTOR_ID]=new
  1794. Controls\HiddenField($token);$this[self::PROTECTOR_ID]->addRule(self::PROTECTION,$message,$token);}function
  1795. addGroup($caption=NULL,$setAsCurrent=TRUE){$group=new
  1796. ControlGroup;$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
  1797. removeGroup($name){if(is_string($name)&&isset($this->groups[$name])){$group=$this->groups[$name];}elseif($name
  1798. instanceof
  1799. ControlGroup&&in_array($name,$this->groups,TRUE)){$group=$name;$name=array_search($group,$this->groups,TRUE);}else{throw
  1800. new
  1801. Nette\InvalidArgumentException("Group not found in form '$this->name'");}foreach($group->getControls()as$control){$this->removeComponent($control);}unset($this->groups[$name]);}function
  1802. getGroups(){return$this->groups;}function
  1803. getGroup($name){return
  1804. isset($this->groups[$name])?$this->groups[$name]:NULL;}function
  1805. setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->translator=$translator;return$this;}final
  1806. function
  1807. getTranslator(){return$this->translator;}function
  1808. isAnchored(){return
  1809. TRUE;}final
  1810. function
  1811. isSubmitted(){if($this->submittedBy===NULL&&count($this->getControls())){$this->getHttpData();$this->submittedBy=$this->httpData!==NULL;}return$this->submittedBy;}final
  1812. function
  1813. isSuccess(){return$this->isSubmitted()&&$this->isValid();}function
  1814. setSubmittedBy(ISubmitterControl$by=NULL){$this->submittedBy=$by===NULL?FALSE:$by;return$this;}final
  1815. function
  1816. getHttpData(){if($this->httpData===NULL){if(!$this->isAnchored()){throw
  1817. new
  1818. Nette\InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');}$this->httpData=$this->receiveHttpData();}return$this->httpData;}function
  1819. fireEvents(){if(!$this->isSubmitted()){return;}elseif($this->submittedBy
  1820. instanceof
  1821. ISubmitterControl){if(!$this->submittedBy->getValidationScope()||$this->isValid()){$this->submittedBy->click();$valid=TRUE;}else{$this->submittedBy->onInvalidClick($this->submittedBy);}}if(isset($valid)||$this->isValid()){$this->onSuccess($this);}else{$this->onError($this);if($this->onInvalidSubmit){trigger_error(__CLASS__.'->onInvalidSubmit is deprecated; use onError instead.',E_USER_WARNING);$this->onInvalidSubmit($this);}}if($this->onSuccess){$this->onSubmit($this);}elseif($this->onSubmit){trigger_error(__CLASS__.'->onSubmit changed its behavior; use onSuccess instead.',E_USER_WARNING);if(isset($valid)||$this->isValid()){$this->onSubmit($this);}}}protected
  1822. function
  1823. receiveHttpData(){$httpRequest=$this->getHttpRequest();if(strcasecmp($this->getMethod(),$httpRequest->getMethod())){return;}if($httpRequest->isMethod('post')){$data=Nette\Utils\Arrays::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
  1824. getValues($asArray=FALSE){$values=parent::getValues($asArray);unset($values[self::TRACKER_ID],$values[self::PROTECTOR_ID]);return$values;}function
  1825. addError($message){$this->valid=FALSE;if($message!==NULL&&!in_array($message,$this->errors,TRUE)){$this->errors[]=$message;}}function
  1826. getErrors(){return$this->errors;}function
  1827. hasErrors(){return(bool)$this->getErrors();}function
  1828. cleanErrors(){$this->errors=array();$this->valid=NULL;}function
  1829. getElementPrototype(){return$this->element;}function
  1830. setRenderer(IFormRenderer$renderer){$this->renderer=$renderer;return$this;}final
  1831. function
  1832. getRenderer(){if($this->renderer===NULL){$this->renderer=new
  1833. Rendering\DefaultFormRenderer;}return$this->renderer;}function
  1834. render(){$args=func_get_args();array_unshift($args,$this);echo
  1835. call_user_func_array(array($this->getRenderer(),'render'),$args);}function
  1836. __toString(){try{return$this->getRenderer()->render($this);}catch(\Exception$e){if(func_get_args()&&func_get_arg(0)){throw$e;}else{Nette\Diagnostics\Debugger::toStringException($e);}}}protected
  1837. function
  1838. getHttpRequest(){return
  1839. Nette\Environment::getHttpRequest();}protected
  1840. function
  1841. getSession(){return
  1842. Nette\Environment::getSession();}}}namespace Nette\Application\UI{use
  1843. Nette;class
  1844. Form
  1845. extends
  1846. Nette\Forms\Form
  1847. implements
  1848. ISignalReceiver{function
  1849. __construct(Nette\ComponentModel\IContainer$parent=NULL,$name=NULL){parent::__construct();$this->monitor('Nette\Application\UI\Presenter');if($parent!==NULL){$parent->addComponent($this,$name);}}function
  1850. getPresenter($need=TRUE){return$this->lookup('Nette\Application\UI\Presenter',$need);}protected
  1851. function
  1852. attached($presenter){if($presenter
  1853. instanceof
  1854. Presenter){$name=$this->lookupPath('Nette\Application\UI\Presenter');if(!isset($this->getElementPrototype()->id)){$this->getElementPrototype()->id='frm-'.$name;}$this->setAction(new
  1855. Link($presenter,$name.self::NAME_SEPARATOR.'submit!',array()));if($this->isSubmitted()){foreach($this->getControls()as$control){$control->loadHttpData();}}}parent::attached($presenter);}function
  1856. isAnchored(){return(bool)$this->getPresenter(FALSE);}protected
  1857. function
  1858. 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
  1859. Nette\Utils\Arrays::mergeTree($request->getPost(),$request->getFiles());}else{return$request->getParameters();}}function
  1860. signalReceived($signal){if($signal==='submit'){if(!$this->getPresenter()->getRequest()->hasFlag(Nette\Application\Request::RESTORED)){$this->fireEvents();}}else{$class=get_class($this);throw
  1861. new
  1862. BadSignalException("Missing handler for signal '$signal' in $class.");}}}class
  1863. InvalidLinkException
  1864. extends\Exception{}class
  1865. Link
  1866. extends
  1867. Nette\Object{private$component;private$destination;private$params;function
  1868. __construct(PresenterComponent$component,$destination,array$params){$this->component=$component;$this->destination=$destination;$this->params=$params;}function
  1869. getDestination(){return$this->destination;}function
  1870. setParameter($key,$value){$this->params[$key]=$value;return$this;}function
  1871. getParameter($key){return
  1872. isset($this->params[$key])?$this->params[$key]:NULL;}function
  1873. getParameters(){return$this->params;}function
  1874. __toString(){try{return$this->component->link($this->destination,$this->params);}catch(\Exception$e){Nette\Diagnostics\Debugger::toStringException($e);}}}class
  1875. Multiplier
  1876. extends
  1877. PresenterComponent{private$factory;function
  1878. __construct($factory){parent::__construct();$this->factory=callback($factory);}protected
  1879. function
  1880. createComponent($name){return$this->factory->invoke($name,$this);}}use
  1881. Nette\Application;use
  1882. Nette\Application\Responses;use
  1883. Nette\Http;use
  1884. Nette\Reflection;abstract
  1885. class
  1886. Presenter
  1887. extends
  1888. Control
  1889. implements
  1890. Application\IPresenter{const
  1891. INVALID_LINK_SILENT=1,INVALID_LINK_WARNING=2,INVALID_LINK_EXCEPTION=3;const
  1892. SIGNAL_KEY='do',ACTION_KEY='action',FLASH_KEY='_fid',DEFAULT_ACTION='default';public$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;private$context;function
  1893. __construct(Nette\DI\Container$context){$this->context=$context;if($this->invalidLinkMode===NULL){$this->invalidLinkMode=$context->parameters['productionMode']?self::INVALID_LINK_SILENT:self::INVALID_LINK_WARNING;}}final
  1894. function
  1895. getRequest(){return$this->request;}final
  1896. function
  1897. getPresenter($need=TRUE){return$this;}final
  1898. function
  1899. getUniqueId(){return'';}function
  1900. run(Application\Request$request){try{$this->request=$request;$this->payload=(object)NULL;$this->setParent($this->getParent(),$request->getPresenterName());$this->initGlobalParameters();$this->checkRequirements($this->getReflection());$this->startup();if(!$this->startupCheck){$class=$this->getReflection()->getMethod('startup')->getDeclaringClass()->getName();throw
  1901. new
  1902. Nette\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(Application\AbortException$e){if($this->isAjax())try{$hasPayload=(array)$this->payload;unset($hasPayload['state']);if($this->response
  1903. instanceof
  1904. Responses\TextResponse&&$this->isControlInvalid()){$this->snippetMode=TRUE;$this->response->send($this->getHttpRequest(),$this->getHttpResponse());$this->sendPayload();}elseif(!$this->response&&$hasPayload){$this->sendPayload();}}catch(Application\AbortException$e){}if($this->hasFlashSession()){$this->getFlashSession()->setExpiration($this->response
  1905. instanceof
  1906. Responses\RedirectResponse?'+ 30 seconds':'+ 3 seconds');}$this->onShutdown($this,$this->response);$this->shutdown($this->response);return$this->response;}}protected
  1907. function
  1908. startup(){$this->startupCheck=TRUE;}protected
  1909. function
  1910. beforeRender(){}protected
  1911. function
  1912. afterRender(){}protected
  1913. function
  1914. shutdown($response){}function
  1915. checkRequirements($element){$user=(array)$element->getAnnotation('User');if(in_array('loggedIn',$user)&&!$this->getUser()->isLoggedIn()){throw
  1916. new
  1917. Application\ForbiddenRequestException;}}function
  1918. processSignal(){if($this->signal===NULL){return;}try{$component=$this->signalReceiver===''?$this:$this->getComponent($this->signalReceiver,FALSE);}catch(Nette\InvalidArgumentException$e){}if(isset($e)||$component===NULL){throw
  1919. new
  1920. BadSignalException("The signal receiver component '$this->signalReceiver' is not found.");}elseif(!$component
  1921. instanceof
  1922. ISignalReceiver){throw
  1923. new
  1924. BadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");}$component->signalReceived($this->signal);$this->signal=NULL;}final
  1925. function
  1926. getSignal(){return$this->signal===NULL?NULL:array($this->signalReceiver,$this->signal);}final
  1927. function
  1928. isSignalReceiver($component,$signal=NULL){if($component
  1929. instanceof
  1930. Nette\ComponentModel\Component){$component=$component===$this?'':$component->lookupPath(__CLASS__,TRUE);}if($this->signal===NULL){return
  1931. 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
  1932. function
  1933. getAction($fullyQualified=FALSE){return$fullyQualified?':'.$this->getName().':'.$this->action:$this->action;}function
  1934. changeAction($action){if(is_string($action)&&Nette\Utils\Strings::match($action,'#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*$#')){$this->action=$action;$this->view=$action;}else{$this->error('Action name is not alphanumeric string.');}}final
  1935. function
  1936. getView(){return$this->view;}function
  1937. setView($view){$this->view=(string)$view;return$this;}final
  1938. function
  1939. getLayout(){return$this->layout;}function
  1940. setLayout($layout){$this->layout=$layout===FALSE?FALSE:(string)$layout;return$this;}function
  1941. sendTemplate(){$template=$this->getTemplate();if(!$template){return;}if($template
  1942. instanceof
  1943. Nette\Templating\IFileTemplate&&!$template->getFile()){$files=$this->formatTemplateFiles();foreach($files
  1944. as$file){if(is_file($file)){$template->setFile($file);break;}}if(!$template->getFile()){$file=preg_replace('#^.*([/\\\\].{1,70})$#U',"\xE2\x80\xA6\$1",reset($files));$file=strtr($file,'/',DIRECTORY_SEPARATOR);$this->error("Page not found. Missing template '$file'.");}}$this->sendResponse(new
  1945. Responses\TextResponse($template));}function
  1946. findLayoutTemplateFile(){if($this->layout===FALSE){return;}$files=$this->formatLayoutTemplateFiles();foreach($files
  1947. as$file){if(is_file($file)){return$file;}}if($this->layout){$file=preg_replace('#^.*([/\\\\].{1,70})$#U',"\xE2\x80\xA6\$1",reset($files));$file=strtr($file,'/',DIRECTORY_SEPARATOR);throw
  1948. new
  1949. Nette\FileNotFoundException("Layout not found. Missing template '$file'.");}}function
  1950. formatLayoutTemplateFiles(){$name=$this->getName();$presenter=substr($name,strrpos(':'.$name,':'));$layout=$this->layout?$this->layout:'layout';$dir=dirname(dirname($this->getReflection()->getFileName()));$list=array("$dir/templates/$presenter/@$layout.latte","$dir/templates/$presenter.@$layout.latte","$dir/templates/$presenter/@$layout.phtml","$dir/templates/$presenter.@$layout.phtml");do{$list[]="$dir/templates/@$layout.latte";$list[]="$dir/templates/@$layout.phtml";$dir=dirname($dir);}while($dir&&($name=substr($name,0,strrpos($name,':'))));return$list;}function
  1951. formatTemplateFiles(){$name=$this->getName();$presenter=substr($name,strrpos(':'.$name,':'));$dir=dirname(dirname($this->getReflection()->getFileName()));return
  1952. array("$dir/templates/$presenter/$this->view.latte","$dir/templates/$presenter.$this->view.latte","$dir/templates/$presenter/$this->view.phtml","$dir/templates/$presenter.$this->view.phtml");}protected
  1953. static
  1954. function
  1955. formatActionMethod($action){return'action'.$action;}protected
  1956. static
  1957. function
  1958. formatRenderMethod($view){return'render'.$view;}function
  1959. getPayload(){return$this->payload;}function
  1960. isAjax(){if($this->ajaxMode===NULL){$this->ajaxMode=$this->getHttpRequest()->isAjax();}return$this->ajaxMode;}function
  1961. sendPayload(){$this->sendResponse(new
  1962. Responses\JsonResponse($this->payload));}function
  1963. sendResponse(Application\IResponse$response){$this->response=$response;$this->terminate();}function
  1964. terminate(){if(func_num_args()!==0){trigger_error(__METHOD__.' is not intended to send a Application\Response; use sendResponse() instead.',E_USER_WARNING);$this->sendResponse(func_get_arg(0));}throw
  1965. new
  1966. Application\AbortException();}function
  1967. forward($destination,$args=array()){if($destination
  1968. instanceof
  1969. Application\Request){$this->sendResponse(new
  1970. Responses\ForwardResponse($destination));}elseif(!is_array($args)){$args=func_get_args();array_shift($args);}$this->createRequest($this,$destination,$args,'forward');$this->sendResponse(new
  1971. Responses\ForwardResponse($this->lastCreatedRequest));}function
  1972. redirectUrl($url,$code=NULL){if($this->isAjax()){$this->payload->redirect=(string)$url;$this->sendPayload();}elseif(!$code){$code=$this->getHttpRequest()->isMethod('post')?Http\IResponse::S303_POST_GET:Http\IResponse::S302_FOUND;}$this->sendResponse(new
  1973. Responses\RedirectResponse($url,$code));}function
  1974. redirectUri($url,$code=NULL){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::redirectUrl() instead.',E_USER_WARNING);$this->redirectUrl($url,$code);}function
  1975. error($message=NULL,$code=Http\IResponse::S404_NOT_FOUND){throw
  1976. new
  1977. Application\BadRequestException($message,$code);}function
  1978. backlink(){return$this->getAction(TRUE);}function
  1979. getLastCreatedRequest(){return$this->lastCreatedRequest;}function
  1980. getLastCreatedRequestFlag($flag){return!empty($this->lastCreatedRequestFlag[$flag]);}function
  1981. canonicalize(){if(!$this->isAjax()&&($this->request->isMethod('get')||$this->request->isMethod('head'))){try{$url=$this->createRequest($this,$this->action,$this->getGlobalState()+$this->request->getParameters(),'redirectX');}catch(InvalidLinkException$e){}if(isset($url)&&!$this->getHttpRequest()->getUrl()->isEqual($url)){$this->sendResponse(new
  1982. Responses\RedirectResponse($url,Http\IResponse::S301_MOVED_PERMANENTLY));}}}function
  1983. lastModified($lastModified,$etag=NULL,$expire=NULL){if($expire!==NULL){$this->getHttpResponse()->setExpiration($expire);}if(!$this->getHttpContext()->isModified($lastModified,$etag)){$this->terminate();}}final
  1984. protected
  1985. function
  1986. createRequest($component,$destination,array$args,$mode){static$presenterFactory,$router,$refUrl;if($presenterFactory===NULL){$presenterFactory=$this->getApplication()->getPresenterFactory();$router=$this->getApplication()->getRouter();$refUrl=new
  1987. Http\Url($this->getHttpRequest()->getUrl());$refUrl->setPath($this->getHttpRequest()->getUrl()->getScriptPath());}$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
  1988. instanceof
  1989. 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
  1990. new
  1991. InvalidLinkException("Signal must be non-empty string.");}$destination='this';}if($destination==NULL){throw
  1992. new
  1993. 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
  1994. new
  1995. 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);}}try{$presenterClass=$presenterFactory->getPresenterClass($presenter);}catch(Application\InvalidPresenterException$e){throw
  1996. new
  1997. InvalidLinkException($e->getMessage(),NULL,$e);}}if(isset($signal)){$reflection=new
  1998. PresenterComponentReflection(get_class($component));if($signal==='this'){$signal='';if(array_key_exists(0,$args)){throw
  1999. new
  2000. InvalidLinkException("Unable to pass parameters to 'this!' signal.");}}elseif(strpos($signal,self::NAME_SEPARATOR)===FALSE){$method=$component->formatSignalMethod($signal);if(!$reflection->hasCallableMethod($method)){throw
  2001. new
  2002. InvalidLinkException("Unknown signal '$signal', missing handler {$reflection->name}::$method()");}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
  2003. as$key=>$val){unset($args[$key]);$args[$prefix.$key]=$val;}}}if(is_subclass_of($presenterClass,__CLASS__)){if($action===''){$action=self::DEFAULT_ACTION;}$current=($action==='*'||strcasecmp($action,$this->action)===0)&&$presenterClass===get_class($this);$reflection=new
  2004. PresenterComponentReflection($presenterClass);if($args||$destination==='this'){$method=$presenterClass::formatActionMethod($action);if(!$reflection->hasCallableMethod($method)){$method=$presenterClass::formatRenderMethod($action);if(!$reflection->hasCallableMethod($method)){$method=NULL;}}if($method===NULL){if(array_key_exists(0,$args)){throw
  2005. new
  2006. InvalidLinkException("Unable to pass parameters to action '$presenter:$action', missing corresponding method.");}}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);}if($mode==='redirect'){$this->saveGlobalState();}$globalState=$this->getGlobalState($destination==='this'?NULL:$presenterClass);if($current&&$args){$tmp=$globalState+$this->params;foreach($args
  2007. 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->getParameterId($signal);$current=$current&&$args[self::SIGNAL_KEY]===$this->getParameter(self::SIGNAL_KEY);}if(($mode==='redirect'||$mode==='forward')&&$this->hasFlashSession()){$args[self::FLASH_KEY]=$this->getParameter(self::FLASH_KEY);}$this->lastCreatedRequest=new
  2008. Application\Request($presenter,Application\Request::FORWARD,$args,array(),array());$this->lastCreatedRequestFlag=array('current'=>$current);if($mode==='forward'){return;}$url=$router->constructUrl($this->lastCreatedRequest,$refUrl);if($url===NULL){unset($args[self::ACTION_KEY]);$params=urldecode(http_build_query($args,NULL,', '));throw
  2009. new
  2010. InvalidLinkException("No route for $presenter:$action($params)");}if($mode==='link'&&$scheme===FALSE&&!$this->absoluteUrls){$hostUrl=$refUrl->getHostUrl();if(strncmp($url,$hostUrl,strlen($hostUrl))===0){$url=substr($url,strlen($hostUrl));}}return$url.$fragment;}private
  2011. static
  2012. function
  2013. argsToParams($class,$method,&$args,$supplemental=array()){$i=0;$rm=new\ReflectionMethod($class,$method);foreach($rm->getParameters()as$param){$name=$param->getName();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;}$def=$param->isDefaultValueAvailable()?$param->getDefaultValue():NULL;$val=$args[$name];if($val===NULL){continue;}elseif($param->isArray()||is_array($def)){if(!is_array($val)){throw
  2014. new
  2015. InvalidLinkException("Invalid value for parameter '$name', expected array.");}}elseif($param->getClass()||is_object($val)){}elseif(!is_scalar($val)){throw
  2016. new
  2017. InvalidLinkException("Invalid value for parameter '$name', expected scalar.");}elseif($def===NULL){if((string)$val===''){$args[$name]=NULL;}continue;}else{settype($args[$name],gettype($def));if((string)$args[$name]!==(string)$val){throw
  2018. new
  2019. InvalidLinkException("Invalid value for parameter '$name', expected ".gettype($def).".");}}if($args[$name]===$def){$args[$name]=NULL;}}if(array_key_exists($i,$args)){$method=$rm->getName();throw
  2020. new
  2021. InvalidLinkException("Passed more parameters than method $class::$method() expects.");}}protected
  2022. function
  2023. handleInvalidLink($e){if($this->invalidLinkMode===self::INVALID_LINK_SILENT){return'#';}elseif($this->invalidLinkMode===self::INVALID_LINK_WARNING){return'error: '.$e->getMessage();}else{throw$e;}}function
  2024. storeRequest($expiration='+ 10 minutes'){$session=$this->getSession('Nette.Application/requests');do{$key=Nette\Utils\Strings::random(5);}while(isset($session[$key]));$session[$key]=array($this->getUser()->getId(),$this->request);$session->setExpiration($expiration,$key);return$key;}function
  2025. restoreRequest($key){$session=$this->getSession('Nette.Application/requests');if(!isset($session[$key])||($session[$key][0]!==NULL&&$session[$key][0]!==$this->getUser()->getId())){return;}$request=clone$session[$key][1];unset($session[$key]);$request->setFlag(Application\Request::RESTORED,TRUE);$params=$request->getParameters();$params[self::FLASH_KEY]=$this->getParameter(self::FLASH_KEY);$request->setParameters($params);$this->sendResponse(new
  2026. Responses\ForwardResponse($request));}static
  2027. function
  2028. getPersistentComponents(){return(array)Reflection\ClassType::from(get_called_class())->getAnnotation('persistent');}private
  2029. function
  2030. getGlobalState($forClass=NULL){$sinces=&$this->globalStateSinces;if($this->globalState===NULL){$state=array();foreach($this->globalParams
  2031. as$id=>$params){$prefix=$id.self::NAME_SEPARATOR;foreach($params
  2032. as$key=>$val){$state[$prefix.$key]=$val;}}$this->saveState($state,$forClass?new
  2033. 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,'Nette\Application\UI\IStatePersistent');foreach($iterator
  2034. 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
  2035. as$key=>$val){$state[$prefix.$key]=$val;$sinces[$prefix.$key]=$since;}}}else{$state=$this->globalState;}if($forClass!==NULL){$since=NULL;foreach($state
  2036. 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
  2037. function
  2038. saveGlobalState(){foreach($this->globalParams
  2039. as$id=>$foo){$this->getComponent($id,FALSE);}$this->globalParams=array();$this->globalState=$this->getGlobalState();}private
  2040. function
  2041. initGlobalParameters(){$this->globalParams=array();$selfParams=array();$params=$this->request->getParameters();if($this->isAjax()){$params+=$this->request->getPost();}foreach($params
  2042. as$key=>$value){if(!preg_match('#^((?:[a-z0-9_]+-)*)((?!\d+$)[a-z0-9_]+)$#i',$key,$matches)){$this->error("'Invalid parameter name '$key'");}if(!$matches[1]){$selfParams[$key]=$value;}else{$this->globalParams[substr($matches[1],0,-1)][$matches[2]]=$value;}}$this->changeAction(isset($selfParams[self::ACTION_KEY])?$selfParams[self::ACTION_KEY]:self::DEFAULT_ACTION);$this->signalReceiver=$this->getUniqueId();if(isset($selfParams[self::SIGNAL_KEY])){$param=$selfParams[self::SIGNAL_KEY];if(!is_string($param)){$this->error('Signal name is not string.');}$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
  2043. function
  2044. popGlobalParameters($id){if(isset($this->globalParams[$id])){$res=$this->globalParams[$id];unset($this->globalParams[$id]);return$res;}else{return
  2045. array();}}function
  2046. hasFlashSession(){return!empty($this->params[self::FLASH_KEY])&&$this->getSession()->hasSection('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}function
  2047. getFlashSession(){if(empty($this->params[self::FLASH_KEY])){$this->params[self::FLASH_KEY]=Nette\Utils\Strings::random(4);}return$this->getSession('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}final
  2048. function
  2049. getContext(){return$this->context;}final
  2050. function
  2051. getService($name){return$this->context->getService($name);}protected
  2052. function
  2053. getHttpRequest(){return$this->context->getByType('Nette\Http\IRequest');}protected
  2054. function
  2055. getHttpResponse(){return$this->context->getByType('Nette\Http\IResponse');}protected
  2056. function
  2057. getHttpContext(){return$this->context->getByType('Nette\Http\Context');}function
  2058. getApplication(){return$this->context->getByType('Nette\Application\Application');}function
  2059. getSession($namespace=NULL){$handler=$this->context->getByType('Nette\Http\Session');return$namespace===NULL?$handler:$handler->getSection($namespace);}function
  2060. getUser(){return$this->context->getByType('Nette\Security\User');}}}namespace Nette\Reflection{use
  2061. Nette;use
  2062. Nette\ObjectMixin;class
  2063. ClassType
  2064. extends\ReflectionClass{private
  2065. static$extMethods;static
  2066. function
  2067. from($class){return
  2068. new
  2069. static($class);}function
  2070. __toString(){return'Class '.$this->getName();}function
  2071. hasEventProperty($name){if(preg_match('#^on[A-Z]#',$name)&&$this->hasProperty($name)){$rp=$this->getProperty($name);return$rp->isPublic()&&!$rp->isStatic();}return
  2072. FALSE;}function
  2073. setExtensionMethod($name,$callback){$l=&self::$extMethods[strtolower($name)];$l[strtolower($this->getName())]=callback($callback);$l['']=NULL;return$this;}function
  2074. getExtensionMethod($name){$class=strtolower($this->getName());$l=&self::$extMethods[strtolower($name)];if(empty($l)){return
  2075. 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;}function
  2076. is($type){return$this->isSubclassOf($type)||strcasecmp($this->getName(),ltrim($type,'\\'))===0;}function
  2077. getConstructor(){return($ref=parent::getConstructor())?Method::from($this->getName(),$ref->getName()):NULL;}function
  2078. getExtension(){return($name=$this->getExtensionName())?new
  2079. Extension($name):NULL;}function
  2080. getInterfaces(){$res=array();foreach(parent::getInterfaceNames()as$val){$res[$val]=new
  2081. static($val);}return$res;}function
  2082. getMethod($name){return
  2083. new
  2084. Method($this->getName(),$name);}function
  2085. getMethods($filter=-1){foreach($res=parent::getMethods($filter)as$key=>$val){$res[$key]=new
  2086. Method($this->getName(),$val->getName());}return$res;}function
  2087. getParentClass(){return($ref=parent::getParentClass())?new
  2088. static($ref->getName()):NULL;}function
  2089. getProperties($filter=-1){foreach($res=parent::getProperties($filter)as$key=>$val){$res[$key]=new
  2090. Property($this->getName(),$val->getName());}return$res;}function
  2091. getProperty($name){return
  2092. new
  2093. Property($this->getName(),$name);}function
  2094. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  2095. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  2096. isset($res[$name])?end($res[$name]):NULL;}function
  2097. getAnnotations(){return
  2098. AnnotationsParser::getAll($this);}function
  2099. getDescription(){return$this->getAnnotation('description');}static
  2100. function
  2101. getReflection(){return
  2102. new
  2103. ClassType(get_called_class());}function
  2104. __call($name,$args){return
  2105. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  2106. ObjectMixin::get($this,$name);}function
  2107. __set($name,$value){return
  2108. ObjectMixin::set($this,$name,$value);}function
  2109. __isset($name){return
  2110. ObjectMixin::has($this,$name);}function
  2111. __unset($name){ObjectMixin::remove($this,$name);}}}namespace Nette\Application\UI{use
  2112. Nette;use
  2113. Nette\Application\BadRequestException;class
  2114. PresenterComponentReflection
  2115. extends
  2116. Nette\Reflection\ClassType{private
  2117. static$ppCache=array();private
  2118. static$pcCache=array();private
  2119. static$mcCache=array();function
  2120. 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,'Nette\Application\UI\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);}foreach($this->getPersistentParams(get_parent_class($class))as$name=>$param){if(isset($params[$name])){$params[$name]['since']=$param['since'];continue;}$params[$name]=$param;}}return$params;}function
  2121. getPersistentComponents($class=NULL){$class=$class===NULL?$this->getName():$class;$components=&self::$pcCache[$class];if($components!==NULL){return$components;}$components=array();if(is_subclass_of($class,'Nette\Application\UI\Presenter')){foreach(call_user_func(array($class,'getPersistentComponents'),$class)as$name=>$meta){if(is_string($meta)){$name=$meta;}$components[$name]=array('since'=>$class);}$components=$this->getPersistentComponents(get_parent_class($class))+$components;}return$components;}function
  2122. hasCallableMethod($method){$class=$this->getName();$cache=&self::$mcCache[strtolower($class.':'.$method)];if($cache===NULL)try{$cache=FALSE;$rm=Nette\Reflection\Method::from($class,$method);$cache=$this->isInstantiable()&&$rm->isPublic()&&!$rm->isAbstract()&&!$rm->isStatic();}catch(\ReflectionException$e){}return$cache;}static
  2123. function
  2124. combineArgs(\ReflectionFunctionAbstract$method,$args){$res=array();$i=0;foreach($method->getParameters()as$param){$name=$param->getName();$def=$param->isDefaultValueAvailable()?$param->getDefaultValue():NULL;if(!isset($args[$name])){if($param->isArray()&&!$param->allowsNull()){$def=(array)$def;}$res[$i++]=$def;}else{$val=$args[$name];if($param->isArray()||is_array($def)){if(!is_array($val)){throw
  2125. new
  2126. BadRequestException("Invalid value for parameter '$name', expected array.");}}elseif($param->getClass()||is_object($val)){}else{if(!is_scalar($val)){throw
  2127. new
  2128. BadRequestException("Invalid value for parameter '$name', expected scalar.");}if($def!==NULL){settype($val,gettype($def));if(($val===FALSE?'0':(string)$val)!==(string)$args[$name]){throw
  2129. new
  2130. BadRequestException("Invalid value for parameter '$name', expected ".gettype($def).".");}}}$res[$i++]=$val;}}return$res;}}}namespace Nette\Caching{use
  2131. Nette;class
  2132. Cache
  2133. extends
  2134. Nette\Object
  2135. implements\ArrayAccess{const
  2136. PRIORITY='priority',EXPIRATION='expire',EXPIRE='expire',SLIDING='sliding',TAGS='tags',FILES='files',ITEMS='items',CONSTS='consts',CALLBACKS='callbacks',ALL='all';const
  2137. NAMESPACE_SEPARATOR="\x00";private$storage;private$namespace;private$key;private$data;function
  2138. __construct(IStorage$storage,$namespace=NULL){$this->storage=$storage;$this->namespace=$namespace.self::NAMESPACE_SEPARATOR;}function
  2139. getStorage(){return$this->storage;}function
  2140. getNamespace(){return(string)substr($this->namespace,0,-1);}function
  2141. derive($namespace){$derived=new
  2142. static($this->storage,$this->namespace.$namespace);return$derived;}function
  2143. load($key,$fallback=NULL){$data=$this->storage->read($this->generateKey($key));if($data===NULL&&$fallback){return$this->save($key,callback($fallback));}return$data;}function
  2144. save($key,$data,array$dp=NULL){$this->release();$key=$this->generateKey($key);if($data
  2145. instanceof
  2146. Nette\Callback||$data
  2147. instanceof\Closure){$this->storage->lock($key);$data=callback($data)->invokeArgs(array(&$dp));}if($data===NULL){$this->storage->remove($key);}else{$this->storage->write($key,$data,$this->completeDependencies($dp,$data));return$data;}}private
  2148. function
  2149. completeDependencies($dp,$data){if(is_object($data)){$dp[self::CALLBACKS][]=array(array(__CLASS__,'checkSerializationVersion'),get_class($data),Nette\Reflection\ClassType::from($data)->getAnnotation('serializationVersion'));}if(isset($dp[Cache::EXPIRATION])){$dp[Cache::EXPIRATION]=Nette\DateTime::from($dp[Cache::EXPIRATION])->format('U')-time();}if(isset($dp[self::FILES])){foreach(array_unique((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_unique((array)$dp[self::ITEMS]);foreach($dp[self::ITEMS]as$k=>$item){$dp[self::ITEMS][$k]=$this->generateKey($item);}}if(isset($dp[self::CONSTS])){foreach(array_unique((array)$dp[self::CONSTS])as$item){$dp[self::CALLBACKS][]=array(array(__CLASS__,'checkConst'),$item,constant($item));}unset($dp[self::CONSTS]);}if(!is_array($dp)){$dp=array();}return$dp;}function
  2150. remove($key){$this->save($key,NULL);}function
  2151. clean(array$conds=NULL){$this->release();$this->storage->clean((array)$conds);}function
  2152. call($function){$key=func_get_args();return$this->load($key,function()use($function,$key){array_shift($key);return
  2153. callback($function)->invokeArgs($key);});}function
  2154. wrap($function,array$dp=NULL){$cache=$this;return
  2155. function()use($cache,$function,$dp){$key=array($function,func_get_args());$data=$cache->load($key);if($data===NULL){$data=$cache->save($key,callback($function)->invokeArgs($key[1]),$dp);}return$data;};}function
  2156. start($key){$data=$this->load($key);if($data===NULL){return
  2157. new
  2158. OutputHelper($this,$key);}echo$data;}protected
  2159. function
  2160. generateKey($key){return$this->namespace.md5(is_scalar($key)?$key:serialize($key));}function
  2161. offsetSet($key,$data){$this->save($key,$data);}function
  2162. offsetGet($key){$key=is_scalar($key)?(string)$key:serialize($key);if($this->key!==$key){$this->key=$key;$this->data=$this->load($key);}return$this->data;}function
  2163. offsetExists($key){$this->release();return$this->offsetGet($key)!==NULL;}function
  2164. offsetUnset($key){$this->save($key,NULL);}function
  2165. release(){$this->key=$this->data=NULL;}static
  2166. function
  2167. checkCallbacks($callbacks){foreach($callbacks
  2168. as$callback){$func=array_shift($callback);if(!call_user_func_array($func,$callback)){return
  2169. FALSE;}}return
  2170. TRUE;}private
  2171. static
  2172. function
  2173. checkConst($const,$value){return
  2174. defined($const)&&constant($const)===$value;}private
  2175. static
  2176. function
  2177. checkFile($file,$time){return@filemtime($file)==$time;}private
  2178. static
  2179. function
  2180. checkSerializationVersion($class,$value){return
  2181. Nette\Reflection\ClassType::from($class)->getAnnotation('serializationVersion')===$value;}}class
  2182. OutputHelper
  2183. extends
  2184. Nette\Object{public$dependencies;private$cache;private$key;function
  2185. __construct(Cache$cache,$key){$this->cache=$cache;$this->key=$key;ob_start();}function
  2186. end(array$dp=NULL){if($this->cache===NULL){throw
  2187. new
  2188. Nette\InvalidStateException('Output cache has already been saved.');}$this->cache->save($this->key,ob_get_flush(),(array)$dp+(array)$this->dependencies);$this->cache=NULL;}}}namespace Nette\Caching\Storages{use
  2189. Nette;class
  2190. DevNullStorage
  2191. extends
  2192. Nette\Object
  2193. implements
  2194. Nette\Caching\IStorage{function
  2195. read($key){}function
  2196. lock($key){}function
  2197. write($key,$data,array$dp){}function
  2198. remove($key){}function
  2199. clean(array$conds){}}use
  2200. Nette\Caching\Cache;class
  2201. FileJournal
  2202. extends
  2203. Nette\Object
  2204. implements
  2205. IJournal{const
  2206. FILE='btfj.dat';const
  2207. FILE_MAGIC=0x6274666A;const
  2208. INDEX_MAGIC=0x696E6465;const
  2209. DATA_MAGIC=0x64617461;const
  2210. NODE_SIZE=4096;const
  2211. BITROT=12;const
  2212. HEADER_SIZE=4096;const
  2213. INT32_SIZE=4;const
  2214. INFO='i',TYPE='t',IS_LEAF='il',PREV_NODE='p',END='e',MAX='m',INDEX_DATA='id',LAST_INDEX='l';const
  2215. TAGS='t',PRIORITY='p',ENTRIES='e';const
  2216. DATA='d',KEY='k',DELETED='d';public
  2217. static$debug=FALSE;private$file;private$handle;private$lastNode=2;private$lastModTime=NULL;private$nodeCache=array();private$nodeChanged=array();private$toCommit=array();private$deletedLinks=array();private$dataNodeFreeSpace=array();private
  2218. static$startNode=array(self::TAGS=>0,self::PRIORITY=>1,self::ENTRIES=>2,self::DATA=>3);function
  2219. __construct($dir){$this->file=$dir.'/'.self::FILE;if(!file_exists($this->file)){$init=@fopen($this->file,'xb');if(!$init){clearstatcache();if(!file_exists($this->file)){throw
  2220. new
  2221. Nette\InvalidStateException("Cannot create journal file $this->file.");}}else{$writen=fwrite($init,pack('N2',self::FILE_MAGIC,$this->lastNode));fclose($init);if($writen!==self::INT32_SIZE*2){throw
  2222. new
  2223. Nette\InvalidStateException("Cannot write journal header.");}}}$this->handle=fopen($this->file,'r+b');if(!$this->handle){throw
  2224. new
  2225. Nette\InvalidStateException("Cannot open journal file '$this->file'.");}if(!flock($this->handle,LOCK_SH)){throw
  2226. new
  2227. Nette\InvalidStateException('Cannot acquire shared lock on journal.');}$header=stream_get_contents($this->handle,2*self::INT32_SIZE,0);flock($this->handle,LOCK_UN);list(,$fileMagic,$this->lastNode)=unpack('N2',$header);if($fileMagic!==self::FILE_MAGIC){fclose($this->handle);$this->handle=false;throw
  2228. new
  2229. Nette\InvalidStateException("Malformed journal file '$this->file'.");}}function
  2230. __destruct(){if($this->handle){$this->headerCommit();flock($this->handle,LOCK_UN);fclose($this->handle);$this->handle=false;}}function
  2231. write($key,array$dependencies){$this->lock();$priority=!isset($dependencies[Cache::PRIORITY])?FALSE:(int)$dependencies[Cache::PRIORITY];$tags=empty($dependencies[Cache::TAGS])?FALSE:(array)$dependencies[Cache::TAGS];$exists=FALSE;$keyHash=crc32($key);list($entriesNodeId,$entriesNode)=$this->findIndexNode(self::ENTRIES,$keyHash);if(isset($entriesNode[$keyHash])){$entries=$this->mergeIndexData($entriesNode[$keyHash]);foreach($entries
  2232. as$link=>$foo){$dataNode=$this->getNode($link>>self::BITROT);if($dataNode[$link][self::KEY]===$key){if($dataNode[$link][self::TAGS]==$tags&&$dataNode[$link][self::PRIORITY]===$priority){if($dataNode[$link][self::DELETED]){$dataNode[$link][self::DELETED]=FALSE;$this->saveNode($link>>self::BITROT,$dataNode);}$exists=TRUE;}else{$toDelete=array();foreach($dataNode[$link][self::TAGS]as$tag){$toDelete[self::TAGS][$tag][$link]=TRUE;}if($dataNode[$link][self::PRIORITY]!==FALSE){$toDelete[self::PRIORITY][$dataNode[$link][self::PRIORITY]][$link]=TRUE;}$toDelete[self::ENTRIES][$keyHash][$link]=TRUE;$this->cleanFromIndex($toDelete);$entriesNode=$this->getNode($entriesNodeId);unset($dataNode[$link]);$this->saveNode($link>>self::BITROT,$dataNode);}break;}}}if($exists===FALSE){$requiredSize=strlen($key)+75;if($tags){foreach($tags
  2233. as$tag){$requiredSize+=strlen($tag)+13;}}$requiredSize+=$priority?10:1;$freeDataNode=$this->findFreeDataNode($requiredSize);$data=$this->getNode($freeDataNode);if($data===FALSE){$data=array(self::INFO=>array(self::LAST_INDEX=>($freeDataNode<<self::BITROT),self::TYPE=>self::DATA));}$dataNodeKey=++$data[self::INFO][self::LAST_INDEX];$data[$dataNodeKey]=array(self::KEY=>$key,self::TAGS=>$tags?$tags:array(),self::PRIORITY=>$priority,self::DELETED=>FALSE);$this->saveNode($freeDataNode,$data);$entriesNode[$keyHash][$dataNodeKey]=1;$this->saveNode($entriesNodeId,$entriesNode);if($tags){foreach($tags
  2234. as$tag){list($nodeId,$node)=$this->findIndexNode(self::TAGS,$tag);$node[$tag][$dataNodeKey]=1;$this->saveNode($nodeId,$node);}}if($priority){list($nodeId,$node)=$this->findIndexNode(self::PRIORITY,$priority);$node[$priority][$dataNodeKey]=1;$this->saveNode($nodeId,$node);}}$this->commit();$this->unlock();}function
  2235. clean(array$conditions){$this->lock();if(!empty($conditions[Cache::ALL])){$this->nodeCache=$this->nodeChanged=$this->dataNodeFreeSpace=array();$this->deleteAll();$this->unlock();return;}$toDelete=array(self::TAGS=>array(),self::PRIORITY=>array(),self::ENTRIES=>array());$entries=array();if(!empty($conditions[Cache::TAGS])){$entries=$this->cleanTags((array)$conditions[Cache::TAGS],$toDelete);}if(isset($conditions[Cache::PRIORITY])){$this->arrayAppend($entries,$this->cleanPriority((int)$conditions[Cache::PRIORITY],$toDelete));}$this->deletedLinks=array();$this->cleanFromIndex($toDelete);$this->commit();$this->unlock();return$entries;}private
  2236. function
  2237. cleanTags(array$tags,array&$toDelete){$entries=array();foreach($tags
  2238. as$tag){list($nodeId,$node)=$this->findIndexNode(self::TAGS,$tag);if(isset($node[$tag])){$ent=$this->cleanLinks($this->mergeIndexData($node[$tag]),$toDelete);$this->arrayAppend($entries,$ent);}}return$entries;}private
  2239. function
  2240. cleanPriority($priority,array&$toDelete){list($nodeId,$node)=$this->findIndexNode(self::PRIORITY,$priority);ksort($node);$allData=array();foreach($node
  2241. as$prior=>$data){if($prior===self::INFO){continue;}elseif($prior>$priority){break;}$this->arrayAppendKeys($allData,$this->mergeIndexData($data));}$nodeInfo=$node[self::INFO];while($nodeInfo[self::PREV_NODE]!==-1){$nodeId=$nodeInfo[self::PREV_NODE];$node=$this->getNode($nodeId);if($node===FALSE){if(self::$debug){throw
  2242. new
  2243. Nette\InvalidStateException("Cannot load node number $nodeId.");}break;}$nodeInfo=$node[self::INFO];unset($node[self::INFO]);foreach($node
  2244. as$prior=>$data){$this->arrayAppendKeys($allData,$this->mergeIndexData($data));}}return$this->cleanLinks($allData,$toDelete);}private
  2245. function
  2246. cleanLinks(array$data,array&$toDelete){$return=array();$data=array_keys($data);sort($data);$max=count($data);$data[]=0;$i=0;while($i<$max){$searchLink=$data[$i];if(isset($this->deletedLinks[$searchLink])){++$i;continue;}$nodeId=$searchLink>>self::BITROT;$node=$this->getNode($nodeId);if($node===FALSE){if(self::$debug){throw
  2247. new
  2248. Nette\InvalidStateException('Cannot load node number '.($nodeId).'.');}++$i;continue;}do{$link=$data[$i];if(!isset($node[$link])){if(self::$debug){throw
  2249. new
  2250. Nette\InvalidStateException("Link with ID $searchLink is not in node ".($nodeId).'.');}continue;}elseif(isset($this->deletedLinks[$link])){continue;}$nodeLink=&$node[$link];if(!$nodeLink[self::DELETED]){$nodeLink[self::DELETED]=TRUE;$return[]=$nodeLink[self::KEY];}else{foreach($nodeLink[self::TAGS]as$tag){$toDelete[self::TAGS][$tag][$link]=TRUE;}if($nodeLink[self::PRIORITY]!==FALSE){$toDelete[self::PRIORITY][$nodeLink[self::PRIORITY]][$link]=TRUE;}$toDelete[self::ENTRIES][crc32($nodeLink[self::KEY])][$link]=TRUE;unset($node[$link]);$this->deletedLinks[$link]=TRUE;}}while(($data[++$i]>>self::BITROT)===$nodeId);$this->saveNode($nodeId,$node);}return$return;}private
  2251. function
  2252. cleanFromIndex(array$toDeleteFromIndex){foreach($toDeleteFromIndex
  2253. as$type=>$toDelete){ksort($toDelete);while(!empty($toDelete)){reset($toDelete);$searchKey=key($toDelete);list($masterNodeId,$masterNode)=$this->findIndexNode($type,$searchKey);if(!isset($masterNode[$searchKey])){if(self::$debug){throw
  2254. new
  2255. Nette\InvalidStateException('Bad index.');}unset($toDelete[$searchKey]);continue;}foreach($toDelete
  2256. as$key=>$links){if(isset($masterNode[$key])){foreach($links
  2257. as$link=>$foo){if(isset($masterNode[$key][$link])){unset($masterNode[$key][$link],$links[$link]);}}if(!empty($links)&&isset($masterNode[$key][self::INDEX_DATA])){$this->cleanIndexData($masterNode[$key][self::INDEX_DATA],$links,$masterNode[$key]);}if(empty($masterNode[$key])){unset($masterNode[$key]);}unset($toDelete[$key]);}else{break;}}$this->saveNode($masterNodeId,$masterNode);}}}private
  2258. function
  2259. mergeIndexData(array$data){while(isset($data[self::INDEX_DATA])){$id=$data[self::INDEX_DATA];unset($data[self::INDEX_DATA]);$childNode=$this->getNode($id);if($childNode===FALSE){if(self::$debug){throw
  2260. new
  2261. Nette\InvalidStateException("Cannot load node number $id.");}break;}$this->arrayAppendKeys($data,$childNode[self::INDEX_DATA]);}return$data;}private
  2262. function
  2263. cleanIndexData($nextNodeId,array$links,&$masterNodeLink){$prev=-1;while($nextNodeId&&!empty($links)){$nodeId=$nextNodeId;$node=$this->getNode($nodeId);if($node===FALSE){if(self::$debug){throw
  2264. new
  2265. Nette\InvalidStateException("Cannot load node number $nodeId.");}break;}foreach($links
  2266. as$link=>$foo){if(isset($node[self::INDEX_DATA][$link])){unset($node[self::INDEX_DATA][$link],$links[$link]);}}if(isset($node[self::INDEX_DATA][self::INDEX_DATA])){$nextNodeId=$node[self::INDEX_DATA][self::INDEX_DATA];}else{$nextNodeId=FALSE;}if(empty($node[self::INDEX_DATA])||(count($node[self::INDEX_DATA])===1&&$nextNodeId)){if($prev===-1){if($nextNodeId===FALSE){unset($masterNodeLink[self::INDEX_DATA]);}else{$masterNodeLink[self::INDEX_DATA]=$nextNodeId;}}else{$prevNode=$this->getNode($prev);if($prevNode===FALSE){if(self::$debug){throw
  2267. new
  2268. Nette\InvalidStateException("Cannot load node number $prev.");}}else{if($nextNodeId===FALSE){unset($prevNode[self::INDEX_DATA][self::INDEX_DATA]);if(empty($prevNode[self::INDEX_DATA])){unset($prevNode[self::INDEX_DATA]);}}else{$prevNode[self::INDEX_DATA][self::INDEX_DATA]=$nextNodeId;}$this->saveNode($prev,$prevNode);}}unset($node[self::INDEX_DATA]);}else{$prev=$nodeId;}$this->saveNode($nodeId,$node);}}private
  2269. function
  2270. getNode($id){if(isset($this->nodeCache[$id])){return$this->nodeCache[$id];}$binary=stream_get_contents($this->handle,self::NODE_SIZE,self::HEADER_SIZE+self::NODE_SIZE*$id);if(empty($binary)){return
  2271. FALSE;}list(,$magic,$lenght)=unpack('N2',$binary);if($magic!==self::INDEX_MAGIC&&$magic!==self::DATA_MAGIC){if(!empty($magic)){if(self::$debug){throw
  2272. new
  2273. Nette\InvalidStateException("Node $id has malformed header.");}$this->deleteNode($id);}return
  2274. FALSE;}$data=substr($binary,2*self::INT32_SIZE,$lenght-2*self::INT32_SIZE);$node=@unserialize($data);if($node===FALSE){$this->deleteNode($id);if(self::$debug){throw
  2275. new
  2276. Nette\InvalidStateException("Cannot deserialize node number $id.");}return
  2277. FALSE;}return$this->nodeCache[$id]=$node;}private
  2278. function
  2279. saveNode($id,array$node){if(count($node)===1){$nodeInfo=$node[self::INFO];if($nodeInfo[self::TYPE]!==self::DATA){if($nodeInfo[self::END]!==-1){$this->nodeCache[$id]=$node;$this->nodeChanged[$id]=TRUE;return;}if($nodeInfo[self::MAX]===-1){$max=PHP_INT_MAX;}else{$max=$nodeInfo[self::MAX];}list(,,$parentId)=$this->findIndexNode($nodeInfo[self::TYPE],$max,$id);if($parentId!==-1&&$parentId!==$id){$parentNode=$this->getNode($parentId);if($parentNode===FALSE){if(self::$debug){throw
  2280. new
  2281. Nette\InvalidStateException("Cannot load node number $parentId.");}}else{if($parentNode[self::INFO][self::END]===$id){if(count($parentNode)===1){$parentNode[self::INFO][self::END]=-1;}else{end($parentNode);$lastKey=key($parentNode);$parentNode[self::INFO][self::END]=$parentNode[$lastKey];unset($parentNode[$lastKey]);}}else{unset($parentNode[$nodeInfo[self::MAX]]);}$this->saveNode($parentId,$parentNode);}}if($nodeInfo[self::TYPE]===self::PRIORITY){if($nodeInfo[self::MAX]===-1){if($nodeInfo[self::PREV_NODE]!==-1){$prevNode=$this->getNode($nodeInfo[self::PREV_NODE]);if($prevNode===FALSE){if(self::$debug){throw
  2282. new
  2283. Nette\InvalidStateException('Cannot load node number '.$nodeInfo[self::PREV_NODE].'.');}}else{$prevNode[self::INFO][self::MAX]=-1;$this->saveNode($nodeInfo[self::PREV_NODE],$prevNode);}}}else{list($nextId,$nextNode)=$this->findIndexNode($nodeInfo[self::TYPE],$nodeInfo[self::MAX]+1,NULL,$id);if($nextId!==-1&&$nextId!==$id){$nextNode[self::INFO][self::PREV_NODE]=$nodeInfo[self::PREV_NODE];$this->saveNode($nextId,$nextNode);}}}}$this->nodeCache[$id]=FALSE;}else{$this->nodeCache[$id]=$node;}$this->nodeChanged[$id]=TRUE;}private
  2284. function
  2285. commit(){do{foreach($this->nodeChanged
  2286. as$id=>$foo){if($this->prepareNode($id,$this->nodeCache[$id])){unset($this->nodeChanged[$id]);}}}while(!empty($this->nodeChanged));foreach($this->toCommit
  2287. as$node=>$str){$this->commitNode($node,$str);}$this->toCommit=array();}private
  2288. function
  2289. prepareNode($id,$node){if($node===FALSE){if($id<$this->lastNode){$this->lastNode=$id;}unset($this->nodeCache[$id]);unset($this->dataNodeFreeSpace[$id]);$this->deleteNode($id);return
  2290. TRUE;}$data=serialize($node);$dataSize=strlen($data)+2*self::INT32_SIZE;$isData=$node[self::INFO][self::TYPE]===self::DATA;if($dataSize>self::NODE_SIZE){if($isData){throw
  2291. new
  2292. Nette\InvalidStateException('Saving node is bigger than maximum node size.');}else{$this->bisectNode($id,$node);return
  2293. FALSE;}}$this->toCommit[$id]=pack('N2',$isData?self::DATA_MAGIC:self::INDEX_MAGIC,$dataSize).$data;if($this->lastNode<$id){$this->lastNode=$id;}if($isData){$this->dataNodeFreeSpace[$id]=self::NODE_SIZE-$dataSize;}return
  2294. TRUE;}private
  2295. function
  2296. commitNode($id,$str){fseek($this->handle,self::HEADER_SIZE+self::NODE_SIZE*$id);$writen=fwrite($this->handle,$str);if($writen===FALSE){throw
  2297. new
  2298. Nette\InvalidStateException("Cannot write node number $id to journal.");}}private
  2299. function
  2300. findIndexNode($type,$search,$childId=NULL,$prevId=NULL){$nodeId=self::$startNode[$type];$parentId=-1;while(TRUE){$node=$this->getNode($nodeId);if($node===FALSE){return
  2301. array($nodeId,array(self::INFO=>array(self::TYPE=>$type,self::IS_LEAF=>TRUE,self::PREV_NODE=>-1,self::END=>-1,self::MAX=>-1)),$parentId);}if($node[self::INFO][self::IS_LEAF]||$nodeId===$childId||$node[self::INFO][self::PREV_NODE]===$prevId){return
  2302. array($nodeId,$node,$parentId);}$parentId=$nodeId;if(isset($node[$search])){$nodeId=$node[$search];}else{foreach($node
  2303. as$key=>$childNode){if($key>$search
  2304. and$key!==self::INFO){$nodeId=$childNode;continue
  2305. 2;}}$nodeId=$node[self::INFO][self::END];}}}private
  2306. function
  2307. findFreeNode($count=1){$id=$this->lastNode;$nodesId=array();do{if(isset($this->nodeCache[$id])){++$id;continue;}$offset=self::HEADER_SIZE+self::NODE_SIZE*$id;$binary=stream_get_contents($this->handle,self::INT32_SIZE,$offset);if(empty($binary)){$nodesId[]=$id;}else{list(,$magic)=unpack('N',$binary);if($magic!==self::INDEX_MAGIC&&$magic!==self::DATA_MAGIC){$nodesId[]=$id;}}++$id;}while(count($nodesId)!==$count);if($count===1){return$nodesId[0];}else{return$nodesId;}}private
  2308. function
  2309. findFreeDataNode($size){foreach($this->dataNodeFreeSpace
  2310. as$id=>$freeSpace){if($freeSpace>$size){return$id;}}$id=self::$startNode[self::DATA];while(TRUE){if(isset($this->dataNodeFreeSpace[$id])||isset($this->nodeCache[$id])){++$id;continue;}$offset=self::HEADER_SIZE+self::NODE_SIZE*$id;$binary=stream_get_contents($this->handle,2*self::INT32_SIZE,$offset);if(empty($binary)){$this->dataNodeFreeSpace[$id]=self::NODE_SIZE;return$id;}list(,$magic,$nodeSize)=unpack('N2',$binary);if(empty($magic)){$this->dataNodeFreeSpace[$id]=self::NODE_SIZE;return$id;}elseif($magic===self::DATA_MAGIC){$freeSpace=self::NODE_SIZE-$nodeSize;$this->dataNodeFreeSpace[$id]=$freeSpace;if($freeSpace>$size){return$id;}}++$id;}}private
  2311. function
  2312. bisectNode($id,array$node){$nodeInfo=$node[self::INFO];unset($node[self::INFO]);if(count($node)===1){$key=key($node);$dataId=$this->findFreeDataNode(self::NODE_SIZE);$this->saveNode($dataId,array(self::INDEX_DATA=>$node[$key],self::INFO=>array(self::TYPE=>self::DATA,self::LAST_INDEX=>($dataId<<self::BITROT))));unset($node[$key]);$node[$key][self::INDEX_DATA]=$dataId;$node[self::INFO]=$nodeInfo;$this->saveNode($id,$node);return;}ksort($node);$halfCount=ceil(count($node)/2);list($first,$second)=array_chunk($node,$halfCount,TRUE);end($first);$halfKey=key($first);if($id<=2){list($firstId,$secondId)=$this->findFreeNode(2);$first[self::INFO]=array(self::TYPE=>$nodeInfo[self::TYPE],self::IS_LEAF=>$nodeInfo[self::IS_LEAF],self::PREV_NODE=>-1,self::END=>-1,self::MAX=>$halfKey);$this->saveNode($firstId,$first);$second[self::INFO]=array(self::TYPE=>$nodeInfo[self::TYPE],self::IS_LEAF=>$nodeInfo[self::IS_LEAF],self::PREV_NODE=>$firstId,self::END=>$nodeInfo[self::END],self::MAX=>-1);$this->saveNode($secondId,$second);$parentNode=array(self::INFO=>array(self::TYPE=>$nodeInfo[self::TYPE],self::IS_LEAF=>FALSE,self::PREV_NODE=>-1,self::END=>$secondId,self::MAX=>-1),$halfKey=>$firstId);$this->saveNode($id,$parentNode);}else{$firstId=$this->findFreeNode();$first[self::INFO]=array(self::TYPE=>$nodeInfo[self::TYPE],self::IS_LEAF=>$nodeInfo[self::IS_LEAF],self::PREV_NODE=>$nodeInfo[self::PREV_NODE],self::END=>-1,self::MAX=>$halfKey);$this->saveNode($firstId,$first);$second[self::INFO]=array(self::TYPE=>$nodeInfo[self::TYPE],self::IS_LEAF=>$nodeInfo[self::IS_LEAF],self::PREV_NODE=>$firstId,self::END=>$nodeInfo[self::END],self::MAX=>$nodeInfo[self::MAX]);$this->saveNode($id,$second);list(,,$parent)=$this->findIndexNode($nodeInfo[self::TYPE],$halfKey);$parentNode=$this->getNode($parent);if($parentNode===FALSE){if(self::$debug){throw
  2313. new
  2314. Nette\InvalidStateException("Cannot load node number $parent.");}}else{$parentNode[$halfKey]=$firstId;ksort($parentNode);$this->saveNode($parent,$parentNode);}}}private
  2315. function
  2316. headerCommit(){fseek($this->handle,self::INT32_SIZE);@fwrite($this->handle,pack('N',$this->lastNode));}private
  2317. function
  2318. deleteNode($id){fseek($this->handle,0,SEEK_END);$end=ftell($this->handle);if($end<=(self::HEADER_SIZE+self::NODE_SIZE*($id+1))){$packedNull=pack('N',0);do{$binary=stream_get_contents($this->handle,self::INT32_SIZE,(self::HEADER_SIZE+self::NODE_SIZE*--$id));}while(empty($binary)||$binary===$packedNull);if(!ftruncate($this->handle,self::HEADER_SIZE+self::NODE_SIZE*($id+1))){throw
  2319. new
  2320. Nette\InvalidStateException('Cannot truncate journal file.');}}else{fseek($this->handle,self::HEADER_SIZE+self::NODE_SIZE*$id);$writen=fwrite($this->handle,pack('N',0));if($writen!==self::INT32_SIZE){throw
  2321. new
  2322. Nette\InvalidStateException("Cannot delete node number $id from journal.");}}}private
  2323. function
  2324. deleteAll(){if(!ftruncate($this->handle,self::HEADER_SIZE)){throw
  2325. new
  2326. Nette\InvalidStateException('Cannot truncate journal file.');}}private
  2327. function
  2328. lock(){if(!$this->handle){throw
  2329. new
  2330. Nette\InvalidStateException('File journal file is not opened');}if(!flock($this->handle,LOCK_EX)){throw
  2331. new
  2332. Nette\InvalidStateException('Cannot acquire exclusive lock on journal.');}if($this->lastModTime!==NULL){clearstatcache();if($this->lastModTime<@filemtime($this->file)){$this->nodeCache=$this->dataNodeFreeSpace=array();}}}private
  2333. function
  2334. unlock(){if($this->handle){fflush($this->handle);flock($this->handle,LOCK_UN);clearstatcache();$this->lastModTime=@filemtime($this->file);}}private
  2335. function
  2336. arrayAppend(array&$array,array$append){foreach($append
  2337. as$value){$array[]=$value;}}private
  2338. function
  2339. arrayAppendKeys(array&$array,array$append){foreach($append
  2340. as$key=>$value){$array[$key]=$value;}}}class
  2341. FileStorage
  2342. extends
  2343. Nette\Object
  2344. implements
  2345. Nette\Caching\IStorage{const
  2346. META_HEADER_LEN=28,META_TIME='time',META_SERIALIZED='serialized',META_EXPIRE='expire',META_DELTA='delta',META_ITEMS='di',META_CALLBACKS='callbacks';const
  2347. FILE='file',HANDLE='handle';public
  2348. static$gcProbability=0.001;public
  2349. static$useDirectories=TRUE;private$dir;private$useDirs;private$journal;private$locks;function
  2350. __construct($dir,IJournal$journal=NULL){$this->dir=realpath($dir);if($this->dir===FALSE){throw
  2351. new
  2352. Nette\DirectoryNotFoundException("Directory '$dir' not found.");}$this->useDirs=(bool)static::$useDirectories;$this->journal=$journal;if(mt_rand()/mt_getrandmax()<static::$gcProbability){$this->clean(array());}}function
  2353. read($key){$meta=$this->readMetaAndLock($this->getCacheFile($key),LOCK_SH);if($meta&&$this->verify($meta)){return$this->readData($meta);}else{return
  2354. NULL;}}private
  2355. function
  2356. 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->readMetaAndLock($depFile,LOCK_SH);if($m[self::META_TIME]!==$time||($m&&!$this->verify($m))){break
  2357. 2;}}}return
  2358. TRUE;}while(FALSE);$this->delete($meta[self::FILE],$meta[self::HANDLE]);return
  2359. FALSE;}function
  2360. lock($key){$cacheFile=$this->getCacheFile($key);if($this->useDirs&&!is_dir($dir=dirname($cacheFile))){@mkdir($dir,0777);}$handle=@fopen($cacheFile,'r+b');if(!$handle){$handle=fopen($cacheFile,'wb');if(!$handle){return;}}$this->locks[$key]=$handle;flock($handle,LOCK_EX);}function
  2361. write($key,$data,array$dp){$meta=array(self::META_TIME=>microtime());if(isset($dp[Cache::EXPIRATION])){if(empty($dp[Cache::SLIDING])){$meta[self::META_EXPIRE]=$dp[Cache::EXPIRATION]+time();}else{$meta[self::META_DELTA]=(int)$dp[Cache::EXPIRATION];}}if(isset($dp[Cache::ITEMS])){foreach((array)$dp[Cache::ITEMS]as$item){$depFile=$this->getCacheFile($item);$m=$this->readMetaAndLock($depFile,LOCK_SH);$meta[self::META_ITEMS][$depFile]=$m[self::META_TIME];unset($m);}}if(isset($dp[Cache::CALLBACKS])){$meta[self::META_CALLBACKS]=$dp[Cache::CALLBACKS];}if(!isset($this->locks[$key])){$this->lock($key);if(!isset($this->locks[$key])){return;}}$handle=$this->locks[$key];unset($this->locks[$key]);$cacheFile=$this->getCacheFile($key);if(isset($dp[Cache::TAGS])||isset($dp[Cache::PRIORITY])){if(!$this->journal){throw
  2362. new
  2363. Nette\InvalidStateException('CacheJournal has not been provided.');}$this->journal->write($cacheFile,$dp);}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;}flock($handle,LOCK_UN);fclose($handle);return;}while(FALSE);$this->delete($cacheFile,$handle);}function
  2364. remove($key){unset($this->locks[$key]);$this->delete($this->getCacheFile($key));}function
  2365. clean(array$conds){$all=!empty($conds[Cache::ALL]);$collector=empty($conds);if($all||$collector){$now=time();foreach(Nette\Utils\Finder::find('_*')->from($this->dir)->childFirst()as$entry){$path=(string)$entry;if($entry->isDir()){@rmdir($path);continue;}if($all){$this->delete($path);}else{$meta=$this->readMetaAndLock($path,LOCK_SH);if(!$meta){continue;}if((!empty($meta[self::META_DELTA])&&filemtime($meta[self::FILE])+$meta[self::META_DELTA]<$now)||(!empty($meta[self::META_EXPIRE])&&$meta[self::META_EXPIRE]<$now)){$this->delete($path,$meta[self::HANDLE]);continue;}flock($meta[self::HANDLE],LOCK_UN);fclose($meta[self::HANDLE]);}}if($this->journal){$this->journal->clean($conds);}return;}if($this->journal){foreach($this->journal->clean($conds)as$file){$this->delete($file);}}}protected
  2366. function
  2367. readMetaAndLock($file,$lock){$handle=@fopen($file,'r+b');if(!$handle){return
  2368. 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;}}flock($handle,LOCK_UN);fclose($handle);return
  2369. NULL;}protected
  2370. function
  2371. readData($meta){$data=stream_get_contents($meta[self::HANDLE]);flock($meta[self::HANDLE],LOCK_UN);fclose($meta[self::HANDLE]);if(empty($meta[self::META_SERIALIZED])){return$data;}else{return@unserialize($data);}}protected
  2372. function
  2373. getCacheFile($key){$file=urlencode($key);if($this->useDirs&&$a=strrpos($file,'%00')){$file=substr_replace($file,'/_',$a,3);}return$this->dir.'/_'.$file;}private
  2374. static
  2375. function
  2376. delete($file,$handle=NULL){if(@unlink($file)){if($handle){flock($handle,LOCK_UN);fclose($handle);}return;}if(!$handle){$handle=@fopen($file,'r+');}if($handle){flock($handle,LOCK_EX);ftruncate($handle,0);flock($handle,LOCK_UN);fclose($handle);@unlink($file);}}}class
  2377. MemcachedStorage
  2378. extends
  2379. Nette\Object
  2380. implements
  2381. Nette\Caching\IStorage{const
  2382. META_CALLBACKS='callbacks',META_DATA='data',META_DELTA='delta';private$memcache;private$prefix;private$journal;static
  2383. function
  2384. isAvailable(){return
  2385. extension_loaded('memcache');}function
  2386. __construct($host='localhost',$port=11211,$prefix='',IJournal$journal=NULL){if(!static::isAvailable()){throw
  2387. new
  2388. Nette\NotSupportedException("PHP extension 'memcache' is not loaded.");}$this->prefix=$prefix;$this->journal=$journal;$this->memcache=new\Memcache;if($host){$this->addServer($host,$port);}}function
  2389. addServer($host='localhost',$port=11211,$timeout=1){Nette\Diagnostics\Debugger::tryError();$this->memcache->addServer($host,$port,TRUE,1,$timeout);if(Nette\Diagnostics\Debugger::catchError($e)){throw
  2390. new
  2391. Nette\InvalidStateException('Memcache::addServer(): '.$e->getMessage(),0,$e);}}function
  2392. getConnection(){return$this->memcache;}function
  2393. read($key){$key=$this->prefix.$key;$meta=$this->memcache->get($key);if(!$meta){return
  2394. NULL;}if(!empty($meta[self::META_CALLBACKS])&&!Cache::checkCallbacks($meta[self::META_CALLBACKS])){$this->memcache->delete($key,0);return
  2395. NULL;}if(!empty($meta[self::META_DELTA])){$this->memcache->replace($key,$meta,0,$meta[self::META_DELTA]+time());}return$meta[self::META_DATA];}function
  2396. lock($key){}function
  2397. write($key,$data,array$dp){if(isset($dp[Cache::ITEMS])){throw
  2398. new
  2399. Nette\NotSupportedException('Dependent items are not supported by MemcachedStorage.');}$key=$this->prefix.$key;$meta=array(self::META_DATA=>$data);$expire=0;if(isset($dp[Cache::EXPIRATION])){$expire=(int)$dp[Cache::EXPIRATION];if(!empty($dp[Cache::SLIDING])){$meta[self::META_DELTA]=$expire;}}if(isset($dp[Cache::CALLBACKS])){$meta[self::META_CALLBACKS]=$dp[Cache::CALLBACKS];}if(isset($dp[Cache::TAGS])||isset($dp[Cache::PRIORITY])){if(!$this->journal){throw
  2400. new
  2401. Nette\InvalidStateException('CacheJournal has not been provided.');}$this->journal->write($key,$dp);}$this->memcache->set($key,$meta,0,$expire);}function
  2402. remove($key){$this->memcache->delete($this->prefix.$key,0);}function
  2403. clean(array$conds){if(!empty($conds[Cache::ALL])){$this->memcache->flush();}elseif($this->journal){foreach($this->journal->clean($conds)as$entry){$this->memcache->delete($entry,0);}}}}class
  2404. MemoryStorage
  2405. extends
  2406. Nette\Object
  2407. implements
  2408. Nette\Caching\IStorage{private$data=array();function
  2409. read($key){return
  2410. isset($this->data[$key])?$this->data[$key]:NULL;}function
  2411. lock($key){}function
  2412. write($key,$data,array$dp){$this->data[$key]=$data;}function
  2413. remove($key){unset($this->data[$key]);}function
  2414. clean(array$conds){if(!empty($conds[Nette\Caching\Cache::ALL])){$this->data=array();}}}class
  2415. PhpFileStorage
  2416. extends
  2417. FileStorage{public$hint;protected
  2418. function
  2419. readData($meta){return
  2420. array('file'=>$meta[self::FILE],'handle'=>$meta[self::HANDLE]);}protected
  2421. function
  2422. getCacheFile($key){return
  2423. parent::getCacheFile(substr_replace($key,trim(strtr($this->hint,'\\/@','.._'),'.').'-',strpos($key,Nette\Caching\Cache::NAMESPACE_SEPARATOR)+1,0)).'.php';}}}namespace Nette{use
  2424. Nette;class
  2425. ArrayHash
  2426. extends\stdClass
  2427. implements\ArrayAccess,\Countable,\IteratorAggregate{static
  2428. function
  2429. from($arr,$recursive=TRUE){$obj=new
  2430. static;foreach($arr
  2431. as$key=>$value){if($recursive&&is_array($value)){$obj->$key=static::from($value,TRUE);}else{$obj->$key=$value;}}return$obj;}function
  2432. getIterator(){return
  2433. new\RecursiveArrayIterator($this);}function
  2434. count(){return
  2435. count((array)$this);}function
  2436. offsetSet($key,$value){if(!is_scalar($key)){throw
  2437. new
  2438. InvalidArgumentException("Key must be either a string or an integer, ".gettype($key)." given.");}$this->$key=$value;}function
  2439. offsetGet($key){return$this->$key;}function
  2440. offsetExists($key){return
  2441. isset($this->$key);}function
  2442. offsetUnset($key){unset($this->$key);}}final
  2443. class
  2444. Callback
  2445. extends
  2446. Object{private$cb;function
  2447. __construct($cb,$m=NULL){if($m!==NULL){$cb=array($cb,$m);}if(!is_callable($cb,TRUE)){throw
  2448. new
  2449. InvalidArgumentException("Invalid callback.");}$this->cb=$cb;}function
  2450. __invoke(){if(!is_callable($this->cb)){throw
  2451. new
  2452. InvalidStateException("Callback '$this' is not callable.");}$args=func_get_args();return
  2453. call_user_func_array($this->cb,$args);}function
  2454. invoke(){if(!is_callable($this->cb)){throw
  2455. new
  2456. InvalidStateException("Callback '$this' is not callable.");}$args=func_get_args();return
  2457. call_user_func_array($this->cb,$args);}function
  2458. invokeArgs(array$args){if(!is_callable($this->cb)){throw
  2459. new
  2460. InvalidStateException("Callback '$this' is not callable.");}return
  2461. call_user_func_array($this->cb,$args);}function
  2462. isCallable(){return
  2463. is_callable($this->cb);}function
  2464. getNative(){return$this->cb;}function
  2465. toReflection(){if(is_string($this->cb)&&strpos($this->cb,'::')){return
  2466. new
  2467. Nette\Reflection\Method($this->cb);}elseif(is_array($this->cb)){return
  2468. new
  2469. Nette\Reflection\Method($this->cb[0],$this->cb[1]);}elseif(is_object($this->cb)&&!$this->cb
  2470. instanceof\Closure){return
  2471. new
  2472. Nette\Reflection\Method($this->cb,'__invoke');}else{return
  2473. new
  2474. Nette\Reflection\GlobalFunction($this->cb);}}function
  2475. isStatic(){return
  2476. is_array($this->cb)?is_string($this->cb[0]):is_string($this->cb);}function
  2477. __toString(){if($this->cb
  2478. instanceof\Closure){return'{closure}';}elseif(is_string($this->cb)&&$this->cb[0]==="\0"){return'{lambda}';}else{is_callable($this->cb,TRUE,$textual);return$textual;}}}class
  2479. DateTime
  2480. extends\DateTime{const
  2481. MINUTE=60;const
  2482. HOUR=3600;const
  2483. DAY=86400;const
  2484. WEEK=604800;const
  2485. MONTH=2629800;const
  2486. YEAR=31557600;static
  2487. function
  2488. from($time){if($time
  2489. instanceof\DateTime){return
  2490. clone$time;}elseif(is_numeric($time)){if($time<=self::YEAR){$time+=time();}return
  2491. new
  2492. static(date('Y-m-d H:i:s',$time));}else{return
  2493. new
  2494. static($time);}}function
  2495. __toString(){return$this->format('Y-m-d H:i:s');}function
  2496. modifyClone($modify=''){$dolly=clone$this;return$modify?$dolly->modify($modify):$dolly;}}final
  2497. class
  2498. Environment{const
  2499. DEVELOPMENT='development',PRODUCTION='production',CONSOLE='console';private
  2500. static$productionMode;private
  2501. static$createdAt;private
  2502. static$context;final
  2503. function
  2504. __construct(){throw
  2505. new
  2506. StaticClassException;}static
  2507. function
  2508. isConsole(){return
  2509. PHP_SAPI==='cli';}static
  2510. function
  2511. isProduction(){if(self::$productionMode===NULL){self::$productionMode=!Nette\Config\Configurator::detectDebugMode();}return
  2512. self::$productionMode;}static
  2513. function
  2514. setProductionMode($value=TRUE){self::$productionMode=(bool)$value;}static
  2515. function
  2516. setVariable($name,$value,$expand=TRUE){if($expand&&is_string($value)){$value=self::getContext()->expand($value);}self::getContext()->parameters[$name]=$value;}static
  2517. function
  2518. getVariable($name,$default=NULL){if(isset(self::getContext()->parameters[$name])){return
  2519. self::getContext()->parameters[$name];}elseif(func_num_args()>1){return$default;}else{throw
  2520. new
  2521. InvalidStateException("Unknown environment variable '$name'.");}}static
  2522. function
  2523. getVariables(){return
  2524. self::getContext()->parameters;}static
  2525. function
  2526. expand($s){return
  2527. self::getContext()->expand($s);}static
  2528. function
  2529. setContext(DI\Container$context){if(self::$createdAt){throw
  2530. new
  2531. Nette\InvalidStateException('Configurator & SystemContainer has already been created automatically by Nette\Environment at '.self::$createdAt);}self::$context=$context;}static
  2532. function
  2533. getContext(){if(self::$context===NULL){self::loadConfig();}return
  2534. self::$context;}static
  2535. function
  2536. getService($name){return
  2537. self::getContext()->getService($name);}static
  2538. function
  2539. __callStatic($name,$args){if(!$args&&strncasecmp($name,'get',3)===0){return
  2540. self::getContext()->getService(lcfirst(substr($name,3)));}else{throw
  2541. new
  2542. MemberAccessException("Call to undefined static method Nette\\Environment::$name().");}}static
  2543. function
  2544. getHttpRequest(){return
  2545. self::getContext()->getByType('Nette\Http\IRequest');}static
  2546. function
  2547. getHttpContext(){return
  2548. self::getContext()->getByType('Nette\Http\Context');}static
  2549. function
  2550. getHttpResponse(){return
  2551. self::getContext()->getByType('Nette\Http\IResponse');}static
  2552. function
  2553. getApplication(){return
  2554. self::getContext()->getByType('Nette\Application\Application');}static
  2555. function
  2556. getUser(){return
  2557. self::getContext()->getByType('Nette\Security\User');}static
  2558. function
  2559. getRobotLoader(){return
  2560. self::getContext()->getByType('Nette\Loaders\RobotLoader');}static
  2561. function
  2562. getCache($namespace=''){return
  2563. new
  2564. Caching\Cache(self::getContext()->cacheStorage,$namespace);}static
  2565. function
  2566. getSession($namespace=NULL){return$namespace===NULL?self::getContext()->session:self::getContext()->session->getSection($namespace);}static
  2567. function
  2568. loadConfig($file=NULL,$section=NULL){if(self::$createdAt){throw
  2569. new
  2570. Nette\InvalidStateException('Nette\Config\Configurator has already been created automatically by Nette\Environment at '.self::$createdAt);}$configurator=new
  2571. Nette\Config\Configurator;$configurator->setDebugMode(!self::isProduction())->setTempDirectory(defined('TEMP_DIR')?TEMP_DIR:'');if($file){$configurator->addConfig($file,$section);}self::$context=$configurator->createContainer();self::$createdAt='?';foreach(debug_backtrace(FALSE)as$row){if(isset($row['file'])&&is_file($row['file'])&&strpos($row['file'],NETTE_DIR.DIRECTORY_SEPARATOR)!==0){self::$createdAt="$row[file]:$row[line]";break;}}return
  2572. self::getConfig();}static
  2573. function
  2574. getConfig($key=NULL,$default=NULL){$params=Nette\ArrayHash::from(self::getContext()->parameters);if(func_num_args()){return
  2575. isset($params[$key])?$params[$key]:$default;}else{return$params;}}}final
  2576. class
  2577. Framework{const
  2578. NAME='Nette Framework',VERSION='2.0.3',REVISION='eb558ae released on 2012-04-04';public
  2579. static$iAmUsingBadHost=FALSE;final
  2580. function
  2581. __construct(){throw
  2582. new
  2583. StaticClassException;}}class
  2584. Image
  2585. extends
  2586. Object{const
  2587. SHRINK_ONLY=1;const
  2588. STRETCH=2;const
  2589. FIT=0;const
  2590. FILL=4;const
  2591. EXACT=8;const
  2592. JPEG=IMAGETYPE_JPEG,PNG=IMAGETYPE_PNG,GIF=IMAGETYPE_GIF;const
  2593. 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;";const
  2594. ENLARGE=0;private$image;static
  2595. function
  2596. rgb($red,$green,$blue,$transparency=0){return
  2597. 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
  2598. function
  2599. fromFile($file,&$format=NULL){if(!extension_loaded('gd')){throw
  2600. new
  2601. NotSupportedException("PHP extension GD is not loaded.");}$info=@getimagesize($file);switch($format=$info[2]){case
  2602. self::JPEG:return
  2603. new
  2604. static(imagecreatefromjpeg($file));case
  2605. self::PNG:return
  2606. new
  2607. static(imagecreatefrompng($file));case
  2608. self::GIF:return
  2609. new
  2610. static(imagecreatefromgif($file));default:throw
  2611. new
  2612. UnknownImageFileException("Unknown image type or file '$file' not found.");}}static
  2613. function
  2614. getFormatFromString($s){$types=array('image/jpeg'=>self::JPEG,'image/gif'=>self::GIF,'image/png'=>self::PNG);$type=Utils\MimeTypeDetector::fromString($s);return
  2615. isset($types[$type])?$types[$type]:NULL;}static
  2616. function
  2617. fromString($s,&$format=NULL){if(!extension_loaded('gd')){throw
  2618. new
  2619. NotSupportedException("PHP extension GD is not loaded.");}$format=static::getFormatFromString($s);return
  2620. new
  2621. static(imagecreatefromstring($s));}static
  2622. function
  2623. fromBlank($width,$height,$color=NULL){if(!extension_loaded('gd')){throw
  2624. new
  2625. NotSupportedException("PHP extension GD is not loaded.");}$width=(int)$width;$height=(int)$height;if($width<1||$height<1){throw
  2626. new
  2627. 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
  2628. new
  2629. static($image);}function
  2630. __construct($image){$this->setImageResource($image);imagesavealpha($image,TRUE);}function
  2631. getWidth(){return
  2632. imagesx($this->image);}function
  2633. getHeight(){return
  2634. imagesy($this->image);}protected
  2635. function
  2636. setImageResource($image){if(!is_resource($image)||get_resource_type($image)!=='gd'){throw
  2637. new
  2638. InvalidArgumentException('Image is not valid.');}$this->image=$image;return$this;}function
  2639. getImageResource(){return$this->image;}function
  2640. resize($width,$height,$flags=self::FIT){if($flags&self::EXACT){return$this->resize($width,$height,self::FILL)->crop('50%','50%',$width,$height);}list($newWidth,$newHeight)=static::calculateSize($this->getWidth(),$this->getHeight(),$width,$height,$flags);if($newWidth!==$this->getWidth()||$newHeight!==$this->getHeight()){$newImage=static::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=static::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
  2641. function
  2642. calculateSize($srcWidth,$srcHeight,$newWidth,$newHeight,$flags=self::FIT){if(substr($newWidth,-1)==='%'){$newWidth=round($srcWidth/100*abs($newWidth));$percents=TRUE;}else{$newWidth=(int)abs($newWidth);}if(substr($newHeight,-1)==='%'){$newHeight=round($srcHeight/100*abs($newHeight));$flags|=empty($percents)?0:self::STRETCH;}else{$newHeight=(int)abs($newHeight);}if($flags&self::STRETCH){if(empty($newWidth)||empty($newHeight)){throw
  2643. new
  2644. InvalidArgumentException('For stretching must be both width and height specified.');}if($flags&self::SHRINK_ONLY){$newWidth=round($srcWidth*min(1,$newWidth/$srcWidth));$newHeight=round($srcHeight*min(1,$newHeight/$srcHeight));}}else{if(empty($newWidth)&&empty($newHeight)){throw
  2645. new
  2646. 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::SHRINK_ONLY){$scale[]=1;}$scale=min($scale);$newWidth=round($srcWidth*$scale);$newHeight=round($srcHeight*$scale);}return
  2647. array(max((int)$newWidth,1),max((int)$newHeight,1));}function
  2648. crop($left,$top,$width,$height){list($left,$top,$width,$height)=static::calculateCutout($this->getWidth(),$this->getHeight(),$left,$top,$width,$height);$newImage=static::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;}static
  2649. function
  2650. calculateCutout($srcWidth,$srcHeight,$left,$top,$newWidth,$newHeight){if(substr($newWidth,-1)==='%'){$newWidth=round($srcWidth/100*$newWidth);}if(substr($newHeight,-1)==='%'){$newHeight=round($srcHeight/100*$newHeight);}if(substr($left,-1)==='%'){$left=round(($srcWidth-$newWidth)/100*$left);}if(substr($top,-1)==='%'){$top=round(($srcHeight-$newHeight)/100*$top);}if($left<0){$newWidth+=$left;$left=0;}if($top<0){$newHeight+=$top;$top=0;}$newWidth=min((int)$newWidth,$srcWidth-$left);$newHeight=min((int)$newHeight,$srcHeight-$top);return
  2651. array($left,$top,$newWidth,$newHeight);}function
  2652. sharpen(){imageconvolution($this->getImageResource(),array(array(-1,-1,-1),array(-1,24,-1),array(-1,-1,-1)),16,0);return$this;}function
  2653. 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
  2654. 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
  2655. self::JPEG:$quality=$quality===NULL?85:max(0,min(100,(int)$quality));return
  2656. imagejpeg($this->getImageResource(),$file,$quality);case
  2657. self::PNG:$quality=$quality===NULL?9:max(0,min(9,(int)$quality));return
  2658. imagepng($this->getImageResource(),$file,$quality);case
  2659. self::GIF:return$file===NULL?imagegif($this->getImageResource()):imagegif($this->getImageResource(),$file);default:throw
  2660. new
  2661. InvalidArgumentException("Unsupported image type.");}}function
  2662. toString($type=self::JPEG,$quality=NULL){ob_start();$this->save(NULL,$quality,$type);return
  2663. ob_get_clean();}function
  2664. __toString(){try{return$this->toString();}catch(\Exception$e){Diagnostics\Debugger::toStringException($e);}}function
  2665. send($type=self::JPEG,$quality=NULL){if($type!==self::GIF&&$type!==self::PNG&&$type!==self::JPEG){throw
  2666. new
  2667. InvalidArgumentException("Unsupported image type.");}header('Content-Type: '.image_type_to_mime_type($type));return$this->save(NULL,$quality,$type);}function
  2668. __call($name,$args){$function='image'.$name;if(function_exists($function)){foreach($args
  2669. as$key=>$value){if($value
  2670. instanceof
  2671. 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
  2672. is_resource($res)&&get_resource_type($res)==='gd'?$this->setImageResource($res):$res;}return
  2673. parent::__call($name,$args);}}class
  2674. UnknownImageFileException
  2675. extends\Exception{}final
  2676. class
  2677. ObjectMixin{private
  2678. static$methods;final
  2679. function
  2680. __construct(){throw
  2681. new
  2682. StaticClassException;}static
  2683. function
  2684. call($_this,$name,$args){$class=new
  2685. Reflection\ClassType($_this);if($name===''){throw
  2686. new
  2687. MemberAccessException("Call to class '$class->name' method without name.");}if($class->hasEventProperty($name)){if(is_array($list=$_this->$name)||$list
  2688. instanceof\Traversable){foreach($list
  2689. as$handler){callback($handler)->invokeArgs($args);}}elseif($list!==NULL){throw
  2690. new
  2691. UnexpectedValueException("Property $class->name::$$name must be array or NULL, ".gettype($list)." given.");}return
  2692. NULL;}if($cb=$class->getExtensionMethod($name)){array_unshift($args,$_this);return$cb->invokeArgs($args);}throw
  2693. new
  2694. MemberAccessException("Call to undefined method $class->name::$name().");}static
  2695. function
  2696. callProperty($_this,$name,$args){if(strlen($name)>3){$op=substr($name,0,3);$prop=strtolower($name[3]).substr($name,4);if($op==='add'&&property_exists($_this,$prop.'s')){$_this->{$prop.'s'}[]=$args[0];return$_this;}elseif($op==='set'&&property_exists($_this,$prop)){$_this->$prop=$args[0];return$_this;}elseif($op==='get'&&property_exists($_this,$prop)){return$_this->$prop;}}self::call($_this,$name,$args);}static
  2697. function
  2698. callStatic($class,$name,$args){throw
  2699. new
  2700. MemberAccessException("Call to undefined static method $class::$name().");}static
  2701. function&get($_this,$name){$class=get_class($_this);if($name===''){throw
  2702. new
  2703. 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;}$type=isset(self::$methods[$class]['set'.$name])?'a write-only':'an undeclared';$name=func_get_arg(1);throw
  2704. new
  2705. MemberAccessException("Cannot read $type property $class::\$$name.");}static
  2706. function
  2707. set($_this,$name,$value){$class=get_class($_this);if($name===''){throw
  2708. new
  2709. 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";$m='set'.$name;if(isset(self::$methods[$class][$m])){$_this->$m($value);return;}$type=isset(self::$methods[$class]['get'.$name])||isset(self::$methods[$class]['is'.$name])?'a read-only':'an undeclared';$name=func_get_arg(1);throw
  2710. new
  2711. MemberAccessException("Cannot write to $type property $class::\$$name.");}static
  2712. function
  2713. remove($_this,$name){$class=get_class($_this);throw
  2714. new
  2715. MemberAccessException("Cannot unset the property $class::\$$name.");}static
  2716. function
  2717. has($_this,$name){if($name===''){return
  2718. 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
  2719. isset(self::$methods[$class]['get'.$name])||isset(self::$methods[$class]['is'.$name]);}}}namespace Nette\ComponentModel{use
  2720. Nette;class
  2721. RecursiveComponentIterator
  2722. extends\RecursiveArrayIterator
  2723. implements\Countable{function
  2724. hasChildren(){return$this->current()instanceof
  2725. IContainer;}function
  2726. getChildren(){return$this->current()->getComponents();}function
  2727. count(){return
  2728. iterator_count($this);}}}namespace Nette\Config\Adapters{use
  2729. Nette;use
  2730. Nette\Config\Helpers;class
  2731. IniAdapter
  2732. extends
  2733. Nette\Object
  2734. implements
  2735. Nette\Config\IAdapter{const
  2736. INHERITING_SEPARATOR='<',KEY_SEPARATOR='.',ESCAPED_KEY_SEPARATOR='..',RAW_SECTION='!';function
  2737. load($file){Nette\Diagnostics\Debugger::tryError();$ini=parse_ini_file($file,TRUE);if(Nette\Diagnostics\Debugger::catchError($e)){throw
  2738. new
  2739. Nette\InvalidStateException('parse_ini_file(): '.$e->getMessage(),0,$e);}$data=array();foreach($ini
  2740. as$secName=>$secData){if(is_array($secData)){if(substr($secName,-1)===self::RAW_SECTION){$secName=substr($secName,0,-1);}else{$tmp=array();foreach($secData
  2741. as$key=>$val){$cursor=&$tmp;$key=str_replace(self::ESCAPED_KEY_SEPARATOR,"\xFF",$key);foreach(explode(self::KEY_SEPARATOR,$key)as$part){$part=str_replace("\xFF",self::KEY_SEPARATOR,$part);if(!isset($cursor[$part])||is_array($cursor[$part])){$cursor=&$cursor[$part];}else{throw
  2742. new
  2743. Nette\InvalidStateException("Invalid key '$key' in section [$secName] in file '$file'.");}}$cursor=$val;}$secData=$tmp;}$parts=explode(self::INHERITING_SEPARATOR,$secName);if(count($parts)>1){$secName=trim($parts[0]);$secData[Helpers::EXTENDS_KEY]=trim($parts[1]);}}$cursor=&$data;foreach(explode(self::KEY_SEPARATOR,$secName)as$part){if(!isset($cursor[$part])||is_array($cursor[$part])){$cursor=&$cursor[$part];}else{throw
  2744. new
  2745. Nette\InvalidStateException("Invalid section [$secName] in file '$file'.");}}if(is_array($secData)&&is_array($cursor)){$secData=Helpers::merge($secData,$cursor);}$cursor=$secData;}return$data;}function
  2746. dump(array$data){$output=array();foreach($data
  2747. as$name=>$secData){if(!is_array($secData)){$output=array();self::build($data,$output,'');break;}if($parent=Helpers::takeParent($secData)){$output[]="[$name ".self::INHERITING_SEPARATOR." $parent]";}else{$output[]="[$name]";}self::build($secData,$output,'');$output[]='';}return"; generated by Nette\n\n".implode(PHP_EOL,$output);}private
  2748. static
  2749. function
  2750. build($input,&$output,$prefix){foreach($input
  2751. as$key=>$val){$key=str_replace(self::KEY_SEPARATOR,self::ESCAPED_KEY_SEPARATOR,$key);if(is_array($val)){self::build($val,$output,$prefix.$key.self::KEY_SEPARATOR);}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
  2752. new
  2753. Nette\InvalidArgumentException("The '$prefix$key' item must be scalar or array, ".gettype($val)." given.");}}}}use
  2754. Nette\Utils\Neon;class
  2755. NeonAdapter
  2756. extends
  2757. Nette\Object
  2758. implements
  2759. Nette\Config\IAdapter{const
  2760. INHERITING_SEPARATOR='<',PREVENT_MERGING='!';function
  2761. load($file){return$this->process((array)Neon::decode(file_get_contents($file)));}private
  2762. function
  2763. process(array$arr){$res=array();foreach($arr
  2764. as$key=>$val){if(substr($key,-1)===self::PREVENT_MERGING){if(!is_array($val)&&$val!==NULL){throw
  2765. new
  2766. Nette\InvalidStateException("Replacing operator is available only for arrays, item '$key' is not array.");}$key=substr($key,0,-1);$val[Helpers::EXTENDS_KEY]=Helpers::OVERWRITE;}elseif(preg_match('#^(\S+)\s+'.self::INHERITING_SEPARATOR.'\s+(\S+)$#',$key,$matches)){if(!is_array($val)&&$val!==NULL){throw
  2767. new
  2768. Nette\InvalidStateException("Inheritance operator is available only for arrays, item '$key' is not array.");}list(,$key,$val[Helpers::EXTENDS_KEY])=$matches;if(isset($res[$key])){throw
  2769. new
  2770. Nette\InvalidStateException("Duplicated key '$key'.");}}if(is_array($val)){$val=$this->process($val);}elseif($val
  2771. instanceof
  2772. Nette\Utils\NeonEntity){$val=(object)array('value'=>$val->value,'attributes'=>$this->process($val->attributes));}$res[$key]=$val;}return$res;}function
  2773. dump(array$data){$tmp=array();foreach($data
  2774. as$name=>$secData){if($parent=Helpers::takeParent($secData)){$name.=' '.self::INHERITING_SEPARATOR.' '.$parent;}$tmp[$name]=$secData;}return"# generated by Nette\n\n".Neon::encode($tmp,Neon::BLOCK);}}class
  2775. PhpAdapter
  2776. extends
  2777. Nette\Object
  2778. implements
  2779. Nette\Config\IAdapter{function
  2780. load($file){return
  2781. Nette\Utils\LimitedScope::load($file);}function
  2782. dump(array$data){return"<?php // generated by Nette \nreturn ".Nette\Utils\PhpGenerator\Helpers::dump($data).';';}}}namespace Nette\Config{use
  2783. Nette;use
  2784. Nette\Utils\Validators;class
  2785. Compiler
  2786. extends
  2787. Nette\Object{private$extensions=array();private$container;private$config;private
  2788. static$reserved=array('services'=>1,'factories'=>1,'parameters'=>1);function
  2789. addExtension($name,CompilerExtension$extension){if(isset(self::$reserved[$name])){throw
  2790. new
  2791. Nette\InvalidArgumentException("Name '$name' is reserved.");}$this->extensions[$name]=$extension->setCompiler($this,$name);return$this;}function
  2792. getExtensions(){return$this->extensions;}function
  2793. getContainerBuilder(){return$this->container;}function
  2794. getConfig(){return$this->config;}function
  2795. compile(array$config,$className,$parentName){$this->config=$config;$this->container=new
  2796. Nette\DI\ContainerBuilder;$this->processParameters();$this->processExtensions();$this->processServices();return$this->generateCode($className,$parentName);}function
  2797. processParameters(){if(isset($this->config['parameters'])){$this->container->parameters=$this->config['parameters'];}}function
  2798. processExtensions(){if($extra=array_diff_key($this->config,self::$reserved,$this->extensions)){$extra=implode("', '",array_keys($extra));throw
  2799. new
  2800. Nette\InvalidStateException("Found sections '$extra' in configuration, but corresponding extensions are missing.");}foreach($this->extensions
  2801. as$name=>$extension){$extension->loadConfiguration();}}function
  2802. processServices(){$this->parseServices($this->container,$this->config);foreach($this->extensions
  2803. as$name=>$extension){$this->container->addDefinition($name)->setClass('Nette\DI\NestedAccessor',array('@container',$name))->setAutowired(FALSE);if(isset($this->config[$name])){$this->parseServices($this->container,$this->config[$name],$name);}}foreach($this->container->getDefinitions()as$name=>$def){$factory=$name.'Factory';if(!$def->shared&&!$def->internal&&!$this->container->hasDefinition($factory)){$this->container->addDefinition($factory)->setClass('Nette\Callback',array('@container',Nette\DI\Container::getMethodName($name,FALSE)))->setAutowired(FALSE)->tags=$def->tags;}}}function
  2804. generateCode($className,$parentName){foreach($this->extensions
  2805. as$extension){$extension->beforeCompile();}$classes[]=$class=$this->container->generateClass($parentName);$class->setName($className)->addMethod('initialize');foreach($this->extensions
  2806. as$extension){$extension->afterCompile($class);}$defs=$this->container->getDefinitions();ksort($defs);$list=array_keys($defs);foreach(array_reverse($defs,TRUE)as$name=>$def){if($def->class==='Nette\DI\NestedAccessor'&&($found=preg_grep('#^'.$name.'\.#i',$list))){$list=array_diff($list,$found);$def->class=$className.'_'.preg_replace('#\W+#','_',$name);$class->documents=preg_replace("#\S+(?= \\$$name$)#",$def->class,$class->documents);$classes[]=$accessor=new
  2807. Nette\Utils\PhpGenerator\ClassType($def->class);foreach($found
  2808. as$item){$short=substr($item,strlen($name)+1);$accessor->addDocument($defs[$item]->shared?"@property {$defs[$item]->class} \$$short":"@method {$defs[$item]->class} create".ucfirst("$short()"));}}}return
  2809. implode("\n\n\n",$classes);}static
  2810. function
  2811. parseServices(Nette\DI\ContainerBuilder$container,array$config,$namespace=NULL){$services=isset($config['services'])?$config['services']:array();$factories=isset($config['factories'])?$config['factories']:array();if($tmp=array_intersect_key($services,$factories)){$tmp=implode("', '",array_keys($tmp));throw
  2812. new
  2813. Nette\DI\ServiceCreationException("It is not allowed to use services and factories with the same names: '$tmp'.");}$all=$services+$factories;uasort($all,function($a,$b){return
  2814. strcmp(Helpers::isInheriting($a),Helpers::isInheriting($b));});foreach($all
  2815. as$name=>$def){$shared=array_key_exists($name,$services);$name=($namespace?$namespace.'.':'').$name;if(($parent=Helpers::takeParent($def))&&$parent!==$name){$container->removeDefinition($name);$definition=$container->addDefinition($name);if($parent!==Helpers::OVERWRITE){foreach($container->getDefinition($parent)as$k=>$v){$definition->$k=$v;}}}elseif($container->hasDefinition($name)){$definition=$container->getDefinition($name);if($definition->shared!==$shared){throw
  2816. new
  2817. Nette\DI\ServiceCreationException("It is not allowed to use service and factory with the same name '$name'.");}}else{$definition=$container->addDefinition($name);}try{static::parseService($definition,$def,$shared);}catch(\Exception$e){throw
  2818. new
  2819. Nette\DI\ServiceCreationException("Service '$name': ".$e->getMessage(),NULL,$e);}}}static
  2820. function
  2821. parseService(Nette\DI\ServiceDefinition$definition,$config,$shared=TRUE){if($config===NULL){return;}elseif(!is_array($config)){$config=array('class'=>NULL,'factory'=>$config);}$known=$shared?array('class','factory','arguments','setup','autowired','run','tags'):array('class','factory','arguments','setup','autowired','tags','internal','parameters');if($error=array_diff(array_keys($config),$known)){throw
  2822. new
  2823. Nette\InvalidStateException("Unknown key '".implode("', '",$error)."' in definition of service.");}$arguments=array();if(array_key_exists('arguments',$config)){Validators::assertField($config,'arguments','array');$arguments=self::filterArguments($config['arguments']);$definition->setArguments($arguments);}if(array_key_exists('class',$config)||array_key_exists('factory',$config)){$definition->class=NULL;$definition->factory=NULL;}if(array_key_exists('class',$config)){Validators::assertField($config,'class','string|stdClass|null');if($config['class']instanceof\stdClass){$definition->setClass($config['class']->value,self::filterArguments($config['class']->attributes));}else{$definition->setClass($config['class'],$arguments);}}if(array_key_exists('factory',$config)){Validators::assertField($config,'factory','callable|stdClass|null');if($config['factory']instanceof\stdClass){$definition->setFactory($config['factory']->value,self::filterArguments($config['factory']->attributes));}else{$definition->setFactory($config['factory'],$arguments);}}if(isset($config['setup'])){if(Helpers::takeParent($config['setup'])){$definition->setup=array();}Validators::assertField($config,'setup','list');foreach($config['setup']as$id=>$setup){Validators::assert($setup,'callable|stdClass',"setup item #$id");if($setup
  2824. instanceof\stdClass){Validators::assert($setup->value,'callable',"setup item #$id");$definition->addSetup($setup->value,self::filterArguments($setup->attributes));}else{$definition->addSetup($setup);}}}$definition->setShared($shared);if(isset($config['parameters'])){Validators::assertField($config,'parameters','array');$definition->setParameters($config['parameters']);}if(isset($config['autowired'])){Validators::assertField($config,'autowired','bool');$definition->setAutowired($config['autowired']);}if(isset($config['internal'])){Validators::assertField($config,'internal','bool');$definition->setInternal($config['internal']);}if(isset($config['run'])){$config['tags']['run']=(bool)$config['run'];}if(isset($config['tags'])){Validators::assertField($config,'tags','array');if(Helpers::takeParent($config['tags'])){$definition->tags=array();}foreach($config['tags']as$tag=>$attrs){if(is_int($tag)&&is_string($attrs)){$definition->addTag($attrs);}else{$definition->addTag($tag,$attrs);}}}}static
  2825. function
  2826. filterArguments(array$args){foreach($args
  2827. as$k=>$v){if($v==='...'){unset($args[$k]);}elseif($v
  2828. instanceof\stdClass&&isset($v->value,$v->attributes)){$args[$k]=new
  2829. Nette\DI\Statement($v->value,self::filterArguments($v->attributes));}}return$args;}}use
  2830. Nette\DI\ContainerBuilder;abstract
  2831. class
  2832. CompilerExtension
  2833. extends
  2834. Nette\Object{protected$compiler;protected$name;function
  2835. setCompiler(Compiler$compiler,$name){$this->compiler=$compiler;$this->name=$name;return$this;}function
  2836. getConfig(array$defaults=NULL,$expand=TRUE){$config=$this->compiler->getConfig();$config=isset($config[$this->name])?$config[$this->name]:array();unset($config['services'],$config['factories']);$config=Helpers::merge($config,$defaults);return$expand?$this->compiler->getContainerBuilder()->expand($config):$config;}function
  2837. getContainerBuilder(){return$this->compiler->getContainerBuilder();}function
  2838. loadFromFile($file){$loader=new
  2839. Loader;$res=$loader->load($file);$container=$this->compiler->getContainerBuilder();foreach($loader->getDependencies()as$file){$container->addDependency($file);}return$res;}function
  2840. prefix($id){return
  2841. substr_replace($id,$this->name.'.',substr($id,0,1)==='@'?1:0,0);}function
  2842. loadConfiguration(){}function
  2843. beforeCompile(){}function
  2844. afterCompile(Nette\Utils\PhpGenerator\ClassType$class){}}use
  2845. Nette\Caching\Cache;class
  2846. Configurator
  2847. extends
  2848. Nette\Object{const
  2849. DEVELOPMENT='development',PRODUCTION='production',AUTO=NULL,NONE=FALSE;public$onCompile;protected$parameters;protected$files=array();function
  2850. __construct(){$this->parameters=$this->getDefaultParameters();}function
  2851. setDebugMode($value=TRUE){$this->parameters['debugMode']=is_bool($value)?$value:self::detectDebugMode($value);$this->parameters['productionMode']=!$this->parameters['debugMode'];return$this;}function
  2852. isDebugMode(){return!$this->parameters['productionMode'];}function
  2853. setTempDirectory($path){$this->parameters['tempDir']=$path;if(($cacheDir=$this->getCacheDirectory())&&!is_dir($cacheDir)){mkdir($cacheDir,0777);}return$this;}function
  2854. addParameters(array$params){$this->parameters=Helpers::merge($params,$this->parameters);return$this;}protected
  2855. function
  2856. getDefaultParameters(){$trace=debug_backtrace(FALSE);$debugMode=static::detectDebugMode();return
  2857. array('appDir'=>isset($trace[1]['file'])?dirname($trace[1]['file']):NULL,'wwwDir'=>isset($_SERVER['SCRIPT_FILENAME'])?dirname($_SERVER['SCRIPT_FILENAME']):NULL,'debugMode'=>$debugMode,'productionMode'=>!$debugMode,'environment'=>$debugMode?self::DEVELOPMENT:self::PRODUCTION,'consoleMode'=>PHP_SAPI==='cli','container'=>array('class'=>'SystemContainer','parent'=>'Nette\DI\Container'));}function
  2858. enableDebugger($logDirectory=NULL,$email=NULL){Nette\Diagnostics\Debugger::$strictMode=TRUE;Nette\Diagnostics\Debugger::enable($this->parameters['productionMode'],$logDirectory,$email);}function
  2859. createRobotLoader(){if(!($cacheDir=$this->getCacheDirectory())){throw
  2860. new
  2861. Nette\InvalidStateException("Set path to temporary directory using setTempDirectory().");}$loader=new
  2862. Nette\Loaders\RobotLoader;$loader->setCacheStorage(new
  2863. Nette\Caching\Storages\FileStorage($cacheDir));$loader->autoRebuild=!$this->parameters['productionMode'];return$loader;}function
  2864. addConfig($file,$section=self::AUTO){$this->files[]=array($file,$section===self::AUTO?$this->parameters['environment']:$section);return$this;}function
  2865. loadConfig($file,$section=NULL){trigger_error(__METHOD__.'() is deprecated; use addConfig(file, [section])->createContainer() instead.',E_USER_WARNING);return$this->addConfig($file,$section)->createContainer();}function
  2866. createContainer(){if($cacheDir=$this->getCacheDirectory()){$cache=new
  2867. Cache(new
  2868. Nette\Caching\Storages\PhpFileStorage($cacheDir),'Nette.Configurator');$cacheKey=array($this->parameters,$this->files);$cached=$cache->load($cacheKey);if(!$cached){$code=$this->buildContainer($dependencies);$cache->save($cacheKey,$code,array(Cache::FILES=>$this->parameters['productionMode']?NULL:$dependencies));$cached=$cache->load($cacheKey);}Nette\Utils\LimitedScope::load($cached['file'],TRUE);}elseif($this->files){throw
  2869. new
  2870. Nette\InvalidStateException("Set path to temporary directory using setTempDirectory().");}else{Nette\Utils\LimitedScope::evaluate($this->buildContainer());}$container=new$this->parameters['container']['class'];$container->initialize();Nette\Environment::setContext($container);return$container;}protected
  2871. function
  2872. buildContainer(&$dependencies=NULL){$loader=$this->createLoader();$config=array();$code="<?php\n";foreach($this->files
  2873. as$tmp){list($file,$section)=$tmp;$config=Helpers::merge($loader->load($file,$section),$config);$code.="// source: $file $section\n";}$code.="\n";$this->checkCompatibility($config);if(!isset($config['parameters'])){$config['parameters']=array();}$config['parameters']=Helpers::merge($config['parameters'],$this->parameters);$compiler=$this->createCompiler();$this->onCompile($this,$compiler);$code.=$compiler->compile($config,$this->parameters['container']['class'],$config['parameters']['container']['parent']);$dependencies=array_merge($loader->getDependencies(),$compiler->getContainerBuilder()->getDependencies());return$code;}protected
  2874. function
  2875. checkCompatibility(array$config){foreach(array('service'=>'services','variable'=>'parameters','variables'=>'parameters','mode'=>'parameters','const'=>'constants')as$old=>$new){if(isset($config[$old])){throw
  2876. new
  2877. Nette\DeprecatedException("Section '$old' in configuration file is deprecated; use '$new' instead.");}}if(isset($config['services'])){foreach($config['services']as$key=>$def){foreach(array('option'=>'arguments','methods'=>'setup')as$old=>$new){if(is_array($def)&&isset($def[$old])){throw
  2878. new
  2879. Nette\DeprecatedException("Section '$old' in service definition is deprecated; refactor it into '$new'.");}}}}}protected
  2880. function
  2881. createCompiler(){$compiler=new
  2882. Compiler;$compiler->addExtension('php',new
  2883. Extensions\PhpExtension)->addExtension('constants',new
  2884. Extensions\ConstantsExtension)->addExtension('nette',new
  2885. Extensions\NetteExtension);return$compiler;}protected
  2886. function
  2887. createLoader(){return
  2888. new
  2889. Loader;}protected
  2890. function
  2891. getCacheDirectory(){return
  2892. empty($this->parameters['tempDir'])?NULL:$this->parameters['tempDir'].'/cache';}static
  2893. function
  2894. detectDebugMode($list=NULL){$list=is_string($list)?preg_split('#[,\s]+#',$list):$list;$list[]='127.0.0.1';$list[]='::1';return
  2895. in_array(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:php_uname('n'),$list,TRUE);}function
  2896. setProductionMode($value=TRUE){return$this->setDebugMode(is_bool($value)?!$value:$value);}function
  2897. isProductionMode(){return!$this->isDebugMode();}static
  2898. function
  2899. detectProductionMode($list=NULL){return!static::detectDebugMode($list);}}}namespace Nette\Config\Extensions{use
  2900. Nette;use
  2901. Nette\DI\ContainerBuilder;class
  2902. ConstantsExtension
  2903. extends
  2904. Nette\Config\CompilerExtension{function
  2905. afterCompile(Nette\Utils\PhpGenerator\ClassType$class){foreach($this->getConfig()as$name=>$value){$class->methods['initialize']->addBody('define(?, ?);',array($name,$value));}}}use
  2906. Nette\Utils\Validators;class
  2907. NetteExtension
  2908. extends
  2909. Nette\Config\CompilerExtension{public$defaults=array('xhtml'=>TRUE,'session'=>array('iAmUsingBadHost'=>NULL,'autoStart'=>'smart','expiration'=>NULL),'application'=>array('debugger'=>TRUE,'errorPresenter'=>NULL,'catchExceptions'=>'%productionMode%'),'routing'=>array('debugger'=>TRUE,'routes'=>array()),'security'=>array('debugger'=>TRUE,'frames'=>'SAMEORIGIN','users'=>array(),'roles'=>array(),'resources'=>array()),'mailer'=>array('smtp'=>FALSE),'database'=>array(),'forms'=>array('messages'=>array()),'container'=>array('debugger'=>FALSE),'debugger'=>array('email'=>NULL,'editor'=>NULL,'browser'=>NULL,'strictMode'=>NULL,'bar'=>array(),'blueScreen'=>array()));public$databaseDefaults=array('dsn'=>NULL,'user'=>NULL,'password'=>NULL,'options'=>NULL,'debugger'=>TRUE,'explain'=>TRUE,'reflection'=>'Nette\Database\Reflection\DiscoveredReflection');function
  2910. loadConfiguration(){$container=$this->getContainerBuilder();$config=$this->getConfig($this->defaults);$container->addDefinition($this->prefix('cacheJournal'))->setClass('Nette\Caching\Storages\FileJournal',array('%tempDir%'));$container->addDefinition('cacheStorage')->setClass('Nette\Caching\Storages\FileStorage',array('%tempDir%/cache'));$container->addDefinition($this->prefix('templateCacheStorage'))->setClass('Nette\Caching\Storages\PhpFileStorage',array('%tempDir%/cache'))->setAutowired(FALSE);$container->addDefinition($this->prefix('cache'))->setClass('Nette\Caching\Cache',array(1=>'%namespace%'))->setParameters(array('namespace'=>NULL));$container->addDefinition($this->prefix('httpRequestFactory'))->setClass('Nette\Http\RequestFactory')->addSetup('setEncoding',array('UTF-8'))->setInternal(TRUE);$container->addDefinition('httpRequest')->setClass('Nette\Http\Request')->setFactory('@Nette\Http\RequestFactory::createHttpRequest');$container->addDefinition('httpResponse')->setClass('Nette\Http\Response');$container->addDefinition($this->prefix('httpContext'))->setClass('Nette\Http\Context');$session=$container->addDefinition('session')->setClass('Nette\Http\Session');if(isset($config['session']['expiration'])){$session->addSetup('setExpiration',array($config['session']['expiration']));}if(isset($config['session']['iAmUsingBadHost'])){$session->addSetup('Nette\Framework::$iAmUsingBadHost = ?;',array((bool)$config['session']['iAmUsingBadHost']));}unset($config['session']['expiration'],$config['session']['autoStart'],$config['session']['iAmUsingBadHost']);if(!empty($config['session'])){$session->addSetup('setOptions',array($config['session']));}$container->addDefinition($this->prefix('userStorage'))->setClass('Nette\Http\UserStorage');$user=$container->addDefinition('user')->setClass('Nette\Security\User');if(!$container->parameters['productionMode']&&$config['security']['debugger']){$user->addSetup('Nette\Diagnostics\Debugger::$bar->addPanel(?)',array(new
  2911. Nette\DI\Statement('Nette\Security\Diagnostics\UserPanel')));}if($config['security']['users']){$container->addDefinition($this->prefix('authenticator'))->setClass('Nette\Security\SimpleAuthenticator',array($config['security']['users']));}if($config['security']['roles']||$config['security']['resources']){$authorizator=$container->addDefinition($this->prefix('authorizator'))->setClass('Nette\Security\Permission');foreach($config['security']['roles']as$role=>$parents){$authorizator->addSetup('addRole',array($role,$parents));}foreach($config['security']['resources']as$resource=>$parents){$authorizator->addSetup('addResource',array($resource,$parents));}}$application=$container->addDefinition('application')->setClass('Nette\Application\Application')->addSetup('$catchExceptions',$config['application']['catchExceptions'])->addSetup('$errorPresenter',$config['application']['errorPresenter']);if($config['application']['debugger']){$application->addSetup('Nette\Application\Diagnostics\RoutingPanel::initializePanel');}$container->addDefinition($this->prefix('presenterFactory'))->setClass('Nette\Application\PresenterFactory',array(isset($container->parameters['appDir'])?$container->parameters['appDir']:NULL));$router=$container->addDefinition('router')->setClass('Nette\Application\Routers\RouteList');foreach($config['routing']['routes']as$mask=>$action){$router->addSetup('$service[] = new Nette\Application\Routers\Route(?, ?);',array($mask,$action));}if(!$container->parameters['productionMode']&&$config['routing']['debugger']){$application->addSetup('Nette\Diagnostics\Debugger::$bar->addPanel(?)',array(new
  2912. Nette\DI\Statement('Nette\Application\Diagnostics\RoutingPanel')));}if(empty($config['mailer']['smtp'])){$container->addDefinition($this->prefix('mailer'))->setClass('Nette\Mail\SendmailMailer');}else{Validators::assertField($config,'mailer','array');$container->addDefinition($this->prefix('mailer'))->setClass('Nette\Mail\SmtpMailer',array($config['mailer']));}$container->addDefinition($this->prefix('mail'))->setClass('Nette\Mail\Message')->addSetup('setMailer')->setShared(FALSE);$container->addDefinition($this->prefix('basicForm'))->setClass('Nette\Forms\Form')->setShared(FALSE);$latte=$container->addDefinition($this->prefix('latte'))->setClass('Nette\Latte\Engine')->setShared(FALSE);if(empty($config['xhtml'])){$latte->addSetup('$service->getCompiler()->defaultContentType = ?',Nette\Latte\Compiler::CONTENT_HTML);}$container->addDefinition($this->prefix('template'))->setClass('Nette\Templating\FileTemplate')->addSetup('registerFilter',array($latte))->addSetup('registerHelperLoader',array('Nette\Templating\Helpers::loader'))->setShared(FALSE);$container->addDefinition($this->prefix('database'))->setClass('Nette\DI\NestedAccessor',array('@container',$this->prefix('database')));$autowired=TRUE;foreach((array)$config['database']as$name=>$info){if(!is_array($info)){continue;}$info+=$this->databaseDefaults+array('autowired'=>$autowired);$autowired=FALSE;foreach((array)$info['options']as$key=>$value){unset($info['options'][$key]);$info['options'][constant($key)]=$value;}$connection=$container->addDefinition($this->prefix("database.$name"))->setClass('Nette\Database\Connection',array($info['dsn'],$info['user'],$info['password'],$info['options']))->setAutowired($info['autowired'])->addSetup('setCacheStorage')->addSetup('Nette\Diagnostics\Debugger::$blueScreen->addPanel(?)',array('Nette\Database\Diagnostics\ConnectionPanel::renderException'));if($info['reflection']){$connection->addSetup('setDatabaseReflection',is_string($info['reflection'])?array(new
  2913. Nette\DI\Statement(preg_match('#^[a-z]+$#',$info['reflection'])?'Nette\Database\Reflection\\'.ucfirst($info['reflection']).'Reflection':$info['reflection'])):Nette\Config\Compiler::filterArguments(array($info['reflection'])));}if(!$container->parameters['productionMode']&&$info['debugger']){$panel=$container->addDefinition($this->prefix("database.{$name}ConnectionPanel"))->setClass('Nette\Database\Diagnostics\ConnectionPanel')->setAutowired(FALSE)->addSetup('$explain',!empty($info['explain']))->addSetup('Nette\Diagnostics\Debugger::$bar->addPanel(?)',array('@self'));$connection->addSetup('$service->onQuery[] = ?',array(array($panel,'logQuery')));}}}function
  2914. afterCompile(Nette\Utils\PhpGenerator\ClassType$class){$initialize=$class->methods['initialize'];$container=$this->getContainerBuilder();$config=$this->getConfig($this->defaults);foreach(array('email','editor','browser','strictMode','maxLen','maxDepth')as$key){if(isset($config['debugger'][$key])){$initialize->addBody('Nette\Diagnostics\Debugger::$? = ?;',array($key,$config['debugger'][$key]));}}if(!$container->parameters['productionMode']){if($config['container']['debugger']){$config['debugger']['bar'][]='Nette\DI\Diagnostics\ContainerPanel';}foreach((array)$config['debugger']['bar']as$item){$initialize->addBody($container->formatPhp('Nette\Diagnostics\Debugger::$bar->addPanel(?);',Nette\Config\Compiler::filterArguments(array(is_string($item)?new
  2915. Nette\DI\Statement($item):$item))));}foreach((array)$config['debugger']['blueScreen']as$item){$initialize->addBody($container->formatPhp('Nette\Diagnostics\Debugger::$blueScreen->addPanel(?);',Nette\Config\Compiler::filterArguments(array($item))));}}if(!empty($container->parameters['tempDir'])){$initialize->addBody($this->checkTempDir($container->expand('%tempDir%/cache')));}foreach((array)$config['forms']['messages']as$name=>$text){$initialize->addBody('Nette\Forms\Rules::$defaultMessages[Nette\Forms\Form::?] = ?;',array($name,$text));}if($config['session']['autoStart']==='smart'){$initialize->addBody('$this->session->exists() && $this->session->start();');}elseif($config['session']['autoStart']){$initialize->addBody('$this->session->start();');}if(empty($config['xhtml'])){$initialize->addBody('Nette\Utils\Html::$xhtml = ?;',array((bool)$config['xhtml']));}if(isset($config['security']['frames'])&&$config['security']['frames']!==TRUE){$frames=$config['security']['frames'];if($frames===FALSE){$frames='DENY';}elseif(preg_match('#^https?:#',$frames)){$frames="ALLOW-FROM $frames";}$initialize->addBody('header(?);',array("X-Frame-Options: $frames"));}foreach($container->findByTag('run')as$name=>$on){if($on){$initialize->addBody('$this->getService(?);',array($name));}}}private
  2916. function
  2917. checkTempDir($dir){$uniq=uniqid('_',TRUE);if(!@mkdir("$dir/$uniq",0777)){throw
  2918. new
  2919. Nette\InvalidStateException("Unable to write to directory '$dir'. Make this directory writable.");}$useDirs=@file_put_contents("$dir/$uniq/_",'')!==FALSE;@unlink("$dir/$uniq/_");@rmdir("$dir/$uniq");return'Nette\Caching\Storages\FileStorage::$useDirectories = '.($useDirs?'TRUE':'FALSE').";\n";}}class
  2920. PhpExtension
  2921. extends
  2922. Nette\Config\CompilerExtension{function
  2923. afterCompile(Nette\Utils\PhpGenerator\ClassType$class){$initialize=$class->methods['initialize'];foreach($this->getConfig()as$name=>$value){if(!is_scalar($value)){throw
  2924. new
  2925. Nette\InvalidStateException("Configuration value for directive '$name' is not scalar.");}elseif($name==='include_path'){$initialize->addBody('set_include_path(?);',array(str_replace(';',PATH_SEPARATOR,$value)));}elseif($name==='ignore_user_abort'){$initialize->addBody('ignore_user_abort(?);',array($value));}elseif($name==='max_execution_time'){$initialize->addBody('set_time_limit(?);',array($value));}elseif($name==='date.timezone'){$initialize->addBody('date_default_timezone_set(?);',array($value));}elseif(function_exists('ini_set')){$initialize->addBody('ini_set(?, ?);',array($name,$value));}elseif(ini_get($name)!=$value){throw
  2926. new
  2927. Nette\NotSupportedException('Required function ini_set() is disabled.');}}}}}namespace Nette\Config{use
  2928. Nette;class
  2929. Helpers{const
  2930. EXTENDS_KEY='_extends',OVERWRITE=TRUE;static
  2931. function
  2932. merge($left,$right){if(is_array($left)&&is_array($right)){foreach($left
  2933. as$key=>$val){if(is_int($key)){$right[]=$val;}else{if(is_array($val)&&isset($val[self::EXTENDS_KEY])){if($val[self::EXTENDS_KEY]===self::OVERWRITE){unset($val[self::EXTENDS_KEY]);}}elseif(isset($right[$key])){$val=static::merge($val,$right[$key]);}$right[$key]=$val;}}return$right;}elseif($left===NULL&&is_array($right)){return$right;}else{return$left;}}static
  2934. function
  2935. takeParent(&$data){if(is_array($data)&&isset($data[self::EXTENDS_KEY])){$parent=$data[self::EXTENDS_KEY];unset($data[self::EXTENDS_KEY]);return$parent;}}static
  2936. function
  2937. isOverwriting(&$data){return
  2938. is_array($data)&&isset($data[self::EXTENDS_KEY])&&$data[self::EXTENDS_KEY]===self::OVERWRITE;}static
  2939. function
  2940. isInheriting(&$data){return
  2941. is_array($data)&&isset($data[self::EXTENDS_KEY])&&$data[self::EXTENDS_KEY]!==self::OVERWRITE;}}use
  2942. Nette\Utils\Validators;class
  2943. Loader
  2944. extends
  2945. Nette\Object{const
  2946. INCLUDES_KEY='includes';private$adapters=array('php'=>'Nette\Config\Adapters\PhpAdapter','ini'=>'Nette\Config\Adapters\IniAdapter','neon'=>'Nette\Config\Adapters\NeonAdapter');private$dependencies=array();function
  2947. load($file,$section=NULL){if(!is_file($file)||!is_readable($file)){throw
  2948. new
  2949. Nette\FileNotFoundException("File '$file' is missing or is not readable.");}$this->dependencies[]=$file=realpath($file);$data=$this->getAdapter($file)->load($file);if($section){if(isset($data[self::INCLUDES_KEY])){throw
  2950. new
  2951. Nette\InvalidStateException("Section 'includes' must be placed under some top section in file '$file'.");}$data=$this->getSection($data,$section,$file);}$merged=array();if(isset($data[self::INCLUDES_KEY])){Validators::assert($data[self::INCLUDES_KEY],'list',"section 'includes' in file '$file'");foreach($data[self::INCLUDES_KEY]as$include){$merged=Helpers::merge($this->load(dirname($file).'/'.$include),$merged);}}unset($data[self::INCLUDES_KEY]);return
  2952. Helpers::merge($data,$merged);}function
  2953. save($data,$file){if(file_put_contents($file,$this->getAdapter($file)->dump($data))===FALSE){throw
  2954. new
  2955. Nette\IOException("Cannot write file '$file'.");}}function
  2956. getDependencies(){return
  2957. array_unique($this->dependencies);}function
  2958. addAdapter($extension,$adapter){$this->adapters[strtolower($extension)]=$adapter;return$this;}private
  2959. function
  2960. getAdapter($file){$extension=strtolower(pathinfo($file,PATHINFO_EXTENSION));if(!isset($this->adapters[$extension])){throw
  2961. new
  2962. Nette\InvalidArgumentException("Unknown file extension '$file'.");}return
  2963. is_object($this->adapters[$extension])?$this->adapters[$extension]:new$this->adapters[$extension];}private
  2964. function
  2965. getSection(array$data,$key,$file){Validators::assertField($data,$key,'array|null',"section '%' in file '$file'");$item=$data[$key];if($parent=Helpers::takeParent($item)){$item=Helpers::merge($item,$this->getSection($data,$parent,$file));}return$item;}}}namespace Nette\Database{use
  2966. Nette;use
  2967. Nette\ObjectMixin;use
  2968. PDO;if(class_exists('PDO')){class
  2969. Connection
  2970. extends
  2971. PDO{private$dsn;private$driver;private$preprocessor;private$databaseReflection;private$cache;public$onQuery;function
  2972. __construct($dsn,$username=NULL,$password=NULL,array$options=NULL,$driverClass=NULL){parent::__construct($this->dsn=$dsn,$username,$password,$options);$this->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);$this->setAttribute(PDO::ATTR_STATEMENT_CLASS,array('Nette\Database\Statement',array($this)));$driverClass=$driverClass?:'Nette\Database\Drivers\\'.ucfirst(str_replace('sql','Sql',$this->getAttribute(PDO::ATTR_DRIVER_NAME))).'Driver';$this->driver=new$driverClass($this,(array)$options);$this->preprocessor=new
  2973. SqlPreprocessor($this);}function
  2974. getDsn(){return$this->dsn;}function
  2975. getSupplementalDriver(){return$this->driver;}function
  2976. setDatabaseReflection(IReflection$databaseReflection){$databaseReflection->setConnection($this);$this->databaseReflection=$databaseReflection;return$this;}function
  2977. getDatabaseReflection(){if(!$this->databaseReflection){$this->setDatabaseReflection(new
  2978. Reflection\ConventionalReflection);}return$this->databaseReflection;}function
  2979. setCacheStorage(Nette\Caching\IStorage$storage=NULL){$this->cache=$storage?new
  2980. Nette\Caching\Cache($storage,'Nette.Database.'.md5($this->dsn)):NULL;return$this;}function
  2981. getCache(){return$this->cache;}function
  2982. query($statement){$args=func_get_args();return$this->queryArgs(array_shift($args),$args);}function
  2983. exec($statement){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->rowCount();}function
  2984. queryArgs($statement,$params){foreach($params
  2985. as$value){if(is_array($value)||is_object($value)){$need=TRUE;break;}}if(isset($need)&&$this->preprocessor!==NULL){list($statement,$params)=$this->preprocessor->process($statement,$params);}return$this->prepare($statement)->execute($params);}function
  2986. fetch($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetch();}function
  2987. fetchColumn($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchColumn();}function
  2988. fetchPairs($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchPairs();}function
  2989. fetchAll($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchAll();}function
  2990. table($table){return
  2991. new
  2992. Table\Selection($table,$this);}static
  2993. function
  2994. getReflection(){return
  2995. new
  2996. Nette\Reflection\ClassType(get_called_class());}function
  2997. __call($name,$args){return
  2998. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  2999. ObjectMixin::get($this,$name);}function
  3000. __set($name,$value){return
  3001. ObjectMixin::set($this,$name,$value);}function
  3002. __isset($name){return
  3003. ObjectMixin::has($this,$name);}function
  3004. __unset($name){ObjectMixin::remove($this,$name);}}}}namespace Nette\Database\Diagnostics{use
  3005. Nette;use
  3006. Nette\Database\Helpers;use
  3007. Nette\Diagnostics\Debugger;class
  3008. ConnectionPanel
  3009. extends
  3010. Nette\Object
  3011. implements
  3012. Nette\Diagnostics\IBarPanel{static
  3013. public$maxLength=1000;private$totalTime=0;private$queries=array();public$name;public$explain=TRUE;public$disabled=FALSE;function
  3014. logQuery(Nette\Database\Statement$result,array$params=NULL){if($this->disabled){return;}$source=NULL;foreach(debug_backtrace(FALSE)as$row){if(isset($row['file'])&&is_file($row['file'])&&strpos($row['file'],NETTE_DIR.DIRECTORY_SEPARATOR)!==0){if(isset($row['function'])&&strpos($row['function'],'call_user_func')===0)continue;if(isset($row['class'])&&is_subclass_of($row['class'],'\\Nette\\Database\\Connection'))continue;$source=array($row['file'],(int)$row['line']);break;}}$this->totalTime+=$result->getTime();$this->queries[]=array($result->queryString,$params,$result->getTime(),$result->rowCount(),$result->getConnection(),$source);}static
  3015. function
  3016. renderException($e){if($e
  3017. instanceof\PDOException&&isset($e->queryString)){return
  3018. array('tab'=>'SQL','panel'=>Helpers::dumpSql($e->queryString));}}function
  3019. getTab(){return'<span title="Nette\\Database '.htmlSpecialChars($this->name).'">'.'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEYSURBVBgZBcHPio5hGAfg6/2+R980k6wmJgsJ5U/ZOAqbSc2GnXOwUg7BESgLUeIQ1GSjLFnMwsKGGg1qxJRmPM97/1zXFAAAAEADdlfZzr26miup2svnelq7d2aYgt3rebl585wN6+K3I1/9fJe7O/uIePP2SypJkiRJ0vMhr55FLCA3zgIAOK9uQ4MS361ZOSX+OrTvkgINSjS/HIvhjxNNFGgQsbSmabohKDNoUGLohsls6BaiQIMSs2FYmnXdUsygQYmumy3Nhi6igwalDEOJEjPKP7CA2aFNK8Bkyy3fdNCg7r9/fW3jgpVJbDmy5+PB2IYp4MXFelQ7izPrhkPHB+P5/PjhD5gCgCenx+VR/dODEwD+A3T7nqbxwf1HAAAAAElFTkSuQmCC" />'.count($this->queries).' queries'.($this->totalTime?' / '.sprintf('%0.1f',$this->totalTime*1000).'ms':'').'</span>';}function
  3020. getPanel(){$this->disabled=TRUE;$s='';$h='htmlSpecialChars';foreach($this->queries
  3021. as$i=>$query){list($sql,$params,$time,$rows,$connection,$source)=$query;$explain=NULL;if($this->explain&&preg_match('#\s*\(?\s*SELECT\s#iA',$sql)){try{$cmd=is_string($this->explain)?$this->explain:'EXPLAIN';$explain=$connection->queryArgs("$cmd $sql",$params)->fetchAll();}catch(\PDOException$e){}}$s.='<tr><td>'.sprintf('%0.3f',$time*1000);if($explain){static$counter;$counter++;$s.="<br /><a href='#' class='nette-toggler' rel='#nette-DbConnectionPanel-row-$counter'>explain&nbsp;&#x25ba;</a>";}$s.='</td><td class="nette-DbConnectionPanel-sql">'.Helpers::dumpSql(self::$maxLength?Nette\Utils\Strings::truncate($sql,self::$maxLength):$sql);if($explain){$s.="<table id='nette-DbConnectionPanel-row-$counter' class='nette-collapsed'><tr>";foreach($explain[0]as$col=>$foo){$s.="<th>{$h($col)}</th>";}$s.="</tr>";foreach($explain
  3022. as$row){$s.="<tr>";foreach($row
  3023. as$col){$s.="<td>{$h($col)}</td>";}$s.="</tr>";}$s.="</table>";}if($source){$s.=Nette\Diagnostics\Helpers::editorLink($source[0],$source[1])->class('nette-DbConnectionPanel-source');}$s.='</td><td>';foreach($params
  3024. as$param){$s.=Debugger::dump($param,TRUE);}$s.='</td><td>'.$rows.'</td></tr>';}return
  3025. empty($this->queries)?'':'<style> #nette-debug td.nette-DbConnectionPanel-sql { background: white !important }
  3026. #nette-debug .nette-DbConnectionPanel-source { color: #BBB !important } </style>
  3027. <h1>Queries: '.count($this->queries).($this->totalTime?', time: '.sprintf('%0.3f',$this->totalTime*1000).' ms':'').'</h1>
  3028. <div class="nette-inner nette-DbConnectionPanel">
  3029. <table>
  3030. <tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Params</th><th>Rows</th></tr>'.$s.'
  3031. </table>
  3032. </div>';}}}namespace Nette\Database\Drivers{use
  3033. Nette;class
  3034. MsSqlDriver
  3035. extends
  3036. Nette\Object
  3037. implements
  3038. Nette\Database\ISupplementalDriver{private$connection;function
  3039. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;}function
  3040. delimite($name){return'['.str_replace(array('[',']'),array('[[',']]'),$name).']';}function
  3041. formatDateTime(\DateTime$value){return$value->format("'Y-m-d H:i:s'");}function
  3042. formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'%'=>'[%]','_'=>'[_]','['=>'[[]'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}function
  3043. applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql='SELECT TOP '.(int)$limit.' * FROM ('.$sql.') t';}if($offset){throw
  3044. new
  3045. Nette\NotImplementedException('Offset is not implemented.');}}function
  3046. normalizeRow($row,$statement){return$row;}function
  3047. getTables(){throw
  3048. new
  3049. NotImplementedException;}function
  3050. getColumns($table){throw
  3051. new
  3052. NotImplementedException;}function
  3053. getIndexes($table){throw
  3054. new
  3055. NotImplementedException;}function
  3056. getForeignKeys($table){throw
  3057. new
  3058. NotImplementedException;}function
  3059. isSupported($item){return$item===self::META;}}class
  3060. MySqlDriver
  3061. extends
  3062. Nette\Object
  3063. implements
  3064. Nette\Database\ISupplementalDriver{const
  3065. ERROR_ACCESS_DENIED=1045;const
  3066. ERROR_DUPLICATE_ENTRY=1062;const
  3067. ERROR_DATA_TRUNCATED=1265;private$connection;function
  3068. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;$charset=isset($options['charset'])?$options['charset']:'utf8';if($charset){$connection->exec("SET NAMES '$charset'");}if(isset($options['sqlmode'])){$connection->exec("SET sql_mode='$options[sqlmode]'");}$connection->exec("SET time_zone='".date('P')."'");}function
  3069. delimite($name){return'`'.str_replace('`','``',$name).'`';}function
  3070. formatDateTime(\DateTime$value){return$value->format("'Y-m-d H:i:s'");}function
  3071. formatLike($value,$pos){$value=addcslashes(str_replace('\\','\\\\',$value),"\x00\n\r\\'%_");return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}function
  3072. applyLimit(&$sql,$limit,$offset){if($limit>=0||$offset>0){$sql.=' LIMIT '.($limit<0?'18446744073709551615':(int)$limit).($offset>0?' OFFSET '.(int)$offset:'');}}function
  3073. normalizeRow($row,$statement){return$row;}function
  3074. getTables(){$tables=array();foreach($this->connection->query('SHOW FULL TABLES',\PDO::FETCH_NUM)as$row){$tables[]=array('name'=>$row[0],'view'=>isset($row[1])&&$row[1]==='VIEW');}return$tables;}function
  3075. getColumns($table){$columns=array();foreach($this->connection->query('SHOW FULL COLUMNS FROM '.$this->delimite($table))as$row){$type=explode('(',$row['Type']);$columns[]=array('name'=>$row['Field'],'table'=>$table,'nativetype'=>strtoupper($type[0]),'size'=>isset($type[1])?(int)$type[1]:NULL,'unsigned'=>(bool)strstr($row['Type'],'unsigned'),'nullable'=>$row['Null']==='YES','default'=>$row['Default'],'autoincrement'=>$row['Extra']==='auto_increment','primary'=>$row['Key']==='PRI','vendor'=>(array)$row);}return$columns;}function
  3076. getIndexes($table){$indexes=array();foreach($this->connection->query('SHOW INDEX FROM '.$this->delimite($table))as$row){$indexes[$row['Key_name']]['name']=$row['Key_name'];$indexes[$row['Key_name']]['unique']=!$row['Non_unique'];$indexes[$row['Key_name']]['primary']=$row['Key_name']==='PRIMARY';$indexes[$row['Key_name']]['columns'][$row['Seq_in_index']-1]=$row['Column_name'];}return
  3077. array_values($indexes);}function
  3078. getForeignKeys($table){$keys=array();$query='SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE '.'WHERE TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME IS NOT NULL AND TABLE_NAME = '.$this->connection->quote($table);foreach($this->connection->query($query)as$id=>$row){$keys[$id]['name']=$row['CONSTRAINT_NAME'];$keys[$id]['local']=$row['COLUMN_NAME'];$keys[$id]['table']=$row['REFERENCED_TABLE_NAME'];$keys[$id]['foreign']=$row['REFERENCED_COLUMN_NAME'];}return
  3079. array_values($keys);}function
  3080. isSupported($item){return$item===self::META;}}class
  3081. OciDriver
  3082. extends
  3083. Nette\Object
  3084. implements
  3085. Nette\Database\ISupplementalDriver{private$connection;private$fmtDateTime;function
  3086. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;$this->fmtDateTime=isset($options['formatDateTime'])?$options['formatDateTime']:'U';}function
  3087. delimite($name){return'"'.str_replace('"','""',$name).'"';}function
  3088. formatDateTime(\DateTime$value){return$value->format($this->fmtDateTime);}function
  3089. formatLike($value,$pos){throw
  3090. new
  3091. Nette\NotImplementedException;}function
  3092. applyLimit(&$sql,$limit,$offset){if($offset>0){$sql='SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM ('.$sql.') t '.($limit>=0?'WHERE ROWNUM <= '.((int)$offset+(int)$limit):'').') WHERE "__rnum" > '.(int)$offset;}elseif($limit>=0){$sql='SELECT * FROM ('.$sql.') WHERE ROWNUM <= '.(int)$limit;}}function
  3093. normalizeRow($row,$statement){return$row;}function
  3094. getTables(){$tables=array();foreach($this->connection->query('SELECT * FROM cat',\PDO::FETCH_NUM)as$row){if($row[1]==='TABLE'||$row[1]==='VIEW'){$tables[]=array('name'=>$row[0],'view'=>$row[1]==='VIEW');}}return$tables;}function
  3095. getColumns($table){throw
  3096. new
  3097. NotImplementedException;}function
  3098. getIndexes($table){throw
  3099. new
  3100. NotImplementedException;}function
  3101. getForeignKeys($table){throw
  3102. new
  3103. NotImplementedException;}function
  3104. isSupported($item){return$item===self::META;}}class
  3105. OdbcDriver
  3106. extends
  3107. Nette\Object
  3108. implements
  3109. Nette\Database\ISupplementalDriver{private$connection;function
  3110. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;}function
  3111. delimite($name){return'['.str_replace(array('[',']'),array('[[',']]'),$name).']';}function
  3112. formatDateTime(\DateTime$value){return$value->format("#m/d/Y H:i:s#");}function
  3113. formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'%'=>'[%]','_'=>'[_]','['=>'[[]'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}function
  3114. applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql='SELECT TOP '.(int)$limit.' * FROM ('.$sql.')';}if($offset){throw
  3115. new
  3116. Nette\InvalidArgumentException('Offset is not implemented in driver odbc.');}}function
  3117. normalizeRow($row,$statement){return$row;}function
  3118. getTables(){throw
  3119. new
  3120. NotImplementedException;}function
  3121. getColumns($table){throw
  3122. new
  3123. NotImplementedException;}function
  3124. getIndexes($table){throw
  3125. new
  3126. NotImplementedException;}function
  3127. getForeignKeys($table){throw
  3128. new
  3129. NotImplementedException;}function
  3130. isSupported($item){return$item===self::META;}}class
  3131. PgSqlDriver
  3132. extends
  3133. Nette\Object
  3134. implements
  3135. Nette\Database\ISupplementalDriver{private$connection;function
  3136. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;}function
  3137. delimite($name){return'"'.str_replace('"','""',$name).'"';}function
  3138. formatDateTime(\DateTime$value){return$value->format("'Y-m-d H:i:s'");}function
  3139. formatLike($value,$pos){throw
  3140. new
  3141. Nette\NotImplementedException;}function
  3142. applyLimit(&$sql,$limit,$offset){if($limit>=0)$sql.=' LIMIT '.(int)$limit;if($offset>0)$sql.=' OFFSET '.(int)$offset;}function
  3143. normalizeRow($row,$statement){return$row;}function
  3144. getTables(){return$this->connection->query("
  3145. SELECT table_name as name, CAST(table_type = 'VIEW' AS INTEGER) as view
  3146. FROM information_schema.tables
  3147. WHERE table_schema = current_schema()
  3148. ")->fetchAll();}function
  3149. getColumns($table){$primary=(int)$this->connection->query("
  3150. SELECT indkey
  3151. FROM pg_class
  3152. LEFT JOIN pg_index on pg_class.oid = pg_index.indrelid AND pg_index.indisprimary
  3153. WHERE pg_class.relname = {$this->connection->quote($table)}
  3154. ")->fetchColumn(0);$columns=array();foreach($this->connection->query("
  3155. SELECT *
  3156. FROM information_schema.columns
  3157. WHERE table_name = {$this->connection->quote($table)} AND table_schema = current_schema()
  3158. ORDER BY ordinal_position
  3159. ")as$row){$size=(int)max($row['character_maximum_length'],$row['numeric_precision']);$columns[]=array('name'=>$row['column_name'],'table'=>$table,'nativetype'=>strtoupper($row['udt_name']),'size'=>$size?$size:NULL,'nullable'=>$row['is_nullable']==='YES','default'=>$row['column_default'],'autoincrement'=>(int)$row['ordinal_position']===$primary&&substr($row['column_default'],0,7)==='nextval','primary'=>(int)$row['ordinal_position']===$primary,'vendor'=>(array)$row);}return$columns;}function
  3160. getIndexes($table){$columns=array();foreach($this->connection->query("
  3161. SELECT ordinal_position, column_name
  3162. FROM information_schema.columns
  3163. WHERE table_name = {$this->connection->quote($table)} AND table_schema = current_schema()
  3164. ORDER BY ordinal_position
  3165. ")as$row){$columns[$row['ordinal_position']]=$row['column_name'];}$indexes=array();foreach($this->connection->query("
  3166. SELECT pg_class2.relname, indisunique, indisprimary, indkey
  3167. FROM pg_class
  3168. LEFT JOIN pg_index on pg_class.oid = pg_index.indrelid
  3169. INNER JOIN pg_class as pg_class2 on pg_class2.oid = pg_index.indexrelid
  3170. WHERE pg_class.relname = {$this->connection->quote($table)}
  3171. ")as$row){$indexes[$row['relname']]['name']=$row['relname'];$indexes[$row['relname']]['unique']=$row['indisunique']==='t';$indexes[$row['relname']]['primary']=$row['indisprimary']==='t';foreach(explode(' ',$row['indkey'])as$index){$indexes[$row['relname']]['columns'][]=$columns[$index];}}return
  3172. array_values($indexes);}function
  3173. getForeignKeys($table){throw
  3174. new
  3175. NotImplementedException;}function
  3176. isSupported($item){return$item===self::META;}}class
  3177. SqliteDriver
  3178. extends
  3179. Nette\Object
  3180. implements
  3181. Nette\Database\ISupplementalDriver{private$connection;private$fmtDateTime;function
  3182. __construct(Nette\Database\Connection$connection,array$options){$this->connection=$connection;$this->fmtDateTime=isset($options['formatDateTime'])?$options['formatDateTime']:'U';}function
  3183. delimite($name){return'['.strtr($name,'[]',' ').']';}function
  3184. formatDateTime(\DateTime$value){return$value->format($this->fmtDateTime);}function
  3185. formatLike($value,$pos){$value=addcslashes(substr($this->connection->quote($value),1,-1),'%_\\');return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'")." ESCAPE '\\'";}function
  3186. applyLimit(&$sql,$limit,$offset){if($limit>=0||$offset>0){$sql.=' LIMIT '.$limit.($offset>0?' OFFSET '.(int)$offset:'');}}function
  3187. normalizeRow($row,$statement){return$row;}function
  3188. getTables(){return$this->connection->query("
  3189. SELECT name, type = 'view' as view FROM sqlite_master WHERE type IN ('table', 'view')
  3190. UNION ALL
  3191. SELECT name, type = 'view' as view FROM sqlite_temp_master WHERE type IN ('table', 'view')
  3192. ORDER BY name
  3193. ")->fetchAll();}function
  3194. getColumns($table){$meta=$this->connection->query("
  3195. SELECT sql FROM sqlite_master WHERE type = 'table' AND name = {$this->connection->quote($table)}
  3196. UNION ALL
  3197. SELECT sql FROM sqlite_temp_master WHERE type = 'table' AND name = {$this->connection->quote($table)}
  3198. ")->fetch();$columns=array();foreach($this->connection->query("PRAGMA table_info({$this->delimite($table)})")as$row){$column=$row['name'];$pattern="/(\"$column\"|\[$column\]|$column)\s+[^,]+\s+PRIMARY\s+KEY\s+AUTOINCREMENT/Ui";$type=explode('(',$row['type']);$columns[]=array('name'=>$column,'table'=>$table,'fullname'=>"$table.$column",'nativetype'=>strtoupper($type[0]),'size'=>isset($type[1])?(int)$type[1]:NULL,'nullable'=>$row['notnull']=='0','default'=>$row['dflt_value'],'autoincrement'=>(bool)preg_match($pattern,$meta['sql']),'primary'=>$row['pk']=='1','vendor'=>(array)$row);}return$columns;}function
  3199. getIndexes($table){$indexes=array();foreach($this->connection->query("PRAGMA index_list({$this->delimite($table)})")as$row){$indexes[$row['name']]['name']=$row['name'];$indexes[$row['name']]['unique']=(bool)$row['unique'];}foreach($indexes
  3200. as$index=>$values){$res=$this->connection->query("PRAGMA index_info({$this->delimite($index)})");while($row=$res->fetch(TRUE)){$indexes[$index]['columns'][$row['seqno']]=$row['name'];}}$columns=$this->getColumns($table);foreach($indexes
  3201. as$index=>$values){$column=$indexes[$index]['columns'][0];$primary=FALSE;foreach($columns
  3202. as$info){if($column==$info['name']){$primary=$info['primary'];break;}}$indexes[$index]['primary']=(bool)$primary;}if(!$indexes){foreach($columns
  3203. as$column){if($column['vendor']['pk']){$indexes[]=array('name'=>'ROWID','unique'=>TRUE,'primary'=>TRUE,'columns'=>array($column['name']));break;}}}return
  3204. array_values($indexes);}function
  3205. getForeignKeys($table){$keys=array();foreach($this->connection->query("PRAGMA foreign_key_list({$this->delimite($table)})")as$row){$keys[$row['id']]['name']=$row['id'];$keys[$row['id']]['local'][$row['seq']]=$row['from'];$keys[$row['id']]['table']=$row['table'];$keys[$row['id']]['foreign'][$row['seq']]=$row['to'];$keys[$row['id']]['onDelete']=$row['on_delete'];$keys[$row['id']]['onUpdate']=$row['on_update'];if($keys[$row['id']]['foreign'][0]==NULL){$keys[$row['id']]['foreign']=NULL;}}return
  3206. array_values($keys);}function
  3207. isSupported($item){return
  3208. FALSE;}}class
  3209. Sqlite2Driver
  3210. extends
  3211. SqliteDriver{function
  3212. formatLike($value,$pos){throw
  3213. new
  3214. Nette\NotSupportedException;}function
  3215. normalizeRow($row,$statement){if(!is_object($row)){$iterator=$row;}elseif($row
  3216. instanceof\Traversable){$iterator=iterator_to_array($row);}else{$iterator=(array)$row;}foreach($iterator
  3217. as$key=>$value){unset($row[$key]);if($key[0]==='['||$key[0]==='"'){$key=substr($key,1,-1);}$row[$key]=$value;}return$row;}function
  3218. getForeignKeys($table){throw
  3219. new
  3220. NotSupportedException;}}}namespace Nette\Database{use
  3221. Nette;class
  3222. Helpers{public
  3223. static$typePatterns=array('^_'=>IReflection::FIELD_TEXT,'BYTEA|BLOB|BIN'=>IReflection::FIELD_BINARY,'TEXT|CHAR'=>IReflection::FIELD_TEXT,'YEAR|BYTE|COUNTER|SERIAL|INT|LONG'=>IReflection::FIELD_INTEGER,'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER'=>IReflection::FIELD_FLOAT,'^TIME$'=>IReflection::FIELD_TIME,'TIME'=>IReflection::FIELD_DATETIME,'DATE'=>IReflection::FIELD_DATE,'BOOL|BIT'=>IReflection::FIELD_BOOL);static
  3224. function
  3225. dumpResult(Statement$statement){echo"\n<table class=\"dump\">\n<caption>".htmlSpecialChars($statement->queryString)."</caption>\n";if(!$statement->columnCount()){echo"\t<tr>\n\t\t<th>Affected rows:</th>\n\t\t<td>",$statement->rowCount(),"</td>\n\t</tr>\n</table>\n";return;}$i=0;foreach($statement
  3226. as$row){if($i===0){echo"<thead>\n\t<tr>\n\t\t<th>#row</th>\n";foreach($row
  3227. as$col=>$foo){echo"\t\t<th>".htmlSpecialChars($col)."</th>\n";}echo"\t</tr>\n</thead>\n<tbody>\n";}echo"\t<tr>\n\t\t<th>",$i,"</th>\n";foreach($row
  3228. as$col){echo"\t\t<td>",htmlSpecialChars($col),"</td>\n";}echo"\t</tr>\n";$i++;}if($i===0){echo"\t<tr>\n\t\t<td><em>empty result set</em></td>\n\t</tr>\n</table>\n";}else{echo"</tbody>\n</table>\n";}}static
  3229. function
  3230. dumpSql($sql){static$keywords1='SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE';static$keywords2='ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';$sql=" $sql ";$sql=preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i","\n\$1",$sql);$sql=preg_replace('#[ \t]{2,}#'," ",$sql);$sql=wordwrap($sql,100);$sql=preg_replace("#([ \t]*\r?\n){2,}#","\n",$sql);$sql=htmlSpecialChars($sql);$sql=preg_replace_callback("#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is",function($matches){if(!empty($matches[1]))return'<em style="color:gray">'.$matches[1].'</em>';if(!empty($matches[2]))return'<strong style="color:red">'.$matches[2].'</strong>';if(!empty($matches[3]))return'<strong style="color:blue">'.$matches[3].'</strong>';if(!empty($matches[4]))return'<strong style="color:green">'.$matches[4].'</strong>';},$sql);return'<pre class="dump">'.trim($sql)."</pre>\n";}static
  3231. function
  3232. detectType($type){static$cache;if(!isset($cache[$type])){$cache[$type]='string';foreach(self::$typePatterns
  3233. as$s=>$val){if(preg_match("#$s#i",$type)){return$cache[$type]=$val;}}}return$cache[$type];}static
  3234. function
  3235. loadFromFile(Connection$connection,$file){@set_time_limit(0);$handle=@fopen($file,'r');if(!$handle){throw
  3236. new
  3237. Nette\FileNotFoundException("Cannot open file '$file'.");}$count=0;$sql='';while(!feof($handle)){$s=fgets($handle);$sql.=$s;if(substr(rtrim($s),-1)===';'){$connection->exec($sql);$sql='';$count++;}}if($sql!==''){$connection->exec($sql);$count++;}fclose($handle);return$count;}}}namespace Nette\Database\Reflection{use
  3238. Nette;class
  3239. ConventionalReflection
  3240. extends
  3241. Nette\Object
  3242. implements
  3243. Nette\Database\IReflection{protected$primary;protected$foreign;protected$table;function
  3244. __construct($primary='id',$foreign='%s_id',$table='%s'){$this->primary=$primary;$this->foreign=$foreign;$this->table=$table;}function
  3245. getPrimary($table){return
  3246. sprintf($this->primary,$this->getColumnFromTable($table));}function
  3247. getHasManyReference($table,$key){$table=$this->getColumnFromTable($table);return
  3248. array(sprintf($this->table,$key,$table),sprintf($this->foreign,$table,$key));}function
  3249. getBelongsToReference($table,$key){$table=$this->getColumnFromTable($table);return
  3250. array(sprintf($this->table,$key,$table),sprintf($this->foreign,$key,$table));}function
  3251. setConnection(Nette\Database\Connection$connection){}protected
  3252. function
  3253. getColumnFromTable($name){if($this->table!=='%s'&&preg_match('(^'.str_replace('%s','(.*)',preg_quote($this->table)).'$)',$name,$match)){return$match[1];}return$name;}}class
  3254. DiscoveredReflection
  3255. extends
  3256. Nette\Object
  3257. implements
  3258. Nette\Database\IReflection{protected$cache;protected$cacheStorage;protected$connection;protected$structure=array('primary'=>array(),'hasMany'=>array(),'belongsTo'=>array());function
  3259. __construct(Nette\Caching\IStorage$storage=NULL){$this->cacheStorage=$storage;}function
  3260. setConnection(Nette\Database\Connection$connection){$this->connection=$connection;if($this->cacheStorage){$this->cache=new
  3261. Nette\Caching\Cache($this->cacheStorage,'Nette.Database.'.md5($connection->getDsn()));$this->structure=$this->cache->load('structure')?:$this->structure;}}function
  3262. __destruct(){if($this->cache){$this->cache->save('structure',$this->structure);}}function
  3263. getPrimary($table){$primary=&$this->structure['primary'][$table];if(isset($primary)){return
  3264. empty($primary)?NULL:$primary;}$columns=$this->connection->getSupplementalDriver()->getColumns($table);$primaryCount=0;foreach($columns
  3265. as$column){if($column['primary']){$primary=$column['name'];$primaryCount++;}}if($primaryCount!==1){$primary='';return
  3266. NULL;}return$primary;}function
  3267. getHasManyReference($table,$key,$refresh=TRUE){$reference=$this->structure['hasMany'];if(!empty($reference[$table])){foreach($reference[$table]as$targetTable=>$targetColumn){if(stripos($targetTable,$key)!==FALSE){return
  3268. array($targetTable,$targetColumn);}}}if(!$refresh){throw
  3269. new\PDOException("No reference found for \${$table}->related({$key}).");}$this->reloadAllForeignKeys();return$this->getHasManyReference($table,$key,FALSE);}function
  3270. getBelongsToReference($table,$key,$refresh=TRUE){$reference=$this->structure['belongsTo'];if(!empty($reference[$table])){foreach($reference[$table]as$column=>$targetTable){if(stripos($column,$key)!==FALSE){return
  3271. array($targetTable,$column);}}}if(!$refresh){throw
  3272. new\PDOException("No reference found for \${$table}->{$key}.");}$this->reloadForeignKeys($table);return$this->getBelongsToReference($table,$key,FALSE);}protected
  3273. function
  3274. reloadAllForeignKeys(){foreach($this->connection->getSupplementalDriver()->getTables()as$table){if($table['view']==FALSE){$this->reloadForeignKeys($table['name']);}}foreach(array_keys($this->structure['hasMany'])as$table){uksort($this->structure['hasMany'][$table],function($a,$b){return
  3275. strlen($a)-strlen($b);});}}protected
  3276. function
  3277. reloadForeignKeys($table){foreach($this->connection->getSupplementalDriver()->getForeignKeys($table)as$row){$this->structure['belongsTo'][$table][$row['local']]=$row['table'];$this->structure['hasMany'][$row['table']][$table]=$row['local'];}if(isset($this->structure['belongsTo'][$table])){uksort($this->structure['belongsTo'][$table],function($a,$b){return
  3278. strlen($a)-strlen($b);});}}}}namespace Nette\Database{use
  3279. Nette;class
  3280. Row
  3281. extends
  3282. Nette\ArrayHash{function
  3283. __construct(Statement$statement){$statement->normalizeRow($this);}function
  3284. offsetGet($key){if(is_int($key)){$arr=array_values((array)$this);return$arr[$key];}return$this->$key;}}class
  3285. SqlLiteral
  3286. extends
  3287. Nette\Object{private$value='';function
  3288. __construct($value){$this->value=(string)$value;}function
  3289. __toString(){return$this->value;}}class
  3290. SqlPreprocessor
  3291. extends
  3292. Nette\Object{private$connection;private$driver;private$params;private$remaining;private$counter;private$arrayMode;function
  3293. __construct(Connection$connection){$this->connection=$connection;$this->driver=$connection->getSupplementalDriver();}function
  3294. process($sql,$params){$this->params=$params;$this->counter=0;$this->remaining=array();$cmd=strtoupper(substr(ltrim($sql),0,6));$this->arrayMode=$cmd==='INSERT'||$cmd==='REPLAC'?'values':'assoc';$sql=Nette\Utils\Strings::replace($sql,'~\'.*?\'|".*?"|\?~s',array($this,'callback'));while($this->counter<count($params)){$sql.=' '.$this->formatValue($params[$this->counter++]);}return
  3295. array($sql,$this->remaining);}function
  3296. callback($m){$m=$m[0];if($m[0]==="'"||$m[0]==='"'){return$m;}else{return$this->formatValue($this->params[$this->counter++]);}}private
  3297. function
  3298. formatValue($value){if(is_string($value)){if(strlen($value)>20){$this->remaining[]=$value;return'?';}else{return$this->connection->quote($value);}}elseif(is_int($value)){return(string)$value;}elseif(is_float($value)){return
  3299. rtrim(rtrim(number_format($value,10,'.',''),'0'),'.');}elseif(is_bool($value)){$this->remaining[]=$value;return'?';}elseif($value===NULL){return'NULL';}elseif($value
  3300. instanceof
  3301. Table\ActiveRow){return$value->getPrimary();}elseif(is_array($value)||$value
  3302. instanceof\Traversable){$vx=$kx=array();if(isset($value[0])){foreach($value
  3303. as$v){$vx[]=$this->formatValue($v);}return
  3304. implode(', ',$vx);}elseif($this->arrayMode==='values'){$this->arrayMode='multi';foreach($value
  3305. as$k=>$v){$kx[]=$this->driver->delimite($k);$vx[]=$this->formatValue($v);}return'('.implode(', ',$kx).') VALUES ('.implode(', ',$vx).')';}elseif($this->arrayMode==='assoc'){foreach($value
  3306. as$k=>$v){$vx[]=$this->driver->delimite($k).'='.$this->formatValue($v);}return
  3307. implode(', ',$vx);}elseif($this->arrayMode==='multi'){foreach($value
  3308. as$k=>$v){$vx[]=$this->formatValue($v);}return'('.implode(', ',$vx).')';}}elseif($value
  3309. instanceof\DateTime){return$this->driver->formatDateTime($value);}elseif($value
  3310. instanceof
  3311. SqlLiteral){return$value->__toString();}else{$this->remaining[]=$value;return'?';}}}use
  3312. PDO;use
  3313. Nette\ObjectMixin;if(class_exists('PDO')){class
  3314. Statement
  3315. extends\PDOStatement{private$connection;private$time;private$types;protected
  3316. function
  3317. __construct(Connection$connection){$this->connection=$connection;$this->setFetchMode(PDO::FETCH_CLASS,'Nette\Database\Row',array($this));}function
  3318. getConnection(){return$this->connection;}function
  3319. execute($params=array()){static$types=array('boolean'=>PDO::PARAM_BOOL,'integer'=>PDO::PARAM_INT,'resource'=>PDO::PARAM_LOB,'NULL'=>PDO::PARAM_NULL);foreach($params
  3320. as$key=>$value){$type=gettype($value);$this->bindValue(is_int($key)?$key+1:$key,$value,isset($types[$type])?$types[$type]:PDO::PARAM_STR);}$time=microtime(TRUE);try{parent::execute();}catch(\PDOException$e){$e->queryString=$this->queryString;throw$e;}$this->time=microtime(TRUE)-$time;$this->connection->__call('onQuery',array($this,$params));return$this;}function
  3321. fetchPairs(){return$this->fetchAll(PDO::FETCH_KEY_PAIR);}function
  3322. normalizeRow($row){foreach($this->detectColumnTypes()as$key=>$type){$value=$row[$key];if($value===NULL||$value===FALSE||$type===IReflection::FIELD_TEXT){}elseif($type===IReflection::FIELD_INTEGER){$row[$key]=is_float($tmp=$value*1)?$value:$tmp;}elseif($type===IReflection::FIELD_FLOAT){$row[$key]=(string)($tmp=(float)$value)===$value?$tmp:$value;}elseif($type===IReflection::FIELD_BOOL){$row[$key]=((bool)$value)&&$value!=='f'&&$value!=='F';}elseif($type===IReflection::FIELD_DATETIME||$type===IReflection::FIELD_DATE||$type===IReflection::FIELD_TIME){$row[$key]=new
  3323. Nette\DateTime($value);}}return$this->connection->getSupplementalDriver()->normalizeRow($row,$this);}private
  3324. function
  3325. detectColumnTypes(){if($this->types===NULL){$this->types=array();if($this->connection->getSupplementalDriver()->isSupported(ISupplementalDriver::META)){$col=0;while($meta=$this->getColumnMeta($col++)){if(isset($meta['native_type'])){$this->types[$meta['name']]=Helpers::detectType($meta['native_type']);}}}}return$this->types;}function
  3326. getTime(){return$this->time;}function
  3327. dump(){Helpers::dumpResult($this);}static
  3328. function
  3329. getReflection(){return
  3330. new
  3331. Nette\Reflection\ClassType(get_called_class());}function
  3332. __call($name,$args){return
  3333. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  3334. ObjectMixin::get($this,$name);}function
  3335. __set($name,$value){return
  3336. ObjectMixin::set($this,$name,$value);}function
  3337. __isset($name){return
  3338. ObjectMixin::has($this,$name);}function
  3339. __unset($name){ObjectMixin::remove($this,$name);}}}}namespace Nette\Database\Table{use
  3340. Nette;class
  3341. ActiveRow
  3342. extends
  3343. Nette\Object
  3344. implements\IteratorAggregate,\ArrayAccess{private$table;private$data;private$modified=array();function
  3345. __construct(array$data,Selection$table){$this->data=$data;$this->table=$table;}function
  3346. getTable(){return$this->table;}function
  3347. __toString(){try{return(string)$this->getPrimary();}catch(\Exception$e){Nette\Diagnostics\Debugger::toStringException($e);}}function
  3348. toArray(){$this->access(NULL);return$this->data;}function
  3349. getPrimary(){if(!isset($this->data[$this->table->getPrimary()])){throw
  3350. new
  3351. Nette\NotSupportedException("Table {$this->table->getName()} does not have any primary key.");}return$this[$this->table->getPrimary()];}function
  3352. ref($key,$throughColumn=NULL){if(!$throughColumn){list($key,$throughColumn)=$this->table->getConnection()->getDatabaseReflection()->getBelongsToReference($this->table->getName(),$key);}return$this->getReference($key,$throughColumn);}function
  3353. related($key,$throughColumn=NULL,$forceNewInstance=FALSE){if(strpos($key,'.')!==FALSE){list($key,$throughColumn)=explode('.',$key);}elseif(!is_string($throughColumn)){list($key,$throughColumn)=$this->table->getConnection()->getDatabaseReflection()->getHasManyReference($this->table->getName(),$key);}return$this->table->getReferencingTable($key,$throughColumn,$this[$this->table->getPrimary()],$forceNewInstance);}function
  3354. update($data=NULL){if($data===NULL){$data=$this->modified;}return$this->table->getConnection()->table($this->table->getName())->where($this->table->getPrimary(),$this[$this->table->getPrimary()])->update($data);}function
  3355. delete(){return$this->table->getConnection()->table($this->table->getName())->where($this->table->getPrimary(),$this[$this->table->getPrimary()])->delete();}function
  3356. getIterator(){$this->access(NULL);return
  3357. new\ArrayIterator($this->data);}function
  3358. offsetSet($key,$value){$this->__set($key,$value);}function
  3359. offsetGet($key){return$this->__get($key);}function
  3360. offsetExists($key){return$this->__isset($key);}function
  3361. offsetUnset($key){$this->__unset($key);}function
  3362. __set($key,$value){$this->data[$key]=$value;$this->modified[$key]=$value;}function&__get($key){$this->access($key);if(array_key_exists($key,$this->data)){return$this->data[$key];}list($table,$column)=$this->table->getConnection()->getDatabaseReflection()->getBelongsToReference($this->table->getName(),$key);$referenced=$this->getReference($table,$column);if($referenced!==FALSE){$this->access($key,FALSE);return$referenced;}$this->access($key,NULL);throw
  3363. new
  3364. Nette\MemberAccessException("Cannot read an undeclared column \"$key\".");}function
  3365. __isset($key){$this->access($key);if(array_key_exists($key,$this->data)){return
  3366. isset($this->data[$key]);}$this->access($key,NULL);return
  3367. FALSE;}function
  3368. __unset($key){unset($this->data[$key]);unset($this->modified[$key]);}function
  3369. access($key,$cache=TRUE){if($this->table->getConnection()->getCache()&&!isset($this->modified[$key])&&$this->table->access($key,$cache)){$id=(isset($this->data[$this->table->getPrimary()])?$this->data[$this->table->getPrimary()]:$this->data);$this->data=$this->table[$id]->data;}}protected
  3370. function
  3371. getReference($table,$column){if(array_key_exists($column,$this->data)){$this->access($column);$value=$this->data[$column];$value=$value
  3372. instanceof
  3373. ActiveRow?$value->getPrimary():$value;$referenced=$this->table->getReferencedTable($table,$column,!empty($this->modified[$column]));$referenced=isset($referenced[$value])?$referenced[$value]:NULL;if(!empty($this->modified[$column])){$this->modified[$column]=0;}return$referenced;}return
  3374. FALSE;}}use
  3375. PDO;class
  3376. Selection
  3377. extends
  3378. Nette\Object
  3379. implements\Iterator,\ArrayAccess,\Countable{protected$connection;protected$name;protected$primary;protected$rows;protected$data;protected$select=array();protected$where=array();protected$conditions=array();protected$parameters=array();protected$order=array();protected$limit=NULL;protected$offset=NULL;protected$group='';protected$having='';protected$checkReferenceNewKeys=FALSE;protected$referenced=array();protected$referencing=array();protected$accessed;protected$prevAccessed;protected$keys=array();protected$delimitedName;protected$delimitedPrimary;function
  3380. __construct($table,Nette\Database\Connection$connection){$this->name=$table;$this->connection=$connection;$this->primary=$connection->getDatabaseReflection()->getPrimary($table);$this->delimitedName=$this->tryDelimite($this->name);$this->delimitedPrimary=$connection->getSupplementalDriver()->delimite($this->primary);}function
  3381. __destruct(){$cache=$this->connection->getCache();if($cache&&!$this->select&&$this->rows!==NULL){$cache->save(array(__CLASS__,$this->name,$this->conditions),$this->accessed);}$this->rows=NULL;}function
  3382. getConnection(){return$this->connection;}function
  3383. getName(){return$this->name;}function
  3384. getPrimary(){return$this->primary;}function
  3385. get($key){$clone=clone$this;$clone->where($this->delimitedPrimary,$key);return$clone->fetch();}function
  3386. select($columns){$this->__destruct();$this->select[]=$columns;return$this;}function
  3387. find($key){return$this->where($this->delimitedPrimary,$key);}function
  3388. where($condition,$parameters=array()){if(is_array($condition)){foreach($condition
  3389. as$key=>$val){if(is_int($key)){$this->where($val);}else{$this->where($key,$val);}}return$this;}$hash=md5(json_encode(func_get_args()));if(isset($this->conditions[$hash])){return$this;}$this->__destruct();$this->conditions[$hash]=$condition;$condition=$this->removeExtraTables($condition);$condition=$this->tryDelimite($condition);$args=func_num_args();if($args!==2||strpbrk($condition,'?:')){if($args!==2||!is_array($parameters)){$parameters=func_get_args();array_shift($parameters);}$this->parameters=array_merge($this->parameters,$parameters);}elseif($parameters===NULL){$condition.=' IS NULL';}elseif($parameters
  3390. instanceof
  3391. Selection){$clone=clone$parameters;if(!$clone->select){$clone->select=array($clone->primary);}if($this->connection->getAttribute(PDO::ATTR_DRIVER_NAME)!=='mysql'){$condition.=' IN ('.$clone->getSql().')';}else{$in=array();foreach($clone
  3392. as$row){$this->parameters[]=array_values(iterator_to_array($row));$in[]=(count($row)===1?'?':'(?)');}$condition.=' IN ('.($in?implode(', ',$in):'NULL').')';}}elseif(!is_array($parameters)){$condition.=' = ?';$this->parameters[]=$parameters;}else{if($parameters){$condition.=" IN (?)";$this->parameters[]=$parameters;}else{$condition.=" IN (NULL)";}}$this->where[]=$condition;return$this;}function
  3393. order($columns){$this->rows=NULL;$this->order[]=$columns;return$this;}function
  3394. limit($limit,$offset=NULL){$this->rows=NULL;$this->limit=$limit;$this->offset=$offset;return$this;}function
  3395. page($page,$itemsPerPage){$this->rows=NULL;$this->limit=$itemsPerPage;$this->offset=($page-1)*$itemsPerPage;return$this;}function
  3396. group($columns,$having=''){$this->__destruct();$this->group=$columns;$this->having=$having;return$this;}function
  3397. aggregation($function){$selection=new
  3398. Selection($this->name,$this->connection);$selection->where=$this->where;$selection->parameters=$this->parameters;$selection->conditions=$this->conditions;$selection->select($function);foreach($selection->fetch()as$val){return$val;}}function
  3399. count($column=''){if(!$column){$this->execute();return
  3400. count($this->data);}return$this->aggregation("COUNT($column)");}function
  3401. min($column){return$this->aggregation("MIN($column)");}function
  3402. max($column){return$this->aggregation("MAX($column)");}function
  3403. sum($column){return$this->aggregation("SUM($column)");}function
  3404. getSql(){$join=$this->createJoins(implode(',',$this->conditions),TRUE)+$this->createJoins(implode(',',$this->select).",$this->group,$this->having,".implode(',',$this->order));$cache=$this->connection->getCache();if($this->rows===NULL&&$cache&&!is_string($this->prevAccessed)){$this->accessed=$this->prevAccessed=$cache->load(array(__CLASS__,$this->name,$this->conditions));}$prefix=$join?"$this->delimitedName.":'';if($this->select){$cols=$this->tryDelimite($this->removeExtraTables(implode(', ',$this->select)));}elseif($this->prevAccessed){$cols=array_map(array($this->connection->getSupplementalDriver(),'delimite'),array_keys(array_filter($this->prevAccessed)));$cols=$prefix.implode(', '.$prefix,$cols);}else{$cols=$prefix.'*';}return"SELECT{$this->topString()} $cols FROM $this->delimitedName".implode($join).$this->whereString();}protected
  3405. function
  3406. createJoins($val,$inner=FALSE){$driver=$this->connection->getSupplementalDriver();$reflection=$this->connection->getDatabaseReflection();$joins=array();preg_match_all('~\\b([a-z][\\w.:]*[.:])([a-z]\\w*|\*)(\\s+IS\\b|\\s*<=>)?~i',$val,$matches);foreach($matches[1]as$names){$parent=$this->name;if($names!=="$parent."){preg_match_all('~\\b([a-z][\\w]*|\*)([.:])~i',$names,$matches,PREG_SET_ORDER);foreach($matches
  3407. as$match){list(,$name,$delimiter)=$match;if($delimiter===':'){list($table,$primary)=$reflection->getHasManyReference($parent,$name);$column=$reflection->getPrimary($parent);}else{list($table,$column)=$reflection->getBelongsToReference($parent,$name);$primary=$reflection->getPrimary($table);}$joins[$name]=' '.(!isset($joins[$name])&&$inner&&!isset($match[3])?'INNER':'LEFT').' JOIN '.$driver->delimite($table).($table!==$name?' AS '.$driver->delimite($name):'').' ON '.$driver->delimite($parent).'.'.$driver->delimite($column).' = '.$driver->delimite($name).'.'.$driver->delimite($primary);$parent=$name;}}}return$joins;}protected
  3408. function
  3409. execute(){if($this->rows!==NULL){return;}try{$result=$this->query($this->getSql());}catch(\PDOException$exception){if(!$this->select&&$this->prevAccessed){$this->prevAccessed='';$this->accessed=array();$result=$this->query($this->getSql());}else{throw$exception;}}$this->rows=array();$result->setFetchMode(PDO::FETCH_ASSOC);foreach($result
  3410. as$key=>$row){$row=$result->normalizeRow($row);$this->rows[isset($row[$this->primary])?$row[$this->primary]:$key]=$this->createRow($row);}$this->data=$this->rows;if(isset($row[$this->primary])&&!is_string($this->accessed)){$this->accessed[$this->primary]=TRUE;}}protected
  3411. function
  3412. createRow(array$row){return
  3413. new
  3414. ActiveRow($row,$this);}protected
  3415. function
  3416. whereString(){$return='';$driver=$this->connection->getAttribute(PDO::ATTR_DRIVER_NAME);$where=$this->where;if($this->limit!==NULL&&$driver==='oci'){$where[]=($this->offset?"rownum > $this->offset AND ":'').'rownum <= '.($this->limit+$this->offset);}if($where){$return.=' WHERE ('.implode(') AND (',$where).')';}if($this->group){$return.=' GROUP BY '.$this->tryDelimite($this->removeExtraTables($this->group));}if($this->having){$return.=' HAVING '.$this->tryDelimite($this->removeExtraTables($this->having));}if($this->order){$return.=' ORDER BY '.$this->tryDelimite($this->removeExtraTables(implode(', ',$this->order)));}if($this->limit!==NULL&&$driver!=='oci'&&$driver!=='dblib'){$return.=" LIMIT $this->limit";if($this->offset!==NULL){$return.=" OFFSET $this->offset";}}return$return;}protected
  3417. function
  3418. topString(){if($this->limit!==NULL&&$this->connection->getAttribute(PDO::ATTR_DRIVER_NAME)==='dblib'){return" TOP ($this->limit)";}return'';}protected
  3419. function
  3420. tryDelimite($s){$driver=$this->connection->getSupplementalDriver();return
  3421. preg_replace_callback('#(?<=[^\w`"\[]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|$)#i',function($m)use($driver){return
  3422. strtoupper($m[0])===$m[0]?$m[0]:$driver->delimite($m[0]);},$s);}protected
  3423. function
  3424. removeExtraTables($expression){return
  3425. preg_replace('~(?:\\b[a-z_][a-z0-9_.:]*[.:])?([a-z_][a-z0-9_]*)[.:]([a-z_*])~i','\\1.\\2',$expression);}protected
  3426. function
  3427. query($query){return$this->connection->queryArgs($query,$this->parameters);}function
  3428. access($key,$cache=TRUE){if($cache===NULL){if(is_array($this->accessed)){$this->accessed[$key]=FALSE;}return
  3429. FALSE;}if($key===NULL){$this->accessed='';}elseif(!is_string($this->accessed)){$this->accessed[$key]=$cache;}if($cache&&!$this->select&&$this->prevAccessed&&($key===NULL||!isset($this->prevAccessed[$key]))){$this->prevAccessed='';$this->__destruct();return
  3430. TRUE;}return
  3431. FALSE;}function
  3432. insert($data){if($data
  3433. instanceof
  3434. Selection){$data=$data->getSql();}elseif($data
  3435. instanceof\Traversable){$data=iterator_to_array($data);}$return=$this->connection->query("INSERT INTO $this->delimitedName",$data);if(!is_array($data)){return$return->rowCount();}$this->checkReferenceNewKeys=TRUE;if(!isset($data[$this->primary])&&($id=$this->connection->lastInsertId())){$data[$this->primary]=$id;return$this->rows[$id]=new
  3436. ActiveRow($data,$this);}else{return
  3437. new
  3438. ActiveRow($data,$this);}}function
  3439. update($data){if($data
  3440. instanceof\Traversable){$data=iterator_to_array($data);}elseif(!is_array($data)){throw
  3441. new
  3442. Nette\InvalidArgumentException;}if(!$data){return
  3443. 0;}return$this->connection->queryArgs('UPDATE'.$this->topString()." $this->delimitedName SET ?".$this->whereString(),array_merge(array($data),$this->parameters))->rowCount();}function
  3444. delete(){return$this->query('DELETE'.$this->topString()." FROM $this->delimitedName".$this->whereString())->rowCount();}function
  3445. getReferencedTable($table,$column,$checkReferenceNewKeys=FALSE){$referenced=&$this->referenced["$table.$column"];if($referenced===NULL||$checkReferenceNewKeys||$this->checkReferenceNewKeys){$keys=array();foreach($this->rows
  3446. as$row){if($row[$column]===NULL)continue;$key=$row[$column]instanceof
  3447. ActiveRow?$row[$column]->getPrimary():$row[$column];$keys[$key]=TRUE;}if($referenced!==NULL&&$keys===array_keys($this->rows)){$this->checkReferenceNewKeys=FALSE;return$referenced;}if($keys){$referenced=new
  3448. Selection($table,$this->connection);$referenced->where($table.'.'.$referenced->primary,array_keys($keys));}else{$referenced=array();}}return$referenced;}function
  3449. getReferencingTable($table,$column,$active=NULL,$forceNewInstance=FALSE){$referencing=&$this->referencing["$table:$column"];if(!$referencing||$forceNewInstance){$referencing=new
  3450. GroupedSelection($table,$this,$column);$referencing->where("$table.$column",array_keys((array)$this->rows));}return$referencing->setActive($active);}function
  3451. rewind(){$this->execute();$this->keys=array_keys($this->data);reset($this->keys);}function
  3452. current(){return$this->data[current($this->keys)];}function
  3453. key(){return
  3454. current($this->keys);}function
  3455. next(){next($this->keys);}function
  3456. valid(){return
  3457. current($this->keys)!==FALSE;}function
  3458. offsetSet($key,$value){$this->execute();$this->data[$key]=$value;}function
  3459. offsetGet($key){$this->execute();return$this->data[$key];}function
  3460. offsetExists($key){$this->execute();return
  3461. isset($this->data[$key]);}function
  3462. offsetUnset($key){$this->execute();unset($this->data[$key]);}function
  3463. fetch(){$this->execute();$return=current($this->data);next($this->data);return$return;}function
  3464. fetchPairs($key,$value=''){$return=array();foreach($this
  3465. as$row){$return[is_object($row[$key])?(string)$row[$key]:$row[$key]]=($value!==''?$row[$value]:$row);}return$return;}}class
  3466. GroupedSelection
  3467. extends
  3468. Selection{protected$refTable;protected$column;protected$delimitedColumn;protected$active;protected$referencing;protected$aggregation=array();function
  3469. __construct($name,Selection$refTable,$column){parent::__construct($name,$refTable->connection);$this->refTable=$refTable;$this->column=$column;$this->delimitedColumn=$this->connection->getSupplementalDriver()->delimite($this->column);}function
  3470. setActive($active){$this->rows=NULL;$this->active=$active;$this->select=$this->where=$this->conditions=$this->parameters=$this->order=array();$this->limit=$this->offset=NULL;$this->group=$this->having='';return$this;}function
  3471. through($column){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::related("'.$this->name.'", "'.$column.'") instead.',E_USER_WARNING);$this->column=$column;$this->delimitedColumn=$this->refTable->connection->getSupplementalDriver()->delimite($this->column);return$this;}function
  3472. select($columns){if(!$this->select){$this->select[]="$this->delimitedName.$this->delimitedColumn";}return
  3473. parent::select($columns);}function
  3474. order($columns){if(!$this->order){$this->order[]="$this->delimitedName.$this->delimitedColumn".(preg_match('~\\bDESC$~i',$columns)?' DESC':'');}return
  3475. parent::order($columns);}function
  3476. aggregation($function){$aggregation=&$this->aggregation[$function.implode('',$this->where).implode('',$this->conditions)];if($aggregation===NULL){$aggregation=array();$selection=new
  3477. Selection($this->name,$this->connection);$selection->where=$this->where;$selection->parameters=$this->parameters;$selection->conditions=$this->conditions;$selection->select($function);$selection->select("{$this->name}.{$this->column}");$selection->group("{$this->name}.{$this->column}");foreach($selection
  3478. as$row){$aggregation[$row[$this->column]]=$row;}}if(isset($aggregation[$this->active])){foreach($aggregation[$this->active]as$val){return$val;}}}function
  3479. count($column=''){$return=parent::count($column);return
  3480. isset($return)?$return:0;}function
  3481. insert($data){if($data
  3482. instanceof\Traversable&&!$data
  3483. instanceof
  3484. Selection){$data=iterator_to_array($data);}if(Nette\Utils\Validators::isList($data)){foreach(array_keys($data)as$key){$data[$key][$this->column]=$this->active;}}else{$data[$this->column]=$this->active;}return
  3485. parent::insert($data);}function
  3486. update($data){$condition=array($this->where,$this->parameters);$this->where[0]="$this->delimitedColumn = ?";$this->parameters[0]=$this->active;$return=parent::update($data);list($this->where,$this->parameters)=$condition;return$return;}function
  3487. delete(){$condition=array($this->where,$this->parameters);$this->where[0]="$this->delimitedColumn = ?";$this->parameters[0]=$this->active;$return=parent::delete();list($this->where,$this->parameters)=$condition;return$return;}protected
  3488. function
  3489. execute(){if($this->rows!==NULL){return;}$hash=md5($this->getSql().json_encode($this->parameters));$referencing=&$this->referencing[$hash];if($referencing===NULL){$limit=$this->limit;$rows=count($this->refTable->rows);if($this->limit&&$rows>1){$this->limit=NULL;}parent::execute();$this->limit=$limit;$referencing=array();$offset=array();foreach($this->rows
  3490. as$key=>$row){$ref=&$referencing[$row[$this->column]];$skip=&$offset[$row[$this->column]];if($limit===NULL||$rows<=1||(count($ref)<$limit&&$skip>=$this->offset)){$ref[$key]=$row;}else{unset($this->rows[$key]);}$skip++;unset($ref,$skip);}}$this->data=&$referencing[$this->active];if($this->data===NULL){$this->data=array();}else{reset($this->data);}}}}namespace Nette\DI{use
  3491. Nette;class
  3492. Container
  3493. extends
  3494. Nette\FreezableObject
  3495. implements
  3496. IContainer{const
  3497. TAGS='tags';public$parameters=array();public$params=array();public$classes=array();private$registry=array();private$factories=array();public$meta=array();private$creating;function
  3498. __construct(array$params=array()){$this->parameters=$params+$this->parameters;$this->params=&$this->parameters;}function
  3499. getParameters(){return$this->parameters;}function
  3500. addService($name,$service,array$meta=NULL){$this->updating();if(!is_string($name)||$name===''){throw
  3501. new
  3502. Nette\InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}if(isset($this->registry[$name])){throw
  3503. new
  3504. Nette\InvalidStateException("Service '$name' has already been registered.");}if(is_object($service)&&!$service
  3505. instanceof\Closure&&!$service
  3506. instanceof
  3507. Nette\Callback){$this->registry[$name]=$service;$this->meta[$name]=$meta;return$this;}elseif(!is_string($service)||strpos($service,':')!==FALSE){$service=callback($service);}$this->factories[$name]=array($service);$this->registry[$name]=&$this->factories[$name][1];$this->meta[$name]=$meta;return$this;}function
  3508. removeService($name){$this->updating();unset($this->registry[$name],$this->factories[$name],$this->meta[$name]);}function
  3509. getService($name){if(isset($this->registry[$name])){return$this->registry[$name];}elseif(isset($this->creating[$name])){throw
  3510. new
  3511. Nette\InvalidStateException("Circular reference detected for services: ".implode(', ',array_keys($this->creating)).".");}if(isset($this->factories[$name])){list($factory)=$this->factories[$name];if(is_string($factory)){if(!class_exists($factory)){throw
  3512. new
  3513. Nette\InvalidStateException("Cannot instantiate service, class '$factory' not found.");}try{$this->creating[$name]=TRUE;$service=new$factory;}catch(\Exception$e){}}elseif(!$factory->isCallable()){throw
  3514. new
  3515. Nette\InvalidStateException("Unable to create service '$name', factory '$factory' is not callable.");}else{$this->creating[$name]=TRUE;try{$service=$factory($this);}catch(\Exception$e){}}}elseif(method_exists($this,$factory=Container::getMethodName($name))&&$this->getReflection()->getMethod($factory)->getName()===$factory){$this->creating[$name]=TRUE;try{$service=$this->$factory();}catch(\Exception$e){}}else{throw
  3516. new
  3517. MissingServiceException("Service '$name' not found.");}unset($this->creating[$name]);if(isset($e)){throw$e;}elseif(!is_object($service)){throw
  3518. new
  3519. Nette\UnexpectedValueException("Unable to create service '$name', value returned by factory '$factory' is not object.");}return$this->registry[$name]=$service;}function
  3520. hasService($name){return
  3521. isset($this->registry[$name])||isset($this->factories[$name])||method_exists($this,$method=Container::getMethodName($name))&&$this->getReflection()->getMethod($method)->getName()===$method;}function
  3522. isCreated($name){if(!$this->hasService($name)){throw
  3523. new
  3524. MissingServiceException("Service '$name' not found.");}return
  3525. isset($this->registry[$name]);}function
  3526. getByType($class,$need=TRUE){$lower=ltrim(strtolower($class),'\\');if(!isset($this->classes[$lower])){if($need){throw
  3527. new
  3528. MissingServiceException("Service of type $class not found.");}}elseif($this->classes[$lower]===FALSE){throw
  3529. new
  3530. MissingServiceException("Multiple services of type $class found.");}else{return$this->getService($this->classes[$lower]);}}function
  3531. findByTag($tag){$found=array();foreach($this->meta
  3532. as$name=>$meta){if(isset($meta[self::TAGS][$tag])){$found[$name]=$meta[self::TAGS][$tag];}}return$found;}function
  3533. createInstance($class,array$args=array()){$rc=Nette\Reflection\ClassType::from($class);if(!$rc->isInstantiable()){throw
  3534. new
  3535. Nette\InvalidArgumentException("Class $class is not instantiable.");}elseif($constructor=$rc->getConstructor()){return$rc->newInstanceArgs(Helpers::autowireArguments($constructor,$args,$this));}elseif($args){throw
  3536. new
  3537. Nette\InvalidArgumentException("Unable to pass arguments, class $class has no constructor.");}return
  3538. new$class;}function
  3539. callMethod($function,array$args=array()){$callback=callback($function);return$callback->invokeArgs(Helpers::autowireArguments($callback->toReflection(),$args,$this));}function
  3540. expand($s){return
  3541. Helpers::expand($s,$this->parameters);}function&__get($name){if(!isset($this->registry[$name])){$this->getService($name);}return$this->registry[$name];}function
  3542. __set($name,$service){$this->updating();if(!is_string($name)||$name===''){throw
  3543. new
  3544. Nette\InvalidArgumentException("Service name must be a non-empty string, ".gettype($name)." given.");}elseif(isset($this->registry[$name])){throw
  3545. new
  3546. Nette\InvalidStateException("Service '$name' has already been registered.");}elseif(!is_object($service)){throw
  3547. new
  3548. Nette\InvalidArgumentException("Service must be a object, ".gettype($service)." given.");}$this->registry[$name]=$service;}function
  3549. __isset($name){return$this->hasService($name);}function
  3550. __unset($name){$this->removeService($name);}static
  3551. function
  3552. getMethodName($name,$isService=TRUE){$uname=ucfirst($name);return($isService?'createService':'create').($name===$uname?'__':'').str_replace('.','__',$uname);}}use
  3553. Nette\Utils\Validators;use
  3554. Nette\Utils\Strings;use
  3555. Nette\Utils\PhpGenerator\Helpers as PhpHelpers;use
  3556. Nette\Utils\PhpGenerator\PhpLiteral;class
  3557. ContainerBuilder
  3558. extends
  3559. Nette\Object{const
  3560. CREATED_SERVICE='self',THIS_CONTAINER='container';public$parameters=array();private$definitions=array();private$classes;private$dependencies=array();function
  3561. addDefinition($name){if(isset($this->definitions[$name])){throw
  3562. new
  3563. Nette\InvalidStateException("Service '$name' has already been added.");}return$this->definitions[$name]=new
  3564. ServiceDefinition;}function
  3565. removeDefinition($name){unset($this->definitions[$name]);}function
  3566. getDefinition($name){if(!isset($this->definitions[$name])){throw
  3567. new
  3568. MissingServiceException("Service '$name' not found.");}return$this->definitions[$name];}function
  3569. getDefinitions(){return$this->definitions;}function
  3570. hasDefinition($name){return
  3571. isset($this->definitions[$name]);}function
  3572. getByType($class){$lower=ltrim(strtolower($class),'\\');if(!isset($this->classes[$lower])){return;}elseif(count($this->classes[$lower])===1){return$this->classes[$lower][0];}else{throw
  3573. new
  3574. ServiceCreationException("Multiple services of type $class found: ".implode(', ',$this->classes[$lower]));}}function
  3575. findByTag($tag){$found=array();foreach($this->definitions
  3576. as$name=>$def){if(isset($def->tags[$tag])&&$def->shared){$found[$name]=$def->tags[$tag];}}return$found;}function
  3577. autowireArguments($class,$method,array$arguments){$rc=Nette\Reflection\ClassType::from($class);if(!$rc->hasMethod($method)){if(!Nette\Utils\Validators::isList($arguments)){throw
  3578. new
  3579. ServiceCreationException("Unable to pass specified arguments to $class::$method().");}return$arguments;}$rm=$rc->getMethod($method);if($rm->isAbstract()||!$rm->isPublic()){throw
  3580. new
  3581. ServiceCreationException("$rm is not callable.");}$this->addDependency($rm->getFileName());return
  3582. Helpers::autowireArguments($rm,$arguments,$this);}function
  3583. prepareClassList(){foreach($this->definitions
  3584. as$name=>$def){if($def->class===self::CREATED_SERVICE||($def->factory&&$def->factory->entity===self::CREATED_SERVICE)){$def->class=$name;$def->internal=TRUE;if($def->factory&&$def->factory->entity===self::CREATED_SERVICE){$def->factory->entity=$def->class;}unset($this->definitions[$name]);$this->definitions['_anonymous_'.str_replace('\\','_',strtolower(trim($name,'\\')))]=$def;}if($def->class){$def->class=$this->expand($def->class);if(!$def->factory){$def->factory=new
  3585. Statement($def->class);}}elseif(!$def->factory){throw
  3586. new
  3587. ServiceCreationException("Class and factory are missing in service '$name' definition.");}}$this->classes=FALSE;foreach($this->definitions
  3588. as$name=>$def){$this->resolveClass($name);}$this->classes=array();foreach($this->definitions
  3589. as$name=>$def){if(!$def->class){continue;}if(!class_exists($def->class)&&!interface_exists($def->class)){throw
  3590. new
  3591. Nette\InvalidStateException("Class $def->class has not been found.");}$def->class=Nette\Reflection\ClassType::from($def->class)->getName();if($def->autowired){foreach(class_parents($def->class)+class_implements($def->class)+array($def->class)as$parent){$this->classes[strtolower($parent)][]=$name;}}}foreach($this->classes
  3592. as$class=>$foo){$this->addDependency(Nette\Reflection\ClassType::from($class)->getFileName());}}private
  3593. function
  3594. resolveClass($name,$recursive=array()){if(isset($recursive[$name])){throw
  3595. new
  3596. Nette\InvalidArgumentException('Circular reference detected for services: '.implode(', ',array_keys($recursive)).'.');}$recursive[$name]=TRUE;$def=$this->definitions[$name];$factory=$this->normalizeEntity($this->expand($def->factory->entity));if($def->class){return$def->class;}elseif(is_array($factory)){if($service=$this->getServiceName($factory[0])){if(Strings::contains($service,'\\')){throw
  3597. new
  3598. ServiceCreationException("Unable resolve class name for service '$name'.");}$factory[0]=$this->resolveClass($service,$recursive);if(!$factory[0]){return;}}$factory=callback($factory);if(!$factory->isCallable()){throw
  3599. new
  3600. Nette\InvalidStateException("Factory '$factory' is not callable.");}try{$reflection=$factory->toReflection();$def->class=preg_replace('#[|\s].*#','',$reflection->getAnnotation('return'));if($def->class&&!class_exists($def->class)&&$def->class[0]!=='\\'&&$reflection
  3601. instanceof\ReflectionMethod){$def->class=$reflection->getDeclaringClass()->getNamespaceName().'\\'.$def->class;}}catch(\ReflectionException$e){}}elseif($service=$this->getServiceName($factory)){if(Strings::contains($service,'\\')){$def->autowired=FALSE;return$def->class=$service;}if($this->definitions[$service]->shared){$def->autowired=FALSE;}return$def->class=$this->resolveClass($service,$recursive);}else{return$def->class=$factory;}}function
  3602. addDependency($file){$this->dependencies[$file]=TRUE;return$this;}function
  3603. getDependencies(){unset($this->dependencies[FALSE]);return
  3604. array_keys($this->dependencies);}function
  3605. generateClass($parentClass='Nette\DI\Container'){unset($this->definitions[self::THIS_CONTAINER]);$this->addDefinition(self::THIS_CONTAINER)->setClass($parentClass);$this->prepareClassList();$class=new
  3606. Nette\Utils\PhpGenerator\ClassType('Container');$class->addExtend($parentClass);$class->addMethod('__construct')->addBody('parent::__construct(?);',array($this->expand($this->parameters)));$classes=$class->addProperty('classes',array());foreach($this->classes
  3607. as$name=>$foo){try{$classes->value[$name]=$this->getByType($name);}catch(ServiceCreationException$e){$classes->value[$name]=new
  3608. PhpLiteral('FALSE, //'.strstr($e->getMessage(),':'));}}$definitions=$this->definitions;ksort($definitions);$meta=$class->addProperty('meta',array());foreach($definitions
  3609. as$name=>$def){if($def->shared){foreach($this->expand($def->tags)as$tag=>$value){$meta->value[$name][Container::TAGS][$tag]=$value;}}}foreach($definitions
  3610. as$name=>$def){try{$type=$def->class?:'object';$methodName=Container::getMethodName($name,$def->shared);if(!PhpHelpers::isIdentifier($methodName)){throw
  3611. new
  3612. ServiceCreationException('Name contains invalid characters.');}if($def->shared&&!$def->internal&&PhpHelpers::isIdentifier($name)){$class->addDocument("@property $type \$$name");}$method=$class->addMethod($methodName)->addDocument("@return $type")->setVisibility($def->shared||$def->internal?'protected':'public')->setBody($name===self::THIS_CONTAINER?'return $this;':$this->generateService($name));foreach($this->expand($def->parameters)as$k=>$v){$tmp=explode(' ',is_int($k)?$v:$k);$param=is_int($k)?$method->addParameter(end($tmp)):$method->addParameter(end($tmp),$v);if(isset($tmp[1])){$param->setTypeHint($tmp[0]);}}}catch(\Exception$e){throw
  3613. new
  3614. ServiceCreationException("Service '$name': ".$e->getMessage(),NULL,$e);}}return$class;}private
  3615. function
  3616. generateService($name){$def=$this->definitions[$name];$parameters=$this->parameters;foreach($this->expand($def->parameters)as$k=>$v){$v=explode(' ',is_int($k)?$v:$k);$parameters[end($v)]=new
  3617. PhpLiteral('$'.end($v));}$code='$service = '.$this->formatStatement(Helpers::expand($def->factory,$parameters,TRUE)).";\n";$entity=$this->normalizeEntity($def->factory->entity);if($def->class&&$def->class!==$entity&&!$this->getServiceName($entity)){$code.=PhpHelpers::formatArgs("if (!\$service instanceof $def->class) {\n"."\tthrow new Nette\\UnexpectedValueException(?);\n}\n",array("Unable to create service '$name', value returned by factory is not $def->class type."));}foreach((array)$def->setup
  3618. as$setup){$setup=Helpers::expand($setup,$parameters,TRUE);if(is_string($setup->entity)&&strpbrk($setup->entity,':@?')===FALSE){$setup->entity=array("@$name",$setup->entity);}$code.=$this->formatStatement($setup,$name).";\n";}return$code.='return $service;';}function
  3619. formatStatement(Statement$statement,$self=NULL){$entity=$this->normalizeEntity($statement->entity);$arguments=$statement->arguments;if(is_string($entity)&&Strings::contains($entity,'?')){return$this->formatPhp($entity,$arguments,$self);}elseif($service=$this->getServiceName($entity)){if($this->definitions[$service]->shared){if($arguments){throw
  3620. new
  3621. ServiceCreationException("Unable to call service '$entity'.");}return$this->formatPhp('$this->getService(?)',array($service));}$params=array();foreach($this->definitions[$service]->parameters
  3622. as$k=>$v){$params[]=preg_replace('#\w+$#','\$$0',(is_int($k)?$v:$k)).(is_int($k)?'':' = '.PhpHelpers::dump($v));}$rm=new
  3623. Nette\Reflection\GlobalFunction(create_function(implode(', ',$params),''));$arguments=Helpers::autowireArguments($rm,$arguments,$this);return$this->formatPhp('$this->?(?*)',array(Container::getMethodName($service,FALSE),$arguments),$self);}elseif($entity==='not'){return$this->formatPhp('!?',array($arguments[0]));}elseif(is_string($entity)){if($constructor=Nette\Reflection\ClassType::from($entity)->getConstructor()){$this->addDependency($constructor->getFileName());$arguments=Helpers::autowireArguments($constructor,$arguments,$this);}elseif($arguments){throw
  3624. new
  3625. ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");}return$this->formatPhp("new $entity".($arguments?'(?*)':''),array($arguments),$self);}elseif(!Validators::isList($entity)||count($entity)!==2){throw
  3626. new
  3627. Nette\InvalidStateException("Expected class, method or property, ".PhpHelpers::dump($entity)." given.");}elseif($entity[0]===''){return$this->formatPhp("$entity[1](?*)",array($arguments),$self);}elseif(Strings::contains($entity[1],'$')){Validators::assert($arguments,'list:1',"setup arguments for '".callback($entity)."'");if($this->getServiceName($entity[0],$self)){return$this->formatPhp('?->? = ?',array($entity[0],substr($entity[1],1),$arguments[0]),$self);}else{return$this->formatPhp($entity[0].'::$? = ?',array(substr($entity[1],1),$arguments[0]),$self);}}elseif($service=$this->getServiceName($entity[0],$self)){if($this->definitions[$service]->class){$arguments=$this->autowireArguments($this->definitions[$service]->class,$entity[1],$arguments);}return$this->formatPhp('?->?(?*)',array($entity[0],$entity[1],$arguments),$self);}else{$arguments=$this->autowireArguments($entity[0],$entity[1],$arguments);return$this->formatPhp("$entity[0]::$entity[1](?*)",array($arguments),$self);}}function
  3628. formatPhp($statement,$args,$self=NULL){$that=$this;array_walk_recursive($args,function(&$val)use($self,$that){list($val)=$that->normalizeEntity(array($val));if($val
  3629. instanceof
  3630. Statement){$val=new
  3631. PhpLiteral($that->formatStatement($val,$self));}elseif($val==='@'.ContainerBuilder::THIS_CONTAINER){$val=new
  3632. PhpLiteral('$this');}elseif($service=$that->getServiceName($val,$self)){$val=$service===$self?'$service':$that->formatStatement(new
  3633. Statement($val));$val=new
  3634. PhpLiteral($val,$self);}});return
  3635. PhpHelpers::formatArgs($statement,$args);}function
  3636. expand($value){return
  3637. Helpers::expand($value,$this->parameters,TRUE);}function
  3638. normalizeEntity($entity){if(is_string($entity)&&Strings::contains($entity,'::')&&!Strings::contains($entity,'?')){$entity=explode('::',$entity);}if(is_array($entity)&&$entity[0]instanceof
  3639. ServiceDefinition){$tmp=array_keys($this->definitions,$entity[0],TRUE);$entity[0]="@$tmp[0]";}elseif($entity
  3640. instanceof
  3641. ServiceDefinition){$tmp=array_keys($this->definitions,$entity,TRUE);$entity="@$tmp[0]";}elseif(is_array($entity)&&$entity[0]===$this){$entity[0]='@'.ContainerBuilder::THIS_CONTAINER;}return$entity;}function
  3642. getServiceName($arg,$self=NULL){if(!is_string($arg)||!preg_match('#^@[\w\\\\.].+$#',$arg)){return
  3643. FALSE;}$service=substr($arg,1);if($service===self::CREATED_SERVICE){$service=$self;}if(Strings::contains($service,'\\')){if($this->classes===FALSE){return$service;}$res=$this->getByType($service);if(!$res){throw
  3644. new
  3645. ServiceCreationException("Reference to missing service of type $service.");}return$res;}if(!isset($this->definitions[$service])){throw
  3646. new
  3647. ServiceCreationException("Reference to missing service '$service'.");}return$service;}}}namespace Nette\DI\Diagnostics{use
  3648. Nette;use
  3649. Nette\DI\Container;use
  3650. Nette\Diagnostics\Helpers;class
  3651. ContainerPanel
  3652. extends
  3653. Nette\Object
  3654. implements
  3655. Nette\Diagnostics\IBarPanel{private$container;function
  3656. __construct(Container$container){if(PHP_VERSION_ID<50300){throw
  3657. new
  3658. Nette\NotSupportedException(__CLASS__.' requires PHP 5.3 or newer.');}$this->container=$container;}function
  3659. getTab(){ob_start();?>
  3660. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGSSURBVCjPVVFNSwJhEF78Ad79Cf6PvXQRsotUlzKICosuRYmR2RJR0KE6lBFFZVEbpFBSqKu2rum6llFS9HHI4iUhT153n6ZtIWMOM+/MM88z7wwH7s9Ub16SJcnbmrNcxVm2q7Z8/QPvEOtntpj92NkCqITLepEpjix7xQtiLOoQ2b6+E7YAN/5nfOEJ2WbKqOIOJ4bYVMEQx4LfBBQDsvFMhUcCVU1/CxVXmDBGA5ZETrhDCQVcYAPbyEJBhvrnBVPiSpNr6cYDNCQwo4zzU/ySckkgDYuNuVpI42T9k4gLKGMPs/xPzzovQiY2hQYe0jlJfyNNhTqiWDYBq/wBMcSRpnyPzu1oS7WtxjVBSthU1vgVksiQ3Dn6Gp5ah2YOKQo5GiuHPA6xT1EKpxQNCNYejgIR457KKio0S56YckjSa9jo//3mrj+BV0QQagqGTOo+Y7gZIf1puP3WHoLhEb2PjTlCTCWGXtbp8DCX3hZuOdaIc9A+aQvWk4ihq95p67a7nP+u+Ws+r0dql9z/zv0NCYhdCPKZ7oYAAAAASUVORK5CYII="
  3661. />&nbsp;
  3662. <?php
  3663. return
  3664. ob_get_clean();}function
  3665. getPanel(){$services=$this->getContainerProperty('factories');$factories=array();foreach(Nette\Reflection\ClassType::from($this->container)->getMethods()as$method){if(preg_match('#^create(Service)?(.+)$#',$method->getName(),$m)){$name=str_replace('__','.',strtolower(substr($m[2],0,1)).substr($m[2],1));if($m[1]){$services[$name]=$method->getAnnotation('return');}elseif($method->isPublic()){$a=strrpos(".$name",'.');$factories[substr($name,0,$a).'create'.ucfirst(substr($name,$a))]=$method->getAnnotation('return');}}}ksort($services);ksort($factories);$container=$this->container;$registry=$this->getContainerProperty('registry');ob_start();?>
  3666. <style>#nette-debug .nette-ContainerPanel .nette-inner{width:700px}#nette-debug .nette-ContainerPanel table{width:100%;white-space:nowrap}#nette-debug .nette-ContainerPanel-parameters pre{background:#FDF5CE;padding:.4em .7em;border:1px dotted silver;overflow:auto}#nette-debug .nette-ContainerPanel .created{font-weight:bold}#nette-debug .nette-ContainerPanel .yes{color:green;font-weight:bold}</style>
  3667. <div class="nette-ContainerPanel">
  3668. <h1><?php echo
  3669. get_class($this->container)?></h1>
  3670. <div class="nette-inner">
  3671. <h2>Parameters</h2>
  3672. <div class="nette-ContainerPanel-parameters">
  3673. <?php echo
  3674. Helpers::clickableDump($this->container->parameters);?>
  3675. </div>
  3676. <h2>Services</h2>
  3677. <table>
  3678. <thead>
  3679. <tr>
  3680. <th>Name</th>
  3681. <th>Autowired</th>
  3682. <th>Service</th>
  3683. <th>Meta</th>
  3684. </tr>
  3685. </thead>
  3686. <tbody>
  3687. <?php foreach($services
  3688. as$name=>$class):?>
  3689. <?php $autowired=array_keys($container->classes,$name);?>
  3690. <tr>
  3691. <td class="<?php echo
  3692. isset($registry[$name])?'created':''?>"><?php echo
  3693. htmlSpecialChars(str_replace('.','->',$name))?></td>
  3694. <td title="<?php echo
  3695. htmlSpecialChars(implode(" \n",$autowired))?>" class="<?php echo$autowired?'yes':''?>"><?php echo$autowired?'yes':'no'?></td>
  3696. <td>
  3697. <?php if(isset($registry[$name])&&!$registry[$name]instanceof
  3698. Nette\DI\Container&&!$registry[$name]instanceof
  3699. Nette\DI\NestedAccessor):?>
  3700. <?php echo
  3701. Helpers::clickableDump($registry[$name],TRUE);?>
  3702. <?php elseif(isset($registry[$name])):?>
  3703. <code><?php echo
  3704. get_class($registry[$name])?></code>
  3705. <?php elseif(is_string($class)):?>
  3706. <code><?php echo
  3707. htmlSpecialChars($class)?></code>
  3708. <?php endif?>
  3709. </td>
  3710. <td><?php if(isset($container->meta[$name])){echo
  3711. Helpers::clickableDump($container->meta[$name],TRUE);}?></td>
  3712. </tr>
  3713. <?php endforeach?>
  3714. </tbody>
  3715. </table>
  3716. <h2>Factories</h2>
  3717. <table>
  3718. <thead>
  3719. <tr>
  3720. <th>Method</th>
  3721. <th>Returns</th>
  3722. </tr>
  3723. </thead>
  3724. <tbody>
  3725. <?php foreach($factories
  3726. as$name=>$class):?>
  3727. <tr>
  3728. <td><?php echo
  3729. htmlSpecialChars(str_replace('.','->',$name))?>()</td>
  3730. <td><code><?php echo
  3731. htmlSpecialChars($class)?><code></td>
  3732. </tr>
  3733. <?php endforeach?>
  3734. </tbody>
  3735. </table>
  3736. </div>
  3737. </div>
  3738. <?php
  3739. return
  3740. ob_get_clean();}private
  3741. function
  3742. getContainerProperty($name){$prop=Nette\Reflection\ClassType::from('Nette\DI\Container')->getProperty($name);$prop->setAccessible(TRUE);return$prop->getValue($this->container);}}}namespace Nette\DI{use
  3743. Nette;class
  3744. MissingServiceException
  3745. extends
  3746. Nette\InvalidStateException{}class
  3747. ServiceCreationException
  3748. extends
  3749. Nette\InvalidStateException{}final
  3750. class
  3751. Helpers{static
  3752. function
  3753. expand($var,array$params,$recursive=FALSE){if(is_array($var)){$res=array();foreach($var
  3754. as$key=>$val){$res[$key]=self::expand($val,$params,$recursive);}return$res;}elseif($var
  3755. instanceof
  3756. Statement){return
  3757. new
  3758. Statement(self::expand($var->entity,$params,$recursive),self::expand($var->arguments,$params,$recursive));}elseif(!is_string($var)){return$var;}$parts=preg_split('#%([\w.-]*)%#i',$var,-1,PREG_SPLIT_DELIM_CAPTURE);$res='';foreach($parts
  3759. as$n=>$part){if($n
  3760. %
  3761. 2===0){$res.=$part;}elseif($part===''){$res.='%';}elseif(isset($recursive[$part])){throw
  3762. new
  3763. Nette\InvalidArgumentException('Circular reference detected for variables: '.implode(', ',array_keys($recursive)).'.');}else{$val=Nette\Utils\Arrays::get($params,explode('.',$part));if($recursive){$val=self::expand($val,$params,(is_array($recursive)?$recursive:array())+array($part=>1));}if(strlen($part)+2===strlen($var)){return$val;}if(!is_scalar($val)){throw
  3764. new
  3765. Nette\InvalidArgumentException("Unable to concatenate non-scalar parameter '$part' into '$var'.");}$res.=$val;}}return$res;}static
  3766. function
  3767. escape($value){if(is_array($value)){array_walk_recursive($value,function(&$val){$val=is_string($val)?str_replace('%','%%',$val):$val;});}elseif(is_string($value)){$value=str_replace('%','%%',$value);}return$value;}static
  3768. function
  3769. autowireArguments(\ReflectionFunctionAbstract$method,array$arguments,$container){$optCount=0;$num=-1;$res=array();foreach($method->getParameters()as$num=>$parameter){if(array_key_exists($num,$arguments)){$res[$num]=$arguments[$num];unset($arguments[$num]);$optCount=0;}elseif(array_key_exists($parameter->getName(),$arguments)){$res[$num]=$arguments[$parameter->getName()];unset($arguments[$parameter->getName()]);$optCount=0;}elseif($class=$parameter->getClassName()){$res[$num]=$container->getByType($class,FALSE);if($res[$num]===NULL){if($parameter->allowsNull()){$optCount++;}else{throw
  3770. new
  3771. Nette\InvalidArgumentException("No service of type {$class} found");}}else{if($container
  3772. instanceof
  3773. ContainerBuilder){$res[$num]='@'.$res[$num];}$optCount=0;}}elseif($parameter->isOptional()){$res[$num]=$parameter->isDefaultValueAvailable()?$parameter->getDefaultValue():NULL;$optCount++;}else{throw
  3774. new
  3775. Nette\InvalidArgumentException("$parameter is missing.");}}while(array_key_exists(++$num,$arguments)){$res[$num]=$arguments[$num];unset($arguments[$num]);$optCount=0;}if($arguments){throw
  3776. new
  3777. Nette\InvalidArgumentException("Unable to pass specified arguments to $method.");}return$optCount?array_slice($res,0,-$optCount):$res;}}class
  3778. NestedAccessor
  3779. extends
  3780. Nette\Object{public$parameters;private$container;private$namespace;function
  3781. __construct(Container$container,$namespace){$this->container=$container;$this->namespace=$namespace.'.';$this->parameters=&$container->parameters[$namespace];}function
  3782. __call($name,$args){if(substr($name,0,6)==='create'){return
  3783. call_user_func_array(array($this->container,Container::getMethodName($this->namespace.substr($name,6),FALSE)),$args);}throw
  3784. new
  3785. Nette\NotSupportedException;}function&__get($name){$service=$this->container->getService($this->namespace.$name);return$service;}function
  3786. __set($name,$service){throw
  3787. new
  3788. Nette\NotSupportedException;}function
  3789. __isset($name){return$this->container->hasService($this->namespace.$name);}function
  3790. __unset($name){throw
  3791. new
  3792. Nette\NotSupportedException;}}class
  3793. ServiceDefinition
  3794. extends
  3795. Nette\Object{public$class;public$factory;public$setup=array();public$parameters=array();public$tags=array();public$autowired=TRUE;public$shared=TRUE;public$internal=FALSE;function
  3796. setClass($class,array$args=array()){$this->class=$class;if($args){$this->setFactory($class,$args);}return$this;}function
  3797. setFactory($factory,array$args=array()){$this->factory=new
  3798. Statement($factory,$args);return$this;}function
  3799. setArguments(array$args=array()){if($this->factory){$this->factory->arguments=$args;}else{$this->setClass($this->class,$args);}return$this;}function
  3800. addSetup($target,$args=NULL){if(!is_array($args)){$args=func_get_args();array_shift($args);}$this->setup[]=new
  3801. Statement($target,$args);return$this;}function
  3802. setParameters(array$params){$this->shared=$this->autowired=FALSE;$this->parameters=$params;return$this;}function
  3803. addTag($tag,$attrs=TRUE){$this->tags[$tag]=$attrs;return$this;}function
  3804. setAutowired($on){$this->autowired=$on;return$this;}function
  3805. setShared($on){$this->shared=(bool)$on;$this->autowired=$this->shared?$this->autowired:FALSE;return$this;}function
  3806. setInternal($on){$this->internal=(bool)$on;return$this;}}if(class_exists('PDO')){class
  3807. Statement
  3808. extends
  3809. Nette\Object{public$entity;public$arguments;function
  3810. __construct($entity,array$arguments=array()){$this->entity=$entity;$this->arguments=$arguments;}}}}namespace Nette\Forms{use
  3811. Nette;class
  3812. ControlGroup
  3813. extends
  3814. Nette\Object{protected$controls;private$options=array();function
  3815. __construct(){$this->controls=new\SplObjectStorage;}function
  3816. add(){foreach(func_get_args()as$num=>$item){if($item
  3817. instanceof
  3818. IControl){$this->controls->attach($item);}elseif($item
  3819. instanceof\Traversable||is_array($item)){foreach($item
  3820. as$control){$this->controls->attach($control);}}else{throw
  3821. new
  3822. Nette\InvalidArgumentException("Only IFormControl items are allowed, the #$num parameter is invalid.");}}return$this;}function
  3823. getControls(){return
  3824. iterator_to_array($this->controls);}function
  3825. setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}final
  3826. function
  3827. getOption($key,$default=NULL){return
  3828. isset($this->options[$key])?$this->options[$key]:$default;}final
  3829. function
  3830. getOptions(){return$this->options;}}}namespace Nette\Forms\Controls{use
  3831. Nette;use
  3832. Nette\Forms\IControl;use
  3833. Nette\Utils\Html;use
  3834. Nette\Forms\Form;use
  3835. Nette\Forms\Rule;abstract
  3836. class
  3837. BaseControl
  3838. extends
  3839. Nette\ComponentModel\Component
  3840. implements
  3841. IControl{public
  3842. 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
  3843. __construct($caption=NULL){$this->monitor('Nette\Forms\Form');parent::__construct();$this->control=Html::el('input');$this->label=Html::el('label');$this->caption=$caption;$this->rules=new
  3844. Nette\Forms\Rules($this);}protected
  3845. function
  3846. attached($form){if(!$this->disabled&&$form
  3847. instanceof
  3848. Form&&$form->isAnchored()&&$form->isSubmitted()){$this->htmlName=NULL;$this->loadHttpData();}}function
  3849. getForm($need=TRUE){return$this->lookup('Nette\Forms\Form',$need);}function
  3850. getHtmlName(){if($this->htmlName===NULL){$name=str_replace(self::NAME_SEPARATOR,'][',$this->lookupPath('Nette\Forms\Form'),$count);if($count){$name=substr_replace($name,'',strpos($name,']'),1).']';}if(is_numeric($name)||in_array($name,array('attributes','children','elements','focus','length','reset','style','submit','onsubmit'))){$name.='_';}$this->htmlName=$name;}return$this->htmlName;}function
  3851. setHtmlId($id){$this->htmlId=$id;return$this;}function
  3852. getHtmlId(){if($this->htmlId===FALSE){return
  3853. NULL;}elseif($this->htmlId===NULL){$this->htmlId=sprintf(self::$idMask,$this->getForm()->getName(),$this->lookupPath('Nette\Forms\Form'));}return$this->htmlId;}function
  3854. setAttribute($name,$value=TRUE){$this->control->$name=$value;return$this;}function
  3855. setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}final
  3856. function
  3857. getOption($key,$default=NULL){return
  3858. isset($this->options[$key])?$this->options[$key]:$default;}final
  3859. function
  3860. getOptions(){return$this->options;}function
  3861. setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->translator=$translator;return$this;}final
  3862. function
  3863. getTranslator(){if($this->translator===TRUE){return$this->getForm(FALSE)?$this->getForm()->getTranslator():NULL;}return$this->translator;}function
  3864. translate($s,$count=NULL){$translator=$this->getTranslator();return$translator===NULL||$s==NULL?$s:$translator->translate($s,$count);}function
  3865. setValue($value){$this->value=$value;return$this;}function
  3866. getValue(){return$this->value;}function
  3867. isFilled(){return(string)$this->getValue()!=='';}function
  3868. setDefaultValue($value){$form=$this->getForm(FALSE);if(!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValue($value);}return$this;}function
  3869. loadHttpData(){$path=explode('[',strtr(str_replace(array('[]',']'),'',$this->getHtmlName()),'.','_'));$this->setValue(Nette\Utils\Arrays::get($this->getForm()->getHttpData(),$path,NULL));}function
  3870. setDisabled($value=TRUE){$this->disabled=(bool)$value;return$this;}function
  3871. isDisabled(){return$this->disabled;}function
  3872. getControl(){$this->setOption('rendered',TRUE);$control=clone$this->control;$control->name=$this->getHtmlName();$control->disabled=$this->disabled;$control->id=$this->getHtmlId();$control->required=$this->isRequired();$rules=self::exportRules($this->rules);$rules=substr(json_encode($rules),1,-1);$rules=preg_replace('#"([a-z0-9]+)":#i','$1:',$rules);$rules=preg_replace('#(?<!\\\\)"([^\\\\\',]*)"#i',"'$1'",$rules);$control->data('nette-rules',$rules?$rules:NULL);return$control;}function
  3873. getLabel($caption=NULL){$label=clone$this->label;$label->for=$this->getHtmlId();if($caption!==NULL){$label->setText($this->translate($caption));}elseif($this->caption
  3874. instanceof
  3875. Html){$label->add($this->caption);}else{$label->setText($this->translate($this->caption));}return$label;}final
  3876. function
  3877. getControlPrototype(){return$this->control;}final
  3878. function
  3879. getLabelPrototype(){return$this->label;}function
  3880. addRule($operation,$message=NULL,$arg=NULL){$this->rules->addRule($operation,$message,$arg);return$this;}function
  3881. addCondition($operation,$value=NULL){return$this->rules->addCondition($operation,$value);}function
  3882. addConditionOn(IControl$control,$operation,$value=NULL){return$this->rules->addConditionOn($control,$operation,$value);}final
  3883. function
  3884. getRules(){return$this->rules;}final
  3885. function
  3886. setRequired($message=NULL){return$this->addRule(Form::FILLED,$message);}final
  3887. function
  3888. isRequired(){foreach($this->rules
  3889. as$rule){if($rule->type===Rule::VALIDATOR&&!$rule->isNegative&&$rule->operation===Form::FILLED){return
  3890. TRUE;}}return
  3891. FALSE;}protected
  3892. static
  3893. function
  3894. exportRules($rules){$payload=array();foreach($rules
  3895. as$rule){if(!is_string($op=$rule->operation)){$op=callback($op);if(!$op->isStatic()){continue;}}if($rule->type===Rule::VALIDATOR){$item=array('op'=>($rule->isNegative?'~':'').$op,'msg'=>$rules->formatMessage($rule,FALSE));}elseif($rule->type===Rule::CONDITION){$item=array('op'=>($rule->isNegative?'~':'').$op,'rules'=>self::exportRules($rule->subRules),'control'=>$rule->control->getHtmlName());if($rule->subRules->getToggles()){$item['toggle']=$rule->subRules->getToggles();}}if(is_array($rule->arg)){foreach($rule->arg
  3896. as$key=>$value){$item['arg'][$key]=$value
  3897. instanceof
  3898. IControl?(object)array('control'=>$value->getHtmlName()):$value;}}elseif($rule->arg!==NULL){$item['arg']=$rule->arg
  3899. instanceof
  3900. IControl?(object)array('control'=>$rule->arg->getHtmlName()):$rule->arg;}$payload[]=$item;}return$payload;}static
  3901. function
  3902. validateEqual(IControl$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
  3903. instanceof
  3904. IControl?$item->value:$item)){return
  3905. TRUE;}}}return
  3906. FALSE;}static
  3907. function
  3908. validateFilled(IControl$control){return$control->isFilled();}static
  3909. function
  3910. validateValid(IControl$control){return$control->rules->validate(TRUE);}function
  3911. addError($message){if(!in_array($message,$this->errors,TRUE)){$this->errors[]=$message;}$this->getForm()->addError($message);}function
  3912. getErrors(){return$this->errors;}function
  3913. hasErrors(){return(bool)$this->errors;}function
  3914. cleanErrors(){$this->errors=array();}}class
  3915. Button
  3916. extends
  3917. BaseControl{function
  3918. __construct($caption=NULL){parent::__construct($caption);$this->control->type='button';}function
  3919. getLabel($caption=NULL){return
  3920. NULL;}function
  3921. getControl($caption=NULL){$control=parent::getControl();$control->value=$this->translate($caption===NULL?$this->caption:$caption);return$control;}}class
  3922. Checkbox
  3923. extends
  3924. BaseControl{function
  3925. __construct($label=NULL){parent::__construct($label);$this->control->type='checkbox';$this->value=FALSE;}function
  3926. setValue($value){$this->value=is_scalar($value)?(bool)$value:FALSE;return$this;}function
  3927. getControl(){return
  3928. parent::getControl()->checked($this->value);}}class
  3929. HiddenField
  3930. extends
  3931. BaseControl{private$forcedValue;function
  3932. __construct($forcedValue=NULL){parent::__construct();$this->control->type='hidden';$this->value=(string)$forcedValue;$this->forcedValue=$forcedValue;}function
  3933. getLabel($caption=NULL){return
  3934. NULL;}function
  3935. setValue($value){$this->value=is_scalar($value)?(string)$value:'';return$this;}function
  3936. getControl(){return
  3937. parent::getControl()->value($this->forcedValue===NULL?$this->value:$this->forcedValue)->data('nette-rules',NULL);}}class
  3938. SubmitButton
  3939. extends
  3940. Button
  3941. implements
  3942. Nette\Forms\ISubmitterControl{public$onClick;public$onInvalidClick;private$validationScope=TRUE;function
  3943. __construct($caption=NULL){parent::__construct($caption);$this->control->type='submit';}function
  3944. setValue($value){if($this->value=$value!==NULL){$this->getForm()->setSubmittedBy($this);}return$this;}function
  3945. isSubmittedBy(){return$this->getForm()->isSubmitted()===$this;}function
  3946. setValidationScope($scope){$this->validationScope=(bool)$scope;$this->control->formnovalidate=!$this->validationScope;return$this;}final
  3947. function
  3948. getValidationScope(){return$this->validationScope;}function
  3949. click(){$this->onClick($this);}static
  3950. function
  3951. validateSubmitted(Nette\Forms\ISubmitterControl$control){return$control->isSubmittedBy();}}class
  3952. ImageButton
  3953. extends
  3954. SubmitButton{function
  3955. __construct($src=NULL,$alt=NULL){parent::__construct();$this->control->type='image';$this->control->src=$src;$this->control->alt=$alt;}function
  3956. getHtmlName(){$name=parent::getHtmlName();return
  3957. strpos($name,'[')===FALSE?$name:$name.'[]';}function
  3958. loadHttpData(){$path=$this->getHtmlName();$path=explode('[',strtr(str_replace(']','',strpos($path,'[')===FALSE?$path.'.x':substr($path,0,-2)),'.','_'));$this->setValue(Nette\Utils\Arrays::get($this->getForm()->getHttpData(),$path,NULL)!==NULL);}}class
  3959. SelectBox
  3960. extends
  3961. BaseControl{private$items=array();protected$allowed=array();private$prompt=FALSE;private$useKeys=TRUE;function
  3962. __construct($label=NULL,array$items=NULL,$size=NULL){parent::__construct($label);$this->control->setName('select');$this->control->size=$size>1?(int)$size:NULL;if($items!==NULL){$this->setItems($items);}}function
  3963. getValue(){$allowed=$this->allowed;if($this->prompt){$allowed=array_slice($allowed,1,count($allowed),TRUE);}return
  3964. is_scalar($this->value)&&isset($allowed[$this->value])?$this->value:NULL;}function
  3965. getRawValue(){return
  3966. is_scalar($this->value)?$this->value:NULL;}function
  3967. isFilled(){$value=$this->getValue();return
  3968. is_array($value)?count($value)>0:$value!==NULL;}function
  3969. setPrompt($prompt){if(is_bool($prompt)){$this->prompt=$prompt;}else{$this->prompt=TRUE;if($prompt!==NULL){$this->items=array(''=>$prompt)+$this->items;$this->allowed=array(''=>'')+$this->allowed;}}return$this;}function
  3970. skipFirst($v=NULL){trigger_error(__METHOD__.'() is deprecated; use setPrompt() instead.',E_USER_WARNING);return$this->setPrompt($v);}final
  3971. function
  3972. getPrompt(){return$this->prompt;}final
  3973. function
  3974. areKeysUsed(){return$this->useKeys;}function
  3975. setItems(array$items,$useKeys=TRUE){$this->items=$items;$this->allowed=array();$this->useKeys=(bool)$useKeys;foreach($items
  3976. as$key=>$value){if(!is_array($value)){$value=array($key=>$value);}foreach($value
  3977. as$key2=>$value2){if(!$this->useKeys){if(!is_scalar($value2)){throw
  3978. new
  3979. Nette\InvalidArgumentException("All items must be scalar.");}$key2=$value2;}if(isset($this->allowed[$key2])){throw
  3980. new
  3981. Nette\InvalidArgumentException("Items contain duplication for key '$key2'.");}$this->allowed[$key2]=$value2;}}return$this;}final
  3982. function
  3983. getItems(){return$this->items;}function
  3984. getSelectedItem(){if(!$this->useKeys){return$this->getValue();}else{$value=$this->getValue();return$value===NULL?NULL:$this->allowed[$value];}}function
  3985. getControl(){$control=parent::getControl();if($this->prompt){reset($this->items);$control->data('nette-empty-value',$this->useKeys?key($this->items):current($this->items));}$selected=$this->getValue();$selected=is_array($selected)?array_flip($selected):array($selected=>TRUE);$option=Nette\Utils\Html::el('option');foreach($this->items
  3986. as$key=>$value){if(!is_array($value)){$value=array($key=>$value);$dest=$control;}else{$dest=$control->create('optgroup')->label($this->translate($key));}foreach($value
  3987. as$key2=>$value2){if($value2
  3988. instanceof
  3989. Nette\Utils\Html){$dest->add((string)$value2->selected(isset($selected[$key2])));}else{$key2=$this->useKeys?$key2:$value2;$value2=$this->translate((string)$value2);$dest->add((string)$option->value($key2)->selected(isset($selected[$key2]))->setText($value2));}}}return$control;}}class
  3990. MultiSelectBox
  3991. extends
  3992. SelectBox{function
  3993. getValue(){$allowed=array_keys($this->allowed);if($this->getPrompt()){unset($allowed[0]);}return
  3994. array_intersect($this->getRawValue(),$allowed);}function
  3995. 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
  3996. as$val){if(is_scalar($val)){$res[]=$val;}}return$res;}function
  3997. getSelectedItem(){if(!$this->areKeysUsed()){return$this->getValue();}else{$res=array();foreach($this->getValue()as$value){$res[$value]=$this->allowed[$value];}return$res;}}function
  3998. getHtmlName(){return
  3999. parent::getHtmlName().'[]';}function
  4000. getControl(){$control=parent::getControl();$control->multiple=TRUE;return$control;}static
  4001. function
  4002. validateLength(MultiSelectBox$control,$range){if(!is_array($range)){$range=array($range,$range);}$count=count($control->getSelectedItem());return($range[0]===NULL||$count>=$range[0])&&($range[1]===NULL||$count<=$range[1]);}}class
  4003. RadioList
  4004. extends
  4005. BaseControl{protected$separator;protected$container;protected$items=array();function
  4006. __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
  4007. getValue($raw=FALSE){return
  4008. is_scalar($this->value)&&($raw||isset($this->items[$this->value]))?$this->value:NULL;}function
  4009. isFilled(){return$this->getValue()!==NULL;}function
  4010. setItems(array$items){$this->items=$items;return$this;}final
  4011. function
  4012. getItems(){return$this->items;}final
  4013. function
  4014. getSeparatorPrototype(){return$this->separator;}final
  4015. function
  4016. getContainerPrototype(){return$this->container;}function
  4017. getControl($key=NULL){if($key===NULL){$container=clone$this->container;$separator=(string)$this->separator;}elseif(!isset($this->items[$key])){return
  4018. NULL;}$control=parent::getControl();$id=$control->id;$counter=-1;$value=$this->value===NULL?NULL:(string)$this->getValue();$label=Html::el('label');foreach($this->items
  4019. as$k=>$val){$counter++;if($key!==NULL&&(string)$key!==(string)$k){continue;}$control->id=$label->for=$id.'-'.$counter;$control->checked=(string)$k===$value;$control->value=$k;if($val
  4020. instanceof
  4021. Html){$label->setHtml($val);}else{$label->setText($this->translate((string)$val));}if($key!==NULL){return
  4022. Html::el()->add($control)->add($label);}$container->add((string)$control.(string)$label.$separator);$control->data('nette-rules',NULL);}return$container;}function
  4023. getLabel($caption=NULL){$label=parent::getLabel($caption);$label->for=NULL;return$label;}}use
  4024. Nette\Utils\Strings;use
  4025. Nette\Utils\Validators;abstract
  4026. class
  4027. TextBase
  4028. extends
  4029. BaseControl{protected$emptyValue='';protected$filters=array();function
  4030. setValue($value){$this->value=is_array($value)?'':(string)$value;return$this;}function
  4031. getValue(){$value=$this->value;foreach($this->filters
  4032. as$filter){$value=(string)$filter($value);}return$value===$this->translate($this->emptyValue)?'':$value;}function
  4033. setEmptyValue($value){$this->emptyValue=(string)$value;return$this;}final
  4034. function
  4035. getEmptyValue(){return$this->emptyValue;}function
  4036. addFilter($filter){$this->filters[]=callback($filter);return$this;}function
  4037. getControl(){$control=parent::getControl();foreach($this->getRules()as$rule){if($rule->type===Nette\Forms\Rule::VALIDATOR&&!$rule->isNegative&&($rule->operation===Form::LENGTH||$rule->operation===Form::MAX_LENGTH)){$control->maxlength=is_array($rule->arg)?$rule->arg[1]:$rule->arg;}}if($this->emptyValue!==''){$control->data('nette-empty-value',$this->translate($this->emptyValue));}return$control;}function
  4038. addRule($operation,$message=NULL,$arg=NULL){if($operation===Form::FLOAT){$this->addFilter(callback(__CLASS__,'filterFloat'));}return
  4039. parent::addRule($operation,$message,$arg);}static
  4040. function
  4041. validateMinLength(TextBase$control,$length){return
  4042. Strings::length($control->getValue())>=$length;}static
  4043. function
  4044. validateMaxLength(TextBase$control,$length){return
  4045. Strings::length($control->getValue())<=$length;}static
  4046. function
  4047. validateLength(TextBase$control,$range){if(!is_array($range)){$range=array($range,$range);}return
  4048. Validators::isInRange(Strings::length($control->getValue()),$range);}static
  4049. function
  4050. validateEmail(TextBase$control){return
  4051. Validators::isEmail($control->getValue());}static
  4052. function
  4053. validateUrl(TextBase$control){return
  4054. Validators::isUrl($control->getValue())||Validators::isUrl('http://'.$control->getValue());}static
  4055. function
  4056. validateRegexp(TextBase$control,$regexp){return(bool)Strings::match($control->getValue(),$regexp);}static
  4057. function
  4058. validatePattern(TextBase$control,$pattern){return(bool)Strings::match($control->getValue(),"\x01^($pattern)$\x01u");}static
  4059. function
  4060. validateInteger(TextBase$control){return
  4061. Validators::isNumericInt($control->getValue());}static
  4062. function
  4063. validateFloat(TextBase$control){return
  4064. Validators::isNumeric(static::filterFloat($control->getValue()));}static
  4065. function
  4066. validateRange(TextBase$control,$range){return
  4067. Validators::isInRange($control->getValue(),$range);}static
  4068. function
  4069. filterFloat($s){return
  4070. str_replace(array(' ',','),array('','.'),$s);}}class
  4071. TextArea
  4072. extends
  4073. TextBase{function
  4074. __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
  4075. getControl(){$control=parent::getControl();$control->setText($this->getValue()===''?$this->translate($this->emptyValue):$this->value);return$control;}}class
  4076. TextInput
  4077. extends
  4078. TextBase{function
  4079. __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($this,'sanitize');$this->value='';}function
  4080. sanitize($value){if($this->control->maxlength&&Nette\Utils\Strings::length($value)>$this->control->maxlength){$value=Nette\Utils\Strings::substring($value,0,$this->control->maxlength);}return
  4081. Nette\Utils\Strings::trim(strtr($value,"\r\n",' '));}function
  4082. setType($type){$this->control->type=$type;return$this;}function
  4083. setPasswordMode($mode=TRUE){$this->control->type=$mode?'password':'text';return$this;}function
  4084. getControl(){$control=parent::getControl();foreach($this->getRules()as$rule){if($rule->isNegative||$rule->type!==Nette\Forms\Rule::VALIDATOR){}elseif($rule->operation===Nette\Forms\Form::RANGE&&$control->type!=='text'){list($control->min,$control->max)=$rule->arg;}elseif($rule->operation===Nette\Forms\Form::PATTERN){$control->pattern=$rule->arg;}}if($control->type!=='password'){$control->value=$this->getValue()===''?$this->translate($this->emptyValue):$this->value;}return$control;}}use
  4085. Nette\Http;class
  4086. UploadControl
  4087. extends
  4088. BaseControl{function
  4089. __construct($label=NULL){parent::__construct($label);$this->control->type='file';}protected
  4090. function
  4091. attached($form){if($form
  4092. instanceof
  4093. Nette\Forms\Form){if($form->getMethod()!==Nette\Forms\Form::POST){throw
  4094. new
  4095. Nette\InvalidStateException('File upload requires method POST.');}$form->getElementPrototype()->enctype='multipart/form-data';}parent::attached($form);}function
  4096. setValue($value){if(is_array($value)){$this->value=new
  4097. Http\FileUpload($value);}elseif($value
  4098. instanceof
  4099. Http\FileUpload){$this->value=$value;}else{$this->value=new
  4100. Http\FileUpload(NULL);}return$this;}function
  4101. isFilled(){return$this->value
  4102. instanceof
  4103. Http\FileUpload&&$this->value->isOK();}static
  4104. function
  4105. validateFileSize(UploadControl$control,$limit){$file=$control->getValue();return$file
  4106. instanceof
  4107. Http\FileUpload&&$file->getSize()<=$limit;}static
  4108. function
  4109. validateMimeType(UploadControl$control,$mimeType){$file=$control->getValue();if($file
  4110. instanceof
  4111. Http\FileUpload){$type=strtolower($file->getContentType());$mimeTypes=is_array($mimeType)?$mimeType:explode(',',$mimeType);if(in_array($type,$mimeTypes,TRUE)){return
  4112. TRUE;}if(in_array(preg_replace('#/.*#','/*',$type),$mimeTypes,TRUE)){return
  4113. TRUE;}}return
  4114. FALSE;}static
  4115. function
  4116. validateImage(UploadControl$control){$file=$control->getValue();return$file
  4117. instanceof
  4118. Http\FileUpload&&$file->isImage();}}}namespace Nette\Forms\Rendering{use
  4119. Nette;use
  4120. Nette\Utils\Html;class
  4121. DefaultFormRenderer
  4122. extends
  4123. Nette\Object
  4124. implements
  4125. Nette\Forms\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$counter;function
  4126. render(Nette\Forms\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
  4127. setClientScript(){trigger_error(__METHOD__.'() is deprecated; use unobstructive JavaScript instead.',E_USER_WARNING);return$this;}protected
  4128. function
  4129. init(){$wrapper=&$this->wrappers['control'];foreach($this->form->getControls()as$control){if($control->isRequired()&&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
  4130. 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();$url=explode('?',(string)$el->action,2);$el->action=$url[0];$s='';if(isset($url[1])){foreach(preg_split('#[;&]#',$url[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
  4131. renderEnd(){$s='';foreach($this->form->getControls()as$control){if($control
  4132. instanceof
  4133. Nette\Forms\Controls\HiddenField&&!$control->getOption('rendered')){$s.=(string)$control->getControl();}}if(iterator_count($this->form->getComponents(TRUE,'Nette\Forms\Controls\TextInput'))<2){$s.='<!--[if IE]><input type=IEbug disabled style="display:none"><![endif]-->';}if($s){$s=$this->getWrapper('hidden container')->setHtml($s)."\n";}return$s.$this->form->getElementPrototype()->endTag()."\n";}function
  4134. renderErrors(Nette\Forms\IControl$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
  4135. as$error){$item=clone$li;if($error
  4136. instanceof
  4137. Html){$item->add($error);}else{$item->setText($error);}$ul->add($item);}return"\n".$ul->render(0);}}function
  4138. 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
  4139. instanceof
  4140. Html?clone$container:Html::el($container);$s.="\n".$container->startTag();$text=$group->getOption('label');if($text
  4141. instanceof
  4142. 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
  4143. instanceof
  4144. 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
  4145. renderControls($parent){if(!($parent
  4146. instanceof
  4147. Nette\Forms\Container||$parent
  4148. instanceof
  4149. Nette\Forms\ControlGroup)){throw
  4150. new
  4151. Nette\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
  4152. instanceof
  4153. Nette\Forms\Controls\HiddenField||$control->getForm(FALSE)!==$this->form){}elseif($control
  4154. instanceof
  4155. Nette\Forms\Controls\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
  4156. renderPair(Nette\Forms\IControl$control){$pair=$this->getWrapper('pair container');$pair->add($this->renderLabel($control));$pair->add($this->renderControl($control));$pair->class($this->getValue($control->isRequired()?'pair .required':'pair .optional'),TRUE);$pair->class($control->getOption('class'),TRUE);if(++$this->counter
  4157. %
  4158. 2){$pair->class($this->getValue('pair .odd'),TRUE);}$pair->id=$control->getOption('id');return$pair->render(0);}function
  4159. renderPairMulti(array$controls){$s=array();foreach($controls
  4160. as$control){if(!$control
  4161. instanceof
  4162. Nette\Forms\IControl){throw
  4163. new
  4164. Nette\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
  4165. renderLabel(Nette\Forms\IControl$control){$head=$this->getWrapper('label container');if($control
  4166. instanceof
  4167. Nette\Forms\Controls\Checkbox||$control
  4168. instanceof
  4169. Nette\Forms\Controls\Button){return$head->setHtml(($head->getName()==='td'||$head->getName()==='th')?'&nbsp;':'');}else{$label=$control->getLabel();$suffix=$this->getValue('label suffix').($control->isRequired()?$this->getValue('label requiredsuffix'):'');if($label
  4170. instanceof
  4171. Html){$label->setHtml($label->getHtml().$suffix);$suffix='';}return$head->setHtml((string)$label.$suffix);}}function
  4172. renderControl(Nette\Forms\IControl$control){$body=$this->getWrapper('control container');if($this->counter
  4173. %
  4174. 2){$body->class($this->getValue('control .odd'),TRUE);}$description=$control->getOption('description');if($description
  4175. instanceof
  4176. Html){$description=' '.$control->getOption('description');}elseif(is_string($description)){$description=' '.$this->getWrapper('control description')->setText($control->translate($description));}else{$description='';}if($control->isRequired()){$description=$this->getValue('control requiredsuffix').$description;}if($this->getValue('control errors')){$description.=$this->renderErrors($control);}if($control
  4177. instanceof
  4178. Nette\Forms\Controls\Checkbox||$control
  4179. instanceof
  4180. Nette\Forms\Controls\Button){return$body->setHtml((string)$control->getControl().(string)$control->getLabel().$description);}else{return$body->setHtml((string)$control->getControl().$description);}}protected
  4181. function
  4182. getWrapper($name){$data=$this->getValue($name);return$data
  4183. instanceof
  4184. Html?clone$data:Html::el($data);}protected
  4185. function
  4186. getValue($name){$name=explode(' ',$name);$data=&$this->wrappers[$name[0]][$name[1]];return$data;}}}namespace Nette\Forms{use
  4187. Nette;final
  4188. class
  4189. Rule
  4190. extends
  4191. Nette\Object{const
  4192. CONDITION=1;const
  4193. VALIDATOR=2;const
  4194. FILTER=3;public$control;public$operation;public$arg;public$type;public$isNegative=FALSE;public$message;public$subRules;}final
  4195. class
  4196. Rules
  4197. extends
  4198. Nette\Object
  4199. implements\IteratorAggregate{const
  4200. VALIDATE_PREFIX='validate';public
  4201. static$defaultMessages=array(Form::PROTECTION=>'Security token did not match. Possible CSRF attack.',Form::EQUAL=>'Please enter %s.',Form::FILLED=>'Please complete mandatory field.',Form::MIN_LENGTH=>'Please enter a value of at least %d characters.',Form::MAX_LENGTH=>'Please enter a value no longer than %d characters.',Form::LENGTH=>'Please enter a value between %d and %d characters long.',Form::EMAIL=>'Please enter a valid email address.',Form::URL=>'Please enter a valid URL.',Form::INTEGER=>'Please enter a numeric value.',Form::FLOAT=>'Please enter a numeric value.',Form::RANGE=>'Please enter a value between %d and %d.',Form::MAX_FILE_SIZE=>'The size of the uploaded file can be up to %d bytes.',Form::IMAGE=>'The uploaded file must be image in format JPEG, GIF or PNG.');private$rules=array();private$parent;private$toggles=array();private$control;function
  4202. __construct(IControl$control){$this->control=$control;}function
  4203. addRule($operation,$message=NULL,$arg=NULL){$rule=new
  4204. Rule;$rule->control=$this->control;$rule->operation=$operation;$this->adjustOperation($rule);$rule->arg=$arg;$rule->type=Rule::VALIDATOR;if($message===NULL&&is_string($rule->operation)&&isset(static::$defaultMessages[$rule->operation])){$rule->message=static::$defaultMessages[$rule->operation];}else{$rule->message=$message;}$this->rules[]=$rule;return$this;}function
  4205. addCondition($operation,$arg=NULL){return$this->addConditionOn($this->control,$operation,$arg);}function
  4206. addConditionOn(IControl$control,$operation,$arg=NULL){$rule=new
  4207. Rule;$rule->control=$control;$rule->operation=$operation;$this->adjustOperation($rule);$rule->arg=$arg;$rule->type=Rule::CONDITION;$rule->subRules=new
  4208. static($this->control);$rule->subRules->parent=$this;$this->rules[]=$rule;return$rule->subRules;}function
  4209. elseCondition(){$rule=clone
  4210. end($this->parent->rules);$rule->isNegative=!$rule->isNegative;$rule->subRules=new
  4211. static($this->parent->control);$rule->subRules->parent=$this->parent;$this->parent->rules[]=$rule;return$rule->subRules;}function
  4212. endCondition(){return$this->parent;}function
  4213. toggle($id,$hide=TRUE){$this->toggles[$id]=$hide;return$this;}function
  4214. validate($onlyCheck=FALSE){foreach($this->rules
  4215. as$rule){if($rule->control->isDisabled()){continue;}$success=($rule->isNegative
  4216. xor$this->getCallback($rule)->invoke($rule->control,$rule->arg));if($rule->type===Rule::CONDITION&&$success){if(!$rule->subRules->validate($onlyCheck)){return
  4217. FALSE;}}elseif($rule->type===Rule::VALIDATOR&&!$success){if(!$onlyCheck){$rule->control->addError(static::formatMessage($rule,TRUE));}return
  4218. FALSE;}}return
  4219. TRUE;}final
  4220. function
  4221. getIterator(){return
  4222. new\ArrayIterator($this->rules);}final
  4223. function
  4224. getToggles(){return$this->toggles;}private
  4225. function
  4226. 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
  4227. new
  4228. Nette\InvalidArgumentException("Unknown operation$operation for control '{$rule->control->name}'.");}}private
  4229. function
  4230. getCallback($rule){$op=$rule->operation;if(is_string($op)&&strncmp($op,':',1)===0){return
  4231. callback(get_class($rule->control),self::VALIDATE_PREFIX.ltrim($op,':'));}else{return
  4232. callback($op);}}static
  4233. function
  4234. formatMessage($rule,$withValue){$message=$rule->message;if($message
  4235. instanceof
  4236. Nette\Utils\Html){return$message;}if(!isset($message)){$message=static::$defaultMessages[$rule->operation];}if($translator=$rule->control->getForm()->getTranslator()){$message=$translator->translate($message,is_int($rule->arg)?$rule->arg:NULL);}$message=vsprintf(preg_replace('#%(name|label|value)#','%$0',$message),(array)$rule->arg);$message=str_replace('%name',$rule->control->getName(),$message);$message=str_replace('%label',$rule->control->translate($rule->control->caption),$message);if($withValue&&strpos($message,'%value')!==FALSE){$message=str_replace('%value',$rule->control->getValue(),$message);}return$message;}}}namespace Nette\Http{use
  4237. Nette;class
  4238. Context
  4239. extends
  4240. Nette\Object{private$request;private$response;function
  4241. __construct(IRequest$request,IResponse$response){$this->request=$request;$this->response=$response;}function
  4242. isModified($lastModified=NULL,$etag=NULL){if($lastModified){$this->response->setHeader('Last-Modified',$this->response->date($lastModified));}if($etag){$this->response->setHeader('ETag','"'.addslashes($etag).'"');}$ifNoneMatch=$this->request->getHeader('If-None-Match');if($ifNoneMatch==='*'){$match=TRUE;}elseif($ifNoneMatch!==NULL){$etag=$this->response->getHeader('ETag');if($etag==NULL||strpos(' '.strtr($ifNoneMatch,",\t",' '),' '.$etag)===FALSE){return
  4243. TRUE;}else{$match=TRUE;}}$ifModifiedSince=$this->request->getHeader('If-Modified-Since');if($ifModifiedSince!==NULL){$lastModified=$this->response->getHeader('Last-Modified');if($lastModified!=NULL&&strtotime($lastModified)<=strtotime($ifModifiedSince)){$match=TRUE;}else{return
  4244. TRUE;}}if(empty($match)){return
  4245. TRUE;}$this->response->setCode(IResponse::S304_NOT_MODIFIED);return
  4246. FALSE;}function
  4247. getRequest(){return$this->request;}function
  4248. getResponse(){return$this->response;}}class
  4249. FileUpload
  4250. extends
  4251. Nette\Object{private$name;private$type;private$size;private$tmpName;private$error;function
  4252. __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
  4253. getName(){return$this->name;}function
  4254. getSanitizedName(){return
  4255. trim(Nette\Utils\Strings::webalize($this->name,'.',FALSE),'.-');}function
  4256. getContentType(){if($this->isOk()&&$this->type===NULL){$this->type=Nette\Utils\MimeTypeDetector::fromFile($this->tmpName);}return$this->type;}function
  4257. getSize(){return$this->size;}function
  4258. getTemporaryFile(){return$this->tmpName;}function
  4259. __toString(){return$this->tmpName;}function
  4260. getError(){return$this->error;}function
  4261. isOk(){return$this->error===UPLOAD_ERR_OK;}function
  4262. move($dest){@mkdir(dirname($dest),0777,TRUE);if(!call_user_func(is_uploaded_file($this->tmpName)?'move_uploaded_file':'rename',$this->tmpName,$dest)){throw
  4263. new
  4264. Nette\InvalidStateException("Unable to move uploaded file '$this->tmpName' to '$dest'.");}chmod($dest,0666);$this->tmpName=$dest;return$this;}function
  4265. isImage(){return
  4266. in_array($this->getContentType(),array('image/gif','image/png','image/jpeg'),TRUE);}function
  4267. toImage(){return
  4268. Nette\Image::fromFile($this->tmpName);}function
  4269. getImageSize(){return$this->isOk()?@getimagesize($this->tmpName):NULL;}function
  4270. getContents(){return$this->isOk()?file_get_contents($this->tmpName):NULL;}}class
  4271. Request
  4272. extends
  4273. Nette\Object
  4274. implements
  4275. IRequest{private$method;private$url;private$query;private$post;private$files;private$cookies;private$headers;private$remoteAddress;private$remoteHost;function
  4276. __construct(UrlScript$url,$query=NULL,$post=NULL,$files=NULL,$cookies=NULL,$headers=NULL,$method=NULL,$remoteAddress=NULL,$remoteHost=NULL){$this->url=$url;$this->url->freeze();if($query===NULL){parse_str($url->query,$this->query);}else{$this->query=(array)$query;}$this->post=(array)$post;$this->files=(array)$files;$this->cookies=(array)$cookies;$this->headers=(array)$headers;$this->method=$method;$this->remoteAddress=$remoteAddress;$this->remoteHost=$remoteHost;}final
  4277. function
  4278. getUrl(){return$this->url;}function
  4279. getUri(){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::getUrl() instead.',E_USER_WARNING);return$this->getUrl();}final
  4280. function
  4281. getQuery($key=NULL,$default=NULL){if(func_num_args()===0){return$this->query;}elseif(isset($this->query[$key])){return$this->query[$key];}else{return$default;}}final
  4282. function
  4283. getPost($key=NULL,$default=NULL){if(func_num_args()===0){return$this->post;}elseif(isset($this->post[$key])){return$this->post[$key];}else{return$default;}}final
  4284. function
  4285. getFile($key){$args=func_get_args();return
  4286. Nette\Utils\Arrays::get($this->files,$args,NULL);}final
  4287. function
  4288. getFiles(){return$this->files;}final
  4289. function
  4290. getCookie($key,$default=NULL){if(func_num_args()===0){return$this->cookies;}elseif(isset($this->cookies[$key])){return$this->cookies[$key];}else{return$default;}}final
  4291. function
  4292. getCookies(){return$this->cookies;}function
  4293. getMethod(){return$this->method;}function
  4294. isMethod($method){return
  4295. strcasecmp($this->method,$method)===0;}function
  4296. isPost(){return$this->isMethod('POST');}final
  4297. function
  4298. getHeader($header,$default=NULL){$header=strtolower($header);if(isset($this->headers[$header])){return$this->headers[$header];}else{return$default;}}function
  4299. getHeaders(){return$this->headers;}final
  4300. function
  4301. getReferer(){return
  4302. isset($this->headers['referer'])?new
  4303. Url($this->headers['referer']):NULL;}function
  4304. isSecured(){return$this->url->scheme==='https';}function
  4305. isAjax(){return$this->getHeader('X-Requested-With')==='XMLHttpRequest';}function
  4306. getRemoteAddress(){return$this->remoteAddress;}function
  4307. getRemoteHost(){if(!$this->remoteHost){$this->remoteHost=$this->remoteAddress?getHostByAddr($this->remoteAddress):NULL;}return$this->remoteHost;}function
  4308. detectLanguage(array$langs){$header=$this->getHeader('Accept-Language');if(!$header){return
  4309. 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
  4310. 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;}}use
  4311. Nette\Utils\Strings;class
  4312. RequestFactory
  4313. extends
  4314. Nette\Object{const
  4315. NONCHARS='#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';public$urlFilters=array('path'=>array('#/{2,}#'=>'/'),'url'=>array());private$encoding;function
  4316. setEncoding($encoding){$this->encoding=$encoding;return$this;}function
  4317. createHttpRequest(){$url=new
  4318. UrlScript;$url->scheme=isset($_SERVER['HTTPS'])&&strcasecmp($_SERVER['HTTPS'],'off')?'https':'http';$url->user=isset($_SERVER['PHP_AUTH_USER'])?$_SERVER['PHP_AUTH_USER']:'';$url->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('');}$url->host=preg_match('#^[-._a-z0-9]+$#',$pair[0])?$pair[0]:'';if(isset($pair[1])){$url->port=(int)$pair[1];}elseif(isset($_SERVER['SERVER_PORT'])){$url->port=(int)$_SERVER['SERVER_PORT'];}if(isset($_SERVER['REQUEST_URI'])){$requestUrl=$_SERVER['REQUEST_URI'];}elseif(isset($_SERVER['ORIG_PATH_INFO'])){$requestUrl=$_SERVER['ORIG_PATH_INFO'];if(isset($_SERVER['QUERY_STRING'])&&$_SERVER['QUERY_STRING']!=''){$requestUrl.='?'.$_SERVER['QUERY_STRING'];}}else{$requestUrl='';}$requestUrl=Strings::replace($requestUrl,$this->urlFilters['url']);$tmp=explode('?',$requestUrl,2);$url->path=Strings::replace($tmp[0],$this->urlFilters['path']);$url->query=isset($tmp[1])?$tmp[1]:'';$url->canonicalize();$url->path=Strings::fixEncoding($url->path);if(isset($_SERVER['SCRIPT_NAME'])){$script=$_SERVER['SCRIPT_NAME'];}elseif(isset($_SERVER['DOCUMENT_ROOT'],$_SERVER['SCRIPT_FILENAME'])&&strncmp($_SERVER['DOCUMENT_ROOT'],$_SERVER['SCRIPT_FILENAME'],strlen($_SERVER['DOCUMENT_ROOT']))===0){$script='/'.ltrim(strtr(substr($_SERVER['SCRIPT_FILENAME'],strlen($_SERVER['DOCUMENT_ROOT'])),'\\','/'),'/');}else{$script='/';}$path=strtolower($url->path).'/';$script=strtolower($script).'/';$max=min(strlen($path),strlen($script));for($i=0;$i<$max;$i++){if($path[$i]!==$script[$i]){break;}elseif($path[$i]==='/'){$url->scriptPath=substr($url->path,0,$i+1);}}$useFilter=(!in_array(ini_get('filter.default'),array('','unsafe_raw'))||ini_get('filter.default_flags'));parse_str($url->query,$query);if(!$query){$query=$useFilter?filter_input_array(INPUT_GET,FILTER_UNSAFE_RAW):(empty($_GET)?array():$_GET);}$post=$useFilter?filter_input_array(INPUT_POST,FILTER_UNSAFE_RAW):(empty($_POST)?array():$_POST);$cookies=$useFilter?filter_input_array(INPUT_COOKIE,FILTER_UNSAFE_RAW):(empty($_COOKIE)?array():$_COOKIE);$gpc=(bool)get_magic_quotes_gpc();$old=error_reporting(error_reporting()^E_NOTICE);if($gpc||$this->encoding){$utf=strcasecmp($this->encoding,'UTF-8')===0;$list=array(&$query,&$post,&$cookies);while(list($key,$val)=each($list)){foreach($val
  4319. as$k=>$v){unset($list[$key][$k]);if($gpc){$k=stripslashes($k);}if($this->encoding&&is_string($k)&&(preg_match(self::NONCHARS,$k)||preg_last_error())){}elseif(is_array($v)){$list[$key][$k]=$v;$list[]=&$list[$key][$k];}else{if($gpc&&!$useFilter){$v=stripSlashes($v);}if($this->encoding){if($utf){$v=Strings::fixEncoding($v);}else{if(!Strings::checkEncoding($v)){$v=iconv($this->encoding,'UTF-8//IGNORE',$v);}$v=html_entity_decode($v,ENT_QUOTES,'UTF-8');}$v=preg_replace(self::NONCHARS,'',$v);}$list[$key][$k]=$v;}}}unset($list,$key,$val,$k,$v);}$files=array();$list=array();if(!empty($_FILES)){foreach($_FILES
  4320. as$k=>$v){if($this->encoding&&is_string($k)&&(preg_match(self::NONCHARS,$k)||preg_last_error())){continue;}$v['@']=&$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($this->encoding){$v['name']=preg_replace(self::NONCHARS,'',Strings::fixEncoding($v['name']));}$v['@']=new
  4321. FileUpload($v);continue;}foreach($v['name']as$k=>$foo){if($this->encoding&&is_string($k)&&(preg_match(self::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);if(function_exists('apache_request_headers')){$headers=array_change_key_case(apache_request_headers(),CASE_LOWER);}else{$headers=array();foreach($_SERVER
  4322. as$k=>$v){if(strncmp($k,'HTTP_',5)==0){$k=substr($k,5);}elseif(strncmp($k,'CONTENT_',8)){continue;}$headers[strtr(strtolower($k),'_','-')]=$v;}}return
  4323. new
  4324. Request($url,$query,$post,$files,$cookies,$headers,isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:NULL,isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:NULL,isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:NULL);}}final
  4325. class
  4326. Response
  4327. extends
  4328. Nette\Object
  4329. implements
  4330. IResponse{private
  4331. static$fixIE=TRUE;public$cookieDomain='';public$cookiePath='/';public$cookieSecure=FALSE;public$cookieHttpOnly=TRUE;private$code=self::S200_OK;function
  4332. 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,405=>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
  4333. new
  4334. Nette\InvalidArgumentException("Bad HTTP response '$code'.");}elseif(headers_sent($file,$line)){throw
  4335. new
  4336. Nette\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
  4337. getCode(){return$this->code;}function
  4338. setHeader($name,$value){if(headers_sent($file,$line)){throw
  4339. new
  4340. Nette\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
  4341. addHeader($name,$value){if(headers_sent($file,$line)){throw
  4342. new
  4343. Nette\InvalidStateException("Cannot send header after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}header($name.': '.$value,FALSE,$this->code);return$this;}function
  4344. setContentType($type,$charset=NULL){$this->setHeader('Content-Type',$type.($charset?'; charset='.$charset:''));return$this;}function
  4345. 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
  4346. 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=Nette\DateTime::from($time);$this->setHeader('Cache-Control','max-age='.($time->format('U')-time()));$this->setHeader('Expires',self::date($time));return$this;}function
  4347. isSent(){return
  4348. headers_sent();}function
  4349. getHeader($header,$default=NULL){$header.=':';$len=strlen($header);foreach(headers_list()as$item){if(strncasecmp($item,$header,$len)===0){return
  4350. ltrim(substr($item,$len));}}return$default;}function
  4351. getHeaders(){$headers=array();foreach(headers_list()as$header){$a=strpos($header,':');$headers[substr($header,0,$a)]=(string)substr($header,$a+2);}return$headers;}static
  4352. function
  4353. date($time=NULL){$time=Nette\DateTime::from($time);$time->setTimezone(new\DateTimeZone('GMT'));return$time->format('D, d M Y H:i:s \G\M\T');}function
  4354. __destruct(){if(self::$fixIE&&isset($_SERVER['HTTP_USER_AGENT'])&&strpos($_SERVER['HTTP_USER_AGENT'],'MSIE ')!==FALSE&&in_array($this->code,array(400,403,404,405,406,408,409,410,500,501,505),TRUE)&&$this->getHeader('Content-Type','text/html')==='text/html'){echo
  4355. Nette\Utils\Strings::random(2e3," \t\r\n");self::$fixIE=FALSE;}}function
  4356. setCookie($name,$value,$time,$path=NULL,$domain=NULL,$secure=NULL,$httpOnly=NULL){if(headers_sent($file,$line)){throw
  4357. new
  4358. Nette\InvalidStateException("Cannot set cookie after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}setcookie($name,$value,$time?Nette\DateTime::from($time)->format('U'):0,$path===NULL?$this->cookiePath:(string)$path,$domain===NULL?$this->cookieDomain:(string)$domain,$secure===NULL?$this->cookieSecure:(bool)$secure,$httpOnly===NULL?$this->cookieHttpOnly:(bool)$httpOnly);$flatten=array();foreach(headers_list()as$header){if(preg_match('#^Set-Cookie: .+?=#',$header,$m)){$flatten[$m[0]]=$header;if(PHP_VERSION_ID<50300){header('Set-Cookie:');}else{header_remove('Set-Cookie');}}}foreach(array_values($flatten)as$key=>$header){header($header,$key===0);}return$this;}function
  4359. deleteCookie($name,$path=NULL,$domain=NULL,$secure=NULL){$this->setCookie($name,FALSE,0,$path,$domain,$secure);}}class
  4360. Session
  4361. extends
  4362. Nette\Object{const
  4363. DEFAULT_FILE_LIFETIME=10800;const
  4364. REGENERATE_INTERVAL=1800;private$regenerated;private
  4365. 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);private$request;private$response;function
  4366. __construct(IRequest$request,IResponse$response){$this->request=$request;$this->response=$response;}function
  4367. start(){if(self::$started){return;}$this->configure($this->options);Nette\Diagnostics\Debugger::tryError();session_start();if(Nette\Diagnostics\Debugger::catchError($e)&&!session_id()){@session_write_close();throw
  4368. new
  4369. Nette\InvalidStateException('session_start(): '.$e->getMessage(),0,$e);}self::$started=TRUE;unset($_SESSION['__NT'],$_SESSION['__NS'],$_SESSION['__NM']);$nf=&$_SESSION['__NF'];if(empty($nf)){$nf=array('C'=>0);}else{$nf['C']++;}$nfTime=&$nf['Time'];$time=time();if($time-$nfTime>self::REGENERATE_INTERVAL){$this->regenerated=$this->regenerated||isset($nfTime);$nfTime=$time;}$browserKey=$this->request->getCookie('nette-browser');if(!$browserKey){$browserKey=Nette\Utils\Strings::random();}$browserClosed=!isset($nf['B'])||$nf['B']!==$browserKey;$nf['B']=$browserKey;$this->sendCookie();if(isset($nf['META'])){$now=time();foreach($nf['META']as$section=>$metadata){if(is_array($metadata)){foreach($metadata
  4370. as$variable=>$value){if((!empty($value['B'])&&$browserClosed)||(!empty($value['T'])&&$now>$value['T'])||(isset($nf['DATA'][$section][$variable])&&is_object($nf['DATA'][$section][$variable])&&(isset($value['V'])?$value['V']:NULL)!=Nette\Reflection\ClassType::from($nf['DATA'][$section][$variable])->getAnnotation('serializationVersion'))){if($variable===''){unset($nf['META'][$section],$nf['DATA'][$section]);continue
  4371. 2;}unset($nf['META'][$section][$variable],$nf['DATA'][$section][$variable]);}}}}}if($this->regenerated){$this->regenerated=FALSE;$this->regenerateId();}register_shutdown_function(array($this,'clean'));}function
  4372. isStarted(){return(bool)self::$started;}function
  4373. close(){if(self::$started){$this->clean();session_write_close();self::$started=FALSE;}}function
  4374. destroy(){if(!self::$started){throw
  4375. new
  4376. Nette\InvalidStateException('Session is not started.');}session_destroy();$_SESSION=NULL;self::$started=FALSE;if(!$this->response->isSent()){$params=session_get_cookie_params();$this->response->deleteCookie(session_name(),$params['path'],$params['domain'],$params['secure']);}}function
  4377. exists(){return
  4378. self::$started||$this->request->getCookie($this->getName())!==NULL;}function
  4379. regenerateId(){if(self::$started&&!$this->regenerated){if(headers_sent($file,$line)){throw
  4380. new
  4381. Nette\InvalidStateException("Cannot regenerate session ID after HTTP headers have been sent".($file?" (output started at $file:$line).":"."));}session_regenerate_id(TRUE);session_write_close();$backup=$_SESSION;session_start();$_SESSION=$backup;}$this->regenerated=TRUE;}function
  4382. getId(){return
  4383. session_id();}function
  4384. setName($name){if(!is_string($name)||!preg_match('#[^0-9.][^.]*$#A',$name)){throw
  4385. new
  4386. Nette\InvalidArgumentException('Session name must be a string and cannot contain dot.');}session_name($name);return$this->setOptions(array('name'=>$name));}function
  4387. getName(){return
  4388. isset($this->options['name'])?$this->options['name']:session_name();}function
  4389. getSection($section,$class='Nette\Http\SessionSection'){return
  4390. new$class($this,$section);}function
  4391. getNamespace($section){trigger_error(__METHOD__.'() is deprecated; use getSection() instead.',E_USER_WARNING);return$this->getSection($section);}function
  4392. hasSection($section){if($this->exists()&&!self::$started){$this->start();}return!empty($_SESSION['__NF']['DATA'][$section]);}function
  4393. getIterator(){if($this->exists()&&!self::$started){$this->start();}if(isset($_SESSION['__NF']['DATA'])){return
  4394. new\ArrayIterator(array_keys($_SESSION['__NF']['DATA']));}else{return
  4395. new\ArrayIterator;}}function
  4396. 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
  4397. setOptions(array$options){if(self::$started){$this->configure($options);}$this->options=$options+$this->options;if(!empty($options['auto_start'])){$this->start();}return$this;}function
  4398. getOptions(){return$this->options;}private
  4399. function
  4400. configure(array$config){$special=array('cache_expire'=>1,'cache_limiter'=>1,'save_path'=>1,'name'=>1);foreach($config
  4401. as$key=>$value){if(!strncmp($key,'session.',8)){$key=substr($key,8);}$key=strtolower(preg_replace('#(.)(?=[A-Z])#','$1_',$key));if($value===NULL||ini_get("session.$key")==$value){continue;}elseif(strncmp($key,'cookie_',7)===0){if(!isset($cookie)){$cookie=session_get_cookie_params();}$cookie[substr($key,7)]=$value;}else{if(defined('SID')){throw
  4402. new
  4403. Nette\InvalidStateException("Unable to set 'session.$key' to value '$value' when session has been started".($this->started?".":" by session.auto_start or session_start()."));}if(isset($special[$key])){$key="session_$key";$key($value);}elseif(function_exists('ini_set')){ini_set("session.$key",$value);}elseif(!Nette\Framework::$iAmUsingBadHost){throw
  4404. new
  4405. Nette\NotSupportedException('Required function ini_set() is disabled.');}}}if(isset($cookie)){session_set_cookie_params($cookie['lifetime'],$cookie['path'],$cookie['domain'],$cookie['secure'],$cookie['httponly']);if(self::$started){$this->sendCookie();}}}function
  4406. setExpiration($time){if(empty($time)){return$this->setOptions(array('gc_maxlifetime'=>self::DEFAULT_FILE_LIFETIME,'cookie_lifetime'=>0));}else{$time=Nette\DateTime::from($time)->format('U')-time();return$this->setOptions(array('gc_maxlifetime'=>$time,'cookie_lifetime'=>$time));}}function
  4407. setCookieParameters($path,$domain=NULL,$secure=NULL){return$this->setOptions(array('cookie_path'=>$path,'cookie_domain'=>$domain,'cookie_secure'=>$secure));}function
  4408. getCookieParameters(){return
  4409. session_get_cookie_params();}function
  4410. setCookieParams($path,$domain=NULL,$secure=NULL){trigger_error(__METHOD__.'() is deprecated; use setCookieParameters() instead.',E_USER_WARNING);return$this->setCookieParameters($path,$domain,$secure);}function
  4411. setSavePath($path){return$this->setOptions(array('save_path'=>$path));}function
  4412. setStorage(ISessionStorage$storage){if(self::$started){throw
  4413. new
  4414. Nette\InvalidStateException("Unable to set storage when session has been started.");}session_set_save_handler(array($storage,'open'),array($storage,'close'),array($storage,'read'),array($storage,'write'),array($storage,'remove'),array($storage,'clean'));}private
  4415. function
  4416. sendCookie(){$cookie=$this->getCookieParameters();$this->response->setCookie(session_name(),session_id(),$cookie['lifetime']?$cookie['lifetime']+time():0,$cookie['path'],$cookie['domain'],$cookie['secure'],$cookie['httponly'])->setCookie('nette-browser',$_SESSION['__NF']['B'],Response::BROWSER,$cookie['path'],$cookie['domain']);}}final
  4417. class
  4418. SessionSection
  4419. extends
  4420. Nette\Object
  4421. implements\IteratorAggregate,\ArrayAccess{private$session;private$name;private$data;private$meta=FALSE;public$warnOnUndefined=FALSE;function
  4422. __construct(Session$session,$name){if(!is_string($name)){throw
  4423. new
  4424. Nette\InvalidArgumentException("Session namespace must be a string, ".gettype($name)." given.");}$this->session=$session;$this->name=$name;}private
  4425. function
  4426. start(){if($this->meta===FALSE){$this->session->start();$this->data=&$_SESSION['__NF']['DATA'][$this->name];$this->meta=&$_SESSION['__NF']['META'][$this->name];}}function
  4427. getIterator(){$this->start();if(isset($this->data)){return
  4428. new\ArrayIterator($this->data);}else{return
  4429. new\ArrayIterator;}}function
  4430. __set($name,$value){$this->start();$this->data[$name]=$value;if(is_object($value)){$this->meta[$name]['V']=Nette\Reflection\ClassType::from($value)->getAnnotation('serializationVersion');}}function&__get($name){$this->start();if($this->warnOnUndefined&&!array_key_exists($name,$this->data)){trigger_error("The variable '$name' does not exist in session section",E_USER_NOTICE);}return$this->data[$name];}function
  4431. __isset($name){if($this->session->exists()){$this->start();}return
  4432. isset($this->data[$name]);}function
  4433. __unset($name){$this->start();unset($this->data[$name],$this->meta[$name]);}function
  4434. offsetSet($name,$value){$this->__set($name,$value);}function
  4435. offsetGet($name){return$this->__get($name);}function
  4436. offsetExists($name){return$this->__isset($name);}function
  4437. offsetUnset($name){$this->__unset($name);}function
  4438. setExpiration($time,$variables=NULL){$this->start();if(empty($time)){$time=NULL;$whenBrowserIsClosed=TRUE;}else{$time=Nette\DateTime::from($time)->format('U');$max=ini_get('session.gc_maxlifetime');if($time-time()>$max+3){trigger_error("The expiration time is greater than the session expiration $max seconds",E_USER_NOTICE);}$whenBrowserIsClosed=FALSE;}if($variables===NULL){$this->meta['']['T']=$time;$this->meta['']['B']=$whenBrowserIsClosed;}elseif(is_array($variables)){foreach($variables
  4439. 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
  4440. removeExpiration($variables=NULL){$this->start();if($variables===NULL){unset($this->meta['']['T'],$this->meta['']['B']);}elseif(is_array($variables)){foreach($variables
  4441. as$variable){unset($this->meta[$variable]['T'],$this->meta[$variable]['B']);}}else{unset($this->meta[$variables]['T'],$this->meta[$variable]['B']);}}function
  4442. remove(){$this->start();$this->data=NULL;$this->meta=NULL;}}class
  4443. Url
  4444. extends
  4445. Nette\FreezableObject{public
  4446. 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
  4447. __construct($url=NULL){if(is_string($url)){$parts=@parse_url($url);if($parts===FALSE){throw
  4448. new
  4449. Nette\InvalidArgumentException("Malformed or unsupported URI '$url'.");}foreach($parts
  4450. as$key=>$val){$this->$key=$val;}if(!$this->port&&isset(self::$defaultPorts[$this->scheme])){$this->port=self::$defaultPorts[$this->scheme];}if($this->path===''&&($this->scheme==='http'||$this->scheme==='https')){$this->path='/';}}elseif($url
  4451. instanceof
  4452. self){foreach($this
  4453. as$key=>$val){$this->$key=$url->$key;}}}function
  4454. setScheme($value){$this->updating();$this->scheme=(string)$value;return$this;}function
  4455. getScheme(){return$this->scheme;}function
  4456. setUser($value){$this->updating();$this->user=(string)$value;return$this;}function
  4457. getUser(){return$this->user;}function
  4458. setPassword($value){$this->updating();$this->pass=(string)$value;return$this;}function
  4459. getPassword(){return$this->pass;}function
  4460. setHost($value){$this->updating();$this->host=(string)$value;return$this;}function
  4461. getHost(){return$this->host;}function
  4462. setPort($value){$this->updating();$this->port=(int)$value;return$this;}function
  4463. getPort(){return$this->port;}function
  4464. setPath($value){$this->updating();$this->path=(string)$value;return$this;}function
  4465. getPath(){return$this->path;}function
  4466. setQuery($value){$this->updating();$this->query=(string)(is_array($value)?http_build_query($value,'','&'):$value);return$this;}function
  4467. appendQuery($value){$this->updating();$value=(string)(is_array($value)?http_build_query($value,'','&'):$value);$this->query.=($this->query===''||$value==='')?$value:'&'.$value;}function
  4468. getQuery(){return$this->query;}function
  4469. setFragment($value){$this->updating();$this->fragment=(string)$value;return$this;}function
  4470. getFragment(){return$this->fragment;}function
  4471. getAbsoluteUrl(){return$this->scheme.'://'.$this->getAuthority().$this->path.($this->query===''?'':'?'.$this->query).($this->fragment===''?'':'#'.$this->fragment);}function
  4472. 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
  4473. getHostUrl(){return$this->scheme.'://'.$this->getAuthority();}function
  4474. getBasePath(){$pos=strrpos($this->path,'/');return$pos===FALSE?'':substr($this->path,0,$pos+1);}function
  4475. getBaseUrl(){return$this->scheme.'://'.$this->getAuthority().$this->getBasePath();}function
  4476. getRelativeUrl(){return(string)substr($this->getAbsoluteUrl(),strlen($this->getBaseUrl()));}function
  4477. isEqual($url){$part=self::unescape(strtok($url,'?#'),'%/');if(strncmp($part,'//',2)===0){if($part!=='//'.$this->getAuthority().$this->path){return
  4478. FALSE;}}elseif(strncmp($part,'/',1)===0){if($part!==$this->path){return
  4479. FALSE;}}else{if($part!==$this->scheme.'://'.$this->getAuthority().$this->path){return
  4480. FALSE;}}$part=preg_split('#[&;]#',self::unescape(strtr((string)strtok('?#'),'+',' '),'%&;=+'));sort($part);$query=preg_split('#[&;]#',$this->query);sort($query);return$part===$query;}function
  4481. 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
  4482. __toString(){return$this->getAbsoluteUrl();}static
  4483. function
  4484. 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;}function
  4485. getRelativeUri(){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::getRelativeUrl() instead.',E_USER_WARNING);return$this->getRelativeUrl();}function
  4486. getAbsoluteUri(){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::getAbsoluteUrl() instead.',E_USER_WARNING);return$this->getAbsoluteUrl();}function
  4487. getHostUri(){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::getHostUrl() instead.',E_USER_WARNING);return$this->getHostUrl();}function
  4488. getBaseUri(){trigger_error(__METHOD__.'() is deprecated; use '.__CLASS__.'::getBaseUrl() instead.',E_USER_WARNING);return$this->getBaseUrl();}}class
  4489. UrlScript
  4490. extends
  4491. Url{private$scriptPath='/';function
  4492. setScriptPath($value){$this->updating();$this->scriptPath=(string)$value;return$this;}function
  4493. getScriptPath(){return$this->scriptPath;}function
  4494. getBasePath(){$pos=strrpos($this->scriptPath,'/');return$pos===FALSE?'':substr($this->path,0,$pos+1);}function
  4495. getPathInfo(){return(string)substr($this->path,strlen($this->scriptPath));}}use
  4496. Nette\Security\IIdentity;class
  4497. UserStorage
  4498. extends
  4499. Nette\Object
  4500. implements
  4501. Nette\Security\IUserStorage{private$namespace='';private$sessionHandler;private$sessionSection;function
  4502. __construct(Session$sessionHandler){$this->sessionHandler=$sessionHandler;}function
  4503. setAuthenticated($state){$section=$this->getSessionSection(TRUE);$section->authenticated=(bool)$state;$this->sessionHandler->regenerateId();if($state){$section->reason=NULL;$section->authTime=time();}else{$section->reason=self::MANUAL;$section->authTime=NULL;}return$this;}function
  4504. isAuthenticated(){$session=$this->getSessionSection(FALSE);return$session&&$session->authenticated;}function
  4505. setIdentity(IIdentity$identity=NULL){$this->getSessionSection(TRUE)->identity=$identity;return$this;}function
  4506. getIdentity(){$session=$this->getSessionSection(FALSE);return$session?$session->identity:NULL;}function
  4507. setNamespace($namespace){if($this->namespace!==$namespace){$this->namespace=(string)$namespace;$this->sessionSection=NULL;}return$this;}function
  4508. getNamespace(){return$this->namespace;}function
  4509. setExpiration($time,$flags=0){$section=$this->getSessionSection(TRUE);if($time){$time=Nette\DateTime::from($time)->format('U');$section->expireTime=$time;$section->expireDelta=$time-time();}else{unset($section->expireTime,$section->expireDelta);}$section->expireIdentity=(bool)($flags&self::CLEAR_IDENTITY);$section->expireBrowser=(bool)($flags&self::BROWSER_CLOSED);$section->browserCheck=TRUE;$section->setExpiration(0,'browserCheck');$section->setExpiration($time,'foo');return$this;}function
  4510. getLogoutReason(){$session=$this->getSessionSection(FALSE);return$session?$session->reason:NULL;}protected
  4511. function
  4512. getSessionSection($need){if($this->sessionSection!==NULL){return$this->sessionSection;}if(!$need&&!$this->sessionHandler->exists()){return
  4513. NULL;}$this->sessionSection=$section=$this->sessionHandler->getSection('Nette.Http.UserStorage/'.$this->namespace);if(!$section->identity
  4514. instanceof
  4515. IIdentity||!is_bool($section->authenticated)){$section->remove();}if($section->authenticated&&$section->expireBrowser&&!$section->browserCheck){$section->reason=self::BROWSER_CLOSED;$section->authenticated=FALSE;if($section->expireIdentity){unset($section->identity);}}if($section->authenticated&&$section->expireDelta>0){if($section->expireTime<time()){$section->reason=self::INACTIVITY;$section->authenticated=FALSE;if($section->expireIdentity){unset($section->identity);}}$section->expireTime=time()+$section->expireDelta;}if(!$section->authenticated){unset($section->expireTime,$section->expireDelta,$section->expireIdentity,$section->expireBrowser,$section->browserCheck,$section->authTime);}return$this->sessionSection;}}}namespace Nette\Iterators{use
  4516. Nette;class
  4517. CachingIterator
  4518. extends\CachingIterator
  4519. implements\Countable{private$counter=0;function
  4520. __construct($iterator){if(is_array($iterator)||$iterator
  4521. instanceof\stdClass){$iterator=new\ArrayIterator($iterator);}elseif($iterator
  4522. instanceof\Traversable){if($iterator
  4523. instanceof\IteratorAggregate){$iterator=$iterator->getIterator();}elseif(!$iterator
  4524. instanceof\Iterator){$iterator=new\IteratorIterator($iterator);}}else{throw
  4525. new
  4526. Nette\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
  4527. isFirst($width=NULL){return$this->counter===1||($width&&$this->counter!==0&&(($this->counter-1)%$width)===0);}function
  4528. isLast($width=NULL){return!$this->hasNext()||($width&&($this->counter
  4529. %$width)===0);}function
  4530. isEmpty(){return$this->counter===0;}function
  4531. isOdd(){return$this->counter
  4532. %
  4533. 2===1;}function
  4534. isEven(){return$this->counter
  4535. %
  4536. 2===0;}function
  4537. getCounter(){return$this->counter;}function
  4538. count(){$inner=$this->getInnerIterator();if($inner
  4539. instanceof\Countable){return$inner->count();}else{throw
  4540. new
  4541. Nette\NotSupportedException('Iterator is not countable.');}}function
  4542. next(){parent::next();if(parent::valid()){$this->counter++;}}function
  4543. rewind(){parent::rewind();$this->counter=parent::valid()?1:0;}function
  4544. getNextKey(){return$this->getInnerIterator()->key();}function
  4545. getNextValue(){return$this->getInnerIterator()->current();}function
  4546. __call($name,$args){return
  4547. Nette\ObjectMixin::call($this,$name,$args);}function&__get($name){return
  4548. Nette\ObjectMixin::get($this,$name);}function
  4549. __set($name,$value){return
  4550. Nette\ObjectMixin::set($this,$name,$value);}function
  4551. __isset($name){return
  4552. Nette\ObjectMixin::has($this,$name);}function
  4553. __unset($name){Nette\ObjectMixin::remove($this,$name);}}class
  4554. Filter
  4555. extends\FilterIterator{private$callback;function
  4556. __construct(\Iterator$iterator,$callback){parent::__construct($iterator);$this->callback=callback($callback);}function
  4557. accept(){return$this->callback->invoke($this);}}class
  4558. InstanceFilter
  4559. extends\FilterIterator
  4560. implements\Countable{private$type;function
  4561. __construct(\Iterator$iterator,$type){$this->type=$type;parent::__construct($iterator);}function
  4562. accept(){return$this->current()instanceof$this->type;}function
  4563. count(){return
  4564. iterator_count($this);}}class
  4565. Mapper
  4566. extends\IteratorIterator{private$callback;function
  4567. __construct(\Traversable$iterator,$callback){parent::__construct($iterator);$this->callback=callback($callback);}function
  4568. current(){return$this->callback->invoke(parent::current(),parent::key());}}class
  4569. RecursiveFilter
  4570. extends\FilterIterator
  4571. implements\RecursiveIterator{private$callback;private$childrenCallback;function
  4572. __construct(\RecursiveIterator$iterator,$callback,$childrenCallback=NULL){parent::__construct($iterator);$this->callback=$callback===NULL?NULL:callback($callback);$this->childrenCallback=$childrenCallback===NULL?NULL:callback($childrenCallback);}function
  4573. accept(){return$this->callback===NULL||$this->callback->invoke($this);}function
  4574. hasChildren(){return$this->getInnerIterator()->hasChildren()&&($this->childrenCallback===NULL||$this->childrenCallback->invoke($this));}function
  4575. getChildren(){return
  4576. new
  4577. static($this->getInnerIterator()->getChildren(),$this->callback,$this->childrenCallback);}}class
  4578. Recursor
  4579. extends\IteratorIterator
  4580. implements\RecursiveIterator,\Countable{function
  4581. hasChildren(){$obj=$this->current();return($obj
  4582. instanceof\IteratorAggregate&&$obj->getIterator()instanceof\RecursiveIterator)||$obj
  4583. instanceof\RecursiveIterator;}function
  4584. getChildren(){$obj=$this->current();return$obj
  4585. instanceof\IteratorAggregate?$obj->getIterator():$obj;}function
  4586. count(){return
  4587. iterator_count($this);}}}namespace Nette\Latte{use
  4588. Nette;use
  4589. Nette\Utils\Strings;class
  4590. Compiler
  4591. extends
  4592. Nette\Object{public$defaultContentType=self::CONTENT_XHTML;private$tokens;private$output;private$position;private$macros;private$macroHandlers;private$htmlNodes=array();private$macroNodes=array();private$attrCodes=array();private$contentType;private$context;private$templateId;const
  4593. CONTENT_HTML='html',CONTENT_XHTML='xhtml',CONTENT_XML='xml',CONTENT_JS='js',CONTENT_CSS='css',CONTENT_ICAL='ical',CONTENT_TEXT='text';const
  4594. CONTEXT_COMMENT='comment',CONTEXT_SINGLE_QUOTED="'",CONTEXT_DOUBLE_QUOTED='"';function
  4595. __construct(){$this->macroHandlers=new\SplObjectStorage;}function
  4596. addMacro($name,IMacro$macro){$this->macros[$name][]=$macro;$this->macroHandlers->attach($macro);return$this;}function
  4597. compile(array$tokens){$this->templateId=Strings::random();$this->tokens=$tokens;$output='';$this->output=&$output;$this->htmlNodes=$this->macroNodes=array();$this->setContentType($this->defaultContentType);foreach($this->macroHandlers
  4598. as$handler){$handler->initialize($this);}try{foreach($tokens
  4599. as$this->position=>$token){if($token->type===Token::TEXT){$this->output.=$token->text;}elseif($token->type===Token::MACRO_TAG){$isRightmost=!isset($tokens[$this->position+1])||substr($tokens[$this->position+1]->text,0,1)==="\n";$this->writeMacro($token->name,$token->value,$token->modifiers,$isRightmost);}elseif($token->type===Token::HTML_TAG_BEGIN){$this->processHtmlTagBegin($token);}elseif($token->type===Token::HTML_TAG_END){$this->processHtmlTagEnd($token);}elseif($token->type===Token::HTML_ATTRIBUTE){$this->processHtmlAttribute($token);}}}catch(CompileException$e){$e->sourceLine=$token->line;throw$e;}foreach($this->htmlNodes
  4600. as$htmlNode){if(!empty($htmlNode->macroAttrs)){throw
  4601. new
  4602. CompileException("Missing end tag </$htmlNode->name> for macro-attribute ".Parser::N_PREFIX.implode(' and '.Parser::N_PREFIX,array_keys($htmlNode->macroAttrs)).".",0,$token->line);}}$prologs=$epilogs='';foreach($this->macroHandlers
  4603. as$handler){$res=$handler->finalize();$handlerName=get_class($handler);$prologs.=empty($res[0])?'':"<?php\n// prolog $handlerName\n$res[0]\n?>";$epilogs=(empty($res[1])?'':"<?php\n// epilog $handlerName\n$res[1]\n?>").$epilogs;}$output=($prologs?$prologs."<?php\n//\n// main template\n//\n?>\n":'').$output.$epilogs;if($this->macroNodes){throw
  4604. new
  4605. CompileException("There are unclosed macros.",0,$token->line);}$output=$this->expandTokens($output);return$output;}function
  4606. setContentType($type){$this->contentType=$type;$this->context=NULL;return$this;}function
  4607. getContentType(){return$this->contentType;}function
  4608. setContext($context,$sub=NULL){$this->context=array($context,$sub);return$this;}function
  4609. getContext(){return$this->context;}function
  4610. getTemplateId(){return$this->templateId;}function
  4611. getLine(){return$this->tokens?$this->tokens[$this->position]->line:NULL;}function
  4612. expandTokens($s){return
  4613. strtr($s,$this->attrCodes);}private
  4614. function
  4615. processHtmlTagBegin($token){if($token->closing){do{$htmlNode=array_pop($this->htmlNodes);if(!$htmlNode){$htmlNode=new
  4616. HtmlNode($token->name);}}while(strcasecmp($htmlNode->name,$token->name));$this->htmlNodes[]=$htmlNode;$htmlNode->closing=TRUE;$htmlNode->offset=strlen($this->output);$this->setContext(NULL);}elseif($token->text==='<!--'){$this->setContext(self::CONTEXT_COMMENT);}else{$this->htmlNodes[]=$htmlNode=new
  4617. HtmlNode($token->name);$htmlNode->isEmpty=in_array($this->contentType,array(self::CONTENT_HTML,self::CONTENT_XHTML))&&isset(Nette\Utils\Html::$emptyElements[strtolower($token->name)]);$htmlNode->offset=strlen($this->output);$this->setContext(NULL);}$this->output.=$token->text;}private
  4618. function
  4619. processHtmlTagEnd($token){if($token->text==='-->'){$this->output.=$token->text;$this->setContext(NULL);return;}$htmlNode=end($this->htmlNodes);$isEmpty=!$htmlNode->closing&&(Strings::contains($token->text,'/')||$htmlNode->isEmpty);if($isEmpty&&in_array($this->contentType,array(self::CONTENT_HTML,self::CONTENT_XHTML))){$token->text=preg_replace('#^.*>#',$this->contentType===self::CONTENT_XHTML?' />':'>',$token->text);}if(empty($htmlNode->macroAttrs)){$this->output.=$token->text;}else{$code=substr($this->output,$htmlNode->offset).$token->text;$this->output=substr($this->output,0,$htmlNode->offset);$this->writeAttrsMacro($code,$htmlNode);if($isEmpty){$htmlNode->closing=TRUE;$this->writeAttrsMacro('',$htmlNode);}}if($isEmpty){$htmlNode->closing=TRUE;}if(!$htmlNode->closing&&(strcasecmp($htmlNode->name,'script')===0||strcasecmp($htmlNode->name,'style')===0)){$this->setContext(strcasecmp($htmlNode->name,'style')?self::CONTENT_JS:self::CONTENT_CSS);}else{$this->setContext(NULL);if($htmlNode->closing){array_pop($this->htmlNodes);}}}private
  4620. function
  4621. processHtmlAttribute($token){$htmlNode=end($this->htmlNodes);if(Strings::startsWith($token->name,Parser::N_PREFIX)){$htmlNode->macroAttrs[substr($token->name,strlen(Parser::N_PREFIX))]=$token->value;}else{$htmlNode->attrs[$token->name]=TRUE;$this->output.=$token->text;if($token->value){$context=NULL;if(strncasecmp($token->name,'on',2)===0){$context=self::CONTENT_JS;}elseif($token->name==='style'){$context=self::CONTENT_CSS;}$this->setContext($token->value,$context);}}}function
  4622. writeMacro($name,$args=NULL,$modifiers=NULL,$isRightmost=FALSE,HtmlNode$htmlNode=NULL,$prefix=NULL){if($name[0]==='/'){$node=end($this->macroNodes);if(!$node||("/$node->name"!==$name&&'/'!==$name)||$modifiers||($args&&$node->args&&!Strings::startsWith("$node->args ","$args "))){$name.=$args?' ':'';throw
  4623. new
  4624. CompileException("Unexpected macro {{$name}{$args}{$modifiers}}".($node?", expecting {/$node->name}".($args&&$node->args?" or eventually {/$node->name $node->args}":''):''));}array_pop($this->macroNodes);if(!$node->args){$node->setArgs($args);}$isLeftmost=$node->content?trim(substr($this->output,strrpos("\n$this->output","\n")))==='':FALSE;$node->closing=TRUE;$node->macro->nodeClosed($node);$this->output=&$node->saved[0];$this->writeCode($node->openingCode,$this->output,$node->saved[1]);$this->writeCode($node->closingCode,$node->content,$isRightmost,$isLeftmost);$this->output.=$node->content;}else{$node=$this->expandMacro($name,$args,$modifiers,$htmlNode,$prefix);if($node->isEmpty){$this->writeCode($node->openingCode,$this->output,$isRightmost);}else{$this->macroNodes[]=$node;$node->saved=array(&$this->output,$isRightmost);$this->output=&$node->content;}}return$node;}private
  4625. function
  4626. writeCode($code,&$output,$isRightmost,$isLeftmost=NULL){if($isRightmost){$leftOfs=strrpos("\n$output","\n");$isLeftmost=$isLeftmost===NULL?trim(substr($output,$leftOfs))==='':$isLeftmost;if($isLeftmost&&substr($code,0,11)!=='<?php echo '){$output=substr($output,0,$leftOfs);}elseif(substr($code,-2)==='?>'){$code.="\n";}}$output.=$code;}function
  4627. writeAttrsMacro($code,HtmlNode$htmlNode){$attrs=$htmlNode->macroAttrs;$left=$right=array();$attrCode='';foreach($this->macros
  4628. as$name=>$foo){$attrName=MacroNode::PREFIX_INNER."-$name";if(isset($attrs[$attrName])){if($htmlNode->closing){$left[]=array("/$name",'',MacroNode::PREFIX_INNER);}else{array_unshift($right,array($name,$attrs[$attrName],MacroNode::PREFIX_INNER));}unset($attrs[$attrName]);}}foreach(array_reverse($this->macros)as$name=>$foo){$attrName=MacroNode::PREFIX_TAG."-$name";if(isset($attrs[$attrName])){$left[]=array($name,$attrs[$attrName],MacroNode::PREFIX_TAG);array_unshift($right,array("/$name",'',MacroNode::PREFIX_TAG));unset($attrs[$attrName]);}}foreach($this->macros
  4629. as$name=>$foo){if(isset($attrs[$name])){if($htmlNode->closing){$right[]=array("/$name",'',NULL);}else{array_unshift($left,array($name,$attrs[$name],NULL));}unset($attrs[$name]);}}if($attrs){throw
  4630. new
  4631. CompileException("Unknown macro-attribute ".Parser::N_PREFIX.implode(' and '.Parser::N_PREFIX,array_keys($attrs)));}if(!$htmlNode->closing){$htmlNode->attrCode=&$this->attrCodes[$uniq=' n:'.Nette\Utils\Strings::random()];$code=substr_replace($code,$uniq,strrpos($code,'/>')?:strrpos($code,'>'),0);}foreach($left
  4632. as$item){$node=$this->writeMacro($item[0],$item[1],NULL,NULL,$htmlNode,$item[2]);if($node->closing||$node->isEmpty){$htmlNode->attrCode.=$node->attrCode;if($node->isEmpty){unset($htmlNode->macroAttrs[$node->name]);}}}$this->output.=$code;foreach($right
  4633. as$item){$node=$this->writeMacro($item[0],$item[1],NULL,NULL,$htmlNode);if($node->closing){$htmlNode->attrCode.=$node->attrCode;}}if($right&&substr($this->output,-2)==='?>'){$this->output.="\n";}}function
  4634. expandMacro($name,$args,$modifiers=NULL,HtmlNode$htmlNode=NULL,$prefix=NULL){if(empty($this->macros[$name])){$cdata=$this->htmlNodes&&in_array(strtolower(end($this->htmlNodes)->name),array('script','style'));throw
  4635. new
  4636. CompileException("Unknown macro {{$name}}".($cdata?" (in JavaScript or CSS, try to put a space after bracket.)":''));}foreach(array_reverse($this->macros[$name])as$macro){$node=new
  4637. MacroNode($macro,$name,$args,$modifiers,$this->macroNodes?end($this->macroNodes):NULL,$htmlNode,$prefix);if($macro->nodeOpened($node)!==FALSE){return$node;}}throw
  4638. new
  4639. CompileException("Unhandled macro {{$name}}");}}class
  4640. Engine
  4641. extends
  4642. Nette\Object{private$parser;private$compiler;function
  4643. __construct(){$this->parser=new
  4644. Parser;$this->compiler=new
  4645. Compiler;$this->compiler->defaultContentType=Compiler::CONTENT_XHTML;Macros\CoreMacros::install($this->compiler);$this->compiler->addMacro('cache',new
  4646. Macros\CacheMacro($this->compiler));Macros\UIMacros::install($this->compiler);Macros\FormMacros::install($this->compiler);}function
  4647. __invoke($s){return$this->compiler->compile($this->parser->parse($s));}function
  4648. getParser(){return$this->parser;}function
  4649. getCompiler(){return$this->compiler;}}}namespace Nette\Templating{use
  4650. Nette;class
  4651. FilterException
  4652. extends
  4653. Nette\InvalidStateException{public$sourceFile;public$sourceLine;function
  4654. __construct($message,$code=0,$sourceLine=0){$this->sourceLine=(int)$sourceLine;parent::__construct($message,$code);}function
  4655. setSourceFile($file){$this->sourceFile=(string)$file;$this->message=rtrim($this->message,'.')." in ".str_replace(dirname(dirname($file)),'...',$file).($this->sourceLine?":$this->sourceLine":'');}}}namespace Nette\Latte{use
  4656. Nette;class
  4657. CompileException
  4658. extends
  4659. Nette\Templating\FilterException{}class_alias('Nette\Latte\CompileException','Nette\Latte\ParseException');class
  4660. HtmlNode
  4661. extends
  4662. Nette\Object{public$name;public$isEmpty=FALSE;public$attrs=array();public$macroAttrs=array();public$closing=FALSE;public$attrCode;public$offset;function
  4663. __construct($name){$this->name=$name;}}class
  4664. MacroNode
  4665. extends
  4666. Nette\Object{const
  4667. PREFIX_INNER='inner',PREFIX_TAG='tag';public$macro;public$name;public$isEmpty=FALSE;public$args;public$modifiers;public$closing=FALSE;public$tokenizer;public$parentNode;public$openingCode;public$closingCode;public$attrCode;public$content;public$data;public$htmlNode;public$prefix;public$saved;function
  4668. __construct(IMacro$macro,$name,$args=NULL,$modifiers=NULL,MacroNode$parentNode=NULL,HtmlNode$htmlNode=NULL,$prefix=NULL){$this->macro=$macro;$this->name=(string)$name;$this->modifiers=(string)$modifiers;$this->parentNode=$parentNode;$this->htmlNode=$htmlNode;$this->prefix=$prefix;$this->tokenizer=new
  4669. MacroTokenizer($this->args);$this->data=new\stdClass;$this->setArgs($args);}function
  4670. setArgs($args){$this->args=(string)$args;$this->tokenizer->tokenize($this->args);}}}namespace Nette\Latte\Macros{use
  4671. Nette;use
  4672. Nette\Latte;class
  4673. CacheMacro
  4674. extends
  4675. Nette\Object
  4676. implements
  4677. Latte\IMacro{private$used;function
  4678. initialize(){$this->used=FALSE;}function
  4679. finalize(){if($this->used){return
  4680. array('Nette\Latte\Macros\CacheMacro::initRuntime($template, $_g);');}}function
  4681. nodeOpened(Latte\MacroNode$node){$this->used=TRUE;$node->isEmpty=FALSE;$node->openingCode=Latte\PhpWriter::using($node)->write('<?php if (Nette\Latte\Macros\CacheMacro::createCache($netteCacheStorage, %var, $_g->caches, %node.array?)) { ?>',Nette\Utils\Strings::random());}function
  4682. nodeClosed(Latte\MacroNode$node){$node->closingCode='<?php $_l->tmp = array_pop($_g->caches); if (!$_l->tmp instanceof stdClass) $_l->tmp->end(); } ?>';}static
  4683. function
  4684. initRuntime(Nette\Templating\FileTemplate$template,\stdClass$global){if(!empty($global->caches)){end($global->caches)->dependencies[Nette\Caching\Cache::FILES][]=$template->getFile();}}static
  4685. function
  4686. createCache(Nette\Caching\IStorage$cacheStorage,$key,&$parents,array$args=NULL){if($args){if(array_key_exists('if',$args)&&!$args['if']){return$parents[]=(object)NULL;}$key=array_merge(array($key),array_intersect_key($args,range(0,count($args))));}if($parents){end($parents)->dependencies[Nette\Caching\Cache::ITEMS][]=$key;}$cache=new
  4687. Nette\Caching\Cache($cacheStorage,'Nette.Templating.Cache');if($helper=$cache->start($key)){if(isset($args['expire'])){$args['expiration']=$args['expire'];}$helper->dependencies=array(Nette\Caching\Cache::TAGS=>isset($args['tags'])?$args['tags']:NULL,Nette\Caching\Cache::EXPIRATION=>isset($args['expiration'])?$args['expiration']:'+ 7 days');$parents[]=$helper;}return$helper;}}use
  4688. Nette\Latte\MacroNode;class
  4689. MacroSet
  4690. extends
  4691. Nette\Object
  4692. implements
  4693. Latte\IMacro{private$compiler;private$macros;function
  4694. __construct(Latte\Compiler$compiler){$this->compiler=$compiler;}function
  4695. addMacro($name,$begin,$end=NULL,$attr=NULL){$this->macros[$name]=array($begin,$end,$attr);$this->compiler->addMacro($name,$this);return$this;}static
  4696. function
  4697. install(Latte\Compiler$compiler){return
  4698. new
  4699. static($compiler);}function
  4700. initialize(){}function
  4701. finalize(){}function
  4702. nodeOpened(MacroNode$node){if($this->macros[$node->name][2]&&$node->htmlNode){$node->isEmpty=TRUE;$this->compiler->setContext(Latte\Compiler::CONTEXT_DOUBLE_QUOTED);$res=$this->compile($node,$this->macros[$node->name][2]);$this->compiler->setContext(NULL);if(!$node->attrCode){$node->attrCode="<?php $res ?>";}}else{$node->isEmpty=!isset($this->macros[$node->name][1]);$res=$this->compile($node,$this->macros[$node->name][0]);if(!$node->openingCode){$node->openingCode="<?php $res ?>";}}return$res!==FALSE;}function
  4703. nodeClosed(MacroNode$node){$res=$this->compile($node,$this->macros[$node->name][1]);if(!$node->closingCode){$node->closingCode="<?php $res ?>";}}private
  4704. function
  4705. compile(MacroNode$node,$def){$node->tokenizer->reset();$writer=Latte\PhpWriter::using($node,$this->compiler);if(is_string($def)){return$writer->write($def);}else{return
  4706. callback($def)->invoke($node,$writer);}}function
  4707. getCompiler(){return$this->compiler;}}use
  4708. Nette\Latte\CompileException;use
  4709. Nette\Latte\PhpWriter;class
  4710. CoreMacros
  4711. extends
  4712. MacroSet{static
  4713. function
  4714. install(Latte\Compiler$compiler){$me=new
  4715. static($compiler);$me->addMacro('if',array($me,'macroIf'),array($me,'macroEndIf'));$me->addMacro('elseif','elseif (%node.args):');$me->addMacro('else',array($me,'macroElse'));$me->addMacro('ifset','if (isset(%node.args)):','endif');$me->addMacro('elseifset','elseif (isset(%node.args)):');$me->addMacro('foreach','',array($me,'macroEndForeach'));$me->addMacro('for','for (%node.args):','endfor');$me->addMacro('while','while (%node.args):','endwhile');$me->addMacro('continueIf','if (%node.args) continue');$me->addMacro('breakIf','if (%node.args) break');$me->addMacro('first','if ($iterator->isFirst(%node.args)):','endif');$me->addMacro('last','if ($iterator->isLast(%node.args)):','endif');$me->addMacro('sep','if (!$iterator->isLast(%node.args)):','endif');$me->addMacro('var',array($me,'macroVar'));$me->addMacro('assign',array($me,'macroVar'));$me->addMacro('default',array($me,'macroVar'));$me->addMacro('dump',array($me,'macroDump'));$me->addMacro('debugbreak',array($me,'macroDebugbreak'));$me->addMacro('l','?>{<?php');$me->addMacro('r','?>}<?php');$me->addMacro('_',array($me,'macroTranslate'),array($me,'macroTranslate'));$me->addMacro('=',array($me,'macroExpr'));$me->addMacro('?',array($me,'macroExpr'));$me->addMacro('capture',array($me,'macroCapture'),array($me,'macroCaptureEnd'));$me->addMacro('include',array($me,'macroInclude'));$me->addMacro('use',array($me,'macroUse'));$me->addMacro('class',NULL,NULL,array($me,'macroClass'));$me->addMacro('attr',array($me,'macroOldAttr'),'',array($me,'macroAttr'));$me->addMacro('href',NULL);}function
  4716. finalize(){return
  4717. array('list($_l, $_g) = Nette\Latte\Macros\CoreMacros::initRuntime($template, '.var_export($this->getCompiler()->getTemplateId(),TRUE).')');}function
  4718. macroIf(MacroNode$node,PhpWriter$writer){if($node->data->capture=($node->args==='')){return'ob_start()';}if($node->prefix===$node::PREFIX_TAG){return$writer->write($node->htmlNode->closing?'if (array_pop($_l->ifs)):':'if ($_l->ifs[] = (%node.args)):');}return$writer->write('if (%node.args):');}function
  4719. macroEndIf(MacroNode$node,PhpWriter$writer){if($node->data->capture){if($node->args===''){throw
  4720. new
  4721. CompileException('Missing condition in {if} macro.');}return$writer->write('if (%node.args) '.(isset($node->data->else)?'{ ob_end_clean(); ob_end_flush(); }':'ob_end_flush();').' else '.(isset($node->data->else)?'{ $_else = ob_get_contents(); ob_end_clean(); ob_end_clean(); echo $_else; }':'ob_end_clean();'));}return'endif';}function
  4722. macroElse(MacroNode$node,PhpWriter$writer){$ifNode=$node->parentNode;if($ifNode&&$ifNode->name==='if'&&$ifNode->data->capture){if(isset($ifNode->data->else)){throw
  4723. new
  4724. CompileException("Macro {if} supports only one {else}.");}$ifNode->data->else=TRUE;return'ob_start()';}return'else:';}function
  4725. macroTranslate(MacroNode$node,PhpWriter$writer){if($node->closing){return$writer->write('echo %modify($template->translate(ob_get_clean()))');}elseif($node->isEmpty=($node->args!=='')){return$writer->write('echo %modify($template->translate(%node.args))');}else{return'ob_start()';}}function
  4726. macroInclude(MacroNode$node,PhpWriter$writer){$code=$writer->write('Nette\Latte\Macros\CoreMacros::includeTemplate(%node.word, %node.array? + $template->getParameters(), $_l->templates[%var])',$this->getCompiler()->getTemplateId());if($node->modifiers){return$writer->write('echo %modify(%raw->__toString(TRUE))',$code);}else{return$code.'->render()';}}function
  4727. macroUse(MacroNode$node,PhpWriter$writer){callback($node->tokenizer->fetchWord(),'install')->invoke($this->getCompiler())->initialize();}function
  4728. macroCapture(MacroNode$node,PhpWriter$writer){$variable=$node->tokenizer->fetchWord();if(substr($variable,0,1)!=='$'){throw
  4729. new
  4730. CompileException("Invalid capture block variable '$variable'");}$node->data->variable=$variable;return'ob_start()';}function
  4731. macroCaptureEnd(MacroNode$node,PhpWriter$writer){return$node->data->variable.$writer->write(" = %modify(ob_get_clean())");}function
  4732. macroEndForeach(MacroNode$node,PhpWriter$writer){if(preg_match('#\W(\$iterator|include|require|get_defined_vars)\W#',$this->getCompiler()->expandTokens($node->content))){$node->openingCode='<?php $iterations = 0; foreach ($iterator = $_l->its[] = new Nette\Iterators\CachingIterator('.preg_replace('#(.*)\s+as\s+#i','$1) as ',$writer->formatArgs(),1).'): ?>';$node->closingCode='<?php $iterations++; endforeach; array_pop($_l->its); $iterator = end($_l->its) ?>';}else{$node->openingCode='<?php $iterations = 0; foreach ('.$writer->formatArgs().'): ?>';$node->closingCode='<?php $iterations++; endforeach ?>';}}function
  4733. macroClass(MacroNode$node,PhpWriter$writer){return$writer->write('if ($_l->tmp = array_filter(%node.array)) echo \' class="\' . %escape(implode(" ", array_unique($_l->tmp))) . \'"\'');}function
  4734. macroAttr(MacroNode$node,PhpWriter$writer){return$writer->write('echo Nette\Utils\Html::el(NULL, %node.array)->attributes()');}function
  4735. macroOldAttr(MacroNode$node){return
  4736. Nette\Utils\Strings::replace($node->args.' ','#\)\s+#',')->');}function
  4737. macroDump(MacroNode$node,PhpWriter$writer){$args=$writer->formatArgs();return'Nette\Diagnostics\Debugger::barDump('.($node->args?"array(".$writer->write('%var',$args)." => $args)":'get_defined_vars()').', "Template " . str_replace(dirname(dirname($template->getFile())), "\xE2\x80\xA6", $template->getFile()))';}function
  4738. macroDebugbreak(MacroNode$node,PhpWriter$writer){return$writer->write(($node->args==NULL?'':'if (!(%node.args)); else').'if (function_exists("debugbreak")) debugbreak(); elseif (function_exists("xdebug_break")) xdebug_break()');}function
  4739. macroVar(MacroNode$node,PhpWriter$writer){$out='';$var=TRUE;$tokenizer=$writer->preprocess();while($token=$tokenizer->fetchToken()){if($var&&($token['type']===Latte\MacroTokenizer::T_SYMBOL||$token['type']===Latte\MacroTokenizer::T_VARIABLE)){if($node->name==='default'){$out.="'".ltrim($token['value'],"$")."'";}else{$out.='$'.ltrim($token['value'],"$");}$var=NULL;}elseif(($token['value']==='='||$token['value']==='=>')&&$token['depth']===0){$out.=$node->name==='default'?'=>':'=';$var=FALSE;}elseif($token['value']===','&&$token['depth']===0){$out.=$node->name==='default'?',':';';$var=TRUE;}elseif($var===NULL&&$node->name==='default'&&$token['type']!==Latte\MacroTokenizer::T_WHITESPACE){throw
  4740. new
  4741. CompileException("Unexpected '$token[value]' in {default $node->args}");}else{$out.=$writer->canQuote($tokenizer)?"'$token[value]'":$token['value'];}}return$node->name==='default'?"extract(array($out), EXTR_SKIP)":$out;}function
  4742. macroExpr(MacroNode$node,PhpWriter$writer){return$writer->write(($node->name==='?'?'':'echo ').'%modify(%node.args)');}static
  4743. function
  4744. includeTemplate($destination,array$params,Nette\Templating\ITemplate$template){if($destination
  4745. instanceof
  4746. Nette\Templating\ITemplate){$tpl=$destination;}elseif($destination==NULL){throw
  4747. new
  4748. Nette\InvalidArgumentException("Template file name was not specified.");}elseif($template
  4749. instanceof
  4750. Nette\Templating\IFileTemplate){if(substr($destination,0,1)!=='/'&&substr($destination,1,1)!==':'){$destination=dirname($template->getFile()).'/'.$destination;}$tpl=clone$template;$tpl->setFile($destination);}else{throw
  4751. new
  4752. Nette\NotSupportedException('Macro {include "filename"} is supported only with Nette\Templating\IFileTemplate.');}$tpl->setParameters($params);return$tpl;}static
  4753. function
  4754. initRuntime(Nette\Templating\ITemplate$template,$templateId){if(isset($template->_l)){$local=$template->_l;unset($template->_l);}else{$local=(object)NULL;}$local->templates[$templateId]=$template;if(!isset($template->_g)){$template->_g=(object)NULL;}return
  4755. array($local,$template->_g);}}use
  4756. Nette\Forms\Form;use
  4757. Nette\Utils\Strings;class
  4758. FormMacros
  4759. extends
  4760. MacroSet{static
  4761. function
  4762. install(Latte\Compiler$compiler){$me=new
  4763. static($compiler);$me->addMacro('form','Nette\Latte\Macros\FormMacros::renderFormBegin($form = $_form = (is_object(%node.word) ? %node.word : $_control[%node.word]), %node.array)','Nette\Latte\Macros\FormMacros::renderFormEnd($_form)');$me->addMacro('label',array($me,'macroLabel'),'?></label><?php');$me->addMacro('input','echo $_form[%node.word]->getControl()->addAttributes(%node.array)',NULL,array($me,'macroAttrInput'));$me->addMacro('formContainer','$_formStack[] = $_form; $formContainer = $_form = $_form[%node.word]','$_form = array_pop($_formStack)');}function
  4764. macroLabel(MacroNode$node,PhpWriter$writer){$cmd='if ($_label = $_form[%node.word]->getLabel()) echo $_label->addAttributes(%node.array)';if($node->isEmpty=(substr($node->args,-1)==='/')){$node->setArgs(substr($node->args,0,-1));return$writer->write($cmd);}else{return$writer->write($cmd.'->startTag()');}}function
  4765. macroAttrInput(MacroNode$node,PhpWriter$writer){if($node->htmlNode->attrs){$reset=array_fill_keys(array_keys($node->htmlNode->attrs),NULL);return$writer->write('echo $_form[%node.word]->getControl()->addAttributes(%var)->attributes()',$reset);}return$writer->write('echo $_form[%node.word]->getControl()->attributes()');}static
  4766. function
  4767. renderFormBegin(Form$form,array$attrs){$el=$form->getElementPrototype();$el->action=(string)$el->action;$el=clone$el;if(strcasecmp($form->getMethod(),'get')===0){list($el->action)=explode('?',$el->action,2);}echo$el->addAttributes($attrs)->startTag();}static
  4768. function
  4769. renderFormEnd(Form$form){$s='';if(strcasecmp($form->getMethod(),'get')===0){$url=explode('?',$form->getElementPrototype()->action,2);if(isset($url[1])){foreach(preg_split('#[;&]#',$url[1])as$param){$parts=explode('=',$param,2);$name=urldecode($parts[0]);if(!isset($form[$name])){$s.=Nette\Utils\Html::el('input',array('type'=>'hidden','name'=>$name,'value'=>urldecode($parts[1])));}}}}foreach($form->getComponents(TRUE,'Nette\Forms\Controls\HiddenField')as$control){if(!$control->getOption('rendered')){$s.=$control->getControl();}}if(iterator_count($form->getComponents(TRUE,'Nette\Forms\Controls\TextInput'))<2){$s.='<!--[if IE]><input type=IEbug disabled style="display:none"><![endif]-->';}echo($s?"<div>$s</div>\n":'').$form->getElementPrototype()->endTag()."\n";}}class
  4770. UIMacros
  4771. extends
  4772. MacroSet{const
  4773. RE_IDENTIFIER='[_a-zA-Z\x7F-\xFF][_a-zA-Z0-9\x7F-\xFF]*';private$namedBlocks=array();private$extends;static
  4774. function
  4775. install(Latte\Compiler$compiler){$me=new
  4776. static($compiler);$me->addMacro('include',array($me,'macroInclude'));$me->addMacro('includeblock',array($me,'macroIncludeBlock'));$me->addMacro('extends',array($me,'macroExtends'));$me->addMacro('layout',array($me,'macroExtends'));$me->addMacro('block',array($me,'macroBlock'),array($me,'macroBlockEnd'));$me->addMacro('define',array($me,'macroBlock'),array($me,'macroBlockEnd'));$me->addMacro('snippet',array($me,'macroBlock'),array($me,'macroBlockEnd'));$me->addMacro('ifset',array($me,'macroIfset'),'endif');$me->addMacro('widget',array($me,'macroControl'));$me->addMacro('control',array($me,'macroControl'));$me->addMacro('href',NULL,NULL,function(MacroNode$node,PhpWriter$writer)use($me){return' ?> href="<?php '.$me->macroLink($node,$writer).' ?>"<?php ';});$me->addMacro('plink',array($me,'macroLink'));$me->addMacro('link',array($me,'macroLink'));$me->addMacro('ifCurrent',array($me,'macroIfCurrent'),'endif');$me->addMacro('contentType',array($me,'macroContentType'));$me->addMacro('status',array($me,'macroStatus'));}function
  4777. initialize(){$this->namedBlocks=array();$this->extends=NULL;}function
  4778. finalize(){try{$this->getCompiler()->writeMacro('/block');}catch(CompileException$e){}$epilog=$prolog=array();if($this->namedBlocks){foreach($this->namedBlocks
  4779. as$name=>$code){$func='_lb'.substr(md5($this->getCompiler()->getTemplateId().$name),0,10).'_'.preg_replace('#[^a-z0-9_]#i','_',$name);$snippet=$name[0]==='_';$prolog[]="//\n// block $name\n//\n"."if (!function_exists(\$_l->blocks[".var_export($name,TRUE)."][] = '$func')) { "."function $func(\$_l, \$_args) { ".(PHP_VERSION_ID>50208?'extract($_args)':'foreach ($_args as $__k => $__v) $$__k = $__v').($snippet?'; $_control->validateControl('.var_export(substr($name,1),TRUE).')':'')."\n?>$code<?php\n}}";}$prolog[]="//\n// end of blocks\n//";}if($this->namedBlocks||$this->extends){$prolog[]="// template extending and snippets support";$prolog[]='$_l->extends = '.($this->extends?$this->extends:'empty($template->_extended) && isset($_control) && $_control instanceof Nette\Application\UI\Presenter ? $_control->findLayoutTemplateFile() : NULL').'; $template->_extended = $_extended = TRUE;';$prolog[]='
  4780. if ($_l->extends) {
  4781. '.($this->namedBlocks?'ob_start();':'return Nette\Latte\Macros\CoreMacros::includeTemplate($_l->extends, get_defined_vars(), $template)->render();').'
  4782. } elseif (!empty($_control->snippetMode)) {
  4783. return Nette\Latte\Macros\UIMacros::renderSnippets($_control, $_l, get_defined_vars());
  4784. }';}else{$prolog[]='
  4785. // snippets support
  4786. if (!empty($_control->snippetMode)) {
  4787. return Nette\Latte\Macros\UIMacros::renderSnippets($_control, $_l, get_defined_vars());
  4788. }';}return
  4789. array(implode("\n\n",$prolog),implode("\n",$epilog));}function
  4790. macroInclude(MacroNode$node,PhpWriter$writer){$destination=$node->tokenizer->fetchWord();if(substr($destination,0,1)!=='#'){return
  4791. FALSE;}$destination=ltrim($destination,'#');if(!Strings::match($destination,'#^\$?'.self::RE_IDENTIFIER.'$#')){throw
  4792. new
  4793. CompileException("Included block name must be alphanumeric string, '$destination' given.");}$parent=$destination==='parent';if($destination==='parent'||$destination==='this'){for($item=$node->parentNode;$item&&$item->name!=='block'&&!isset($item->data->name);$item=$item->parentNode);if(!$item){throw
  4794. new
  4795. CompileException("Cannot include $destination block outside of any block.");}$destination=$item->data->name;}$name=$destination[0]==='$'?$destination:var_export($destination,TRUE);if(isset($this->namedBlocks[$destination])&&!$parent){$cmd="call_user_func(reset(\$_l->blocks[$name]), \$_l, %node.array? + get_defined_vars())";}else{$cmd='Nette\Latte\Macros\UIMacros::callBlock'.($parent?'Parent':'')."(\$_l, $name, %node.array? + ".($parent?'get_defined_vars':'$template->getParameters').'())';}if($node->modifiers){return$writer->write("ob_start(); $cmd; echo %modify(ob_get_clean())");}else{return$writer->write($cmd);}}function
  4796. macroIncludeBlock(MacroNode$node,PhpWriter$writer){return$writer->write('Nette\Latte\Macros\CoreMacros::includeTemplate(%node.word, %node.array? + get_defined_vars(), $_l->templates[%var])->render()',$this->getCompiler()->getTemplateId());}function
  4797. macroExtends(MacroNode$node,PhpWriter$writer){if(!$node->args){throw
  4798. new
  4799. CompileException("Missing destination in {extends}");}if(!empty($node->parentNode)){throw
  4800. new
  4801. CompileException("{extends} must be placed outside any macro.");}if($this->extends!==NULL){throw
  4802. new
  4803. CompileException("Multiple {extends} declarations are not allowed.");}if($node->args==='none'){$this->extends='FALSE';}elseif($node->args==='auto'){$this->extends='$_presenter->findLayoutTemplateFile()';}else{$this->extends=$writer->write('%node.word%node.args');}return;}function
  4804. macroBlock(MacroNode$node,PhpWriter$writer){$name=$node->tokenizer->fetchWord();if($node->name==='block'&&$name===FALSE){return$node->modifiers===''?'':'ob_start()';}$node->data->name=$name=ltrim($name,'#');if($name==NULL){if($node->name!=='snippet'){throw
  4805. new
  4806. CompileException("Missing block name.");}}elseif(!Strings::match($name,'#^'.self::RE_IDENTIFIER.'$#')){if($node->name==='snippet'){for($parent=$node->parentNode;$parent&&$parent->name!=='snippet';$parent=$parent->parentNode);if(!$parent){throw
  4807. new
  4808. CompileException("Dynamic snippets are allowed only inside static snippet.");}$parent->data->dynamic=TRUE;$node->data->leave=TRUE;$node->closingCode="<?php \$_dynSnippets[\$_dynSnippetId] = ob_get_flush() ?>";if($node->htmlNode){$node->attrCode=$writer->write("<?php echo ' id=\"' . (\$_dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)})) . '\"' ?>");return$writer->write('ob_start()');}$tag=trim($node->tokenizer->fetchWord(),'<>');$tag=$tag?$tag:'div';$node->closingCode.="\n</$tag>";return$writer->write("?>\n<$tag id=\"<?php echo \$_dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)}) ?>\"><?php ob_start()");}else{$node->data->leave=TRUE;$fname=$writer->formatWord($name);$node->closingCode="<?php }} call_user_func(reset(\$_l->blocks[$fname]), \$_l, get_defined_vars()) ?>";$func='_lb'.substr(md5($this->getCompiler()->getTemplateId().$name),0,10).'_'.preg_replace('#[^a-z0-9_]#i','_',$name);return"//\n// block $name\n//\n"."if (!function_exists(\$_l->blocks[$fname][] = '$func')) { "."function $func(\$_l, \$_args) { ".(PHP_VERSION_ID>50208?'extract($_args)':'foreach ($_args as $__k => $__v) $$__k = $__v');}}if($node->name==='snippet'){$node->data->name=$name='_'.$name;}if(isset($this->namedBlocks[$name])){throw
  4809. new
  4810. CompileException("Cannot redeclare static block '$name'");}$prolog=$this->namedBlocks?'':"if (\$_l->extends) { ob_end_clean(); return Nette\\Latte\\Macros\\CoreMacros::includeTemplate(\$_l->extends, get_defined_vars(), \$template)->render(); }\n";$top=empty($node->parentNode);$this->namedBlocks[$name]=TRUE;$include='call_user_func(reset($_l->blocks[%var]), $_l, '.($node->name==='snippet'?'$template->getParameters()':'get_defined_vars()').')';if($node->modifiers){$include="ob_start(); $include; echo %modify(ob_get_clean())";}if($node->name==='snippet'){if($node->htmlNode){$node->attrCode=$writer->write('<?php echo \' id="\' . $_control->getSnippetId(%var) . \'"\' ?>',(string)substr($name,1));return$writer->write($prolog.$include,$name);}$tag=trim($node->tokenizer->fetchWord(),'<>');$tag=$tag?$tag:'div';return$writer->write("$prolog ?>\n<$tag id=\"<?php echo \$_control->getSnippetId(%var) ?>\"><?php $include ?>\n</$tag><?php ",(string)substr($name,1),$name);}elseif($node->name==='define'){return$prolog;}else{return$writer->write($prolog.$include,$name);}}function
  4811. macroBlockEnd(MacroNode$node,PhpWriter$writer){if(isset($node->data->name)){if($node->name==='snippet'&&$node->htmlNode&&!$node->prefix&&preg_match("#^.*? n:\w+>\n?#s",$node->content,$m1)&&preg_match("#[ \t]*<[^<]+$#sD",$node->content,$m2)){$node->openingCode=$m1[0].$node->openingCode;$node->content=substr($node->content,strlen($m1[0]),-strlen($m2[0]));$node->closingCode.=$m2[0];}if(empty($node->data->leave)){if(!empty($node->data->dynamic)){$node->content.='<?php if (isset($_dynSnippets)) return $_dynSnippets; ?>';}$this->namedBlocks[$node->data->name]=$tmp=rtrim(ltrim($node->content,"\n")," \t");$node->content=substr_replace($node->content,$node->openingCode."\n",strspn($node->content,"\n"),strlen($tmp));$node->openingCode="<?php ?>";}}elseif($node->modifiers){return$writer->write('echo %modify(ob_get_clean())');}}function
  4812. macroIfset(MacroNode$node,PhpWriter$writer){if(!Strings::contains($node->args,'#')){return
  4813. FALSE;}$list=array();while(($name=$node->tokenizer->fetchWord())!==FALSE){$list[]=$name[0]==='#'?'$_l->blocks["'.substr($name,1).'"]':$name;}return'if (isset('.implode(', ',$list).')):';}function
  4814. macroControl(MacroNode$node,PhpWriter$writer){$pair=$node->tokenizer->fetchWord();if($pair===FALSE){throw
  4815. new
  4816. CompileException("Missing control name in {control}");}$pair=explode(':',$pair,2);$name=$writer->formatWord($pair[0]);$method=isset($pair[1])?ucfirst($pair[1]):'';$method=Strings::match($method,'#^('.self::RE_IDENTIFIER.'|)$#')?"render$method":"{\"render$method\"}";$param=$writer->formatArray();if(!Strings::contains($node->args,'=>')){$param=substr($param,6,-1);}return($name[0]==='$'?"if (is_object($name)) \$_ctrl = $name; else ":'').'$_ctrl = $_control->getComponent('.$name.'); '.'if ($_ctrl instanceof Nette\Application\UI\IRenderable) $_ctrl->validateControl(); '."\$_ctrl->$method($param)";}function
  4817. macroLink(MacroNode$node,PhpWriter$writer){return$writer->write('echo %escape(%modify('.($node->name==='plink'?'$_presenter':'$_control').'->link(%node.word, %node.array?)))');}function
  4818. macroIfCurrent(MacroNode$node,PhpWriter$writer){return$writer->write(($node->args?'try { $_presenter->link(%node.word, %node.array?); } catch (Nette\Application\UI\InvalidLinkException $e) {}':'').'; if ($_presenter->getLastCreatedRequestFlag("current")):');}function
  4819. macroContentType(MacroNode$node,PhpWriter$writer){if(Strings::contains($node->args,'xhtml')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_XHTML);}elseif(Strings::contains($node->args,'html')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_HTML);}elseif(Strings::contains($node->args,'xml')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_XML);}elseif(Strings::contains($node->args,'javascript')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_JS);}elseif(Strings::contains($node->args,'css')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_CSS);}elseif(Strings::contains($node->args,'calendar')){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_ICAL);}else{$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_TEXT);}if(Strings::contains($node->args,'/')){return$writer->write('$netteHttpResponse->setHeader("Content-Type", %var)',$node->args);}}function
  4820. macroStatus(MacroNode$node,PhpWriter$writer){return$writer->write((substr($node->args,-1)==='?'?'if (!$netteHttpResponse->isSent()) ':'').'$netteHttpResponse->setCode(%var)',(int)$node->args);}static
  4821. function
  4822. callBlock(\stdClass$context,$name,array$params){if(empty($context->blocks[$name])){throw
  4823. new
  4824. Nette\InvalidStateException("Cannot include undefined block '$name'.");}$block=reset($context->blocks[$name]);$block($context,$params);}static
  4825. function
  4826. callBlockParent(\stdClass$context,$name,array$params){if(empty($context->blocks[$name])||($block=next($context->blocks[$name]))===FALSE){throw
  4827. new
  4828. Nette\InvalidStateException("Cannot include undefined parent block '$name'.");}$block($context,$params);}static
  4829. function
  4830. renderSnippets(Nette\Application\UI\Control$control,\stdClass$local,array$params){$control->snippetMode=FALSE;$payload=$control->getPresenter()->getPayload();if(isset($local->blocks)){foreach($local->blocks
  4831. as$name=>$function){if($name[0]!=='_'||!$control->isControlInvalid(substr($name,1))){continue;}ob_start();$function=reset($function);$snippets=$function($local,$params);$payload->snippets[$id=$control->getSnippetId(substr($name,1))]=ob_get_clean();if($snippets){$payload->snippets+=$snippets;unset($payload->snippets[$id]);}}}if($control
  4832. instanceof
  4833. Nette\Application\UI\IRenderable){$queue=array($control);do{foreach(array_shift($queue)->getComponents()as$child){if($child
  4834. instanceof
  4835. Nette\Application\UI\IRenderable){if($child->isControlInvalid()){$child->snippetMode=TRUE;$child->render();$child->snippetMode=FALSE;}}elseif($child
  4836. instanceof
  4837. Nette\ComponentModel\IContainer){$queue[]=$child;}}}while($queue);}}}}namespace Nette\Utils{use
  4838. Nette;class
  4839. Tokenizer
  4840. extends
  4841. Nette\Object{public$tokens;public$position=0;public$ignored=array();private$input;private$re;private$types;public$current;function
  4842. __construct(array$patterns,$flags=''){$this->re='~('.implode(')|(',$patterns).')~A'.$flags;$keys=array_keys($patterns);$this->types=$keys===range(0,count($patterns)-1)?FALSE:$keys;}function
  4843. tokenize($input){$this->input=$input;if($this->types){$this->tokens=Strings::matchAll($input,$this->re);$len=0;$count=count($this->types);$line=1;foreach($this->tokens
  4844. as&$match){$type=NULL;for($i=1;$i<=$count;$i++){if(!isset($match[$i])){break;}elseif($match[$i]!=NULL){$type=$this->types[$i-1];break;}}$match=self::createToken($match[0],$type,$line);$len+=strlen($match['value']);$line+=substr_count($match['value'],"\n");}if($len!==strlen($input)){$errorOffset=$len;}}else{$this->tokens=Strings::split($input,$this->re,PREG_SPLIT_NO_EMPTY);if($this->tokens&&!Strings::match(end($this->tokens),$this->re)){$tmp=Strings::split($this->input,$this->re,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE);list(,$errorOffset)=end($tmp);}}if(isset($errorOffset)){$line=$errorOffset?substr_count($this->input,"\n",0,$errorOffset)+1:1;$col=$errorOffset-strrpos(substr($this->input,0,$errorOffset),"\n")+1;$token=str_replace("\n",'\n',substr($input,$errorOffset,10));throw
  4845. new
  4846. TokenizerException("Unexpected '$token' on line $line, column $col.");}return$this->tokens;}static
  4847. function
  4848. createToken($value,$type=NULL,$line=NULL){return
  4849. array('value'=>$value,'type'=>$type,'line'=>$line);}function
  4850. getOffset($i){$tokens=Strings::split($this->input,$this->re,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE);$offset=isset($tokens[$i])?$tokens[$i][1]:strlen($this->input);return
  4851. array($offset,($offset?substr_count($this->input,"\n",0,$offset)+1:1),$offset-strrpos(substr($this->input,0,$offset),"\n"));}function
  4852. fetch(){$args=func_get_args();return$this->scan($args,TRUE);}function
  4853. fetchToken(){$args=func_get_args();return$this->scan($args,TRUE)===FALSE?FALSE:$this->current;}function
  4854. fetchAll(){$args=func_get_args();return$this->scan($args,FALSE);}function
  4855. fetchUntil($arg){$args=func_get_args();return$this->scan($args,FALSE,TRUE,TRUE);}function
  4856. isNext($arg){$args=func_get_args();return(bool)$this->scan($args,TRUE,FALSE);}function
  4857. isPrev($arg){$args=func_get_args();return(bool)$this->scan($args,TRUE,FALSE,FALSE,TRUE);}function
  4858. hasNext(){return
  4859. isset($this->tokens[$this->position]);}function
  4860. hasPrev(){return$this->position>1;}function
  4861. isCurrent($arg){$args=func_get_args();if(is_array($this->current)){return
  4862. in_array($this->current['value'],$args,TRUE)||in_array($this->current['type'],$args,TRUE);}else{return
  4863. in_array($this->current,$args,TRUE);}}function
  4864. reset(){$this->position=0;$this->current=NULL;}private
  4865. function
  4866. scan($wanted,$first,$advance=TRUE,$neg=FALSE,$prev=FALSE){$res=FALSE;$pos=$this->position+($prev?-2:0);while(isset($this->tokens[$pos])){$token=$this->tokens[$pos];$pos+=$prev?-1:1;$value=is_array($token)?$token['value']:$token;$type=is_array($token)?$token['type']:$token;if(!$wanted||(in_array($value,$wanted,TRUE)||in_array($type,$wanted,TRUE))^$neg){if($advance){$this->position=$pos;$this->current=$token;}$res.=$value;if($first){break;}}elseif($neg||!in_array($type,$this->ignored,TRUE)){break;}}return$res;}}class
  4867. TokenizerException
  4868. extends\Exception{}}namespace Nette\Latte{use
  4869. Nette;class
  4870. MacroTokenizer
  4871. extends
  4872. Nette\Utils\Tokenizer{const
  4873. T_WHITESPACE=1,T_COMMENT=2,T_SYMBOL=3,T_NUMBER=4,T_VARIABLE=5,T_STRING=6,T_CAST=7,T_KEYWORD=8,T_CHAR=9;function
  4874. __construct($input){parent::__construct(array(self::T_WHITESPACE=>'\s+',self::T_COMMENT=>'(?s)/\*.*?\*/',self::T_STRING=>Parser::RE_STRING,self::T_KEYWORD=>'(?:true|false|null|and|or|xor|clone|new|instanceof|return|continue|break|[A-Z_][A-Z0-9_]{2,})(?![\w\pL_])',self::T_CAST=>'\((?:expand|string|array|int|integer|float|bool|boolean|object)\)',self::T_VARIABLE=>'\$[\w\pL_]+',self::T_NUMBER=>'[+-]?[0-9]+(?:\.[0-9]+)?(?:e[0-9]+)?',self::T_SYMBOL=>'[\w\pL_]+(?:-[\w\pL_]+)*',self::T_CHAR=>'::|=>|[^"\']'),'u');$this->ignored=array(self::T_COMMENT,self::T_WHITESPACE);$this->tokenize($input);}function
  4875. fetchWord(){$word=$this->fetchUntil(self::T_WHITESPACE,',');$this->fetch(',');$this->fetchAll(self::T_WHITESPACE,self::T_COMMENT);return$word;}}use
  4876. Nette\Utils\Strings;class
  4877. Parser
  4878. extends
  4879. Nette\Object{const
  4880. RE_STRING='\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';const
  4881. N_PREFIX='n:';public$defaultSyntax='latte';public$syntaxes=array('latte'=>array('\\{(?![\\s\'"{}])','\\}'),'double'=>array('\\{\\{(?![\\s\'"{}])','\\}\\}'),'asp'=>array('<%\s*','\s*%>'),'python'=>array('\\{[{%]\s*','\s*[%}]\\}'),'off'=>array('[^\x00-\xFF]',''));private$macroRe;private$input;private$output;private$offset;private$context;private$lastHtmlTag;private$syntaxEndTag;private$xmlMode;const
  4882. CONTEXT_TEXT='text',CONTEXT_CDATA='cdata',CONTEXT_TAG='tag',CONTEXT_ATTRIBUTE='attribute',CONTEXT_NONE='none',CONTEXT_COMMENT='comment';function
  4883. parse($input){if(substr($input,0,3)==="\xEF\xBB\xBF"){$input=substr($input,3);}if(!Strings::checkEncoding($input)){throw
  4884. new
  4885. Nette\InvalidArgumentException('Template is not valid UTF-8 stream.');}$input=str_replace("\r\n","\n",$input);$this->input=$input;$this->output=array();$this->offset=0;$this->setSyntax($this->defaultSyntax);$this->setContext(self::CONTEXT_TEXT);$this->lastHtmlTag=$this->syntaxEndTag=NULL;$this->xmlMode=(bool)preg_match('#^<\?xml\s#m',$input);while($this->offset<strlen($input)){$matches=$this->{"context".$this->context[0]}();if(!$matches){break;}elseif(!empty($matches['comment'])){$this->addToken(Token::COMMENT,$matches[0]);}elseif(!empty($matches['macro'])){$token=$this->addToken(Token::MACRO_TAG,$matches[0]);list($token->name,$token->value,$token->modifiers)=$this->parseMacroTag($matches['macro']);}$this->filter();}if($this->offset<strlen($input)){$this->addToken(Token::TEXT,substr($this->input,$this->offset));}return$this->output;}private
  4886. function
  4887. contextText(){$matches=$this->match('~
  4888. (?:(?<=\n|^)[ \t]*)?<(?P<closing>/?)(?P<tag>[a-z0-9:]+)| ## begin of HTML tag <tag </tag - ignores <!DOCTYPE
  4889. <(?P<htmlcomment>!--)| ## begin of HTML comment <!--
  4890. '.$this->macroRe.' ## macro tag
  4891. ~xsi');if(!empty($matches['htmlcomment'])){$this->addToken(Token::HTML_TAG_BEGIN,$matches[0]);$this->setContext(self::CONTEXT_COMMENT);}elseif(!empty($matches['tag'])){$token=$this->addToken(Token::HTML_TAG_BEGIN,$matches[0]);$token->name=$matches['tag'];$token->closing=(bool)$matches['closing'];$this->lastHtmlTag=$matches['closing'].strtolower($matches['tag']);$this->setContext(self::CONTEXT_TAG);}return$matches;}private
  4892. function
  4893. contextCData(){$matches=$this->match('~
  4894. </(?P<tag>'.$this->lastHtmlTag.')(?![a-z0-9:])| ## end HTML tag </tag
  4895. '.$this->macroRe.' ## macro tag
  4896. ~xsi');if(!empty($matches['tag'])){$token=$this->addToken(Token::HTML_TAG_BEGIN,$matches[0]);$token->name=$this->lastHtmlTag;$token->closing=TRUE;$this->lastHtmlTag='/'.$this->lastHtmlTag;$this->setContext(self::CONTEXT_TAG);}return$matches;}private
  4897. function
  4898. contextTag(){$matches=$this->match('~
  4899. (?P<end>\ ?/?>)([ \t]*\n)?| ## end of HTML tag
  4900. '.$this->macroRe.'| ## macro tag
  4901. \s*(?P<attr>[^\s/>={]+)(?:\s*=\s*(?P<value>["\']|[^\s/>{]+))? ## begin of HTML attribute
  4902. ~xsi');if(!empty($matches['end'])){$this->addToken(Token::HTML_TAG_END,$matches[0]);$this->setContext(!$this->xmlMode&&in_array($this->lastHtmlTag,array('script','style'))?self::CONTEXT_CDATA:self::CONTEXT_TEXT);}elseif(isset($matches['attr'])&&$matches['attr']!==''){$token=$this->addToken(Token::HTML_ATTRIBUTE,$matches[0]);$token->name=$matches['attr'];$token->value=isset($matches['value'])?$matches['value']:'';if($token->value==='"'||$token->value==="'"){if(Strings::startsWith($token->name,self::N_PREFIX)){$token->value='';if($m=$this->match('~(.*?)'.$matches['value'].'~xsi')){$token->value=$m[1];$token->text.=$m[0];}}else{$this->setContext(self::CONTEXT_ATTRIBUTE,$matches['value']);}}}return$matches;}private
  4903. function
  4904. contextAttribute(){$matches=$this->match('~
  4905. (?P<quote>'.$this->context[1].')| ## end of HTML attribute
  4906. '.$this->macroRe.' ## macro tag
  4907. ~xsi');if(!empty($matches['quote'])){$this->addToken(Token::TEXT,$matches[0]);$this->setContext(self::CONTEXT_TAG);}return$matches;}private
  4908. function
  4909. contextComment(){$matches=$this->match('~
  4910. (?P<htmlcomment>--\s*>)| ## end of HTML comment
  4911. '.$this->macroRe.' ## macro tag
  4912. ~xsi');if(!empty($matches['htmlcomment'])){$this->addToken(Token::HTML_TAG_END,$matches[0]);$this->setContext(self::CONTEXT_TEXT);}return$matches;}private
  4913. function
  4914. contextNone(){$matches=$this->match('~
  4915. '.$this->macroRe.' ## macro tag
  4916. ~xsi');return$matches;}private
  4917. function
  4918. match($re){if($matches=Strings::match($this->input,$re,PREG_OFFSET_CAPTURE,$this->offset)){$value=substr($this->input,$this->offset,$matches[0][1]-$this->offset);if($value!==''){$this->addToken(Token::TEXT,$value);}$this->offset=$matches[0][1]+strlen($matches[0][0]);foreach($matches
  4919. as$k=>$v)$matches[$k]=$v[0];}return$matches;}function
  4920. setContext($context,$quote=NULL){$this->context=array($context,$quote);return$this;}function
  4921. setSyntax($type){$type=$type?:$this->defaultSyntax;if(isset($this->syntaxes[$type])){$this->setDelimiters($this->syntaxes[$type][0],$this->syntaxes[$type][1]);}else{throw
  4922. new
  4923. Nette\InvalidArgumentException("Unknown syntax '$type'");}return$this;}function
  4924. setDelimiters($left,$right){$this->macroRe='
  4925. (?P<comment>'.$left.'\\*.*?\\*'.$right.'\n{0,2})|
  4926. '.$left.'
  4927. (?P<macro>(?:'.self::RE_STRING.'|\{
  4928. (?P<inner>'.self::RE_STRING.'|\{(?P>inner)\}|[^\'"{}])*+
  4929. \}|[^\'"{}])+?)
  4930. '.$right.'
  4931. (?P<rmargin>[ \t]*(?=\n))?
  4932. ';return$this;}function
  4933. parseMacroTag($tag){$match=Strings::match($tag,'~^
  4934. (
  4935. (?P<name>\?|/?[a-z]\w*+(?:[.:]\w+)*+(?!::|\())| ## ?, name, /name, but not function( or class::
  4936. (?P<noescape>!?)(?P<shortname>/?[=\~#%^&_]?) ## !expression, !=expression, ...
  4937. )(?P<args>.*?)
  4938. (?P<modifiers>\|[a-z](?:'.Parser::RE_STRING.'|[^\'"])*)?
  4939. ()$~isx');if(!$match){return
  4940. FALSE;}if($match['name']===''){$match['name']=$match['shortname']?:'=';if(!$match['noescape']&&substr($match['shortname'],0,1)!=='/'){$match['modifiers'].='|escape';}}return
  4941. array($match['name'],trim($match['args']),$match['modifiers']);}private
  4942. function
  4943. addToken($type,$text){$this->output[]=$token=new
  4944. Token;$token->type=$type;$token->text=$text;$token->line=substr_count($this->input,"\n",0,max(1,$this->offset-1))+1;return$token;}protected
  4945. function
  4946. filter(){$token=end($this->output);if($token->type===Token::MACRO_TAG&&$token->name==='/syntax'){$this->setSyntax($this->defaultSyntax);$token->type=Token::COMMENT;}elseif($token->type===Token::MACRO_TAG&&$token->name==='syntax'){$this->setSyntax($token->value);$token->type=Token::COMMENT;}elseif($token->type===Token::HTML_ATTRIBUTE&&$token->name==='n:syntax'){$this->setSyntax($token->value);$this->syntaxEndTag='/'.$this->lastHtmlTag;$token->type=Token::COMMENT;}elseif($token->type===Token::HTML_TAG_END&&$this->lastHtmlTag===$this->syntaxEndTag){$this->setSyntax($this->defaultSyntax);}elseif($token->type===Token::MACRO_TAG&&$token->name==='contentType'){if(preg_match('#html|xml#',$token->value,$m)){$this->xmlMode=$m[0]==='xml';$this->setContext(self::CONTEXT_TEXT);}else{$this->setContext(self::CONTEXT_NONE);}}}}class
  4947. PhpWriter
  4948. extends
  4949. Nette\Object{private$argsTokenizer;private$modifiers;private$compiler;static
  4950. function
  4951. using(MacroNode$node,Compiler$compiler=NULL){return
  4952. new
  4953. static($node->tokenizer,$node->modifiers,$compiler);}function
  4954. __construct(MacroTokenizer$argsTokenizer,$modifiers=NULL,Compiler$compiler=NULL){$this->argsTokenizer=$argsTokenizer;$this->modifiers=$modifiers;$this->compiler=$compiler;}function
  4955. write($mask){$args=func_get_args();array_shift($args);$word=strpos($mask,'%node.word')===FALSE?NULL:$this->argsTokenizer->fetchWord();$me=$this;$mask=Nette\Utils\Strings::replace($mask,'#%escape(\(([^()]*+|(?1))+\))#',function($m)use($me){return$me->escape(substr($m[1],1,-1));});$mask=Nette\Utils\Strings::replace($mask,'#%modify(\(([^()]*+|(?1))+\))#',function($m)use($me){return$me->formatModifiers(substr($m[1],1,-1));});return
  4956. Nette\Utils\Strings::replace($mask,'#([,+]\s*)?%(node\.word|node\.array|node\.args|var|raw)(\?)?(\s*\+\s*)?()#',function($m)use($me,$word,&$args){list(,$l,$macro,$cond,$r)=$m;switch($macro){case'node.word':$code=$me->formatWord($word);break;case'node.args':$code=$me->formatArgs();break;case'node.array':$code=$me->formatArray();$code=$cond&&$code==='array()'?'':$code;break;case'var':$code=var_export(array_shift($args),TRUE);break;case'raw':$code=(string)array_shift($args);break;}if($cond&&$code===''){return$r?$l:$r;}else{return$l.$code.$r;}});}function
  4957. formatModifiers($var){$modifiers=ltrim($this->modifiers,'|');if(!$modifiers){return$var;}$tokenizer=$this->preprocess(new
  4958. MacroTokenizer($modifiers));$inside=FALSE;while($token=$tokenizer->fetchToken()){if($token['type']===MacroTokenizer::T_WHITESPACE){$var=rtrim($var).' ';}elseif(!$inside){if($token['type']===MacroTokenizer::T_SYMBOL){if($this->compiler&&$token['value']==='escape'){$var=$this->escape($var);$tokenizer->fetch('|');}else{$var="\$template->".$token['value']."($var";$inside=TRUE;}}else{throw
  4959. new
  4960. CompileException("Modifier name must be alphanumeric string, '$token[value]' given.");}}else{if($token['value']===':'||$token['value']===','){$var=$var.', ';}elseif($token['value']==='|'){$var=$var.')';$inside=FALSE;}else{$var.=$this->canQuote($tokenizer)?"'$token[value]'":$token['value'];}}}return$inside?"$var)":$var;}function
  4961. formatArgs(){$out='';$tokenizer=$this->preprocess();while($token=$tokenizer->fetchToken()){$out.=$this->canQuote($tokenizer)?"'$token[value]'":$token['value'];}return$out;}function
  4962. formatArray(){$out='';$expand=NULL;$tokenizer=$this->preprocess();while($token=$tokenizer->fetchToken()){if($token['value']==='(expand)'&&$token['depth']===0){$expand=TRUE;$out.='),';}elseif($expand&&($token['value']===',')&&!$token['depth']){$expand=FALSE;$out.=', array(';}else{$out.=$this->canQuote($tokenizer)?"'$token[value]'":$token['value'];}}if($expand===NULL){return"array($out)";}else{return"array_merge(array($out".($expand?', array(':'')."))";}}function
  4963. formatWord($s){return(is_numeric($s)||preg_match('#^\\$|[\'"]|^true$|^false$|^null$#i',$s))?$s:'"'.$s.'"';}function
  4964. canQuote(MacroTokenizer$tokenizer){return$tokenizer->isCurrent(MacroTokenizer::T_SYMBOL)&&(!$tokenizer->hasPrev()||$tokenizer->isPrev(',','(','[','=','=>',':','?'))&&(!$tokenizer->hasNext()||$tokenizer->isNext(',',')',']','=','=>',':','|'));}function
  4965. preprocess(MacroTokenizer$tokenizer=NULL){$tokenizer=$tokenizer===NULL?$this->argsTokenizer:$tokenizer;$inTernary=$prev=NULL;$tokens=$arrays=array();while($token=$tokenizer->fetchToken()){$token['depth']=$depth=count($arrays);if($token['type']===MacroTokenizer::T_COMMENT){continue;}elseif($token['type']===MacroTokenizer::T_WHITESPACE){$tokens[]=$token;continue;}if($token['value']==='?'){$inTernary=$depth;}elseif($token['value']===':'){$inTernary=NULL;}elseif($inTernary===$depth&&($token['value']===','||$token['value']===')'||$token['value']===']')){$tokens[]=MacroTokenizer::createToken(':')+array('depth'=>$depth);$tokens[]=MacroTokenizer::createToken('null')+array('depth'=>$depth);$inTernary=NULL;}if($token['value']==='['){if($arrays[]=$prev['value']!==']'&&$prev['type']!==MacroTokenizer::T_SYMBOL&&$prev['type']!==MacroTokenizer::T_VARIABLE&&$prev['type']!==MacroTokenizer::T_KEYWORD){$tokens[]=MacroTokenizer::createToken('array')+array('depth'=>$depth);$token=MacroTokenizer::createToken('(');}}elseif($token['value']===']'){if(array_pop($arrays)===TRUE){$token=MacroTokenizer::createToken(')');}}elseif($token['value']==='('){$arrays[]='(';}elseif($token['value']===')'){array_pop($arrays);}$tokens[]=$prev=$token;}if($inTernary!==NULL){$tokens[]=MacroTokenizer::createToken(':')+array('depth'=>count($arrays));$tokens[]=MacroTokenizer::createToken('null')+array('depth'=>count($arrays));}$tokenizer=clone$tokenizer;$tokenizer->reset();$tokenizer->tokens=$tokens;return$tokenizer;}function
  4966. escape($s){switch($this->compiler->getContentType()){case
  4967. Compiler::CONTENT_XHTML:case
  4968. Compiler::CONTENT_HTML:$context=$this->compiler->getContext();switch($context[0]){case
  4969. Compiler::CONTEXT_SINGLE_QUOTED:case
  4970. Compiler::CONTEXT_DOUBLE_QUOTED:if($context[1]===Compiler::CONTENT_JS){$s="Nette\\Templating\\Helpers::escapeJs($s)";}elseif($context[1]===Compiler::CONTENT_CSS){$s="Nette\\Templating\\Helpers::escapeCss($s)";}$quote=$context[0]===Compiler::CONTEXT_DOUBLE_QUOTED?'':', ENT_QUOTES';return"htmlSpecialChars($s$quote)";case
  4971. Compiler::CONTEXT_COMMENT:return"Nette\\Templating\\Helpers::escapeHtmlComment($s)";case
  4972. Compiler::CONTENT_JS:case
  4973. Compiler::CONTENT_CSS:return'Nette\Templating\Helpers::escape'.ucfirst($context[0])."($s)";default:return"Nette\\Templating\\Helpers::escapeHtml($s, ENT_NOQUOTES)";}case
  4974. Compiler::CONTENT_XML:case
  4975. Compiler::CONTENT_JS:case
  4976. Compiler::CONTENT_CSS:case
  4977. Compiler::CONTENT_ICAL:return'Nette\Templating\Helpers::escape'.ucfirst($this->compiler->getContentType())."($s)";case
  4978. Compiler::CONTENT_TEXT:return$s;default:return"\$template->escape($s)";}}}class
  4979. Token
  4980. extends
  4981. Nette\Object{const
  4982. TEXT='text',MACRO_TAG='macroTag',HTML_TAG_BEGIN='htmlTagBegin',HTML_TAG_END='htmlTagEnd',HTML_ATTRIBUTE='htmlAttribute',COMMENT='comment';public$type;public$text;public$line;public$name;public$value;public$modifiers;public$closing;}}namespace Nette\Loaders{use
  4983. Nette;use
  4984. Nette\Utils\Strings;use
  4985. Nette\Caching\Cache;class
  4986. RobotLoader
  4987. extends
  4988. AutoLoader{const
  4989. RETRY_LIMIT=3;public$scanDirs=array();public$ignoreDirs='.*, *.old, *.bak, *.tmp, temp';public$acceptFiles='*.php, *.php5';public$autoRebuild=TRUE;private$list=array();private$files;private$rebuilt=FALSE;private$checked=array();private$cacheStorage;function
  4990. __construct(){if(!extension_loaded('tokenizer')){throw
  4991. new
  4992. Nette\NotSupportedException("PHP extension Tokenizer is not loaded.");}}function
  4993. register(){$this->list=$this->getCache()->load($this->getKey(),callback($this,'_rebuildCallback'));parent::register();return$this;}function
  4994. tryLoad($type){$type=ltrim(strtolower($type),'\\');$info=&$this->list[$type];if($this->autoRebuild&&empty($this->checked[$type])&&(is_array($info)?!is_file($info[0]):$info<self::RETRY_LIMIT)){$info=is_int($info)?$info+1:0;$this->checked[$type]=TRUE;if($this->rebuilt){$this->getCache()->save($this->getKey(),$this->list,array(Cache::CONSTS=>'Nette\Framework::REVISION'));}else{$this->rebuild();}}if(isset($info[0])){Nette\Utils\LimitedScope::load($info[0],TRUE);if($this->autoRebuild&&!class_exists($type,FALSE)&&!interface_exists($type,FALSE)&&(PHP_VERSION_ID<50400||!trait_exists($type,FALSE))){$info=0;$this->checked[$type]=TRUE;if($this->rebuilt){$this->getCache()->save($this->getKey(),$this->list,array(Cache::CONSTS=>'Nette\Framework::REVISION'));}else{$this->rebuild();}}self::$count++;}}function
  4995. rebuild(){$this->getCache()->save($this->getKey(),callback($this,'_rebuildCallback'));$this->rebuilt=TRUE;}function
  4996. _rebuildCallback(&$dp){foreach($this->list
  4997. as$pair){if(is_array($pair)){$this->files[$pair[0]]=$pair[1];}}foreach(array_unique($this->scanDirs)as$dir){$this->scanDirectory($dir);}$this->files=NULL;$dp=array(Cache::CONSTS=>'Nette\Framework::REVISION');return$this->list;}function
  4998. getIndexedClasses(){$res=array();foreach($this->list
  4999. as$class=>$pair){if(is_array($pair)){$res[$pair[2]]=$pair[0];}}return$res;}function
  5000. addDirectory($path){foreach((array)$path
  5001. as$val){$real=realpath($val);if($real===FALSE){throw
  5002. new
  5003. Nette\DirectoryNotFoundException("Directory '$val' not found.");}$this->scanDirs[]=$real;}return$this;}private
  5004. function
  5005. addClass($class,$file,$time){$lClass=strtolower($class);if(isset($this->list[$lClass][0])&&($file2=$this->list[$lClass][0])!==$file&&is_file($file2)){if($this->files[$file2]!==filemtime($file2)){$this->scanScript($file2);return$this->addClass($class,$file,$time);}$e=new
  5006. Nette\InvalidStateException("Ambiguous class '$class' resolution; defined in $file and in ".$this->list[$lClass][0].".");{throw$e;}}$this->list[$lClass]=array($file,$time,$class);$this->files[$file]=$time;}private
  5007. function
  5008. scanDirectory($dir){if(is_dir($dir)){$ignoreDirs=is_array($this->ignoreDirs)?$this->ignoreDirs:Strings::split($this->ignoreDirs,'#[,\s]+#');$disallow=array();foreach($ignoreDirs
  5009. as$item){if($item=realpath($item)){$disallow[$item]=TRUE;}}$iterator=Nette\Utils\Finder::findFiles(is_array($this->acceptFiles)?$this->acceptFiles:Strings::split($this->acceptFiles,'#[,\s]+#'))->filter(function($file)use(&$disallow){return!isset($disallow[$file->getPathname()]);})->from($dir)->exclude($ignoreDirs)->filter($filter=function($dir)use(&$disallow){$path=$dir->getPathname();if(is_file("$path/netterobots.txt")){foreach(file("$path/netterobots.txt")as$s){if($matches=Strings::match($s,'#^(?:disallow\\s*:)?\\s*(\\S+)#i')){$disallow[$path.str_replace('/',DIRECTORY_SEPARATOR,rtrim('/'.ltrim($matches[1],'/'),'/'))]=TRUE;}}}return!isset($disallow[$path]);});$filter(new\SplFileInfo($dir));}else{$iterator=new\ArrayIterator(array(new\SplFileInfo($dir)));}foreach($iterator
  5010. as$entry){$path=$entry->getPathname();if(!isset($this->files[$path])||$this->files[$path]!==$entry->getMTime()){$this->scanScript($path);}}}private
  5011. function
  5012. scanScript($file){$T_NAMESPACE=PHP_VERSION_ID<50300?-1:T_NAMESPACE;$T_NS_SEPARATOR=PHP_VERSION_ID<50300?-1:T_NS_SEPARATOR;$T_TRAIT=PHP_VERSION_ID<50400?-1:T_TRAIT;$expected=FALSE;$namespace='';$level=$minLevel=0;$time=filemtime($file);$s=file_get_contents($file);foreach($this->list
  5013. as$class=>$pair){if(is_array($pair)&&$pair[0]===$file){unset($this->list[$class]);}}if($matches=Strings::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
  5014. T_COMMENT:case
  5015. T_DOC_COMMENT:case
  5016. T_WHITESPACE:continue
  5017. 2;case$T_NS_SEPARATOR:case
  5018. T_STRING:if($expected){$name.=$token[1];}continue
  5019. 2;case$T_NAMESPACE:case
  5020. T_CLASS:case
  5021. T_INTERFACE:case$T_TRAIT:$expected=$token[0];$name='';continue
  5022. 2;case
  5023. T_CURLY_OPEN:case
  5024. T_DOLLAR_OPEN_CURLY_BRACES:$level++;}}if($expected){switch($expected){case
  5025. T_CLASS:case
  5026. T_INTERFACE:case$T_TRAIT:if($level===$minLevel){$this->addClass($namespace.$name,$file,$time);}break;case$T_NAMESPACE:$namespace=$name?$name.'\\':'';$minLevel=$token==='{'?1:0;}$expected=NULL;}if($token==='{'){$level++;}elseif($token==='}'){$level--;}}}function
  5027. setCacheStorage(Nette\Caching\IStorage$storage){$this->cacheStorage=$storage;return$this;}function
  5028. getCacheStorage(){return$this->cacheStorage;}protected
  5029. function
  5030. getCache(){if(!$this->cacheStorage){trigger_error('Missing cache storage.',E_USER_WARNING);$this->cacheStorage=new
  5031. Nette\Caching\Storages\DevNullStorage;}return
  5032. new
  5033. Cache($this->cacheStorage,'Nette.RobotLoader');}protected
  5034. function
  5035. getKey(){return
  5036. array($this->ignoreDirs,$this->acceptFiles,$this->scanDirs);}}}namespace Nette\Mail{use
  5037. Nette;use
  5038. Nette\Utils\Strings;class
  5039. MimePart
  5040. extends
  5041. Nette\Object{const
  5042. ENCODING_BASE64='base64',ENCODING_7BIT='7bit',ENCODING_8BIT='8bit',ENCODING_QUOTED_PRINTABLE='quoted-printable';const
  5043. EOL="\r\n";const
  5044. LINE_LENGTH=76;private$headers=array();private$parts=array();private$body;function
  5045. setHeader($name,$value,$append=FALSE){if(!$name||preg_match('#[^a-z0-9-]#i',$name)){throw
  5046. new
  5047. Nette\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
  5048. as$email=>$recipient){if($recipient!==NULL&&!Strings::checkEncoding($recipient)){Nette\Utils\Validators::assert($recipient,'unicode',"header '$name'");}if(preg_match('#[\r\n]#',$recipient)){throw
  5049. new
  5050. Nette\InvalidArgumentException("Name must not contain line separator.");}Nette\Utils\Validators::assert($email,'email',"header '$name'");$tmp[$email]=$recipient;}}else{$value=(string)$value;if(!Strings::checkEncoding($value)){throw
  5051. new
  5052. Nette\InvalidArgumentException("Header is not valid UTF-8 string.");}$this->headers[$name]=preg_replace('#[\r\n]+#',' ',$value);}return$this;}function
  5053. getHeader($name){return
  5054. isset($this->headers[$name])?$this->headers[$name]:NULL;}function
  5055. clearHeader($name){unset($this->headers[$name]);return$this;}function
  5056. getEncodedHeader($name){$offset=strlen($name)+2;if(!isset($this->headers[$name])){return
  5057. NULL;}elseif(is_array($this->headers[$name])){$s='';foreach($this->headers[$name]as$email=>$name){if($name!=NULL){$s.=self::encodeHeader(strpbrk($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
  5058. substr($s,0,-1);}elseif(preg_match('#^(\S+; (?:file)?name=)"(.*)"$#',$this->headers[$name],$m)){$offset+=strlen($m[1]);return$m[1].'"'.self::encodeHeader($m[2],$offset).'"';}else{return
  5059. self::encodeHeader($this->headers[$name],$offset);}}function
  5060. getHeaders(){return$this->headers;}function
  5061. setContentType($contentType,$charset=NULL){$this->setHeader('Content-Type',$contentType.($charset?"; charset=$charset":''));return$this;}function
  5062. setEncoding($encoding){$this->setHeader('Content-Transfer-Encoding',$encoding);return$this;}function
  5063. getEncoding(){return$this->getHeader('Content-Transfer-Encoding');}function
  5064. addPart(MimePart$part=NULL){return$this->parts[]=$part===NULL?new
  5065. self:$part;}function
  5066. setBody($body){$this->body=$body;return$this;}function
  5067. getBody(){return$this->body;}function
  5068. generateMessage(){$output='';$boundary='--------'.Strings::random();foreach($this->headers
  5069. 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
  5070. self::ENCODING_QUOTED_PRINTABLE:$output.=function_exists('quoted_printable_encode')?quoted_printable_encode($body):self::encodeQuotedPrintable($body);break;case
  5071. self::ENCODING_BASE64:$output.=rtrim(chunk_split(base64_encode($body),self::LINE_LENGTH,self::EOL));break;case
  5072. self::ENCODING_7BIT:$body=preg_replace('#[\x80-\xFF]+#','',$body);case
  5073. self::ENCODING_8BIT:$body=str_replace(array("\x00","\r"),'',$body);$body=str_replace("\n",self::EOL,$body);$output.=$body;break;default:throw
  5074. new
  5075. Nette\InvalidStateException('Unknown encoding.');}}if($this->parts){if(substr($output,-strlen(self::EOL))!==self::EOL){$output.=self::EOL;}foreach($this->parts
  5076. as$part){$output.='--'.$boundary.self::EOL.$part->generateMessage().self::EOL;}$output.='--'.$boundary.'--';}return$output;}private
  5077. static
  5078. function
  5079. encodeHeader($s,&$offset=0){$o='';if($offset>=55){$o=self::EOL."\t";$offset=1;}if(strspn($s,"!\"#$%&\'()*+,-./0123456789:;<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz{|}=? _\r\n\t")===strlen($s)&&($offset+strlen($s)<=self::LINE_LENGTH)){$offset+=strlen($s);return$o.$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;}}class
  5080. Message
  5081. extends
  5082. MimePart{const
  5083. HIGH=1,NORMAL=3,LOW=5;public
  5084. static$defaultMailer='Nette\Mail\SendmailMailer';public
  5085. static$defaultHeaders=array('MIME-Version'=>'1.0','X-Mailer'=>'Nette Framework');private$mailer;private$attachments=array();private$inlines=array();private$html;private$basePath;function
  5086. __construct(){foreach(static::$defaultHeaders
  5087. as$name=>$value){$this->setHeader($name,$value);}$this->setHeader('Date',date('r'));}function
  5088. setFrom($email,$name=NULL){$this->setHeader('From',$this->formatEmail($email,$name));return$this;}function
  5089. getFrom(){return$this->getHeader('From');}function
  5090. addReplyTo($email,$name=NULL){$this->setHeader('Reply-To',$this->formatEmail($email,$name),TRUE);return$this;}function
  5091. setSubject($subject){$this->setHeader('Subject',$subject);return$this;}function
  5092. getSubject(){return$this->getHeader('Subject');}function
  5093. addTo($email,$name=NULL){$this->setHeader('To',$this->formatEmail($email,$name),TRUE);return$this;}function
  5094. addCc($email,$name=NULL){$this->setHeader('Cc',$this->formatEmail($email,$name),TRUE);return$this;}function
  5095. addBcc($email,$name=NULL){$this->setHeader('Bcc',$this->formatEmail($email,$name),TRUE);return$this;}private
  5096. function
  5097. formatEmail($email,$name){if(!$name&&preg_match('#^(.+) +<(.*)>$#',$email,$matches)){return
  5098. array($matches[2]=>$matches[1]);}else{return
  5099. array($email=>$name);}}function
  5100. setReturnPath($email){$this->setHeader('Return-Path',$email);return$this;}function
  5101. getReturnPath(){return$this->getHeader('From');}function
  5102. setPriority($priority){$this->setHeader('X-Priority',(int)$priority);return$this;}function
  5103. getPriority(){return$this->getHeader('X-Priority');}function
  5104. setHtmlBody($html,$basePath=NULL){$this->html=$html;$this->basePath=$basePath;return$this;}function
  5105. getHtmlBody(){return$this->html;}function
  5106. addEmbeddedFile($file,$content=NULL,$contentType=NULL){return$this->inlines[$file]=$this->createAttachment($file,$content,$contentType,'inline')->setHeader('Content-ID',$this->getRandomId());}function
  5107. addAttachment($file,$content=NULL,$contentType=NULL){return$this->attachments[]=$this->createAttachment($file,$content,$contentType,'attachment');}private
  5108. function
  5109. createAttachment($file,$content,$contentType,$disposition){$part=new
  5110. MimePart;if($content===NULL){$content=file_get_contents($file);if($content===FALSE){throw
  5111. new
  5112. Nette\FileNotFoundException("Unable to read file '$file'.");}}else{$content=(string)$content;}$part->setBody($content);$part->setContentType($contentType?$contentType:Nette\Utils\MimeTypeDetector::fromString($content));$part->setEncoding(preg_match('#(multipart|message)/#A',$contentType)?self::ENCODING_8BIT:self::ENCODING_BASE64);$part->setHeader('Content-Disposition',$disposition.'; filename="'.Strings::fixEncoding(basename($file)).'"');return$part;}function
  5113. send(){$this->getMailer()->send($this->build());}function
  5114. setMailer(IMailer$mailer){$this->mailer=$mailer;return$this;}function
  5115. getMailer(){if($this->mailer===NULL){$this->mailer=is_object(static::$defaultMailer)?static::$defaultMailer:new
  5116. static::$defaultMailer;}return$this->mailer;}function
  5117. generateMessage(){if($this->getHeader('Message-ID')){return
  5118. parent::generateMessage();}else{return$this->build()->generateMessage();}}protected
  5119. function
  5120. build(){$mail=clone$this;$mail->setHeader('Message-ID',$this->getRandomId());$mail->buildHtml();$mail->buildText();$cursor=$mail;if($mail->attachments){$tmp=$cursor->setContentType('multipart/mixed');$cursor=$cursor->addPart();foreach($mail->attachments
  5121. 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
  5122. as$name=>$value){$tmp->addPart($value);}}$alt->setContentType('text/html','UTF-8')->setEncoding(preg_match('#\S{990}#',$mail->html)?self::ENCODING_QUOTED_PRINTABLE:(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('#\S{990}#',$text)?self::ENCODING_QUOTED_PRINTABLE:(preg_match('#[\x80-\xFF]#',$text)?self::ENCODING_8BIT:self::ENCODING_7BIT))->setBody($text);return$mail;}protected
  5123. function
  5124. buildHtml(){if($this->html
  5125. instanceof
  5126. Nette\Templating\ITemplate){$this->html->mail=$this;if($this->basePath===NULL&&$this->html
  5127. instanceof
  5128. Nette\Templating\IFileTemplate){$this->basePath=dirname($this->html->getFile());}$this->html=$this->html->__toString(TRUE);}if($this->basePath!==FALSE){$cids=array();$matches=Strings::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];if(!isset($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:{$cids[$file]}{$m[2][0]}",$m[0][1],strlen($m[0][0]));}}if(!$this->getSubject()&&$matches=Strings::match($this->html,'#<title>(.+?)</title>#is')){$this->setSubject(html_entity_decode($matches[1],ENT_QUOTES,'UTF-8'));}}protected
  5129. function
  5130. buildText(){$text=$this->getBody();if($text
  5131. instanceof
  5132. Nette\Templating\ITemplate){$text->mail=$this;$this->setBody($text->__toString(TRUE));}elseif($text==NULL&&$this->html!=NULL){$text=Strings::replace($this->html,array('#<(style|script|head).*</\\1>#Uis'=>'','#<t[dh][ >]#i'=>" $0",'#[\r\n]+#'=>' ','#<(/?p|/?h\d|li|br|/tr)[ >/]#i'=>"\n$0"));$text=html_entity_decode(strip_tags($text),ENT_QUOTES,'UTF-8');$text=Strings::replace($text,'#[ \t]+#',' ');$this->setBody(trim($text));}}private
  5133. function
  5134. getRandomId(){return'<'.Strings::random().'@'.(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:(isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost')).'>';}}class
  5135. SendmailMailer
  5136. extends
  5137. Nette\Object
  5138. implements
  5139. IMailer{public$commandArgs;function
  5140. send(Message$mail){$tmp=clone$mail;$tmp->setHeader('Subject',NULL);$tmp->setHeader('To',NULL);$parts=explode(Message::EOL.Message::EOL,$tmp->generateMessage(),2);Nette\Diagnostics\Debugger::tryError();$args=array(str_replace(Message::EOL,PHP_EOL,$mail->getEncodedHeader('To')),str_replace(Message::EOL,PHP_EOL,$mail->getEncodedHeader('Subject')),str_replace(Message::EOL,PHP_EOL,$parts[1]),str_replace(Message::EOL,PHP_EOL,$parts[0]));if($this->commandArgs){$args[]=(string)$this->commandArgs;}$res=call_user_func_array('mail',$args);if(Nette\Diagnostics\Debugger::catchError($e)){throw
  5141. new
  5142. Nette\InvalidStateException('mail(): '.$e->getMessage(),0,$e);}elseif(!$res){throw
  5143. new
  5144. Nette\InvalidStateException('Unable to send email.');}}}class
  5145. SmtpMailer
  5146. extends
  5147. Nette\Object
  5148. implements
  5149. IMailer{private$connection;private$host;private$port;private$username;private$password;private$secure;private$timeout;function
  5150. __construct(array$options=array()){if(isset($options['host'])){$this->host=$options['host'];$this->port=isset($options['port'])?(int)$options['port']:NULL;}else{$this->host=ini_get('SMTP');$this->port=(int)ini_get('smtp_port');}$this->username=isset($options['username'])?$options['username']:'';$this->password=isset($options['password'])?$options['password']:'';$this->secure=isset($options['secure'])?$options['secure']:'';$this->timeout=isset($options['timeout'])?(int)$options['timeout']:20;if(!$this->port){$this->port=$this->secure==='ssl'?465:25;}}function
  5151. send(Message$mail){$data=$mail->generateMessage();$this->connect();$from=$mail->getHeader('From');if($from){$from=array_keys($from);$this->write("MAIL FROM:<$from[0]>",250);}foreach(array_merge((array)$mail->getHeader('To'),(array)$mail->getHeader('Cc'),(array)$mail->getHeader('Bcc'))as$email=>$name){$this->write("RCPT TO:<$email>",array(250,251));}$this->write('DATA',354);$data=preg_replace('#^\.#m','..',$data);$this->write($data);$this->write('.',250);$this->write('QUIT',221);$this->disconnect();}private
  5152. function
  5153. connect(){$this->connection=@fsockopen(($this->secure==='ssl'?'ssl://':'').$this->host,$this->port,$errno,$error,$this->timeout);if(!$this->connection){throw
  5154. new
  5155. SmtpException($error,$errno);}stream_set_timeout($this->connection,$this->timeout,0);$this->read();$self=isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost';$this->write("EHLO $self");if((int)$this->read()!==250){$this->write("HELO $self",250);}if($this->secure==='tls'){$this->write('STARTTLS',220);if(!stream_socket_enable_crypto($this->connection,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT)){throw
  5156. new
  5157. SmtpException('Unable to connect via TLS.');}$this->write("EHLO $self",250);}if($this->username!=NULL&&$this->password!=NULL){$this->write('AUTH LOGIN',334);$this->write(base64_encode($this->username),334,'username');$this->write(base64_encode($this->password),235,'password');}}private
  5158. function
  5159. disconnect(){fclose($this->connection);$this->connection=NULL;}private
  5160. function
  5161. write($line,$expectedCode=NULL,$message=NULL){fwrite($this->connection,$line.Message::EOL);if($expectedCode&&!in_array((int)$this->read(),(array)$expectedCode)){throw
  5162. new
  5163. SmtpException('SMTP server did not accept '.($message?$message:$line));}}private
  5164. function
  5165. read(){$s='';while(($line=fgets($this->connection,1e3))!=NULL){$s.=$line;if(substr($line,3,1)===' '){break;}}return$s;}}class
  5166. SmtpException
  5167. extends\Exception{}}namespace Nette\Reflection{use
  5168. Nette;class
  5169. Annotation
  5170. extends
  5171. Nette\Object
  5172. implements
  5173. IAnnotation{function
  5174. __construct(array$values){foreach($values
  5175. as$k=>$v){$this->$k=$v;}}function
  5176. __toString(){return$this->value;}}use
  5177. Nette\Utils\Strings;/**
  5178. * Annotations support for PHP.
  5179. *
  5180. * @author David Grudl
  5181. * @Annotation
  5182. */final
  5183. class
  5184. AnnotationsParser{const
  5185. RE_STRING='\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';const
  5186. RE_IDENTIFIER='[_a-zA-Z\x7F-\xFF][_a-zA-Z0-9\x7F-\xFF-\\\]*';public
  5187. static$useReflection;public
  5188. static$inherited=array('description','param','return');private
  5189. static$cache;private
  5190. static$timestamps;private
  5191. static$cacheStorage;final
  5192. function
  5193. __construct(){throw
  5194. new
  5195. Nette\StaticClassException;}static
  5196. function
  5197. getAll(\Reflector$r){if($r
  5198. instanceof\ReflectionClass){$type=$r->getName();$member='';}elseif($r
  5199. instanceof\ReflectionMethod){$type=$r->getDeclaringClass()->getName();$member=$r->getName();}else{$type=$r->getDeclaringClass()->getName();$member='$'.$r->getName();}if(!self::$useReflection){$file=$r
  5200. instanceof\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
  5201. self::$cache[$type][$member];}if(self::$useReflection===NULL){self::$useReflection=(bool)ClassType::from(__CLASS__)->getDocComment();}if(self::$useReflection){$annotations=self::parseComment($r->getDocComment());}else{if(!self::$cacheStorage){self::$cacheStorage=new
  5202. Nette\Caching\Storages\DevNullStorage;}$outerCache=new
  5203. Nette\Caching\Cache(self::$cacheStorage,'Nette.Reflection.Annotations');if(self::$cache===NULL){self::$cache=(array)$outerCache->offsetGet('list');self::$timestamps=isset(self::$cache['*'])?self::$cache['*']:array();}if(!isset(self::$cache[$type])&&$file){self::$cache['*'][$file]=filemtime($file);self::parseScript($file);$outerCache->save('list',self::$cache);}if(isset(self::$cache[$type][$member])){$annotations=self::$cache[$type][$member];}else{$annotations=array();}}if($r
  5204. instanceof\ReflectionMethod&&!$r->isPrivate()&&(!$r->isConstructor()||!empty($annotations['inheritdoc'][0]))){try{$inherited=self::getAll(new\ReflectionMethod(get_parent_class($type),$member));}catch(\ReflectionException$e){try{$inherited=self::getAll($r->getPrototype());}catch(\ReflectionException$e){$inherited=array();}}$annotations+=array_intersect_key($inherited,array_flip(self::$inherited));}return
  5205. self::$cache[$type][$member]=$annotations;}private
  5206. static
  5207. function
  5208. parseComment($comment){static$tokens=array('true'=>TRUE,'false'=>FALSE,'null'=>NULL,''=>TRUE);$res=array();$comment=preg_replace('#^\s*\*\s?#ms','',trim($comment,'/*'));$parts=preg_split('#^\s*(?=@'.self::RE_IDENTIFIER.')#m',$comment,2);$description=trim($parts[0]);if($description!==''){$res['description']=array($description);}$matches=Strings::matchAll(isset($parts[1])?$parts[1]:'','~
  5209. (?<=\s|^)@('.self::RE_IDENTIFIER.')[ \t]* ## annotation
  5210. (
  5211. \((?>'.self::RE_STRING.'|[^\'")@]+)+\)| ## (value)
  5212. [^(@\r\n][^@\r\n]*|) ## value
  5213. ~xi');foreach($matches
  5214. as$match){list(,$name,$value)=$match;if(substr($value,0,1)==='('){$items=array();$key='';$val=TRUE;$value[0]=',';while($m=Strings::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\ArrayObject($value,\ArrayObject::ARRAY_AS_PROPS):$value;}}return$res;}private
  5215. static
  5216. function
  5217. 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(Strings::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
  5218. T_DOC_COMMENT:$docComment=$token[1];case
  5219. T_WHITESPACE:case
  5220. T_COMMENT:continue
  5221. 2;case
  5222. T_STRING:case$T_NS_SEPARATOR:case
  5223. T_VARIABLE:if($expected){$name.=$token[1];}continue
  5224. 2;case
  5225. T_FUNCTION:case
  5226. T_VAR:case
  5227. T_PUBLIC:case
  5228. T_PROTECTED:case$T_NAMESPACE:case
  5229. T_CLASS:case
  5230. T_INTERFACE:$expected=$token[0];$name=NULL;continue
  5231. 2;case
  5232. T_STATIC:case
  5233. T_ABSTRACT:case
  5234. T_FINAL:continue
  5235. 2;case
  5236. T_CURLY_OPEN:case
  5237. T_DOLLAR_OPEN_CURLY_BRACES:$level++;}}if($expected){switch($expected){case
  5238. T_CLASS:case
  5239. T_INTERFACE:$class=$namespace.$name;$classLevel=$level;$name='';case
  5240. T_FUNCTION:if($token==='&'){continue
  5241. 2;}case
  5242. T_VAR:case
  5243. T_PUBLIC:case
  5244. 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;}}}}static
  5245. function
  5246. setCacheStorage(Nette\Caching\IStorage$storage){self::$cacheStorage=$storage;}static
  5247. function
  5248. getCacheStorage(){return
  5249. self::$cacheStorage;}}use
  5250. Nette\ObjectMixin;class
  5251. Extension
  5252. extends\ReflectionExtension{function
  5253. __toString(){return'Extension '.$this->getName();}function
  5254. getClasses(){$res=array();foreach(parent::getClassNames()as$val){$res[$val]=new
  5255. ClassType($val);}return$res;}function
  5256. getFunctions(){foreach($res=parent::getFunctions()as$key=>$val){$res[$key]=new
  5257. GlobalFunction($key);}return$res;}static
  5258. function
  5259. getReflection(){return
  5260. new
  5261. ClassType(get_called_class());}function
  5262. __call($name,$args){return
  5263. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  5264. ObjectMixin::get($this,$name);}function
  5265. __set($name,$value){return
  5266. ObjectMixin::set($this,$name,$value);}function
  5267. __isset($name){return
  5268. ObjectMixin::has($this,$name);}function
  5269. __unset($name){ObjectMixin::remove($this,$name);}}class
  5270. GlobalFunction
  5271. extends\ReflectionFunction{private$value;function
  5272. __construct($name){parent::__construct($this->value=$name);}function
  5273. toCallback(){return
  5274. new
  5275. Nette\Callback($this->value);}function
  5276. __toString(){return'Function '.$this->getName().'()';}function
  5277. getClosure(){return$this->isClosure()?$this->value:NULL;}function
  5278. getExtension(){return($name=$this->getExtensionName())?new
  5279. Extension($name):NULL;}function
  5280. getParameters(){foreach($res=parent::getParameters()as$key=>$val){$res[$key]=new
  5281. Parameter($this->value,$val->getName());}return$res;}static
  5282. function
  5283. getReflection(){return
  5284. new
  5285. ClassType(get_called_class());}function
  5286. __call($name,$args){return
  5287. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  5288. ObjectMixin::get($this,$name);}function
  5289. __set($name,$value){return
  5290. ObjectMixin::set($this,$name,$value);}function
  5291. __isset($name){return
  5292. ObjectMixin::has($this,$name);}function
  5293. __unset($name){ObjectMixin::remove($this,$name);}}class
  5294. Method
  5295. extends\ReflectionMethod{static
  5296. function
  5297. from($class,$method){return
  5298. new
  5299. static(is_object($class)?get_class($class):$class,$method);}function
  5300. toCallback(){return
  5301. new
  5302. Nette\Callback(array(parent::getDeclaringClass()->getName(),$this->getName()));}function
  5303. __toString(){return'Method '.parent::getDeclaringClass()->getName().'::'.$this->getName().'()';}function
  5304. getDeclaringClass(){return
  5305. new
  5306. ClassType(parent::getDeclaringClass()->getName());}function
  5307. getPrototype(){$prototype=parent::getPrototype();return
  5308. new
  5309. Method($prototype->getDeclaringClass()->getName(),$prototype->getName());}function
  5310. getExtension(){return($name=$this->getExtensionName())?new
  5311. Extension($name):NULL;}function
  5312. getParameters(){$me=array(parent::getDeclaringClass()->getName(),$this->getName());foreach($res=parent::getParameters()as$key=>$val){$res[$key]=new
  5313. Parameter($me,$val->getName());}return$res;}function
  5314. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  5315. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  5316. isset($res[$name])?end($res[$name]):NULL;}function
  5317. getAnnotations(){return
  5318. AnnotationsParser::getAll($this);}function
  5319. getDescription(){return$this->getAnnotation('description');}static
  5320. function
  5321. getReflection(){return
  5322. new
  5323. ClassType(get_called_class());}function
  5324. __call($name,$args){return
  5325. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  5326. ObjectMixin::get($this,$name);}function
  5327. __set($name,$value){return
  5328. ObjectMixin::set($this,$name,$value);}function
  5329. __isset($name){return
  5330. ObjectMixin::has($this,$name);}function
  5331. __unset($name){ObjectMixin::remove($this,$name);}}class
  5332. Parameter
  5333. extends\ReflectionParameter{private$function;function
  5334. __construct($function,$parameter){parent::__construct($this->function=$function,$parameter);}function
  5335. getClass(){return($ref=parent::getClass())?new
  5336. ClassType($ref->getName()):NULL;}function
  5337. getClassName(){try{return($ref=parent::getClass())?$ref->getName():NULL;}catch(\ReflectionException$e){if(preg_match('#Class (.+) does not exist#',$e->getMessage(),$m)){return$m[1];}throw$e;}}function
  5338. getDeclaringClass(){return($ref=parent::getDeclaringClass())?new
  5339. ClassType($ref->getName()):NULL;}function
  5340. getDeclaringFunction(){return
  5341. is_array($this->function)?new
  5342. Method($this->function[0],$this->function[1]):new
  5343. GlobalFunction($this->function);}function
  5344. __toString(){return'Parameter $'.parent::getName().' in '.$this->getDeclaringFunction();}static
  5345. function
  5346. getReflection(){return
  5347. new
  5348. ClassType(get_called_class());}function
  5349. __call($name,$args){return
  5350. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  5351. ObjectMixin::get($this,$name);}function
  5352. __set($name,$value){return
  5353. ObjectMixin::set($this,$name,$value);}function
  5354. __isset($name){return
  5355. ObjectMixin::has($this,$name);}function
  5356. __unset($name){ObjectMixin::remove($this,$name);}}class
  5357. Property
  5358. extends\ReflectionProperty{function
  5359. __toString(){return'Property '.parent::getDeclaringClass()->getName().'::$'.$this->getName();}function
  5360. getDeclaringClass(){return
  5361. new
  5362. ClassType(parent::getDeclaringClass()->getName());}function
  5363. hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}function
  5364. getAnnotation($name){$res=AnnotationsParser::getAll($this);return
  5365. isset($res[$name])?end($res[$name]):NULL;}function
  5366. getAnnotations(){return
  5367. AnnotationsParser::getAll($this);}function
  5368. getDescription(){return$this->getAnnotation('description');}static
  5369. function
  5370. getReflection(){return
  5371. new
  5372. ClassType(get_called_class());}function
  5373. __call($name,$args){return
  5374. ObjectMixin::call($this,$name,$args);}function&__get($name){return
  5375. ObjectMixin::get($this,$name);}function
  5376. __set($name,$value){return
  5377. ObjectMixin::set($this,$name,$value);}function
  5378. __isset($name){return
  5379. ObjectMixin::has($this,$name);}function
  5380. __unset($name){ObjectMixin::remove($this,$name);}}}namespace Nette\Security{use
  5381. Nette;class
  5382. AuthenticationException
  5383. extends\Exception{}}namespace Nette\Security\Diagnostics{use
  5384. Nette;use
  5385. Nette\Diagnostics\Helpers;class
  5386. UserPanel
  5387. extends
  5388. Nette\Object
  5389. implements
  5390. Nette\Diagnostics\IBarPanel{private$user;function
  5391. __construct(Nette\Security\User$user){$this->user=$user;}function
  5392. getTab(){ob_start();?>
  5393. <?php if($this->user->isLoggedIn()):?>
  5394. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVDjLhVLPSxRhGH5mf8yOs9O6aa2b6BJhsW3RilAXDSW65clDdgwkEBH/gIiI6FC3uoRBQYeooP4Aw9isQ2xG5YZEVFrINmnFto67s7sz33xf76wedEfwgxdm4H1+vO/zSkIINL7Bax/PpxLRkXhUTVuMY/7Hci4z++2e/njofmNvYDvwqe726/2pcJsa9MMhgd7D4T5NUQ8GBibBZka3kPgaCZKk7IKbVT8qNodpcUToe6g33tadOjCyo4NYREkrpGyYHLYDMEfArHFoioTE/o70jgRVC3AIZDMqLogA9fKR12qVefblGWHui54rmDZCsoSaLVClUkMSVlYZZl7P53YkyGQ/T9+dWqoaFY6K5ZaDEo1w42GOVWaz7xv7pc0x9kxkh/uOxa6c6JSSnDz/MgJgFGM0ZCLALTzKrhZePnh1S+gXr3p2cHQ0kx7oSVwePtmWbNUCKFsCKb6+i3K1GXKQY2JfrCW/XJqQfGNvBL/9bMsILRF1/MzxWGo3RfbHoK3VjUkgDlhEsqDXEKJ0Lgx2tSJ56JJnB13tLf3NYR9+F20CCwJSuSnw9W8hJHxdMtHeqiAYix/xEGia0ilLPuRXKnVVx41vYwRG6XEOGGsMst8PWVF3eXZgWUyixChvCc6GMiNwja7RJjR3x3GLRFwyj4PFvPFzQTehNUn1f4e6LIfXCdxDovGR2BvEh+9lVArFNQ/BdCY/Pjq5eGfqbQGC1IPkpEkGwnREMvl09/DkxQpuPs0beDd3ets7cF/HuefL8ViU7YnIYbpcTS+Y0P9apXLe+IeSWRSfzvZs7v8PV6U0ly704DwAAAAASUVORK5CYII=" />
  5395. <?php else:?>
  5396. <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAE4SURBVCjPZdBLSwIBGIXh/lHQb4guyza1CEIqpNoIQdHKXEQQrkS6IUSLFhYFtpCIwUAG07IstTTnqjNTjnSRZmPg4m3lpYZvd84DB74BBjq36zkXk07CORB9nl7aVydtkwZ1NKL2tMcFYqLJOxYGb1QIiC5w5dhYGOgo6EQcFxCcOjV0VCRUdtxgX1R4RaZClTzz7okF/2FLo0SRChvtkdA/sDl1Wk6RQuASAYHg54S/D6wPnjzrNLAwqVJBJsfax/BoFwQjZWw0LEx0SmQocsGk2AVHko6MhoGByhMZEqSZ++qCs5bBLSo1qkgUSBMny1K7C45/qtwho6NQ4oFr4mRZ7IGwmqWAjMILee65IUWMmd6Ed3xlL4qEjkqZR9KE8X2PDf151Kq9ZW03Q+1Ae7np1WZznfwXGfNkzblrzUIAAAAASUVORK5CYII=" />
  5397. <?php endif?>&nbsp;
  5398. <?php
  5399. return
  5400. ob_get_clean();}function
  5401. getPanel(){ob_start();?>
  5402. <style>#nette-debug .nette-UserPanel pre{background:#FDF5CE;padding:.4em .7em;border:1px dotted silver;overflow:auto}</style>
  5403. <div class="nette-UserPanel">
  5404. <h1><?php if($this->user->isLoggedIn()):?>Logged in<?php else:?>Unlogged<?php endif?></h1>
  5405. <?php if($this->user->getIdentity()):echo
  5406. Helpers::clickableDump($this->user->getIdentity());else:?><p>no identity</p><?php endif?>
  5407. </div>
  5408. <?php
  5409. return
  5410. ob_get_clean();}}}namespace Nette\Security{use
  5411. Nette;class
  5412. Identity
  5413. extends
  5414. Nette\FreezableObject
  5415. implements
  5416. IIdentity{private$id;private$roles;private$data;function
  5417. __construct($id,$roles=NULL,$data=NULL){$this->setId($id);$this->setRoles((array)$roles);$this->data=$data
  5418. instanceof\Traversable?iterator_to_array($data):(array)$data;}function
  5419. setId($id){$this->updating();$this->id=is_numeric($id)?1*$id:$id;return$this;}function
  5420. getId(){return$this->id;}function
  5421. setRoles(array$roles){$this->updating();$this->roles=$roles;return$this;}function
  5422. getRoles(){return$this->roles;}function
  5423. getData(){return$this->data;}function
  5424. __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
  5425. parent::__get($key);}else{return$this->data[$key];}}function
  5426. __isset($key){return
  5427. isset($this->data[$key])||parent::__isset($key);}function
  5428. __unset($name){Nette\ObjectMixin::remove($this,$name);}}class
  5429. Permission
  5430. extends
  5431. Nette\Object
  5432. implements
  5433. 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
  5434. addRole($role,$parents=NULL){$this->checkRole($role,FALSE);if(isset($this->roles[$role])){throw
  5435. new
  5436. Nette\InvalidStateException("Role '$role' already exists in the list.");}$roleParents=array();if($parents!==NULL){if(!is_array($parents)){$parents=array($parents);}foreach($parents
  5437. 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
  5438. hasRole($role){$this->checkRole($role,FALSE);return
  5439. isset($this->roles[$role]);}private
  5440. function
  5441. checkRole($role,$need=TRUE){if(!is_string($role)||$role===''){throw
  5442. new
  5443. Nette\InvalidArgumentException("Role must be a non-empty string.");}elseif($need&&!isset($this->roles[$role])){throw
  5444. new
  5445. Nette\InvalidStateException("Role '$role' does not exist.");}}function
  5446. getRoles(){return
  5447. array_keys($this->roles);}function
  5448. getRoleParents($role){$this->checkRole($role);return
  5449. array_keys($this->roles[$role]['parents']);}function
  5450. 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
  5451. TRUE;}}return
  5452. FALSE;}function
  5453. 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
  5454. 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
  5455. addResource($resource,$parent=NULL){$this->checkResource($resource,FALSE);if(isset($this->resources[$resource])){throw
  5456. new
  5457. Nette\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
  5458. hasResource($resource){$this->checkResource($resource,FALSE);return
  5459. isset($this->resources[$resource]);}private
  5460. function
  5461. checkResource($resource,$need=TRUE){if(!is_string($resource)||$resource===''){throw
  5462. new
  5463. Nette\InvalidArgumentException("Resource must be a non-empty string.");}elseif($need&&!isset($this->resources[$resource])){throw
  5464. new
  5465. Nette\InvalidStateException("Resource '$resource' does not exist.");}}function
  5466. getResources(){return
  5467. array_keys($this->resources);}function
  5468. resourceInheritsFrom($resource,$inherit,$onlyParent=FALSE){$this->checkResource($resource);$this->checkResource($inherit);if($this->resources[$resource]['parent']===NULL){return
  5469. FALSE;}$parent=$this->resources[$resource]['parent'];if($inherit===$parent){return
  5470. TRUE;}elseif($onlyParent){return
  5471. FALSE;}while($this->resources[$parent]['parent']!==NULL){$parent=$this->resources[$parent]['parent'];if($inherit===$parent){return
  5472. TRUE;}}return
  5473. FALSE;}function
  5474. 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
  5475. as$resourceRemoved){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resourceRemoved===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}unset($this->resources[$resource]);return$this;}function
  5476. removeAllResources(){foreach($this->resources
  5477. as$resource=>$foo){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resource===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}$this->resources=array();return$this;}function
  5478. allow($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=NULL){$this->setRule(TRUE,self::ALLOW,$roles,$resources,$privileges,$assertion);return$this;}function
  5479. deny($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=