@*Application/Application.phpt St BmApplication/ErrorPresenter.phpS+Application/exceptions.phpS:M@Application/IPresenter.phpaSa[ܶ!Application/IPresenterFactory.phpSApplication/IResponse.phpSάApplication/IRouter.phpSApplication/MicroPresenter.php" S" *nS Application/PresenterFactory.php S UApplication/Request.phpvSv>&Application/Responses/FileResponse.phpS-۶)Application/Responses/ForwardResponse.php~S~W&Application/Responses/JsonResponse.php.S.@~*Application/Responses/RedirectResponse.phpSB^-޶&Application/Responses/TextResponse.phpSIo!Application/Routers/CliRouter.php:S:S(ŶApplication/Routers/Route.php^5S^5Iȶ!Application/Routers/RouteList.phpSaf㨶$Application/Routers/SimpleRouter.phpSs!Application/templates/error.phtmlS{%Application/UI/BadSignalException.phpSêApplication/UI/Control.phpSnApplication/UI/Form.phpSnVR'Application/UI/InvalidLinkException.php^S^8yApplication/UI/IRenderable.php|S|#k"Application/UI/ISignalReceiver.phplSlNL#Application/UI/IStatePersistent.phpS밌Application/UI/ITemplate.phpS#Application/UI/ITemplateFactory.phpuSulApplication/UI/Link.php]S]tIApplication/UI/Multiplier.php<S<zApplication/UI/Presenter.phpUSU=%Application/UI/PresenterComponent.phpS 8/Application/UI/PresenterComponentReflection.php S 6lBootstrap/Configurator.phpySy!+*Bridges/ApplicationLatte/ILatteFactory.phpkSk-{#Bridges/ApplicationLatte/Loader.phpSrҶ%Bridges/ApplicationLatte/Template.phpS4Ŷ,Bridges/ApplicationLatte/TemplateFactory.php S *}ض%Bridges/ApplicationLatte/UIMacros.php S [X)Bridges/ApplicationTracy/RoutingPanel.php S t;Bridges/ApplicationTracy/templates/RoutingPanel.panel.phtml S D9Bridges/ApplicationTracy/templates/RoutingPanel.tab.phtmloSo9¶!Bridges/CacheLatte/CacheMacro.phpS̶(Bridges/DatabaseDI/DatabaseExtension.php) S) (H)Bridges/DatabaseTracy/ConnectionPanel.php]S]7#M"Bridges/DITracy/ContainerPanel.phpSP2Ҷ4Bridges/DITracy/templates/ContainerPanel.panel.phtmlnSnB2Bridges/DITracy/templates/ContainerPanel.tab.phtml S 7Ѷ!Bridges/FormsLatte/FormMacros.phpSL#Bridges/Framework/NetteAccessor.phpS W.w$Bridges/Framework/NetteExtension.php1S1)A!Bridges/Framework/TracyBridge.phpS"Bridges/HttpTracy/SessionPanel.php_S_4Bridges/HttpTracy/templates/SessionPanel.panel.phtmleSeޏ2Bridges/HttpTracy/templates/SessionPanel.tab.phtml'S',5Bridges/SecurityTracy/templates/UserPanel.panel.phtmlDSD/7Q3Bridges/SecurityTracy/templates/UserPanel.tab.phtmlS:#Bridges/SecurityTracy/UserPanel.phpSimCaching/Cache.phpSCaching/IStorage.phpSweCaching/OutputHelper.phpSyL#Caching/Storages/DevNullStorage.php4S4Dt Caching/Storages/FileJournal.phpmKSmK! Caching/Storages/FileStorage.php"S"e'Caching/Storages/IJournal.phpS%Caching/Storages/MemcachedStorage.php, S, :"Caching/Storages/MemoryStorage.phpSDz"Caching/Storages/SQLiteStorage.phpDSD3ComponentModel/Component.php S _ComponentModel/Container.phpS@ComponentModel/IComponent.phpSڶComponentModel/IContainer.php S Yx-ComponentModel/RecursiveComponentIterator.phpNSNb{iDatabase/Connection.php S 7Database/Context.phpiSih¶ Database/Drivers/MsSqlDriver.phpS̶ Database/Drivers/MySqlDriver.php S гDatabase/Drivers/OciDriver.phpS7Database/Drivers/OdbcDriver.phpSs< Database/Drivers/PgSqlDriver.phpS "Database/Drivers/Sqlite2Driver.php2S2i޶!Database/Drivers/SqliteDriver.phpS\!Database/Drivers/SqlsrvDriver.php<S<{;Database/Helpers.phpS$Database/IReflection.phpSeDatabase/IRow.phpQSQmDatabase/IRowContainer.phpSh Database/ISupplementalDriver.phpS&$.Database/Reflection/ConventionalReflection.phpS,Database/Reflection/DiscoveredReflection.php S &v"Database/Reflection/exceptions.phpSGgDatabase/ResultSet.phpS L?Database/Row.php=S=3KDatabase/SqlLiteral.phpTST Database/SqlPreprocessor.phpS' WDatabase/Table/ActiveRow.php<S< nL#Database/Table/GroupedSelection.phpSҶDatabase/Table/IRow.php)S)z Database/Table/IRowContainer.phpHSHDatabase/Table/Selection.php<1S<1?ADatabase/Table/SqlBuilder.php&S&1S%deprecated/Caching/PhpFileStorage.phpSxdeprecated/Callback.phpS[$#deprecated/Diagnostics/Debugger.phpSö"deprecated/Diagnostics/Helpers.phpCSC:K$deprecated/Diagnostics/IBarPanel.php`S`4|deprecated/Environment.php^S^λ»deprecated/FreezableObject.phpSd{deprecated/IFreezable.php]S]'deprecated/Latte/Engine.phpdSd0'Ӷ&deprecated/Templating/FileTemplate.php,S,gA޶!deprecated/Templating/Helpers.phpS`'e'deprecated/Templating/IFileTemplate.phpSj#deprecated/Templating/ITemplate.phpSSS$;"deprecated/Templating/Template.phpS,!deprecated/Utils/LimitedScope.phpS߃@P%deprecated/Utils/MimeTypeDetector.phpS%ڶDI/Compiler.php S nDI/CompilerExtension.php4S4B!DI/Config/Adapters/IniAdapter.php S _"DI/Config/Adapters/NeonAdapter.phpSɶ!DI/Config/Adapters/PhpAdapter.php,S,w:DI/Config/Helpers.phpSDI/Config/IAdapter.phpnSnDI/Config/Loader.php S 5\DI/Container.phpS7DI/ContainerBuilder.php?S?dDI/ContainerFactory.phpS܁߶DI/exceptions.phpS(篶$DI/Extensions/ConstantsExtension.php&S&³w%DI/Extensions/ExtensionsExtension.phpS`DI/Extensions/PhpExtension.phpS۰5DI/Helpers.php~S~DwDI/ServiceDefinition.phpSU*QDI/Statement.phpqSqˣ!Finder/CallbackFilterIterator.phpHSHhiFinder/Finder.phpS*Finder/RecursiveCallbackFilterIterator.phpS51Forms/Container.phpmSmcmForms/ControlGroup.phpSyForms/Controls/BaseControl.phpSꇶForms/Controls/Button.phpiSi2ZӶForms/Controls/Checkbox.phpSeMForms/Controls/CheckboxList.phpSa Forms/Controls/ChoiceControl.phpS !Forms/Controls/CsrfProtection.phpSnForms/Controls/HiddenField.phpS $Forms/Controls/ImageButton.phpSGܶ%Forms/Controls/MultiChoiceControl.phpSq!Forms/Controls/MultiSelectBox.phpS!Forms/Controls/RadioList.phpSӱForms/Controls/SelectBox.phpSForms/Controls/SubmitButton.phpSvForms/Controls/TextArea.php[S[|Forms/Controls/TextBase.phpE SE ,%`FForms/Controls/TextInput.phpSk Forms/Controls/UploadControl.phpSForms/Form.phpSN9Forms/Helpers.php S 1Forms/IControl.phpSForms/IFormRenderer.php[S[X)Forms/ISubmitterControl.phpsSs(Y5'Forms/Rendering/DefaultFormRenderer.phpS1yForms/Rule.phpS4SForms/Rules.phpSǗg Framework.phpS fHttp/Context.phpSHttp/FileUpload.phpSC8Http/Helpers.phpSpBHttp/IRequest.php-S--pHttp/IResponse.phpSW]Http/ISessionStorage.phpS6N}Http/Request.php S H}Http/RequestFactory.phpSJQHttp/Response.phpS@nGlHttp/Session.phpSpHttp/SessionSection.phpW SW vz Http/Url.phpS;ɶHttp/UrlScript.phpSHttp/UserStorage.php S $Iterators/CachingIterator.php S JIterators/Filter.phpYSY!XMIterators/Mapper.phpYSYIterators/RecursiveFilter.phpS7$Latte/Compiler.php?-S?-pLatte/Engine.phpSkrLatte/exceptions.phpS ALatte/Helpers.php\S\C:[Latte/HtmlNode.php4S4 cgLatte/ILoader.phpS&kLatte/IMacro.phpS-WLatte/Loaders/FileLoader.php S #7նLatte/Loaders/StringLoader.phpSձLatte/MacroNode.phpASAC9:Latte/Macros/BlockMacros.php#S#'Latte/Macros/CoreMacros.php%S%7Latte/Macros/MacroSet.phpSӧadLatte/MacroTokens.phpWSW|ǶLatte/Object.phpSLatte/Parser.phpdSd2T`Latte/PhpWriter.php S Ւ{!Latte/Runtime/CachingIterator.php_ S_ DyLatte/Runtime/Filters.phpS>Latte/Runtime/Html.phpS7Latte/Runtime/IHtmlString.phpVSV:9Latte/Template.php|S|[isLatte/Token.php-S-röLatte/TokenIterator.phpS Latte/Tokenizer.phpGSG1*G loader.phpSE]Loaders/NetteLoader.phpS5Mail/IMailer.phpUSUw>Mail/Message.phpiSi9Mail/MimePart.php#S#T^ԶMail/SendmailMailer.php S A'OMail/SmtpMailer.php S 0aNeon/Decoder.phpSx>Neon/Encoder.phpSh:Neon/Entity.phpSѧNeon/Exception.phpISI~UWD Neon/Neon.phpSv۶PhpGenerator/ClassType.phpS\#PhpGenerator/Helpers.php;S;\7}PhpGenerator/Method.phpq Sq zPhpGenerator/Parameter.phpSKhnPhpGenerator/PhpLiteral.phpS-[oPhpGenerator/Property.phpASA,Reflection/Annotation.phpSA@ Reflection/AnnotationsParser.php.S.aReflection/ClassType.phpSo嶶Reflection/Extension.phpSReflection/GlobalFunction.phpSReflection/IAnnotation.phpfSf.5Reflection/Method.php~S~okReflection/Parameter.phpSTReflection/Property.phpS+KRobotLoader/RobotLoader.phpS~޶SafeStream/SafeStream.php S ϒ$Security/AuthenticationException.php[S[xسSecurity/IAuthenticator.phpSԶSecurity/IAuthorizator.phpS"Security/Identity.phpSXSecurity/IIdentity.phpdSdXSecurity/IResource.phpXSXp( Security/IRole.phpPSP˄ضSecurity/IUserStorage.phpJSJɞSecurity/Passwords.phpS5TNSecurity/Permission.php9)S9)m~ Security/SimpleAuthenticator.phpSCSecurity/User.phpt St 9A shortcuts.phpS-WdTokenizer/TokenIterator.phpSژTokenizer/Tokenizer.phpPSP֟ Tokenizer/TokenizerException.phpSSS؜! Tracy/Bar.phpzSz`,O Tracy/BlueScreen.php S [ vTracy/Debugger.phpK)SK).Tracy/DefaultBarPanel.phpS{$8HTracy/Dumper.phpS3k>Tracy/FireLogger.php S eTracy/Helpers.phpS3ĶTracy/IBarPanel.php\S\3Tracy/Logger.phpSSSohTracy/OutputDebugger.php'S'a]STracy/templates/bar.cssCSCB4S%Tracy/templates/bar.dumps.panel.phtmlRSR\$,#Tracy/templates/bar.dumps.tab.phtmlS&Tracy/templates/bar.errors.panel.phtmlS!#t$Tracy/templates/bar.errors.tab.phtmlCSCTracy/templates/bar.jsO SO $Tracy/templates/bar.memory.tab.phtmlSr/BTracy/templates/bar.phtmlKSK94?"Tracy/templates/bar.time.tab.phtmlS.$Tracy/templates/bluescreen.cssS Tracy/templates/bluescreen.phtmlJSJQTracy/templates/dumper.cssS*WTracy/templates/dumper.jsS*Tracy/templates/error.phtml]S]cm Tracy/templates/tracyQ.jsR!SR!Utils/ArrayHash.php5S52ZMUtils/ArrayList.phpS\~PUtils/Arrays.php S djUtils/Callback.phpG SG @Utils/DateTime.php;S; "wUtils/exceptions.phpSԃ%Utils/FileSystem.php S 0#Utils/Html.phpSUtils/IHtmlString.phpTST#i Utils/Image.php1S1 RUtils/ITranslator.phpnSnl Utils/Json.phpS4|93Utils/Object.php7S7QUtils/ObjectMixin.phpS@;Utils/Paginator.phpS&`Utils/Random.phpSzUtils/Strings.phpbSbF•Utils/Validators.phpS& httpRequest=$httpRequest;$this->httpResponse=$httpResponse;$this->presenterFactory=$presenterFactory;$this->router=$router;}public function run(){try{$this->onStartup($this);$this->processRequest($this->createInitialRequest());$this->onShutdown($this);}catch(\Exception$e){$this->onError($this,$e);if($this->catchExceptions&&$this->errorPresenter){try{$this->processException($e);$this->onShutdown($this,$e);return;}catch(\Exception$e){$this->onError($this,$e);}}$this->onShutdown($this,$e);throw$e;}}public function createInitialRequest(){$request=$this->router->match($this->httpRequest);if(!$request instanceof Request){throw new BadRequestException('No route for HTTP request.');}elseif(strcasecmp($request->getPresenterName(),$this->errorPresenter)===0){throw new BadRequestException('Invalid request. Presenter is not achievable.');}try{$name=$request->getPresenterName();$this->presenterFactory->getPresenterClass($name);$request->setPresenterName($name);}catch(InvalidPresenterException$e){throw new BadRequestException($e->getMessage(),0,$e);}return$request;}public function processRequest(Request$request){if(count($this->requests)>self::$maxLoop){throw new ApplicationException('Too many loops detected in application life cycle.');}$this->requests[]=$request;$this->onRequest($this,$request);$this->presenter=$this->presenterFactory->createPresenter($request->getPresenterName());$this->onPresenter($this,$this->presenter);$response=$this->presenter->run($request);if($response instanceof Responses\ForwardResponse){$this->processRequest($response->getRequest());}elseif($response){$this->onResponse($this,$response);$response->send($this->httpRequest,$this->httpResponse);}}public function processException(\Exception$e){if(!$e instanceof BadRequestException){$this->httpResponse->warnOnBuffer=FALSE;}if(!$this->httpResponse->isSent()){$this->httpResponse->setCode($e instanceof BadRequestException?($e->getCode()?:404):500);}$args=array('exception'=>$e,'request'=>end($this->requests)?:NULL);if($this->presenter instanceof UI\Presenter){try{$this->presenter->forward(":$this->errorPresenter:",$args);}catch(AbortException$foo){$this->processRequest($this->presenter->getLastCreatedRequest());}}else{$this->processRequest(new Request($this->errorPresenter,Request::FORWARD,$args));}}public function getRequests(){return$this->requests;}public function getPresenter(){return$this->presenter;}public function getRouter(){return$this->router;}public function getPresenterFactory(){return$this->presenterFactory;}function storeRequest($expiration='+ 10 minutes'){trigger_error(__METHOD__.'() is deprecated; use $presenter->storeRequest() instead.',E_USER_DEPRECATED);return$this->presenter->storeRequest($expiration);}function restoreRequest($key){trigger_error(__METHOD__.'() is deprecated; use $presenter->restoreRequest() instead.',E_USER_DEPRECATED);return$this->presenter->restoreRequest($key);}}parameters['exception'];if($e instanceof Application\BadRequestException){$code=$e->getCode();}else{$code=500;Debugger::log($e,Debugger::ERROR);}ob_start();require __DIR__.'/templates/error.phtml';return new Application\Responses\TextResponse(ob_get_clean());}}504?$this->defaultCode:$code,$previous);}}class ForbiddenRequestException extends BadRequestException{protected$defaultCode=403;}context=$context;$this->httpRequest=$httpRequest;$this->router=$router;}public function getContext(){return$this->context;}public function run(Application\Request$request){$this->request=$request;if($this->httpRequest&&$this->router&&!$this->httpRequest->isAjax()&&($request->isMethod('get')||$request->isMethod('head'))){$refUrl=clone$this->httpRequest->getUrl();$url=$this->router->constructUrl($request,$refUrl->setPath($refUrl->getScriptPath()));if($url!==NULL&&!$this->httpRequest->getUrl()->isEqual($url)){return new Responses\RedirectResponse($url,Http\IResponse::S301_MOVED_PERMANENTLY);}}$params=$request->getParameters();if(!isset($params['callback'])){throw new Application\BadRequestException('Parameter callback is missing.');}$params['presenter']=$this;$callback=$params['callback'];$reflection=Nette\Utils\Callback::toReflection(Nette\Utils\Callback::check($callback));$params=Application\UI\PresenterComponentReflection::combineArgs($reflection,$params);foreach($reflection->getParameters()as$param){if($param->getClassName()){unset($params[$param->getPosition()]);}}if($this->context){$params=Nette\DI\Helpers::autowireArguments($reflection,$params,$this->context);}$response=call_user_func_array($callback,$params);if(is_string($response)){$response=array($response,array());}if(is_array($response)){$response=$this->createTemplate()->setParameters($response[1]);if($response[0]instanceof\SplFileInfo){$response->setFile($response[0]);}else{$response->setSource($response[0]);}}if($response instanceof Application\UI\ITemplate){return new Responses\TextResponse($response);}else{return$response;}}public function createTemplate($class=NULL,$latteFactory=NULL){$latte=$latteFactory?$latteFactory():$this->getContext()->getByType('Nette\Bridges\ApplicationLatte\ILatteFactory')->create();$template=$class?new$class:new Nette\Bridges\ApplicationLatte\Template($latte);$template->setParameters($this->request->getParameters());$template->presenter=$this;$template->context=$this->context;if($this->httpRequest){$url=$this->httpRequest->getUrl();$template->baseUrl=rtrim($url->getBaseUrl(),'/');$template->basePath=rtrim($url->getBasePath(),'/');}return$template;}public function redirectUrl($url,$code=Http\IResponse::S302_FOUND){return new Responses\RedirectResponse($url,$code);}public function error($message=NULL,$code=Http\IResponse::S404_NOT_FOUND){throw new Application\BadRequestException($message,$code);}public function getRequest(){return$this->request;}}array('','*Module\\','*Presenter'),'Nette'=>array('NetteModule\\','*\\','*Presenter'));private$baseDir;private$cache=array();private$container;public function __construct($baseDir,Nette\DI\Container$container){$this->baseDir=$baseDir;$this->container=$container;}public function createPresenter($name){$class=$this->getPresenterClass($name);if(count($services=$this->container->findByType($class))===1){$presenter=$this->container->createService($services[0]);}else{$presenter=$this->container->createInstance($class);}$this->container->callInjects($presenter);if($presenter instanceof UI\Presenter&&$presenter->invalidLinkMode===NULL){$presenter->invalidLinkMode=$this->container->parameters['debugMode']?UI\Presenter::INVALID_LINK_WARNING:UI\Presenter::INVALID_LINK_SILENT;}return$presenter;}public function 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:]*\z#')){throw new 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)){call_user_func(function()use($file){require$file;});}if(!class_exists($class)){throw new InvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");}}$reflection=new Nette\Reflection\ClassType($class);$class=$reflection->getName();if(!$reflection->implementsInterface('Nette\Application\IPresenter')){throw new InvalidPresenterException("Cannot load presenter '$name', class '$class' is not Nette\\Application\\IPresenter implementor.");}if($reflection->isAbstract()){throw new InvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");}$realName=$this->unformatPresenterClass($class);if($name!==$realName){if($this->caseSensitive){throw new 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;}public function setMapping(array$mapping){foreach($mapping as$module=>$mask){if(!preg_match('#^\\\\?([\w\\\\]*\\\\)?(\w*\*\w*?\\\\)?([\w\\\\]*\*\w*)\z#',$mask,$m)){throw new Nette\InvalidStateException("Invalid mapping mask '$mask'.");}$this->mapping[$module]=array($m[1],$m[2]?:'*Module\\',$m[3]);}return$this;}public function formatPresenterClass($presenter){$parts=explode(':',$presenter);$mapping=isset($parts[1],$this->mapping[$parts[0]])?$this->mapping[array_shift($parts)]:$this->mapping['*'];while($part=array_shift($parts)){$mapping[0].=str_replace('*',$part,$mapping[$parts?1:2]);}return$mapping[0];}public function unformatPresenterClass($class){foreach($this->mapping as$module=>$mapping){$mapping=str_replace(array('\\','*'),array('\\\\','(\w+)'),$mapping);if(preg_match("#^\\\\?$mapping[0]((?:$mapping[1])*)$mapping[2]\\z#i",$class,$matches)){return($module==='*'?'':$module.':').preg_replace("#$mapping[1]#iA",'$1:',$matches[1]).$matches[3];}}}public function formatPresenterFile($presenter){$path='/'.str_replace(':','Module/',$presenter);return$this->baseDir.substr_replace($path,'/presenters',strrpos($path,'/'),0).'Presenter.php';}}name=$name;$this->method=$method;$this->params=$params;$this->post=$post;$this->files=$files;$this->flags=$flags;}public function setPresenterName($name){$this->name=$name;return$this;}public function getPresenterName(){return$this->name;}public function setParameters(array$params){$this->params=$params;return$this;}public function getParameters(){return$this->params;}public function setPost(array$params){$this->post=$params;return$this;}public function getPost(){return$this->post;}public function setFiles(array$files){$this->files=$files;return$this;}public function getFiles(){return$this->files;}public function setMethod($method){$this->method=$method;return$this;}public function getMethod(){return$this->method;}public function isMethod($method){return strcasecmp($this->method,$method)===0;}public function isPost(){return strcasecmp($this->method,'post')===0;}public function setFlag($flag,$value=TRUE){$this->flags[$flag]=(bool)$value;return$this;}public function hasFlag($flag){return!empty($this->flags[$flag]);}}file=$file;$this->name=$name?$name:basename($file);$this->contentType=$contentType?$contentType:'application/octet-stream';$this->forceDownload=$forceDownload;}public function getFile(){return$this->file;}public function getName(){return$this->name;}public function getContentType(){return$this->contentType;}public function send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){$httpResponse->setContentType($this->contentType);$httpResponse->setHeader('Content-Disposition',($this->forceDownload?'attachment':'inline').'; filename="'.$this->name.'"');$filesize=$length=filesize($this->file);$handle=fopen($this->file,'r');if($this->resuming){$httpResponse->setHeader('Accept-Ranges','bytes');if(preg_match('#^bytes=(\d*)-(\d*)\z#',$httpRequest->getHeader('Range'),$matches)){list(,$start,$end)=$matches;if($start===''){$start=max(0,$filesize-$end);$end=$filesize-1;}elseif($end===''||$end>$filesize-1){$end=$filesize-1;}if($end<$start){$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)&&$length>0){echo$s=fread($handle,min(4e6,$length));$length-=strlen($s);}fclose($handle);}}request=$request;}public function getRequest(){return$this->request;}public function send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){}}payload=$payload;$this->contentType=$contentType?$contentType:'application/json';}public function getPayload(){return$this->payload;}public function getContentType(){return$this->contentType;}public function send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){$httpResponse->setContentType($this->contentType);$httpResponse->setExpiration(FALSE);echo Nette\Utils\Json::encode($this->payload);}}url=(string)$url;$this->code=(int)$code;}public function getUrl(){return$this->url;}public function getCode(){return$this->code;}public function send(Http\IRequest$httpRequest,Http\IResponse$httpResponse){$httpResponse->redirect($this->url,$this->code);}}source=$source;}public function getSource(){return$this->source;}public function send(Nette\Http\IRequest$httpRequest,Nette\Http\IResponse$httpResponse){if($this->source instanceof Nette\Application\UI\ITemplate||$this->source instanceof Nette\Templating\ITemplate){$this->source->render();}else{echo$this->source;}}}defaults=$defaults;}public function match(Nette\Http\IRequest$httpRequest){if(empty($_SERVER['argv'])||!is_array($_SERVER['argv'])){return NULL;}$names=array(self::PRESENTER_KEY);$params=$this->defaults;$args=$_SERVER['argv'];array_shift($args);$args[]='--';foreach($args 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 new 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 new Application\Request($presenter,'CLI',$params);}public function constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){return NULL;}public function getDefaults(){return$this->defaults;}}array(self::PATTERN=>'[^/]+',self::FILTER_IN=>'rawurldecode',self::FILTER_OUT=>array(__CLASS__,'param2path')),'?#'=>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$aliases;private$metadata=array();private$xlat;private$type;private$flags;public function __construct($mask,$metadata=array(),$flags=0){if(is_string($metadata)){$a=strrpos($metadata,':');if(!$a){throw new 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 instanceof\Closure||$metadata instanceof Nette\Callback){$metadata=array(self::PRESENTER_KEY=>'Nette:Micro','callback'=>$metadata);}$this->flags=$flags|static::$defaultFlags;$this->setMask($mask,$metadata);}public function match(Nette\Http\IRequest$httpRequest){$url=$httpRequest->getUrl();$re=$this->re;if($this->type===self::HOST){$path='//'.$url->getHost().$url->getPath();$host=array_reverse(explode('.',$url->getHost()));$re=strtr($re,array('/%basePath%/'=>preg_quote($url->getBasePath(),'#'),'%tld%'=>$host[0],'%domain%'=>isset($host[1])?"$host[1]\\.$host[0]":$host[0]));}elseif($this->type===self::RELATIVE){$basePath=$url->getBasePath();if(strncmp($url->getPath(),$basePath,strlen($basePath))!==0){return NULL;}$path=(string)substr($url->getPath(),strlen($basePath));}else{$path=$url->getPath();}if($path!==''){$path=rtrim($path,'/').'/';}if(!$matches=Strings::match($path,$re)){return NULL;}$params=array();foreach($matches as$k=>$v){if(is_string($k)&&$v!==''){$params[$this->aliases[$k]]=$v;}}foreach($this->metadata 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 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 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 NULL;}}}elseif(isset($meta['fixity'])){$params[$name]=$meta[self::VALUE];}}if(isset($this->metadata[NULL][self::FILTER_IN])){$params=call_user_func($this->metadata[NULL][self::FILTER_IN],$params);if($params===NULL){return NULL;}}if(!isset($params[self::PRESENTER_KEY])){throw new Nette\InvalidStateException('Missing presenter in route definition.');}elseif(!is_string($params[self::PRESENTER_KEY])){return NULL;}if(isset($this->metadata[self::MODULE_KEY])){if(!isset($params[self::MODULE_KEY])){throw new 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 new Application\Request($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(Application\Request::SECURED=>$httpRequest->isSecured()));}public function constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->flags&self::ONE_WAY){return NULL;}$params=$appRequest->getParameters();$metadata=$this->metadata;$presenter=$appRequest->getPresenterName();$params[self::PRESENTER_KEY]=$presenter;if(isset($metadata[NULL][self::FILTER_OUT])){$params=call_user_func($metadata[NULL][self::FILTER_OUT],$params);if($params===NULL){return NULL;}}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 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 NULL;}}if(is_scalar($params[$name])&&isset($meta['filterTable2'][$params[$name]])){$params[$name]=$meta['filterTable2'][$params[$name]];}elseif(isset($meta['filterTable2'])&&!empty($meta[self::FILTER_STRICT])){return 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 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($requiredtype===self::RELATIVE){$url='//'.$refUrl->getAuthority().$refUrl->getBasePath().$url;}elseif($this->type===self::PATH){$url='//'.$refUrl->getAuthority().$url;}else{$host=array_reverse(explode('.',$refUrl->getHost()));$url=strtr($url,array('/%basePath%/'=>$refUrl->getBasePath(),'%tld%'=>$host[0],'%domain%'=>isset($host[1])?"$host[1].$host[0]":$host[0]));}if(strpos($url,'//',2)!==FALSE){return NULL;}$url=($this->flags&self::SECURED?'https:':'http:').$url;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;}return$url;}private function 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 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 as$match){list(,$param,$name,$pattern,$class)=$match;if($class!==''){if(!isset(static::$styles[$class])){throw new 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;$aliases=array();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 new 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]==='?'){$name=substr($name,1);$re=$pattern?'(?:'.preg_quote($name,'#')."|$pattern)$re":preg_quote($name,'#').$re;$sequence[1]=$name.$sequence[1];continue;}if(preg_match('#[^a-z0-9_-]#i',$name)){throw new Nette\InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '$name' given.");}if($class!==''){if(!isset(static::$styles[$class])){throw new 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)\\z#A".($this->flags&self::CASE_SENSITIVE?'':'iu');$aliases['p'.$i]=$name;$re='(?P(?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 new Nette\InvalidArgumentException("Missing closing ']' in mask '$mask'.");}$this->aliases=$aliases;$this->re='#'.$re.'/?\z#A'.($this->flags&self::CASE_SENSITIVE?'':'iu');$this->metadata=$metadata;$this->sequence=$sequence;}public function getMask(){return$this->mask;}public function getDefaults(){$defaults=array();foreach($this->metadata as$name=>$meta){if(isset($meta['fixity'])){$defaults[$name]=$meta[self::VALUE];}}return$defaults;}public function getFlags(){return$this->flags;}public function getTargetPresenter(){if($this->flags&self::ONE_WAY){return 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 NULL;}}if(isset($m[self::PRESENTER_KEY]['fixity'])&&$m[self::PRESENTER_KEY]['fixity']===self::CONSTANT){return$module.$m[self::PRESENTER_KEY][self::VALUE];}return NULL;}private static function renameKeys($arr,$xlat){if(empty($xlat)){return$arr;}$res=array();$occupied=array_flip($xlat);foreach($arr as$k=>$v){if(isset($xlat[$k])){$res[$xlat[$k]]=$v;}elseif(!isset($occupied[$k])){$res[$k]=$v;}}return$res;}private static function action2path($s){$s=preg_replace('#(.)(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private static function path2action($s){$s=strtolower($s);$s=preg_replace('#-(?=[a-z])#',' ',$s);$s=lcfirst(ucwords($s));$s=str_replace(' ','',$s);return$s;}private static function presenter2path($s){$s=strtr($s,':','.');$s=preg_replace('#([^.])(?=[A-Z])#','$1-',$s);$s=strtolower($s);$s=rawurlencode($s);return$s;}private static function 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;}private static function param2path($s){return str_replace('%2F','/',rawurlencode($s));}public static function addStyle($style,$parent='#'){if(isset(static::$styles[$style])){throw new Nette\InvalidArgumentException("Style '$style' already exists.");}if($parent!==NULL){if(!isset(static::$styles[$parent])){throw new Nette\InvalidArgumentException("Parent style '$parent' doesn't exist.");}static::$styles[$style]=static::$styles[$parent];}else{static::$styles[$style]=array();}}public static function setStyleProperty($style,$key,$value){if(!isset(static::$styles[$style])){throw new Nette\InvalidArgumentException("Style '$style' doesn't exist.");}static::$styles[$style][$key]=$value;}}module=$module?$module.':':'';}public function match(Nette\Http\IRequest$httpRequest){foreach($this as$route){$appRequest=$route->match($httpRequest);if($appRequest!==NULL){$name=$appRequest->getPresenterName();if(strncmp($name,'Nette:',6)){$appRequest->setPresenterName($this->module.$name);}return$appRequest;}}return NULL;}public function constructUrl(Nette\Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->cachedRoutes===NULL){$routes=array();$routes['*']=array();foreach($this as$route){$presenter=$route instanceof 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 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 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 NULL;}public function offsetSet($index,$route){if(!$route instanceof Nette\Application\IRouter){throw new Nette\InvalidArgumentException('Argument must be IRouter descendant.');}parent::offsetSet($index,$route);}public function getModule(){return$this->module;}}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;}public function match(Nette\Http\IRequest$httpRequest){if($httpRequest->getUrl()->getPathInfo()!==''){return NULL;}$params=$httpRequest->getQuery();$params+=$this->defaults;if(!isset($params[self::PRESENTER_KEY])||!is_string($params[self::PRESENTER_KEY])){return NULL;}$presenter=$this->module.$params[self::PRESENTER_KEY];unset($params[self::PRESENTER_KEY]);return new Application\Request($presenter,$httpRequest->getMethod(),$params,$httpRequest->getPost(),$httpRequest->getFiles(),array(Application\Request::SECURED=>$httpRequest->isSecured()));}public function constructUrl(Application\Request$appRequest,Nette\Http\Url$refUrl){if($this->flags&self::ONE_WAY){return 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 NULL;}foreach($this->defaults 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;}public function getDefaults(){return$this->defaults;}public function getFlags(){return$this->flags;}}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];?> <?php echo$message[0]?>

error

templateFactory=$templateFactory;}public function getTemplate(){if($this->template===NULL){$value=$this->createTemplate();if(!$value instanceof ITemplate&&$value!==NULL){$class2=get_class($value);$class=get_class($this);throw new Nette\UnexpectedValueException("Object returned by $class::createTemplate() must be instance of Nette\\Application\\UI\\ITemplate, '$class2' given.");}$this->template=$value;}return$this->template;}protected function createTemplate(){$templateFactory=$this->templateFactory?:$this->getPresenter()->getTemplateFactory();return$templateFactory->createTemplate($this);}public function templatePrepareFilters($template){}public function 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;}public function redrawControl($snippet=NULL,$redraw=TRUE){if($redraw){$this->invalidSnippets[$snippet]=TRUE;}elseif($snippet===NULL){$this->invalidSnippets=array();}else{unset($this->invalidSnippets[$snippet]);}}function invalidateControl($snippet=NULL){$this->redrawControl($snippet);}function validateControl($snippet=NULL){$this->redrawControl($snippet,FALSE);}public function isControlInvalid($snippet=NULL){if($snippet===NULL){if(count($this->invalidSnippets)>0){return TRUE;}else{$queue=array($this);do{foreach(array_shift($queue)->getComponents()as$component){if($component instanceof IRenderable){if($component->isControlInvalid()){return TRUE;}}elseif($component instanceof Nette\ComponentModel\IContainer){$queue[]=$component;}}}while($queue);return FALSE;}}else{return isset($this->invalidSnippets[NULL])||isset($this->invalidSnippets[$snippet]);}}public function getSnippetId($name=NULL){return'snippet-'.$this->getUniqueId().'-'.$name;}}addComponent($this,$name);}}protected function validateParent(Nette\ComponentModel\IContainer$parent){parent::validateParent($parent);$this->monitor('Nette\Application\UI\Presenter');}public function getPresenter($need=TRUE){return$this->lookup('Nette\Application\UI\Presenter',$need);}protected function attached($presenter){if($presenter instanceof Presenter){$name=$this->lookupPath('Nette\Application\UI\Presenter');if(!isset($this->getElementPrototype()->id)){$this->getElementPrototype()->id='frm-'.$name;}if(!$this->getAction()){$this->setAction(new Link($presenter,'this',array()));}if(iterator_count($this->getControls())&&$this->isSubmitted()){foreach($this->getControls()as$control){if(!$control->isDisabled()){$control->loadHttpData();}}}$signal=new Nette\Forms\Controls\HiddenField($name.self::NAME_SEPARATOR.'submit');$signal->setOmitted()->setHtmlId(FALSE);$this[Presenter::SIGNAL_KEY]=$signal;}parent::attached($presenter);}public function isAnchored(){return(bool)$this->getPresenter(FALSE);}protected function 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 Nette\Utils\Arrays::mergeTree($request->getPost(),$request->getFiles());}else{return$request->getParameters();}}public function signalReceived($signal){if($signal==='submit'){if(!$this->getPresenter()->getRequest()->hasFlag(Nette\Application\Request::RESTORED)){$this->fireEvents();}}else{$class=get_class($this);throw new BadSignalException("Missing handler for signal '$signal' in $class.");}}}component=$component;$this->destination=$destination;$this->params=$params;}public function getDestination(){return$this->destination;}public function setParameter($key,$value){$this->params[$key]=$value;return$this;}public function getParameter($key){return isset($this->params[$key])?$this->params[$key]:NULL;}public function getParameters(){return$this->params;}public function __toString(){try{return(string)$this->component->link($this->destination,$this->params);}catch(\Exception$e){if(func_num_args()){throw$e;}trigger_error("Exception in ".__METHOD__."(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}",E_USER_ERROR);}}}factory=Nette\Utils\Callback::check($factory);}protected function createComponent($name){return call_user_func($this->factory,$name,$this);}}payload=new\stdClass;}public function getRequest(){return$this->request;}public function getPresenter($need=TRUE){return$this;}public function getUniqueId(){return'';}public function run(Application\Request$request){try{$this->request=$request;$this->payload=$this->payload?:new\stdClass;$this->setParent($this->getParent(),$request->getPresenterName());if(!$this->httpResponse->isSent()){$this->httpResponse->addHeader('Vary','X-Requested-With');}$this->initGlobalParameters();$this->checkRequirements($this->getReflection());$this->startup();if(!$this->startupCheck){$class=$this->getReflection()->getMethod('startup')->getDeclaringClass()->getName();throw new Nette\InvalidStateException("Method $class::startup() or its descendant doesn't call parent::startup().");}$this->tryCall($this->formatActionMethod($this->action),$this->params);foreach($this->globalParams as$id=>$foo){$this->getComponent($id,FALSE);}if($this->autoCanonicalize){$this->canonicalize();}if($this->httpRequest->isMethod('head')){$this->terminate();}$this->processSignal();$this->beforeRender();$this->tryCall($this->formatRenderMethod($this->view),$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 instanceof Responses\TextResponse&&$this->isControlInvalid()){$this->snippetMode=TRUE;$this->response->send($this->httpRequest,$this->httpResponse);$this->sendPayload();}elseif(!$this->response&&$hasPayload){$this->sendPayload();}}catch(Application\AbortException$e){}if($this->hasFlashSession()){$this->getFlashSession()->setExpiration($this->response instanceof Responses\RedirectResponse?'+ 30 seconds':'+ 3 seconds');}$this->onShutdown($this,$this->response);$this->shutdown($this->response);return$this->response;}}protected function startup(){$this->startupCheck=TRUE;}protected function beforeRender(){}protected function afterRender(){}protected function shutdown($response){}public function checkRequirements($element){$user=(array)$element->getAnnotation('User');if(in_array('loggedIn',$user,TRUE)&&!$this->getUser()->isLoggedIn()){throw new Application\ForbiddenRequestException;}}public function 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 new BadSignalException("The signal receiver component '$this->signalReceiver' is not found.",NULL,isset($e)?$e:NULL);}elseif(!$component instanceof ISignalReceiver){throw new BadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");}$component->signalReceived($this->signal);$this->signal=NULL;}public function getSignal(){return$this->signal===NULL?NULL:array($this->signalReceiver,$this->signal);}public function isSignalReceiver($component,$signal=NULL){if($component instanceof Nette\ComponentModel\Component){$component=$component===$this?'':$component->lookupPath(__CLASS__,TRUE);}if($this->signal===NULL){return 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;}}public function getAction($fullyQualified=FALSE){return$fullyQualified?':'.$this->getName().':'.$this->action:$this->action;}public function changeAction($action){if(is_string($action)&&Nette\Utils\Strings::match($action,'#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*\z#')){$this->action=$action;$this->view=$action;}else{$this->error('Action name is not alphanumeric string.');}}public function getView(){return$this->view;}public function setView($view){$this->view=(string)$view;return$this;}public function getLayout(){return$this->layout;}public function setLayout($layout){$this->layout=$layout===FALSE?FALSE:(string)$layout;return$this;}public function sendTemplate(){$template=$this->getTemplate();if(!$template){return;}if(!$template->getFile()){$files=$this->formatTemplateFiles();foreach($files as$file){if(is_file($file)){$template->setFile($file);break;}}if(!$template->getFile()){$file=preg_replace('#^.*([/\\\\].{1,70})\z#U',"\xE2\x80\xA6\$1",reset($files));$file=strtr($file,'/',DIRECTORY_SEPARATOR);$this->error("Page not found. Missing template '$file'.");}}$this->sendResponse(new Responses\TextResponse($template));}public function findLayoutTemplateFile(){if($this->layout===FALSE){return;}$files=$this->formatLayoutTemplateFiles();foreach($files as$file){if(is_file($file)){return$file;}}if($this->layout){$file=preg_replace('#^.*([/\\\\].{1,70})\z#U',"\xE2\x80\xA6\$1",reset($files));$file=strtr($file,'/',DIRECTORY_SEPARATOR);throw new Nette\FileNotFoundException("Layout not found. Missing template '$file'.");}}public function formatLayoutTemplateFiles(){$name=$this->getName();$presenter=substr($name,strrpos(':'.$name,':'));$layout=$this->layout?$this->layout:'layout';$dir=dirname($this->getReflection()->getFileName());$dir=is_dir("$dir/templates")?$dir:dirname($dir);$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;}public function formatTemplateFiles(){$name=$this->getName();$presenter=substr($name,strrpos(':'.$name,':'));$dir=dirname($this->getReflection()->getFileName());$dir=is_dir("$dir/templates")?$dir:dirname($dir);return 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");}public static function formatActionMethod($action){return'action'.$action;}public static function formatRenderMethod($view){return'render'.$view;}protected function createTemplate(){return$this->getTemplateFactory()->createTemplate($this);}public function getPayload(){return$this->payload;}public function isAjax(){if($this->ajaxMode===NULL){$this->ajaxMode=$this->httpRequest->isAjax();}return$this->ajaxMode;}public function sendPayload(){$this->sendResponse(new Responses\JsonResponse($this->payload));}public function sendJson($data){$this->sendResponse(new Responses\JsonResponse($data));}public function sendResponse(Application\IResponse$response){$this->response=$response;$this->terminate();}public function 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 new Application\AbortException();}public function forward($destination,$args=array()){if($destination instanceof Application\Request){$this->sendResponse(new Responses\ForwardResponse($destination));}$this->createRequest($this,$destination,is_array($args)?$args:array_slice(func_get_args(),1),'forward');$this->sendResponse(new Responses\ForwardResponse($this->lastCreatedRequest));}public function redirectUrl($url,$code=NULL){if($this->isAjax()){$this->payload->redirect=(string)$url;$this->sendPayload();}elseif(!$code){$code=$this->httpRequest->isMethod('post')?Http\IResponse::S303_POST_GET:Http\IResponse::S302_FOUND;}$this->sendResponse(new Responses\RedirectResponse($url,$code));}public function error($message=NULL,$code=Http\IResponse::S404_NOT_FOUND){throw new Application\BadRequestException($message,$code);}public function backlink(){return$this->getAction(TRUE);}public function getLastCreatedRequest(){return$this->lastCreatedRequest;}public function getLastCreatedRequestFlag($flag){return!empty($this->lastCreatedRequestFlag[$flag]);}public function 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->httpRequest->getUrl()->isEqual($url)){$this->sendResponse(new Responses\RedirectResponse($url,Http\IResponse::S301_MOVED_PERMANENTLY));}}}public function lastModified($lastModified,$etag=NULL,$expire=NULL){if($expire!==NULL){$this->httpResponse->setExpiration($expire);}$helper=new Nette\Http\Context($this->httpRequest,$this->httpResponse);if(!$helper->isModified($lastModified,$etag)){$this->terminate();}}protected function createRequest($component,$destination,array$args,$mode){$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 instanceof 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 new InvalidLinkException("Signal must be non-empty string.");}$destination='this';}if($destination==NULL){throw new 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 new 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);}}if(!$this->presenterFactory){throw new Nette\InvalidStateException('Unable to create link to other presenter, service PresenterFactory has not been set.');}try{$presenterClass=$this->presenterFactory->getPresenterClass($presenter);}catch(Application\InvalidPresenterException$e){throw new InvalidLinkException($e->getMessage(),NULL,$e);}}if(isset($signal)){$reflection=new PresenterComponentReflection(get_class($component));if($signal==='this'){$signal='';if(array_key_exists(0,$args)){throw new InvalidLinkException("Unable to pass parameters to 'this!' signal.");}}elseif(strpos($signal,self::NAME_SEPARATOR)===FALSE){$method=$component->formatSignalMethod($signal);if(!$reflection->hasCallableMethod($method)){throw new 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 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 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 new 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 as$key=>$val){if(http_build_query(array($val))!==(isset($tmp[$key])?http_build_query(array($tmp[$key])):'')){$current=FALSE;break;}}}$args+=$globalState;}if($action){$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 Application\Request($presenter,Application\Request::FORWARD,$args,array(),array());$this->lastCreatedRequestFlag=array('current'=>$current);if($mode==='forward'||$mode==='test'){return;}static$refUrl;if($refUrl===NULL){$refUrl=new Http\Url($this->httpRequest->getUrl());$refUrl->setPath($this->httpRequest->getUrl()->getScriptPath());}if(!$this->router){throw new Nette\InvalidStateException('Unable to generate URL, service Router has not been set.');}$url=$this->router->constructUrl($this->lastCreatedRequest,$refUrl);if($url===NULL){unset($args[self::ACTION_KEY]);$params=urldecode(http_build_query($args,NULL,', '));throw new 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)-1);}}return$url.$fragment;}private static function 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;}if($args[$name]===NULL){continue;}$def=$param->isDefaultValueAvailable()&&$param->isOptional()?$param->getDefaultValue():NULL;$type=$param->isArray()?'array':gettype($def);if(!PresenterComponentReflection::convertType($args[$name],$type)){throw new InvalidLinkException("Invalid value for parameter '$name' in method $class::$method(), expected ".($type==='NULL'?'scalar':$type).".");}if($args[$name]===$def||($def===NULL&&is_scalar($args[$name])&&(string)$args[$name]==='')){$args[$name]=NULL;}}if(array_key_exists($i,$args)){$method=$rm->getName();throw new InvalidLinkException("Passed more parameters than method $class::$method() expects.");}}protected function handleInvalidLink(InvalidLinkException$e){if($this->invalidLinkMode===self::INVALID_LINK_SILENT){return'#';}elseif($this->invalidLinkMode===self::INVALID_LINK_WARNING){return'#error: '.$e->getMessage();}else{throw$e;}}public function storeRequest($expiration='+ 10 minutes'){$session=$this->getSession('Nette.Application/requests');do{$key=Nette\Utils\Random::generate(5);}while(isset($session[$key]));$session[$key]=array($this->getUser()->getId(),$this->request);$session->setExpiration($expiration,$key);return$key;}public function 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 Responses\ForwardResponse($request));}public static function getPersistentComponents(){return(array)Reflection\ClassType::from(get_called_class())->getAnnotation('persistent');}private function getGlobalState($forClass=NULL){$sinces=&$this->globalStateSinces;if($this->globalState===NULL){$state=array();foreach($this->globalParams as$id=>$params){$prefix=$id.self::NAME_SEPARATOR;foreach($params as$key=>$val){$state[$prefix.$key]=$val;}}$this->saveState($state,$forClass?new PresenterComponentReflection($forClass):NULL);if($sinces===NULL){$sinces=array();foreach($this->getReflection()->getPersistentParams()as$name=>$meta){$sinces[$name]=$meta['since'];}}$components=$this->getReflection()->getPersistentComponents();$iterator=$this->getComponents(TRUE,'Nette\Application\UI\IStatePersistent');foreach($iterator 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 as$key=>$val){$state[$prefix.$key]=$val;$sinces[$prefix.$key]=$since;}}}else{$state=$this->globalState;}if($forClass!==NULL){$since=NULL;foreach($state 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 function saveGlobalState(){$this->globalParams=array();$this->globalState=$this->getGlobalState();}private function initGlobalParameters(){$this->globalParams=array();$selfParams=array();$params=$this->request->getParameters();if($this->isAjax()){$params+=$this->request->getPost();}elseif(isset($this->request->post[self::SIGNAL_KEY])){$params[self::SIGNAL_KEY]=$this->request->post[self::SIGNAL_KEY];}foreach($params as$key=>$value){if(!preg_match('#^((?:[a-z0-9_]+-)*)((?!\d+\z)[a-z0-9_]+)\z#i',$key,$matches)){continue;}elseif(!$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);}public function popGlobalParameters($id){if(isset($this->globalParams[$id])){$res=$this->globalParams[$id];unset($this->globalParams[$id]);return$res;}else{return array();}}public function hasFlashSession(){return!empty($this->params[self::FLASH_KEY])&&$this->getSession()->hasSection('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}public function getFlashSession(){if(empty($this->params[self::FLASH_KEY])){$this->params[self::FLASH_KEY]=Nette\Utils\Random::generate(4);}return$this->getSession('Nette.Application.Flash/'.$this->params[self::FLASH_KEY]);}public function injectPrimary(Nette\DI\Container$context=NULL,Nette\Application\IPresenterFactory$presenterFactory=NULL,Nette\Application\IRouter$router=NULL,Http\IRequest$httpRequest,Http\IResponse$httpResponse,Http\Session$session=NULL,Nette\Security\User$user=NULL,ITemplateFactory$templateFactory=NULL){if($this->presenterFactory!==NULL){throw new Nette\InvalidStateException("Method ".__METHOD__." is intended for initialization and should not be called more than once.");}$this->context=$context;$this->presenterFactory=$presenterFactory;$this->router=$router;$this->httpRequest=$httpRequest;$this->httpResponse=$httpResponse;$this->session=$session;$this->user=$user;$this->templateFactory=$templateFactory;}public function getContext(){if(!$this->context){throw new Nette\InvalidStateException('Context has not been set.');}return$this->context;}final public function getService($name){trigger_error(__METHOD__.'() is deprecated; use dependency injection instead.',E_USER_DEPRECATED);return$this->context->getService($name);}protected function getHttpRequest(){return$this->httpRequest;}protected function getHttpResponse(){return$this->httpResponse;}public function getSession($namespace=NULL){if(!$this->session){throw new Nette\InvalidStateException('Service Session has not been set.');}return$namespace===NULL?$this->session:$this->session->getSection($namespace);}public function getUser(){if(!$this->user){throw new Nette\InvalidStateException('Service User has not been set.');}return$this->user;}public function getTemplateFactory(){if(!$this->templateFactory){throw new Nette\InvalidStateException('Service TemplateFactory has not been set.');}return$this->templateFactory;}}lookup('Nette\Application\UI\Presenter',$need);}public function getUniqueId(){return$this->lookupPath('Nette\Application\UI\Presenter',TRUE);}protected function attached($presenter){if($presenter instanceof Presenter){$this->loadState($presenter->popGlobalParameters($this->getUniqueId()));}}protected function validateParent(Nette\ComponentModel\IContainer$parent){parent::validateParent($parent);$this->monitor('Nette\Application\UI\Presenter');}protected function 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 TRUE;}}return FALSE;}public function checkRequirements($element){}public static function getReflection(){return new PresenterComponentReflection(get_called_class());}public function loadState(array$params){$reflection=$this->getReflection();foreach($reflection->getPersistentParams()as$name=>$meta){if(isset($params[$name])){$type=gettype($meta['def']);if(!$reflection->convertType($params[$name],$type)){throw new Nette\Application\BadRequestException("Invalid value for persistent parameter '$name' in '{$this->getName()}', expected ".($type==='NULL'?'scalar':$type).".");}$this->$name=$params[$name];}else{$params[$name]=$this->$name;}}$this->params=$params;}public function saveState(array&$params,$reflection=NULL){$reflection=$reflection===NULL?$this->getReflection():$reflection;foreach($reflection->getPersistentParams()as$name=>$meta){if(isset($params[$name])){}elseif(array_key_exists($name,$params)){continue;}elseif(!isset($meta['since'])||$this instanceof$meta['since']){$params[$name]=$this->$name;}else{continue;}$type=gettype($meta['def']);if(!PresenterComponentReflection::convertType($params[$name],$type)){throw new InvalidLinkException(sprintf("Invalid value for persistent parameter '%s' in '%s', expected %s.",$name,$this->getName(),$type==='NULL'?'scalar':$type));}if($params[$name]===$meta['def']||($meta['def']===NULL&&is_scalar($params[$name])&&(string)$params[$name]==='')){$params[$name]=NULL;}}}public function getParameter($name,$default=NULL){if(func_num_args()===0){trigger_error('Calling '.__METHOD__.' with no arguments to get all parameters is deprecated, use getParameters() instead.',E_USER_DEPRECATED);return$this->params;}elseif(isset($this->params[$name])){return$this->params[$name];}else{return$default;}}public function getParameters(){return$this->params;}public function getParameterId($name){$uid=$this->getUniqueId();return$uid===''?$name:$uid.self::NAME_SEPARATOR.$name;}function getParam($name=NULL,$default=NULL){return func_num_args()?$this->getParameter($name,$default):$this->getParameters();}public static function getPersistentParams(){$rc=new 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;}public function signalReceived($signal){if(!$this->tryCall($this->formatSignalMethod($signal),$this->params)){$class=get_class($this);throw new BadSignalException("There is no handler for signal '$signal' in class $class.");}}public static function formatSignalMethod($signal){return$signal==NULL?NULL:'handle'.$signal;}public function link($destination,$args=array()){try{return$this->getPresenter()->createRequest($this,$destination,is_array($args)?$args:array_slice(func_get_args(),1),'link');}catch(InvalidLinkException$e){return$this->getPresenter()->handleInvalidLink($e);}}public function lazyLink($destination,$args=array()){return new Link($this,$destination,is_array($args)?$args:array_slice(func_get_args(),1));}public function isLinkCurrent($destination=NULL,$args=array()){if($destination!==NULL){$this->getPresenter()->createRequest($this,$destination,is_array($args)?$args:array_slice(func_get_args(),1),'test');}return$this->getPresenter()->getLastCreatedRequestFlag('current');}public function redirect($code,$destination=NULL,$args=array()){if(!is_numeric($code)){$args=$destination;$destination=$code;$code=NULL;}if(!is_array($args)){$args=array_slice(func_get_args(),is_numeric($code)?2:1);}$presenter=$this->getPresenter();$presenter->redirectUrl($presenter->createRequest($this,$destination,$args,'redirect'),$code);}public function offsetSet($name,$component){$this->addComponent($component,$name);}public function offsetGet($name){return$this->getComponent($name,TRUE);}public function offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}public function offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}}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($class::getPersistentParams()as$name=>$default){if(is_int($name)){$name=$default;$default=$defaults[$name];}$params[$name]=array('def'=>$default,'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;}public function 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($class::getPersistentComponents()as$name=>$meta){if(is_string($meta)){$name=$meta;}$components[$name]=array('since'=>$class);}$components=$this->getPersistentComponents(get_parent_class($class))+$components;}return$components;}public function 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;}public static function combineArgs(\ReflectionFunctionAbstract$method,$args){$res=array();$i=0;foreach($method->getParameters()as$param){$name=$param->getName();if(isset($args[$name])){$res[$i++]=$args[$name];$type=$param->isArray()?'array':($param->isDefaultValueAvailable()&&$param->isOptional()?gettype($param->getDefaultValue()):'NULL');if(!self::convertType($res[$i-1],$type)){$mName=$method instanceof\ReflectionMethod?$method->getDeclaringClass()->getName().'::'.$method->getName():$method->getName();throw new BadRequestException("Invalid value for parameter '$name' in method $mName(), expected ".($type==='NULL'?'scalar':$type).".");}}else{$res[$i++]=$param->isDefaultValueAvailable()&&$param->isOptional()?$param->getDefaultValue():($param->isArray()?array():NULL);}}return$res;}public static function convertType(&$val,$type){if($val===NULL||is_object($val)){}elseif($type==='array'){if(!is_array($val)){return FALSE;}}elseif(!is_scalar($val)){return FALSE;}elseif($type!=='NULL'){$old=$val=($val===FALSE?'0':(string)$val);settype($val,$type);if($old!==($val===FALSE?'0':(string)$val)){return FALSE;}}return TRUE;}}'Nette\DI\Extensions\PhpExtension','constants'=>'Nette\DI\Extensions\ConstantsExtension','nette'=>'Nette\Bridges\Framework\NetteExtension','database'=>'Nette\Bridges\DatabaseDI\DatabaseExtension','extensions'=>'Nette\DI\Extensions\ExtensionsExtension');protected$parameters;protected$files=array();public function __construct(){$this->parameters=$this->getDefaultParameters();}public function setDebugMode($value){$this->parameters['debugMode']=is_string($value)||is_array($value)?static::detectDebugMode($value):(bool)$value;$this->parameters['productionMode']=!$this->parameters['debugMode'];return$this;}public function isDebugMode(){return$this->parameters['debugMode'];}public function setTempDirectory($path){$this->parameters['tempDir']=$path;return$this;}public function addParameters(array$params){$this->parameters=DI\Config\Helpers::merge($params,$this->parameters);return$this;}protected function getDefaultParameters(){$trace=debug_backtrace(PHP_VERSION_ID>=50306?DEBUG_BACKTRACE_IGNORE_ARGS:FALSE);$debugMode=static::detectDebugMode();return array('appDir'=>isset($trace[1]['file'])?dirname($trace[1]['file']):NULL,'wwwDir'=>isset($_SERVER['SCRIPT_FILENAME'])?dirname(realpath($_SERVER['SCRIPT_FILENAME'])):NULL,'debugMode'=>$debugMode,'productionMode'=>!$debugMode,'environment'=>$debugMode?'development':'production','consoleMode'=>PHP_SAPI==='cli','container'=>array('class'=>'SystemContainer','parent'=>'Nette\DI\Container'));}public function enableDebugger($logDirectory=NULL,$email=NULL){Tracy\Debugger::$strictMode=TRUE;Tracy\Debugger::enable(!$this->parameters['debugMode'],$logDirectory,$email);}public function createRobotLoader(){if(!class_exists('Nette\Loaders\RobotLoader')){throw new Nette\NotSupportedException('RobotLoader not found, do you have `nette/robot-loader` package installed?');}$loader=new Nette\Loaders\RobotLoader;$loader->setCacheStorage(new Nette\Caching\Storages\FileStorage($this->getCacheDirectory()));$loader->autoRebuild=$this->parameters['debugMode'];return$loader;}public function addConfig($file,$section=NULL){if($section===NULL&&$this->parameters['debugMode']){try{$loader=new DI\Config\Loader;$loader->load($file,$this->parameters['environment']);trigger_error("Config file '$file' has sections, call addConfig() with second parameter Configurator::AUTO.",E_USER_WARNING);$section=$this->parameters['environment'];}catch(\Exception$e){}}$this->files[]=array($file,$section===self::AUTO?$this->parameters['environment']:$section);return$this;}public function createContainer(){$container=$this->createContainerFactory()->create();$container->initialize();if(class_exists('Nette\Environment')){Nette\Environment::setContext($container);}return$container;}protected function createContainerFactory(){$factory=new DI\ContainerFactory(NULL);$factory->autoRebuild=$this->parameters['debugMode']?TRUE:'compat';$factory->class=$this->parameters['container']['class'];$factory->config=array('parameters'=>$this->parameters);$factory->configFiles=$this->files;$factory->tempDirectory=$this->getCacheDirectory().'/Nette.Configurator';if(!is_dir($factory->tempDirectory)){mkdir($factory->tempDirectory);}$me=$this;$factory->onCompile[]=function(DI\ContainerFactory$factory,DI\Compiler$compiler,$config)use($me){foreach($me->defaultExtensions as$name=>$class){if(class_exists($class)){$compiler->addExtension($name,new$class);}}$factory->parentClass=$config['parameters']['container']['parent'];$me->onCompile($me,$compiler);};return$factory;}protected function getCacheDirectory(){if(empty($this->parameters['tempDir'])){throw new Nette\InvalidStateException('Set path to temporary directory using setTempDirectory().');}$dir=$this->parameters['tempDir'].'/cache';if(!is_dir($dir)){mkdir($dir);}return$dir;}public static function detectDebugMode($list=NULL){$addr=isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:php_uname('n');$secret=isset($_COOKIE[self::COOKIE_SECRET])&&is_string($_COOKIE[self::COOKIE_SECRET])?$_COOKIE[self::COOKIE_SECRET]:NULL;$list=is_string($list)?preg_split('#[,\s]+#',$list):(array)$list;if(!isset($_SERVER['HTTP_X_FORWARDED_FOR'])){$list[]='127.0.0.1';$list[]='::1';}return in_array($addr,$list,TRUE)||in_array("$secret@$addr",$list,TRUE);}}presenter=$presenter;}}latte=$latte;}public function getLatte(){return$this->latte;}public function render($file=NULL,array$params=array()){$this->latte->render($file?:$this->file,$params?:$this->params);}public function __toString(){ob_start();try{$this->render();return ob_get_clean();}catch(\Exception$e){ob_end_clean();if(func_num_args()){throw$e;}trigger_error("Exception in ".__METHOD__."(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}",E_USER_ERROR);}}public function addFilter($name,$callback){return$this->latte->addFilter($name,$callback);}public function registerHelper($name,$callback){return$this->latte->addFilter($name,$callback);}public function registerHelperLoader($loader){$latte=$this->latte;$this->latte->addFilter(NULL,function($name)use($loader,$latte){if($callback=call_user_func($loader,$name)){$latte->addFilter($name,$callback);}});return$this;}public function setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->latte->addFilter('translate',$translator===NULL?NULL:array($translator,'translate'));return$this;}public function registerFilter($callback){throw new Nette\DeprecatedException(__METHOD__.'() is deprecated.');}public function setFile($file){$this->file=$file;return$this;}public function getFile(){return$this->file;}public function add($name,$value){if(array_key_exists($name,$this->params)){throw new Nette\InvalidStateException("The variable '$name' already exists.");}$this->params[$name]=$value;return$this;}public function setParameters(array$params){$this->params=$params+$this->params;return$this;}public function getParameters(){return$this->params;}public function __set($name,$value){$this->params[$name]=$value;}public function&__get($name){if(!array_key_exists($name,$this->params)){trigger_error("The variable '$name' does not exist in template.",E_USER_NOTICE);}return$this->params[$name];}public function __isset($name){return isset($this->params[$name]);}public function __unset($name){unset($this->params[$name]);}}latteFactory=$latteFactory;$this->httpRequest=$httpRequest;$this->httpResponse=$httpResponse;$this->user=$user;$this->cacheStorage=$cacheStorage;}public function createTemplate(UI\Control$control){$latte=$this->latteFactory->create();$template=new Template($latte);$presenter=$control->getPresenter(FALSE);if($control instanceof UI\Presenter){$latte->setLoader(new Loader($control));}if($latte->onCompile instanceof\Traversable){$latte->onCompile=iterator_to_array($latte->onCompile);}array_unshift($latte->onCompile,function($latte)use($control,$template){$latte->getParser()->shortNoEscape=TRUE;$latte->getCompiler()->addMacro('cache',new Nette\Bridges\CacheLatte\CacheMacro($latte->getCompiler()));UIMacros::install($latte->getCompiler());Nette\Bridges\FormsLatte\FormMacros::install($latte->getCompiler());$control->templatePrepareFilters($template);});$latte->addFilter('url','rawurlencode');foreach(array('normalize','toAscii','webalize','padLeft','padRight','reverse')as$name){$latte->addFilter($name,'Nette\Utils\Strings::'.$name);}$latte->addFilter('null',function(){});$latte->addFilter('length',function($var){return is_string($var)?Nette\Utils\Strings::length($var):count($var);});$latte->addFilter('modifyDate',function($time,$delta,$unit=NULL){return$time==NULL?NULL:Nette\Utils\DateTime::from($time)->modify($delta.$unit);});$template->control=$template->_control=$control;$template->presenter=$template->_presenter=$presenter;$template->user=$this->user;$template->netteHttpResponse=$this->httpResponse;$template->netteCacheStorage=$this->cacheStorage;$template->baseUri=$template->baseUrl=$this->httpRequest?rtrim($this->httpRequest->getUrl()->getBaseUrl(),'/'):NULL;$template->basePath=preg_replace('#https?://[^/]+#A','',$template->baseUrl);$template->flashes=array();if($presenter instanceof UI\Presenter&&$presenter->hasFlashSession()){$id=$control->getParameterId('flash');$template->flashes=(array)$presenter->getFlashSession()->$id;}return$template;}}addMacro('control',array($me,'macroControl'));$me->addMacro('href',NULL,NULL,function(MacroNode$node,PhpWriter$writer)use($me){return' ?> href="macroLink($node,$writer).' ?>"addMacro('plink',array($me,'macroLink'));$me->addMacro('link',array($me,'macroLink'));$me->addMacro('ifCurrent',array($me,'macroIfCurrent'),'}');}public function finalize(){$prolog=' // snippets support if (empty($_l->extends) && !empty($_control->snippetMode)) { return Nette\Bridges\ApplicationLatte\UIMacros::renderSnippets($_control, $_b, get_defined_vars()); }';return array($prolog,'');}public function macroControl(MacroNode$node,PhpWriter$writer){$words=$node->tokenizer->fetchWords();if(!$words){throw new CompileException('Missing control name in {control}');}$name=$writer->formatWord($words[0]);$method=isset($words[1])?ucfirst($words[1]):'';$method=Strings::match($method,'#^\w*\z#')?"render$method":"{\"render$method\"}";$param=$writer->formatArray();if(!Strings::contains($node->args,'=>')){$param=substr($param,6,-1);}return($name[0]==='$'?"if (is_object($name)) \$_l->tmp = $name; else ":'').'$_l->tmp = $_control->getComponent('.$name.'); '.'if ($_l->tmp instanceof Nette\Application\UI\IRenderable) $_l->tmp->redrawControl(NULL, FALSE); '.($node->modifiers===''?"\$_l->tmp->$method($param)":$writer->write("ob_start(); \$_l->tmp->$method($param); echo %modify(ob_get_clean())"));}public function macroLink(MacroNode$node,PhpWriter$writer){$node->modifiers=preg_replace('#\|safeurl\s*(?=\||\z)#i','',$node->modifiers);return$writer->using($node,$this->getCompiler())->write('echo %escape(%modify('.($node->name==='plink'?'$_presenter':'$_control').'->link(%node.word, %node.array?)))');}public function 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")) {');}public static function renderSnippets(Nette\Application\UI\Control$control,\stdClass$local,array$params){$control->snippetMode=FALSE;$payload=$control->getPresenter()->getPayload();if(isset($local->blocks)){foreach($local->blocks as$name=>$function){if($name[0]!=='_'||!$control->isControlInvalid(substr($name,1))){continue;}ob_start();$function=reset($function);$snippets=$function($local,$params+array('_snippetMode'=>TRUE));$payload->snippets[$id=$control->getSnippetId(substr($name,1))]=ob_get_clean();if($snippets!==NULL){if($snippets){$payload->snippets+=$snippets;}unset($payload->snippets[$id]);}}}$control->snippetMode=TRUE;if($control instanceof Nette\Application\UI\IRenderable){$queue=array($control);do{foreach(array_shift($queue)->getComponents()as$child){if($child instanceof Nette\Application\UI\IRenderable){if($child->isControlInvalid()){$child->snippetMode=TRUE;$child->render();$child->snippetMode=FALSE;}}elseif($child instanceof Nette\ComponentModel\IContainer){$queue[]=$child;}}}while($queue);}}}addPanel(function($e)use($application){return$e?NULL:array('tab'=>'Nette Application','panel'=>'

Requests

'.Tracy\Dumper::toHtml($application->getRequests()).'

Presenter

'.Tracy\Dumper::toHtml($application->getPresenter()));});}public function __construct(Nette\Application\IRouter$router,Nette\Http\IRequest$httpRequest,Nette\Application\IPresenterFactory$presenterFactory){$this->router=$router;$this->httpRequest=$httpRequest;$this->presenterFactory=$presenterFactory;}public function getTab(){$this->analyse($this->router);ob_start();$request=$this->request;require __DIR__.'/templates/RoutingPanel.tab.phtml';return ob_get_clean();}public function getPanel(){ob_start();$request=$this->request;$routers=$this->routers;$source=$this->source;$url=$this->httpRequest->getUrl();require __DIR__.'/templates/RoutingPanel.panel.phtml';return ob_get_clean();}private function analyse($router,$module=''){if($router instanceof Routers\RouteList){foreach($router 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;$this->findSource();$matched='yes';}}$this->routers[]=array('matched'=>$matched,'class'=>get_class($router),'defaults'=>$router instanceof Routers\Route||$router instanceof Routers\SimpleRouter?$router->getDefaults():array(),'mask'=>$router instanceof Routers\Route?$router->getMask():NULL,'request'=>$request,'module'=>rtrim($module,':'));}private function findSource(){$request=$this->request;$presenter=$request->getPresenterName();try{$class=$this->presenterFactory->getPresenterClass($presenter);}catch(Nette\Application\InvalidPresenterException$e){return;}$rc=Nette\Reflection\ClassType::from($class);if($rc->isSubclassOf('Nette\Application\UI\Presenter')){if(isset($request->parameters[Presenter::SIGNAL_KEY])){$method=$class::formatSignalMethod($request->parameters[Presenter::SIGNAL_KEY]);}elseif(isset($request->parameters[Presenter::ACTION_KEY])){$action=$request->parameters[Presenter::ACTION_KEY];$method=$class::formatActionMethod($action);if(!$rc->hasMethod($method)){$method=$class::formatRenderMethod($action);}}}$this->source=isset($method)&&$rc->hasMethod($method)?$rc->getMethod($method):$rc;}}

no route getPresenterName().':'.(isset($request->parameters[Presenter::ACTION_KEY])?$request->parameters[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION).(isset($request->parameters[Presenter::SIGNAL_KEY])?" {$request->parameters[Presenter::SIGNAL_KEY]}!":''))?>

No routers defined.

Matched? Class Mask Defaults Module Request
$value):?> TRUE)))?>
getParameters();?> getPresenterName().':'.(isset($params[Presenter::ACTION_KEY])?$params[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION))?>
$value):?> TRUE)))?>

in getFileName(),$source->getStartLine())?>

no routegetPresenterName().':'.(isset($request->parameters[Presenter::ACTION_KEY])?$request->parameters[Presenter::ACTION_KEY]:Presenter::DEFAULT_ACTION).(isset($request->parameters[Presenter::SIGNAL_KEY])?" {$request->parameters[Presenter::SIGNAL_KEY]}!":''));endif?>used=FALSE;}public function finalize(){if($this->used){return array('Nette\Bridges\CacheLatte\CacheMacro::initRuntime($template, $_g);');}}public function nodeOpened(Latte\MacroNode$node){$this->used=TRUE;$node->isEmpty=FALSE;$node->openingCode=Latte\PhpWriter::using($node)->write('caches, %node.array?)) { ?>',Nette\Utils\Random::generate());}public function nodeClosed(Latte\MacroNode$node){$node->closingCode='tmp = array_pop($_g->caches); if (!$_l->tmp instanceof stdClass) $_l->tmp->end(); } ?>';}public static function initRuntime(Latte\Template$template,\stdClass$global){if(!empty($global->caches)&&$template->getEngine()->getLoader()instanceof Latte\Loaders\FileLoader){end($global->caches)->dependencies[Nette\Caching\Cache::FILES][]=$template->getName();}}public static function createCache(Nette\Caching\IStorage$cacheStorage,$key,&$parents,array$args=NULL){if($args){if(array_key_exists('if',$args)&&!$args['if']){return$parents[]=new\stdClass;}$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 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;}}NULL,'user'=>NULL,'password'=>NULL,'options'=>NULL,'debugger'=>TRUE,'explain'=>TRUE,'reflection'=>'discovered','autowired'=>NULL);public function loadConfiguration(){$container=$this->getContainerBuilder();$config=$this->compiler->getConfig();if(isset($config['nette']['database'])){$config=$config['nette']['database'];$prefix='nette.';}else{$config=isset($config[$this->name])?$config[$this->name]:array();$prefix='';}if(isset($config['dsn'])){$config=array('default'=>$config);}$autowired=TRUE;foreach((array)$config as$name=>$info){if(!is_array($info)){continue;}$this->validate($info,$this->databaseDefaults,'database');$info+=array('autowired'=>$autowired)+$this->databaseDefaults;$autowired=FALSE;foreach((array)$info['options']as$key=>$value){if(preg_match('#^PDO::\w+\z#',$key)){unset($info['options'][$key]);$info['options'][constant($key)]=$value;}}$connection=$container->addDefinition($prefix.$this->prefix($name))->setClass('Nette\Database\Connection',array($info['dsn'],$info['user'],$info['password'],$info['options']))->setAutowired($info['autowired'])->addSetup('Tracy\Debugger::getBlueScreen()->addPanel(?)',array('Nette\Bridges\DatabaseTracy\ConnectionPanel::renderException'));if(!$info['reflection']){$reflection=NULL;}elseif(is_string($info['reflection'])){$reflection=new Nette\DI\Statement(preg_match('#^[a-z]+\z#',$info['reflection'])?'Nette\Database\Reflection\\'.ucfirst($info['reflection']).'Reflection':$info['reflection'],strtolower($info['reflection'])==='discovered'?array($connection):array());}else{$tmp=Nette\DI\Compiler::filterArguments(array($info['reflection']));$reflection=reset($tmp);}$container->addDefinition($prefix.$this->prefix("$name.context"))->setClass('Nette\Database\Context',array($connection,$reflection))->setAutowired($info['autowired']);if($container->parameters['debugMode']&&$info['debugger']){$connection->addSetup('Nette\Database\Helpers::createDebugPanel',array($connection,!empty($info['explain']),$name));}}}private function validate(array$config,array$expected,$name){if($extra=array_diff_key($config,$expected)){$extra=implode(", $name.",array_keys($extra));throw new Nette\InvalidStateException("Unknown option $name.$extra.");}}}onQuery[]=array($this,'logQuery');}public function logQuery(Nette\Database\Connection$connection,$result){if($this->disabled){return;}$this->count++;$source=NULL;$trace=$result instanceof\PDOException?$result->getTrace():debug_backtrace(PHP_VERSION_ID>=50306?DEBUG_BACKTRACE_IGNORE_ARGS:FALSE);foreach($trace as$row){if(isset($row['file'])&&is_file($row['file'])&&!Tracy\Debugger::getBluescreen()->isCollapsed($row['file'])){if((isset($row['function'])&&strpos($row['function'],'call_user_func')===0)||(isset($row['class'])&&is_subclass_of($row['class'],'\\Nette\\Database\\Connection'))){continue;}$source=array($row['file'],(int)$row['line']);break;}}if($result instanceof Nette\Database\ResultSet){$this->totalTime+=$result->getTime();if($this->count<$this->maxQueries){$this->queries[]=array($connection,$result->getQueryString(),$result->getParameters(),$source,$result->getTime(),$result->getRowCount(),NULL);}}elseif($result instanceof\PDOException&&$this->count<$this->maxQueries){$this->queries[]=array($connection,$result->queryString,NULL,$source,NULL,NULL,$result->getMessage());}}public static function renderException($e){if(!$e instanceof\PDOException){return;}if(isset($e->queryString)){$sql=$e->queryString;}elseif($item=Tracy\Helpers::findTrace($e->getTrace(),'PDO::prepare')){$sql=$item['args'][0];}return isset($sql)?array('tab'=>'SQL','panel'=>Helpers::dumpSql($sql)):NULL;}public function getTab(){return''.''.$this->count.' '.($this->count===1?'query':'queries').($this->totalTime?sprintf(' / %0.1f ms',$this->totalTime*1000):'').'';}public function getPanel(){$this->disabled=TRUE;$s='';foreach($this->queries as$query){list($connection,$sql,$params,$source,$time,$rows,$error)=$query;$explain=NULL;if(!$error&&$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.='';if($error){$s.='ERROR';}elseif($time!==NULL){$s.=sprintf('%0.3f',$time*1000);}if($explain){static$counter;$counter++;$s.="
explain";}$s.=''.Helpers::dumpSql($sql,$params);if($explain){$s.="";foreach($explain[0]as$col=>$foo){$s.='';}$s.='';foreach($explain as$row){$s.='';foreach($row as$col){$s.='';}$s.='';}$s.='
'.htmlSpecialChars($col).'
'.htmlSpecialChars($col).'
';}if($source){$s.=substr_replace(Tracy\Helpers::editorLink($source[0],$source[1]),' class="nette-DbConnectionPanel-source"',2,0);}$s.=''.$rows.'';}return$this->count?'

Queries: '.$this->count.($this->totalTime?sprintf(', time: %0.3f ms',$this->totalTime*1000):'').', '.htmlSpecialChars($this->name).'

'.$s.'
Time msSQL QueryRows
'.(count($this->queries)<$this->count?'

...and more

':'').'
':'';}}container=$container;}public function getTab(){ob_start();require __DIR__.'/templates/ContainerPanel.tab.phtml';return ob_get_clean();}public function getPanel(){$services=array();foreach(Nette\Reflection\ClassType::from($this->container)->getMethods()as$method){if(preg_match('#^createService_*(.+)\z#',$method->getName(),$m)){$services[str_replace('__','.',strtolower(substr($m[1],0,1)).substr($m[1],1))]=$method->getAnnotation('return');}}ksort($services);$container=$this->container;$registry=$this->getContainerProperty('registry');$tags=array();$meta=$this->getContainerProperty('meta');if(isset($meta[Container::TAGS])){foreach($meta[Container::TAGS]as$tag=>$tmp){foreach($tmp as$service=>$val){$tags[$service][$tag]=$val;}}}ob_start();require __DIR__.'/templates/ContainerPanel.panel.phtml';return ob_get_clean();}private function getContainerProperty($name){$prop=Nette\Reflection\ClassType::from('Nette\DI\Container')->getProperty($name);$prop->setAccessible(TRUE);return$prop->getValue($this->container);}}

Services

$class):?> findByType($class));?>
Name Autowired Service Tags
TRUE));?> TRUE));}?>

Parameters

parameters);?>
 addMacro('form',array($me,'macroForm'),'Nette\Bridges\FormsLatte\FormMacros::renderFormEnd($_form)');$me->addMacro('formContainer',array($me,'macroFormContainer'),'$_form = array_pop($_formStack)');$me->addMacro('label',array($me,'macroLabel'),array($me,'macroLabelEnd'));$me->addMacro('input',array($me,'macroInput'),NULL,array($me,'macroInputAttr'));$me->addMacro('name',array($me,'macroName'),array($me,'macroNameEnd'),array($me,'macroNameAttr'));$me->addMacro('inputError',array($me,'macroInputError'));}public function macroForm(MacroNode$node,PhpWriter$writer){if($node->prefix){throw new CompileException('Did you mean
?');}$name=$node->tokenizer->fetchWord();if($name===FALSE){throw new CompileException("Missing form name in {{$node->name}}.");}$node->tokenizer->reset();$node->replaced=TRUE;return$writer->write('Nette\Bridges\FormsLatte\FormMacros::renderFormBegin($form = $_form = '.($name[0]==='$'?'is_object(%node.word) ? %node.word : ':'').'$_control[%node.word], %node.array)');}public function macroFormContainer(MacroNode$node,PhpWriter$writer){$name=$node->tokenizer->fetchWord();if($name===FALSE){throw new CompileException("Missing name in {{$node->name}}.");}$node->tokenizer->reset();return$writer->write('$_formStack[] = $_form; $formContainer = $_form = '.($name[0]==='$'?'is_object(%node.word) ? %node.word : ':'').'$_form[%node.word]');}public function macroLabel(MacroNode$node,PhpWriter$writer){$words=$node->tokenizer->fetchWords();if(!$words){throw new CompileException("Missing name in {{$node->name}}.");}$name=array_shift($words);return$writer->write(($name[0]==='$'?'$_input = is_object(%0.word) ? %0.word : $_form[%0.word]; if ($_label = $_input':'if ($_label = $_form[%0.word]').'->%1.raw) echo $_label'.($node->tokenizer->isNext()?'->addAttributes(%node.array)':''),$name,$words?('getLabelPart('.implode(', ',array_map(array($writer,'formatWord'),$words)).')'):'getLabel()');}public function macroLabelEnd(MacroNode$node,PhpWriter$writer){if($node->content!=NULL){$node->openingCode=rtrim($node->openingCode,'?> ').'->startTag() ?>';return$writer->write('if ($_label) echo $_label->endTag()');}}public function macroInput(MacroNode$node,PhpWriter$writer){$words=$node->tokenizer->fetchWords();if(!$words){throw new CompileException("Missing name in {{$node->name}}.");}$name=array_shift($words);return$writer->write(($name[0]==='$'?'$_input = is_object(%0.word) ? %0.word : $_form[%0.word]; echo $_input':'echo $_form[%0.word]').'->%1.raw'.($node->tokenizer->isNext()?'->addAttributes(%node.array)':''),$name,$words?'getControlPart('.implode(', ',array_map(array($writer,'formatWord'),$words)).')':'getControl()');}public function macroInputAttr(MacroNode$node,PhpWriter$writer){throw new CompileException('Use n:name instead of n:input.');}public function macroNameAttr(MacroNode$node,PhpWriter$writer){$words=$node->tokenizer->fetchWords();if(!$words){throw new CompileException("Missing name in n:{$node->name}.");}$name=array_shift($words);$tagName=strtolower($node->htmlNode->name);$node->isEmpty=!in_array($tagName,array('form','select','textarea'),TRUE);$node->replaced=TRUE;if($tagName==='form'){return$writer->write('Nette\Bridges\FormsLatte\FormMacros::renderFormBegin($form = $_form = '.($name[0]==='$'?'is_object(%0.word) ? %0.word : ':'').'$_control[%0.word], %1.var, FALSE)',$name,array_fill_keys(array_keys($node->htmlNode->attrs),NULL));}else{$method=$tagName==='label'?'getLabel':'getControl';return$writer->write('$_input = '.($name[0]==='$'?'is_object(%0.word) ? %0.word : ':'').'$_form[%0.word]; echo $_input->%1.raw'.($node->htmlNode->attrs?'->addAttributes(%2.var)':'').'->attributes()',$name,$words?$method.'Part('.implode(', ',array_map(array($writer,'formatWord'),$words)).')':"{method_exists(\$_input, '{$method}Part')?'{$method}Part':'{$method}'}()",array_fill_keys(array_keys($node->htmlNode->attrs),NULL));}}public function macroName(MacroNode$node,PhpWriter$writer){if(!$node->prefix){throw new CompileException("Unknown macro {{$node->name}}, use n:{$node->name} attribute.");}elseif($node->prefix!==MacroNode::PREFIX_NONE){throw new CompileException("Unknown attribute n:{$node->prefix}-{$node->name}, use n:{$node->name} attribute.");}}public function macroNameEnd(MacroNode$node,PhpWriter$writer){preg_match('#^(.*? n:\w+>)(.*)(<[^?].*)\z#s',$node->content,$parts);$node->replaced=TRUE;if(strtolower($node->htmlNode->name)==='form'){$node->content=$parts[1].$parts[2].''.$parts[3];}else{$node->content=$parts[1].'getControl()->getHtml() ?>'.$parts[3];}}public function macroInputError(MacroNode$node,PhpWriter$writer){$name=$node->tokenizer->fetchWord();if(!$name){return$writer->write('echo %escape($_input->getError())');}elseif($name[0]==='$'){return$writer->write('$_input = is_object(%0.word) ? %0.word : $_form[%0.word]; echo %escape($_input->getError())',$name);}else{return$writer->write('echo %escape($_form[%0.word]->getError())',$name);}}public static function renderFormBegin(Form$form,array$attrs,$withTags=TRUE){foreach($form->getControls()as$control){$control->setOption('rendered',FALSE);}$el=$form->getElementPrototype();$el->action=(string)$el->action;$el=clone$el;if(strcasecmp($form->getMethod(),'get')===0){$el->action=preg_replace('~\?[^#]*~','',$el->action,1);}$el->addAttributes($attrs);echo$withTags?$el->startTag():$el->attributes();}public static function renderFormEnd(Form$form,$withTags=TRUE){$s='';if(strcasecmp($form->getMethod(),'get')===0){foreach(preg_split('#[;&]#',parse_url($form->getElementPrototype()->action,PHP_URL_QUERY),NULL,PREG_SPLIT_NO_EMPTY)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.='';}echo($s?"
$s
\n":'').($withTags?$form->getElementPrototype()->endTag()."\n":'');}}container=$container;}public function __call($name,$args){if(substr($name,0,6)==='create'){$method=$this->container->getMethodName('nette.'.substr($name,6));trigger_error("Factory accessing via nette->$name() is deprecated, use $method().",E_USER_DEPRECATED);return call_user_func_array(array($this->container,$method),$args);}throw new Nette\NotSupportedException;}public function&__get($name){trigger_error("Service accessing via nette->$name is deprecated, use 'nette.$name'.",E_USER_DEPRECATED);$service=$this->container->getService("nette.$name");return$service;}}array('proxy'=>array(),'headers'=>array('X-Powered-By'=>'Nette Framework','Content-Type'=>'text/html; charset=utf-8')),'session'=>array('debugger'=>FALSE,'autoStart'=>'smart','expiration'=>NULL),'application'=>array('debugger'=>TRUE,'errorPresenter'=>'Nette:Error','catchExceptions'=>'%productionMode%','mapping'=>NULL),'routing'=>array('debugger'=>TRUE,'routes'=>array()),'security'=>array('debugger'=>TRUE,'frames'=>'SAMEORIGIN','users'=>array(),'roles'=>array(),'resources'=>array()),'mailer'=>array('smtp'=>FALSE,'host'=>NULL,'port'=>NULL,'username'=>NULL,'password'=>NULL,'secure'=>NULL,'timeout'=>NULL),'database'=>array(),'forms'=>array('messages'=>array()),'latte'=>array('xhtml'=>FALSE,'macros'=>array()),'container'=>array('debugger'=>FALSE,'accessors'=>TRUE),'debugger'=>array('email'=>NULL,'editor'=>NULL,'browser'=>NULL,'strictMode'=>NULL,'maxLen'=>NULL,'maxDepth'=>NULL,'showLocation'=>NULL,'scream'=>NULL,'bar'=>array(),'blueScreen'=>array()));public function loadConfiguration(){$container=$this->getContainerBuilder();$config=$this->getConfig($this->defaults);if(isset($config['xhtml'])){$config['latte']['xhtml']=$config['xhtml'];unset($config['xhtml']);}$container->addDefinition('nette')->setClass('Nette\Bridges\Framework\NetteAccessor',array('@container'));$this->validate($config,$this->defaults,'nette');$this->setupCache($container);$this->setupHttp($container,$config['http']);$this->setupSession($container,$config['session']);$this->setupSecurity($container,$config['security']);$this->setupApplication($container,$config['application']);$this->setupRouting($container,$config['routing']);$this->setupMailer($container,$config['mailer']);$this->setupLatte($container,$config['latte']);$this->setupContainer($container,$config['container']);}private function setupCache(ContainerBuilder$container){$container->addDefinition($this->prefix('cacheJournal'))->setClass('Nette\Caching\Storages\FileJournal',array($container->expand('%tempDir%')));$container->addDefinition('cacheStorage')->setClass('Nette\Caching\Storages\FileStorage',array($container->expand('%tempDir%/cache')));if(class_exists('Nette\Caching\Storages\PhpFileStorage')){$container->addDefinition($this->prefix('templateCacheStorage'))->setClass('Nette\Caching\Storages\PhpFileStorage',array($container->expand('%tempDir%/cache')))->addSetup('::trigger_error',array('Service templateCacheStorage is deprecated.',E_USER_DEPRECATED))->setAutowired(FALSE);}$container->addDefinition($this->prefix('cache'))->setClass('Nette\Caching\Cache',array(1=>$container::literal('$namespace')))->addSetup('::trigger_error',array('Service cache is deprecated.',E_USER_DEPRECATED))->setParameters(array('namespace'=>NULL))->setAutowired(FALSE);}private function setupHttp(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['http'],'nette.http');$container->addDefinition($this->prefix('httpRequestFactory'))->setClass('Nette\Http\RequestFactory')->addSetup('setProxy',array($config['proxy']));$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');}private function setupSession(ContainerBuilder$container,array$config){$session=$container->addDefinition('session')->setClass('Nette\Http\Session');if(isset($config['expiration'])){$session->addSetup('setExpiration',array($config['expiration']));}if($container->parameters['debugMode']&&$config['debugger']){$session->addSetup('Tracy\Debugger::getBar()->addPanel(?)',array(new Nette\DI\Statement('Nette\Bridges\HttpTracy\SessionPanel')));}unset($config['expiration'],$config['autoStart'],$config['debugger']);if(!empty($config)){$session->addSetup('setOptions',array($config));}}private function setupSecurity(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['security'],'nette.security');$container->addDefinition($this->prefix('userStorage'))->setClass('Nette\Http\UserStorage');$user=$container->addDefinition('user')->setClass('Nette\Security\User');if($container->parameters['debugMode']&&$config['debugger']){$user->addSetup('Tracy\Debugger::getBar()->addPanel(?)',array(new Nette\DI\Statement('Nette\Bridges\SecurityTracy\UserPanel')));}if($config['users']){$usersList=$usersRoles=array();foreach($config['users']as$username=>$data){$usersList[$username]=is_array($data)?$data['password']:$data;$usersRoles[$username]=is_array($data)&&isset($data['roles'])?$data['roles']:NULL;}$container->addDefinition($this->prefix('authenticator'))->setClass('Nette\Security\SimpleAuthenticator',array($usersList,$usersRoles));}if($config['roles']||$config['resources']){$authorizator=$container->addDefinition($this->prefix('authorizator'))->setClass('Nette\Security\Permission');foreach($config['roles']as$role=>$parents){$authorizator->addSetup('addRole',array($role,$parents));}foreach($config['resources']as$resource=>$parents){$authorizator->addSetup('addResource',array($resource,$parents));}}}private function setupApplication(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['application'],'nette.application');$application=$container->addDefinition('application')->setClass('Nette\Application\Application')->addSetup('$catchExceptions',array($config['catchExceptions']))->addSetup('$errorPresenter',array($config['errorPresenter']));if($config['debugger']){$application->addSetup('Nette\Bridges\ApplicationTracy\RoutingPanel::initializePanel');}$presenterFactory=$container->addDefinition($this->prefix('presenterFactory'))->setClass('Nette\Application\PresenterFactory',array(isset($container->parameters['appDir'])?$container->parameters['appDir']:NULL));if($config['mapping']){$presenterFactory->addSetup('setMapping',array($config['mapping']));}}private function setupRouting(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['routing'],'nette.routing');$router=$container->addDefinition('router')->setClass('Nette\Application\Routers\RouteList');foreach($config['routes']as$mask=>$action){$router->addSetup('$service[] = new Nette\Application\Routers\Route(?, ?);',array($mask,$action));}if($container->parameters['debugMode']&&$config['debugger']){$container->getDefinition('application')->addSetup('Tracy\Debugger::getBar()->addPanel(?)',array(new Nette\DI\Statement('Nette\Bridges\ApplicationTracy\RoutingPanel')));}}private function setupMailer(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['mailer'],'nette.mailer');if(empty($config['smtp'])){$container->addDefinition($this->prefix('mailer'))->setClass('Nette\Mail\SendmailMailer');}else{$container->addDefinition($this->prefix('mailer'))->setClass('Nette\Mail\SmtpMailer',array($config));}}private function setupLatte(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['latte'],'nette.latte');$latteFactory=$container->addDefinition($this->prefix('latteFactory'))->setClass('Latte\Engine')->addSetup('setTempDirectory',array($container->expand('%tempDir%/cache/latte')))->addSetup('setAutoRefresh',array($container->parameters['debugMode']))->addSetup('setContentType',array($config['xhtml']?Latte\Compiler::CONTENT_XHTML:Latte\Compiler::CONTENT_HTML))->setImplement('Nette\Bridges\ApplicationLatte\ILatteFactory');$container->addDefinition($this->prefix('templateFactory'))->setClass('Nette\Bridges\ApplicationLatte\TemplateFactory');$latte=$container->addDefinition($this->prefix('latte'))->setClass('Latte\Engine')->addSetup('setTempDirectory',array($container->expand('%tempDir%/cache/latte')))->addSetup('setAutoRefresh',array($container->parameters['debugMode']))->addSetup('setContentType',array($config['xhtml']?Latte\Compiler::CONTENT_XHTML:Latte\Compiler::CONTENT_HTML))->setAutowired(FALSE);foreach($config['macros']as$macro){if(strpos($macro,'::')===FALSE&&class_exists($macro)){$macro.='::install';}else{Validators::assert($macro,'callable');}$latte->addSetup('?->onCompile[] = function($engine) { '.$macro.'($engine->getCompiler()); }',array('@self'));$latteFactory->addSetup('?->onCompile[] = function($engine) { '.$macro.'($engine->getCompiler()); }',array('@self'));}if(class_exists('Nette\Templating\FileTemplate')){$container->addDefinition($this->prefix('template'))->setClass('Nette\Templating\FileTemplate')->addSetup('registerFilter',array(new Nette\DI\Statement(array($latteFactory,'create'))))->addSetup('registerHelperLoader',array('Nette\Templating\Helpers::loader'))->setAutowired(FALSE);}}private function setupContainer(ContainerBuilder$container,array$config){$this->validate($config,$this->defaults['container'],'nette.container');if($config['accessors']){$container->parameters['container']['accessors']=TRUE;}}public function afterCompile(Nette\PhpGenerator\ClassType$class){$initialize=$class->methods['initialize'];$container=$this->getContainerBuilder();$config=$this->getConfig($this->defaults);$initialize->addBody('Nette\Bridges\Framework\TracyBridge::initialize();');foreach(array('email','editor','browser','strictMode','maxLen','maxDepth','showLocation','scream')as$key){if(isset($config['debugger'][$key])){$initialize->addBody('Tracy\Debugger::$? = ?;',array($key,$config['debugger'][$key]));}}if($container->parameters['debugMode']){if($config['container']['debugger']){$config['debugger']['bar'][]='Nette\Bridges\DITracy\ContainerPanel';}foreach((array)$config['debugger']['bar']as$item){$initialize->addBody($container->formatPhp('Tracy\Debugger::getBar()->addPanel(?);',Nette\DI\Compiler::filterArguments(array(is_string($item)?new Nette\DI\Statement($item):$item))));}}foreach((array)$config['debugger']['blueScreen']as$item){$initialize->addBody($container->formatPhp('Tracy\Debugger::getBlueScreen()->addPanel(?);',Nette\DI\Compiler::filterArguments(array($item))));}if(!empty($container->parameters['tempDir'])){$initialize->addBody('Nette\Caching\Storages\FileStorage::$useDirectories = ?;',array($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->getByType("Nette\Http\Session")->exists() && $this->getByType("Nette\Http\Session")->start();');}elseif($config['session']['autoStart']){$initialize->addBody('$this->getByType("Nette\Http\Session")->start();');}if($config['latte']['xhtml']){$initialize->addBody('Nette\Utils\Html::$xhtml = ?;',array(TRUE));}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));}}if(!empty($config['container']['accessors'])){$definitions=$container->definitions;ksort($definitions);foreach($definitions as$name=>$def){if(Nette\PhpGenerator\Helpers::isIdentifier($name)){$type=$def->implement?:$def->class;$class->addDocument("@property $type \$$name");}}}foreach($config['http']['headers']as$key=>$value){if($value!=NULL){$initialize->addBody('header(?);',array("$key: $value"));}}$initialize->addBody('Nette\Utils\SafeStream::register();');$initialize->addBody('Nette\Reflection\AnnotationsParser::setCacheStorage($this->getByType("Nette\Caching\IStorage"));');$initialize->addBody('Nette\Reflection\AnnotationsParser::$autoRefresh = ?;',array($container->parameters['debugMode']));}private function checkTempDir($dir){$uniq=uniqid('_',TRUE);if(!@mkdir("$dir/$uniq")){throw new Nette\InvalidStateException("Unable to write to directory '$dir'. Make this directory writable.");}$isWritable=@file_put_contents("$dir/$uniq/_",'')!==FALSE;if($isWritable){unlink("$dir/$uniq/_");}rmdir("$dir/$uniq");return$isWritable;}private function validate(array$config,array$expected,$name){if($extra=array_diff_key($config,$expected)){$extra=implode(", $name.",array_keys($extra));throw new Nette\InvalidStateException("Unknown option $name.$extra.");}}}collapsePaths[]="$m2[1]/nette";$blueScreen->collapsePaths[]="$m2[1]/latte";}else{$blueScreen->collapsePaths[]=$m[1];}}if(class_exists('Nette\Framework')){$bar=Tracy\Debugger::getBar();$bar->info[]=$blueScreen->info[]='Nette Framework '.Nette\Framework::VERSION.' ('.Nette\Framework::REVISION.')';}$blueScreen->addPanel(function($e){if($e instanceof Latte\CompileException){return array('tab'=>'Template','panel'=>'

'.(is_file($e->sourceName)?'File: '.Helpers::editorLink($e->sourceName,$e->sourceLine):htmlspecialchars($e->sourceName)).'

'.($e->sourceCode?'
'.BlueScreen::highlightLine(htmlspecialchars($e->sourceCode),$e->sourceLine).'
':''));}elseif($e instanceof Nette\Neon\Exception&&preg_match('#line (\d+)#',$e->getMessage(),$m)){if($item=Helpers::findTrace($e->getTrace(),'Nette\DI\Config\Adapters\NeonAdapter::load')){return array('tab'=>'NEON','panel'=>'

File: '.Helpers::editorLink($item['args'][0],$m[1]).'

'.BlueScreen::highlightFile($item['args'][0],$m[1]));}elseif($item=Helpers::findTrace($e->getTrace(),'Nette\Neon\Decoder::decode')){return array('tab'=>'NEON','panel'=>BlueScreen::highlightPhp($item['args'][0],$m[1]));}}});}}

Session # (Lifetime: )

empty

$v){if($k==='__NF'){$k='Nette Session';$v=isset($v['DATA'])?$v['DATA']:NULL;}echo'\n";}?>
',htmlspecialchars($k),'',Dumper::toHtml($v),"
Session

user->isLoggedIn()):?>Logged inUnlogged

user->getIdentity()):echo Tracy\Dumper::toHtml($this->user->getIdentity());else:?>

no identity

user->isLoggedIn()):?>     user=$user;}public function getTab(){ob_start();require __DIR__.'/templates/UserPanel.tab.phtml';return ob_get_clean();}public function getPanel(){ob_start();require __DIR__.'/templates/UserPanel.panel.phtml';return ob_get_clean();}}storage=$storage;$this->namespace=$namespace.self::NAMESPACE_SEPARATOR;}public function getStorage(){return$this->storage;}public function getNamespace(){return(string)substr($this->namespace,0,-1);}public function derive($namespace){$derived=new static($this->storage,$this->namespace.$namespace);return$derived;}public function load($key,$fallback=NULL){$data=$this->storage->read($this->generateKey($key));if($data===NULL&&$fallback){return$this->save($key,Callback::closure($fallback));}return$data;}public function save($key,$data,array$dependencies=NULL){$this->release();$key=$this->generateKey($key);if($data instanceof Nette\Callback||$data instanceof\Closure){$this->storage->lock($key);$data=call_user_func_array($data,array(&$dependencies));}if($data===NULL){$this->storage->remove($key);}else{$this->storage->write($key,$data,$this->completeDependencies($dependencies,$data));return$data;}}private function completeDependencies($dp,$data){if(isset($dp[Cache::EXPIRATION])){$dp[Cache::EXPIRATION]=Nette\Utils\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_map(array($this,'generateKey'),(array)$dp[self::ITEMS]));}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;}public function remove($key){$this->save($key,NULL);}public function clean(array$conditions=NULL){$this->release();$this->storage->clean((array)$conditions);}public function call($function){$key=func_get_args();$key[0]=Callback::toReflection($function);return$this->load($key,function()use($function,$key){return Callback::invokeArgs($function,array_slice($key,1));});}public function wrap($function,array$dependencies=NULL){$cache=$this;return function()use($cache,$function,$dependencies){$key=array(Callback::toReflection($function),func_get_args());$data=$cache->load($key);if($data===NULL){$data=$cache->save($key,Callback::invokeArgs($function,$key[1]),$dependencies);}return$data;};}public function start($key){$data=$this->load($key);if($data===NULL){return new OutputHelper($this,$key);}echo$data;}protected function generateKey($key){return$this->namespace.md5(is_scalar($key)?$key:serialize($key));}public function offsetSet($key,$data){$this->save($key,$data);}public function 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;}public function offsetExists($key){$this->release();return$this->offsetGet($key)!==NULL;}public function offsetUnset($key){$this->save($key,NULL);}public function release(){$this->key=$this->data=NULL;}public static function checkCallbacks($callbacks){foreach($callbacks as$callback){if(!call_user_func_array(array_shift($callback),$callback)){return FALSE;}}return TRUE;}private static function checkConst($const,$value){return defined($const)&&constant($const)===$value;}private static function checkFile($file,$time){return@filemtime($file)==$time;}}cache=$cache;$this->key=$key;ob_start();}public function end(array$dependencies=NULL){if($this->cache===NULL){throw new Nette\InvalidStateException('Output cache has already been saved.');}$this->cache->save($this->key,ob_get_flush(),(array)$dependencies+(array)$this->dependencies);$this->cache=NULL;}}0,self::PRIORITY=>1,self::ENTRIES=>2,self::DATA=>3);public function __construct($dir){$this->file=$dir.'/'.self::FILE;}public function __destruct(){if($this->handle){$this->headerCommit();flock($this->handle,LOCK_UN);fclose($this->handle);$this->handle=FALSE;}}public function 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 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);unset($dataNode[$link]);$this->saveNode($link>>self::BITROT,$dataNode);list($entriesNodeId,$entriesNode)=$this->findIndexNode(self::ENTRIES,$keyHash);}break;}}}if($exists===FALSE){$requiredSize=strlen($key)+75;if($tags){foreach($tags 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::DATA));}$dataNodeKey=$this->findNextFreeKey($freeDataNode,$data);$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 as$tag){list($nodeId,$node)=$this->findIndexNode(self::TAGS,$tag);$node[$tag][$dataNodeKey]=1;$this->saveNode($nodeId,$node);}}if($priority!==FALSE){list($nodeId,$node)=$this->findIndexNode(self::PRIORITY,$priority);$node[$priority][$dataNodeKey]=1;$this->saveNode($nodeId,$node);}}$this->commit();$this->unlock();}public function clean(array$conditions){$this->lock();if(!empty($conditions[Cache::ALL])){$this->nodeCache=$this->nodeChanged=$this->dataNodeFreeSpace=array();$this->deleteAll();$this->unlock();return NULL;}$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 function cleanTags(array$tags,array&$toDelete){$entries=array();foreach($tags as$tag){list(,$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 function cleanPriority($priority,array&$toDelete){list(,$node)=$this->findIndexNode(self::PRIORITY,$priority);ksort($node);$allData=array();foreach($node 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 new Nette\InvalidStateException("Cannot load node number $nodeId.");}break;}$nodeInfo=$node[self::INFO];unset($node[self::INFO]);foreach($node as$data){$this->arrayAppendKeys($allData,$this->mergeIndexData($data));}}return$this->cleanLinks($allData,$toDelete);}private function 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 new Nette\InvalidStateException("Cannot load node number $nodeId.");}++$i;continue;}do{$link=$data[$i];if(!isset($node[$link])){if(self::$debug){throw new 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 function cleanFromIndex(array$toDeleteFromIndex){foreach($toDeleteFromIndex 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 new Nette\InvalidStateException('Bad index.');}unset($toDelete[$searchKey]);continue;}foreach($toDelete as$key=>$links){if(isset($masterNode[$key])){foreach($links 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 function 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 new Nette\InvalidStateException("Cannot load node number $id.");}break;}$this->arrayAppendKeys($data,$childNode[self::INDEX_DATA]);}return$data;}private function cleanIndexData($nextNodeId,array$links,&$masterNodeLink){$prev=-1;while($nextNodeId&&!empty($links)){$nodeId=$nextNodeId;$node=$this->getNode($nodeId);if($node===FALSE){if(self::$debug){throw new Nette\InvalidStateException("Cannot load node number $nodeId.");}break;}foreach($links 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 new 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 function 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 FALSE;}list(,$magic,$length)=unpack('N2',$binary);if($magic!==self::INDEX_MAGIC&&$magic!==self::DATA_MAGIC){if(!empty($magic)){if(self::$debug){throw new Nette\InvalidStateException("Node $id has malformed header.");}$this->deleteNode($id);}return FALSE;}$data=substr($binary,2*self::INT32_SIZE,$length-2*self::INT32_SIZE);$node=@unserialize($data);if($node===FALSE){$this->deleteNode($id);if(self::$debug){throw new Nette\InvalidStateException("Cannot unserialize node number $id.");}return FALSE;}return$this->nodeCache[$id]=$node;}private function 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 new 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 new 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 function commit(){do{foreach($this->nodeChanged as$id=>$foo){if($this->prepareNode($id,$this->nodeCache[$id])){unset($this->nodeChanged[$id]);}}}while(!empty($this->nodeChanged));foreach($this->toCommit as$node=>$str){$this->commitNode($node,$str);}$this->toCommit=array();}private function 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 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 new Nette\InvalidStateException('Saving node is bigger than maximum node size.');}else{$this->bisectNode($id,$node);return 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 TRUE;}private function commitNode($id,$str){fseek($this->handle,self::HEADER_SIZE+self::NODE_SIZE*$id);$written=fwrite($this->handle,$str);if($written===FALSE){throw new Nette\InvalidStateException("Cannot write node number $id to journal.");}}private function findIndexNode($type,$search,$childId=NULL,$prevId=NULL){$nodeId=self::$startNode[$type];$parentId=-1;while(TRUE){$node=$this->getNode($nodeId);if($node===FALSE){return 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 array($nodeId,$node,$parentId);}$parentId=$nodeId;if(isset($node[$search])){$nodeId=$node[$search];}else{foreach($node as$key=>$childNode){if($key>$search and$key!==self::INFO){$nodeId=$childNode;continue 2;}}$nodeId=$node[self::INFO][self::END];}}}private function 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 function findFreeDataNode($size){foreach($this->dataNodeFreeSpace 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 function 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<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 new Nette\InvalidStateException("Cannot load node number $parent.");}}else{$parentNode[$halfKey]=$firstId;ksort($parentNode);$this->saveNode($parent,$parentNode);}}}private function headerCommit(){fseek($this->handle,self::INT32_SIZE);@fwrite($this->handle,pack('N',$this->lastNode));}private function 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 new Nette\InvalidStateException('Cannot truncate journal file.');}}else{fseek($this->handle,self::HEADER_SIZE+self::NODE_SIZE*$id);$written=fwrite($this->handle,pack('N',0));if($written!==self::INT32_SIZE){throw new Nette\InvalidStateException("Cannot delete node number $id from journal.");}}}private function deleteAll(){if(!ftruncate($this->handle,self::HEADER_SIZE)){throw new Nette\InvalidStateException('Cannot truncate journal file.');}}private function lock(){if(!$this->handle){$this->prepare();}if(!flock($this->handle,LOCK_EX)){throw new Nette\InvalidStateException("Cannot acquire exclusive lock on journal file '$this->file'.");}$lastProcessIdentifier=stream_get_contents($this->handle,self::INT32_SIZE,self::INT32_SIZE*2);if($lastProcessIdentifier!==$this->processIdentifier){$this->nodeCache=$this->dataNodeFreeSpace=array();fseek($this->handle,self::INT32_SIZE*2);fwrite($this->handle,$this->processIdentifier);}}private function prepare(){if(!file_exists($this->file)){$init=@fopen($this->file,'xb');if(!$init){clearstatcache();if(!file_exists($this->file)){throw new Nette\InvalidStateException("Cannot create journal file '$this->file'.");}}else{$written=fwrite($init,pack('N2',self::FILE_MAGIC,$this->lastNode));fclose($init);if($written!==self::INT32_SIZE*2){throw new Nette\InvalidStateException("Cannot write journal header.");}}}$this->handle=fopen($this->file,'r+b');if(!$this->handle){throw new Nette\InvalidStateException("Cannot open journal file '$this->file'.");}if(!flock($this->handle,LOCK_SH)){throw new 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 new Nette\InvalidStateException("Malformed journal file '$this->file'.");}$this->processIdentifier=pack('N',mt_rand());}private function unlock(){if($this->handle){fflush($this->handle);flock($this->handle,LOCK_UN);}}private function findNextFreeKey($nodeId,array&$nodeData){$newKey=$nodeData[self::INFO][self::LAST_INDEX]+1;$maxKey=($nodeId+1)<=$maxKey){$start=$nodeId<$value){$array[$key]=$value;}}}dir=realpath($dir);if($this->dir===FALSE){throw new Nette\DirectoryNotFoundException("Directory '$dir' not found.");}$this->useDirs=(bool)static::$useDirectories;$this->journal=$journal;if(mt_rand()/mt_getrandmax()clean(array());}}public function read($key){$meta=$this->readMetaAndLock($this->getCacheFile($key),LOCK_SH);if($meta&&$this->verify($meta)){return$this->readData($meta);}else{return NULL;}}private function verify($meta){do{if(!empty($meta[self::META_DELTA])){if(filemtime($meta[self::FILE])+$meta[self::META_DELTA]$time){$m=$this->readMetaAndLock($depFile,LOCK_SH);if($m[self::META_TIME]!==$time||($m&&!$this->verify($m))){break 2;}}}return TRUE;}while(FALSE);$this->delete($meta[self::FILE],$meta[self::HANDLE]);return FALSE;}public function lock($key){$cacheFile=$this->getCacheFile($key);if($this->useDirs&&!is_dir($dir=dirname($cacheFile))){@mkdir($dir);}$handle=fopen($cacheFile,'c+b');if($handle){$this->locks[$key]=$handle;flock($handle,LOCK_EX);}}public function 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 new 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='delete($cacheFile,$handle);}public function remove($key){unset($this->locks[$key]);$this->delete($this->getCacheFile($key));}public function clean(array$conditions){$all=!empty($conditions[Cache::ALL]);$collector=empty($conditions);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($conditions);}return;}if($this->journal){foreach($this->journal->clean($conditions)as$file){$this->delete($file);}}}protected function readMetaAndLock($file,$lock){$handle=@fopen($file,'r+b');if(!$handle){return 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)){$meta[self::FILE]=$file;$meta[self::HANDLE]=$handle;return$meta;}}flock($handle,LOCK_UN);fclose($handle);return NULL;}protected function 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 function getCacheFile($key){$file=urlencode($key);if($this->useDirs&&$a=strrpos($file,'%00')){$file=substr_replace($file,'/_',$a,3);}return$this->dir.'/_'.$file;}private static function 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);}}}prefix=$prefix;$this->journal=$journal;$this->memcache=new\Memcache;if($host){$this->addServer($host,$port);}}public function addServer($host='localhost',$port=11211,$timeout=1){if($this->memcache->addServer($host,$port,TRUE,1,$timeout)===FALSE){$error=error_get_last();throw new Nette\InvalidStateException("Memcache::addServer(): $error[message].");}}public function getConnection(){return$this->memcache;}public function read($key){$key=$this->prefix.$key;$meta=$this->memcache->get($key);if(!$meta){return NULL;}if(!empty($meta[self::META_CALLBACKS])&&!Cache::checkCallbacks($meta[self::META_CALLBACKS])){$this->memcache->delete($key,0);return NULL;}if(!empty($meta[self::META_DELTA])){$this->memcache->replace($key,$meta,0,$meta[self::META_DELTA]+time());}return$meta[self::META_DATA];}public function lock($key){}public function write($key,$data,array$dp){if(isset($dp[Cache::ITEMS])){throw new 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 new Nette\InvalidStateException('CacheJournal has not been provided.');}$this->journal->write($key,$dp);}$this->memcache->set($key,$meta,0,$expire);}public function remove($key){$this->memcache->delete($this->prefix.$key,0);}public function clean(array$conditions){if(!empty($conditions[Cache::ALL])){$this->memcache->flush();}elseif($this->journal){foreach($this->journal->clean($conditions)as$entry){$this->memcache->delete($entry,0);}}}}data[$key])?$this->data[$key]:NULL;}public function lock($key){}public function write($key,$data,array$dependencies){$this->data[$key]=$data;}public function remove($key){unset($this->data[$key]);}public function clean(array$conditions){if(!empty($conditions[Nette\Caching\Cache::ALL])){$this->data=array();}}}pdo=new\PDO('sqlite:'.$path,NULL,NULL,array(\PDO::ATTR_PERSISTENT=>TRUE));$this->pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);$this->pdo->exec(' PRAGMA foreign_keys = ON; CREATE TABLE IF NOT EXISTS cache ( key BLOB NOT NULL PRIMARY KEY, data BLOB NOT NULL ); CREATE TABLE IF NOT EXISTS tags ( key BLOB NOT NULL REFERENCES cache ON DELETE CASCADE, tag BLOB NOT NULL ); CREATE INDEX IF NOT EXISTS tags_key ON tags(key); CREATE INDEX IF NOT EXISTS tags_tag ON tags(tag); ');}public function read($key){$stmt=$this->pdo->prepare('SELECT data FROM cache WHERE key=?');$stmt->execute(array($key));if($res=$stmt->fetchColumn()){return unserialize($res);}}public function lock($key){}public function write($key,$data,array$dependencies){$this->pdo->prepare('BEGIN TRANSACTION');$this->pdo->prepare('REPLACE INTO cache (key, data) VALUES (?, ?)')->execute(array($key,serialize($data)));if(!empty($dependencies[Cache::TAGS])){foreach((array)$dependencies[Cache::TAGS]as$tag){$arr[]=$key;$arr[]=$tag;}$this->pdo->prepare('INSERT INTO tags (key, tag) SELECT ?, ?'.str_repeat('UNION SELECT ?, ?',count($arr)/2-1))->execute($arr);}$this->pdo->prepare('COMMIT');}public function remove($key){$this->pdo->prepare('DELETE FROM cache WHERE key=?')->execute(array($key));}public function clean(array$conditions){if(!empty($conditions[Cache::ALL])){$this->pdo->prepare('DELETE FROM cache');}elseif(!empty($conditions[Cache::TAGS])){$tags=(array)$conditions[Cache::TAGS];$this->pdo->prepare('DELETE FROM cache WHERE key IN (SELECT key FROM tags WHERE tag IN (?'.str_repeat(',?',count($tags)-1).'))')->execute($tags);}}}addComponent($this,$name);}elseif(is_string($name)){$this->name=$name;}}public function lookup($type,$need=TRUE){if(!isset($this->monitors[$type])){$obj=$this->parent;$path=self::NAME_SEPARATOR.$this->name;$depth=1;while($obj!==NULL){$parent=$obj->getParent();if($type?$obj instanceof$type:$parent===NULL){break;}$path=self::NAME_SEPARATOR.$obj->getName().$path;$depth++;$obj=$parent;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 new Nette\InvalidStateException("Component '$this->name' is not attached to '$type'.");}return$this->monitors[$type][0];}public function lookupPath($type=NULL,$need=TRUE){$this->lookup($type,$need);return$this->monitors[$type][2];}public function monitor($type){if(empty($this->monitors[$type][3])){if($obj=$this->lookup($type,FALSE)){$this->attached($obj);}$this->monitors[$type][3]=TRUE;}}public function unmonitor($type){unset($this->monitors[$type]);}protected function attached($obj){}protected function detached($obj){}public function getName(){return$this->name;}public function getParent(){return$this->parent;}public function 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 new 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 function validateParent(IContainer$parent){}private function refreshMonitors($depth,&$missing=NULL,&$listeners=array()){if($this instanceof IContainer){foreach($this->getComponents()as$component){if($component instanceof Component){$component->refreshMonitors($depth+1,$missing,$listeners);}}}if($missing===NULL){foreach($this->monitors 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 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 as$item){$item[0]->$method($item[1]);}}}public function __clone(){if($this->parent===NULL){return;}elseif($this->parent instanceof Container){$this->parent=$this->parent->_isCloning();if($this->parent===NULL){$this->refreshMonitors(0);}}else{$this->parent=NULL;$this->refreshMonitors(0);}}public function __sleep(){throw new Nette\NotImplementedException('Object serialization is not supported by class '.get_class($this));}public function __wakeup(){throw new Nette\NotImplementedException('Object unserialization is not supported by class '.get_class($this));}}getName();}if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.',gettype($name)));}elseif(!preg_match('#^[a-zA-Z0-9_]+\z#',$name)){throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");}if(isset($this->components[$name])){throw new Nette\InvalidStateException("Component with name '$name' already exists.");}$obj=$this;do{if($obj===$component){throw new 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 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;}public function removeComponent(IComponent$component){$name=$component->getName();if(!isset($this->components[$name])||$this->components[$name]!==$component){throw new Nette\InvalidArgumentException("Component named '$name' is not located in this container.");}unset($this->components[$name]);$component->setParent(NULL);}public function getComponent($name,$need=TRUE){if(is_int($name)){$name=(string)$name;}elseif(!is_string($name)){throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.',gettype($name)));}else{$a=strpos($name,self::NAME_SEPARATOR);if($a!==FALSE){$ext=(string)substr($name,$a+1);$name=substr($name,0,$a);}if($name===''){if($need){throw new Nette\InvalidArgumentException('Component or subcomponent name must not be empty string.');}return;}}if(!isset($this->components[$name])){$component=$this->createComponent($name);if($component instanceof 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 IContainer){return$this->components[$name]->getComponent($ext,$need);}elseif($need){throw new Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$ext' component.");}}elseif($need){throw new Nette\InvalidArgumentException("Component with name '$name' does not exist.");}}protected function 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 instanceof IComponent&&!isset($this->components[$name])){$class=get_class($this);throw new Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");}return$component;}}public function getComponents($deep=FALSE,$filterType=NULL){$iterator=new RecursiveComponentIterator($this->components);if($deep){$deep=$deep>0?\RecursiveIteratorIterator::SELF_FIRST:\RecursiveIteratorIterator::CHILD_FIRST;$iterator=new\RecursiveIteratorIterator($iterator,$deep);}if($filterType){$iterator=new Nette\Iterators\Filter($iterator,function($item)use($filterType){return$item instanceof$filterType;});}return$iterator;}protected function validateChildComponent(IComponent$child){}public function __clone(){if($this->components){$oldMyself=reset($this->components)->getParent();$oldMyself->cloning=$this;foreach($this->components as$name=>$component){$this->components[$name]=clone$component;}$oldMyself->cloning=NULL;}parent::__clone();}public function _isCloning(){return$this->cloning;}}current()instanceof IContainer;}public function getChildren(){return$this->current()->getComponents();}public function count(){return iterator_count($this);}}4){$options['driverClass']=func_get_arg(4);}$this->params=array($dsn,$user,$password);$this->options=(array)$options;if(empty($options['lazy'])){$this->connect();}}public function connect(){if($this->pdo){return;}$this->pdo=new PDO($this->params[0],$this->params[1],$this->params[2],$this->options);$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);$class=empty($this->options['driverClass'])?'Nette\Database\Drivers\\'.ucfirst(str_replace('sql','Sql',$this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME))).'Driver':$this->options['driverClass'];$this->driver=new$class($this,$this->options);$this->preprocessor=new SqlPreprocessor($this);$this->onConnect($this);}public function getDsn(){return$this->params[0];}public function getPdo(){$this->connect();return$this->pdo;}public function getSupplementalDriver(){$this->connect();return$this->driver;}public function getInsertId($name=NULL){return$this->getPdo()->lastInsertId($name);}public function quote($string,$type=PDO::PARAM_STR){return$this->getPdo()->quote($string,$type);}function beginTransaction(){$this->queryArgs('::beginTransaction',array());}function commit(){$this->queryArgs('::commit',array());}public function rollBack(){$this->queryArgs('::rollBack',array());}public function query($statement){$args=func_get_args();return$this->queryArgs(array_shift($args),$args);}function queryArgs($statement,array$params){$this->connect();if($params){array_unshift($params,$statement);list($statement,$params)=$this->preprocessor->process($params);}try{$result=new ResultSet($this,$statement,$params);}catch(\PDOException$e){$e->queryString=$statement;$this->onQuery($this,$e);throw$e;}$this->onQuery($this,$result);return$result;}function fetch($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetch();}function fetchField($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchField();}function fetchPairs($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchPairs();}function fetchAll($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchAll();}static function literal($value){$args=func_get_args();return new SqlLiteral(array_shift($args),$args);}}connection=$connection;$this->reflection=$reflection?:new Reflection\ConventionalReflection;$this->cacheStorage=$cacheStorage;}public function beginTransaction(){$this->queryArgs('::beginTransaction',array());}public function commit(){$this->queryArgs('::commit',array());}public function rollBack(){$this->queryArgs('::rollBack',array());}public function getInsertId($name=NULL){return$this->connection->getInsertId($name);}public function query($statement){$args=func_get_args();return$this->queryArgs(array_shift($args),$args);}public function queryArgs($statement,array$params){$this->connection->connect();if($params){if(!$this->preprocessor){$this->preprocessor=new SqlPreprocessor($this->connection);}array_unshift($params,$statement);list($statement,$params)=$this->preprocessor->process($params);}try{$result=new ResultSet($this->connection,$statement,$params);}catch(\PDOException$e){$e->queryString=$statement;$this->connection->onQuery($this->connection,$e);throw$e;}$this->connection->onQuery($this->connection,$result);return$result;}public function table($table){return new Table\Selection($this->connection,$table,$this->reflection,$this->cacheStorage);}public function getConnection(){return$this->connection;}public function getDatabaseReflection(){return$this->reflection;}public function fetch($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetch();}public function fetchField($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchField();}public function fetchPairs($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchPairs();}public function fetchAll($args){$args=func_get_args();return$this->queryArgs(array_shift($args),$args)->fetchAll();}public static function literal($value){$args=func_get_args();return new SqlLiteral(array_shift($args),$args);}}format("'Y-m-d H:i:s'");}public function formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'%'=>'[%]','_'=>'[_]','['=>'[[]'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}public function applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql=preg_replace('#^\s*(SELECT|UPDATE|DELETE)#i','$0 TOP '.(int)$limit,$sql,1,$count);if(!$count){throw new Nette\InvalidArgumentException('SQL query must begin with SELECT, UPDATE or DELETE command.');}}if($offset){throw new Nette\NotSupportedException('Offset is not supported by this database.');}}public function normalizeRow($row){return$row;}public function getTables(){throw new Nette\NotImplementedException;}public function getColumns($table){throw new Nette\NotImplementedException;}public function getIndexes($table){throw new Nette\NotImplementedException;}public function getForeignKeys($table){throw new Nette\NotImplementedException;}public function getColumnTypes(\PDOStatement$statement){return Nette\Database\Helpers::detectTypes($statement);}public function isSupported($item){return$item===self::SUPPORT_SUBSELECT;}}connection=$connection;$charset=isset($options['charset'])?$options['charset']:'utf8';if($charset){$connection->query("SET NAMES '$charset'");}if(isset($options['sqlmode'])){$connection->query("SET sql_mode='$options[sqlmode]'");}}public function delimite($name){return'`'.str_replace('`','``',$name).'`';}public function formatBool($value){return$value?'1':'0';}public function formatDateTime($value){return$value->format("'Y-m-d H:i:s'");}public function formatLike($value,$pos){$value=addcslashes(str_replace('\\','\\\\',$value),"\x00\n\r\\'%_");return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}public function applyLimit(&$sql,$limit,$offset){if($limit>=0||$offset>0){$sql.=' LIMIT '.($limit<0?'18446744073709551615':(int)$limit).($offset>0?' OFFSET '.(int)$offset:'');}}public function normalizeRow($row){return$row;}public function getTables(){$tables=array();foreach($this->connection->query('SHOW FULL TABLES')as$row){$tables[]=array('name'=>$row[0],'view'=>isset($row[1])&&$row[1]==='VIEW');}return$tables;}public function 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;}public function 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 array_values($indexes);}public function 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 array_values($keys);}public function getColumnTypes(\PDOStatement$statement){$types=array();$count=$statement->columnCount();for($col=0;$col<$count;$col++){$meta=$statement->getColumnMeta($col);if(isset($meta['native_type'])){$types[$meta['name']]=$type=Nette\Database\Helpers::detectType($meta['native_type']);if($type===Nette\Database\IReflection::FIELD_TIME){$types[$meta['name']]=Nette\Database\IReflection::FIELD_TIME_INTERVAL;}}}return$types;}public function isSupported($item){return$item===self::SUPPORT_SELECT_UNGROUPED_COLUMNS||$item===self::SUPPORT_MULTI_COLUMN_AS_OR_COND;}}connection=$connection;$this->fmtDateTime=isset($options['formatDateTime'])?$options['formatDateTime']:'U';}public function delimite($name){return'"'.str_replace('"','""',$name).'"';}public function formatBool($value){return$value?'1':'0';}public function formatDateTime($value){return$value->format($this->fmtDateTime);}public function formatLike($value,$pos){throw new Nette\NotImplementedException;}public function 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;}}public function normalizeRow($row){return$row;}public function getTables(){$tables=array();foreach($this->connection->query('SELECT * FROM cat')as$row){if($row[1]==='TABLE'||$row[1]==='VIEW'){$tables[]=array('name'=>$row[0],'view'=>$row[1]==='VIEW');}}return$tables;}public function getColumns($table){throw new Nette\NotImplementedException;}public function getIndexes($table){throw new Nette\NotImplementedException;}public function getForeignKeys($table){throw new Nette\NotImplementedException;}public function getColumnTypes(\PDOStatement$statement){return Nette\Database\Helpers::detectTypes($statement);}public function isSupported($item){return$item===self::SUPPORT_SEQUENCE||$item===self::SUPPORT_SUBSELECT;}}format('#m/d/Y H:i:s#');}public function formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'%'=>'[%]','_'=>'[_]','['=>'[[]'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}public function applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql=preg_replace('#^\s*(SELECT|UPDATE|DELETE)#i','$0 TOP '.(int)$limit,$sql,1,$count);if(!$count){throw new Nette\InvalidArgumentException('SQL query must begin with SELECT, UPDATE or DELETE command.');}}if($offset){throw new Nette\NotSupportedException('Offset is not supported by this database.');}}public function normalizeRow($row){return$row;}public function getTables(){throw new Nette\NotImplementedException;}public function getColumns($table){throw new Nette\NotImplementedException;}public function getIndexes($table){throw new Nette\NotImplementedException;}public function getForeignKeys($table){throw new Nette\NotImplementedException;}public function getColumnTypes(\PDOStatement$statement){return Nette\Database\Helpers::detectTypes($statement);}public function isSupported($item){return$item===self::SUPPORT_SUBSELECT;}}connection=$connection;}public function delimite($name){return'"'.str_replace('"','""',$name).'"';}public function formatBool($value){return$value?'TRUE':'FALSE';}public function formatDateTime($value){return$value->format("'Y-m-d H:i:s'");}public function formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'\\'=>'\\\\','%'=>'\\\\%','_'=>'\\\\_'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}public function applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql.=' LIMIT '.(int)$limit;}if($offset>0){$sql.=' OFFSET '.(int)$offset;}}public function normalizeRow($row){return$row;}public function getTables(){$tables=array();foreach($this->connection->query(" SELECT DISTINCT ON (c.relname) c.relname::varchar AS name, c.relkind = 'v' AS view FROM pg_catalog.pg_class AS c JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v') AND n.nspname = ANY (pg_catalog.current_schemas(FALSE)) ORDER BY c.relname ")as$row){$tables[]=(array)$row;}return$tables;}public function getColumns($table){$columns=array();foreach($this->connection->query(" SELECT a.attname::varchar AS name, c.relname::varchar AS table, upper(t.typname) AS nativetype, NULL AS size, FALSE AS unsigned, NOT (a.attnotnull OR t.typtype = 'd' AND t.typnotnull) AS nullable, pg_catalog.pg_get_expr(ad.adbin, 'pg_catalog.pg_attrdef'::regclass)::varchar AS default, coalesce(co.contype = 'p' AND strpos(ad.adsrc, 'nextval') = 1, FALSE) AS autoincrement, coalesce(co.contype = 'p', FALSE) AS primary, substring(pg_catalog.pg_get_expr(ad.adbin, 'pg_catalog.pg_attrdef'::regclass) from 'nextval[(]''\"?([^''\"]+)') AS sequence FROM pg_catalog.pg_attribute AS a JOIN pg_catalog.pg_class AS c ON a.attrelid = c.oid JOIN pg_catalog.pg_type AS t ON a.atttypid = t.oid LEFT JOIN pg_catalog.pg_attrdef AS ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum LEFT JOIN pg_catalog.pg_constraint AS co ON co.connamespace = c.relnamespace AND contype = 'p' AND co.conrelid = c.oid AND a.attnum = ANY(co.conkey) WHERE c.relkind IN ('r', 'v') AND c.oid = {$this->connection->quote($this->delimiteFQN($table))}::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum ")as$row){$column=(array)$row;$column['vendor']=$column;unset($column['sequence']);$columns[]=$column;}return$columns;}public function getIndexes($table){$indexes=array();foreach($this->connection->query(" SELECT c2.relname::varchar AS name, i.indisunique AS unique, i.indisprimary AS primary, a.attname::varchar AS column FROM pg_catalog.pg_class AS c1 JOIN pg_catalog.pg_index AS i ON c1.oid = i.indrelid JOIN pg_catalog.pg_class AS c2 ON i.indexrelid = c2.oid LEFT JOIN pg_catalog.pg_attribute AS a ON c1.oid = a.attrelid AND a.attnum = ANY(i.indkey) WHERE c1.relkind = 'r' AND c1.oid = {$this->connection->quote($this->delimiteFQN($table))}::regclass ")as$row){$indexes[$row['name']]['name']=$row['name'];$indexes[$row['name']]['unique']=$row['unique'];$indexes[$row['name']]['primary']=$row['primary'];$indexes[$row['name']]['columns'][]=$row['column'];}return array_values($indexes);}public function getForeignKeys($table){return$this->connection->query(" SELECT co.conname::varchar AS name, al.attname::varchar AS local, cf.relname::varchar AS table, af.attname::varchar AS foreign FROM pg_catalog.pg_constraint AS co JOIN pg_catalog.pg_class AS cl ON co.conrelid = cl.oid JOIN pg_catalog.pg_class AS cf ON co.confrelid = cf.oid JOIN pg_catalog.pg_namespace AS nf ON nf.oid = cf.relnamespace JOIN pg_catalog.pg_attribute AS al ON al.attrelid = cl.oid AND al.attnum = co.conkey[1] JOIN pg_catalog.pg_attribute AS af ON af.attrelid = cf.oid AND af.attnum = co.confkey[1] WHERE co.contype = 'f' AND cl.oid = {$this->connection->quote($this->delimiteFQN($table))}::regclass AND nf.nspname = ANY (pg_catalog.current_schemas(FALSE)) ")->fetchAll();}public function getColumnTypes(\PDOStatement$statement){return Nette\Database\Helpers::detectTypes($statement);}public function isSupported($item){return$item===self::SUPPORT_SEQUENCE||$item===self::SUPPORT_SUBSELECT;}private function delimiteFQN($name){return implode('.',array_map(array($this,'delimite'),explode('.',$name)));}}connection=$connection;$this->fmtDateTime=isset($options['formatDateTime'])?$options['formatDateTime']:'U';}public function delimite($name){return'['.strtr($name,'[]',' ').']';}public function formatBool($value){return$value?'1':'0';}public function formatDateTime($value){return$value->format($this->fmtDateTime);}public function formatLike($value,$pos){$value=addcslashes(substr($this->connection->quote($value),1,-1),'%_\\');return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'")." ESCAPE '\\'";}public function applyLimit(&$sql,$limit,$offset){if($limit>=0||$offset>0){$sql.=' LIMIT '.(int)$limit.($offset>0?' OFFSET '.(int)$offset:'');}}public function normalizeRow($row){foreach($row as$key=>$value){unset($row[$key]);if($key[0]==='['||$key[0]==='"'){$key=substr($key,1,-1);}$row[$key]=$value;}return$row;}public function getTables(){$tables=array();foreach($this->connection->query(" SELECT name, type = 'view' as view FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' UNION ALL SELECT name, type = 'view' as view FROM sqlite_temp_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name ")as$row){$tables[]=array('name'=>$row->name,'view'=>(bool)$row->view);}return$tables;}public function getColumns($table){$meta=$this->connection->query(" SELECT sql FROM sqlite_master WHERE type = 'table' AND name = {$this->connection->quote($table)} UNION ALL SELECT sql FROM sqlite_temp_master WHERE type = 'table' AND name = {$this->connection->quote($table)} ")->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,'nativetype'=>strtoupper($type[0]),'size'=>isset($type[1])?(int)$type[1]:NULL,'unsigned'=>FALSE,'nullable'=>$row['notnull']=='0','default'=>$row['dflt_value'],'autoincrement'=>(bool)preg_match($pattern,$meta['sql']),'primary'=>$row['pk']>0,'vendor'=>(array)$row);}return$columns;}public function 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'];$indexes[$row['name']]['primary']=FALSE;}foreach($indexes 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 as$index=>$values){$column=$indexes[$index]['columns'][0];foreach($columns as$info){if($column==$info['name']){$indexes[$index]['primary']=(bool)$info['primary'];break;}}}if(!$indexes){foreach($columns as$column){if($column['vendor']['pk']){$indexes[]=array('name'=>'ROWID','unique'=>TRUE,'primary'=>TRUE,'columns'=>array($column['name']));break;}}}return array_values($indexes);}public function 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['from'];$keys[$row['id']]['table']=$row['table'];$keys[$row['id']]['foreign']=$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 array_values($keys);}public function getColumnTypes(\PDOStatement$statement){$types=array();$count=$statement->columnCount();for($col=0;$col<$count;$col++){$meta=$statement->getColumnMeta($col);if(isset($meta['sqlite:decl_type'])){if($meta['sqlite:decl_type']==='DATE'){$types[$meta['name']]=Nette\Database\IReflection::FIELD_UNIX_TIMESTAMP;}else{$types[$meta['name']]=Nette\Database\Helpers::detectType($meta['sqlite:decl_type']);}}elseif(isset($meta['native_type'])){$types[$meta['name']]=Nette\Database\Helpers::detectType($meta['native_type']);}}return$types;}public function isSupported($item){return$item===self::SUPPORT_MULTI_INSERT_AS_SELECT||$item===self::SUPPORT_SUBSELECT||$item===self::SUPPORT_MULTI_COLUMN_AS_OR_COND;}}connection=$connection;}public function delimite($name){return'['.str_replace(']',']]',$name).']';}public function formatBool($value){return$value?'1':'0';}public function formatDateTime($value){return$value->format("'Y-m-d H:i:s'");}public function formatLike($value,$pos){$value=strtr($value,array("'"=>"''",'%'=>'[%]','_'=>'[_]','['=>'[[]'));return($pos<=0?"'%":"'").$value.($pos>=0?"%'":"'");}public function applyLimit(&$sql,$limit,$offset){if($limit>=0){$sql=preg_replace('#^\s*(SELECT|UPDATE|DELETE)#i','$0 TOP '.(int)$limit,$sql,1,$count);if(!$count){throw new Nette\InvalidArgumentException('SQL query must begin with SELECT, UPDATE or DELETE command.');}}if($offset>0){throw new Nette\NotSupportedException('Offset is not supported by this database.');}}public function normalizeRow($row){return$row;}public function getTables(){$tables=array();foreach($this->connection->query(" SELECT name, CASE type WHEN 'U' THEN 0 WHEN 'V' THEN 1 END AS [view] FROM sys.objects WHERE type IN ('U', 'V') ")as$row){$tables[]=array('name'=>$row->name,'view'=>(bool)$row->view);}return$tables;}public function getColumns($table){$columns=array();foreach($this->connection->query(" SELECT c.name AS name, o.name AS [table], UPPER(t.name) AS nativetype, NULL AS size, 0 AS unsigned, c.is_nullable AS nullable, OBJECT_DEFINITION(c.default_object_id) AS [default], c.is_identity AS autoincrement, CASE WHEN i.index_id IS NULL THEN 0 ELSE 1 END AS [primary] FROM sys.columns c JOIN sys.objects o ON c.object_id = o.object_id LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id LEFT JOIN sys.key_constraints k ON o.object_id = k.parent_object_id AND k.type = 'PK' LEFT JOIN sys.index_columns i ON k.parent_object_id = i.object_id AND i.index_id = k.unique_index_id AND i.column_id = c.column_id WHERE o.type IN ('U', 'V') AND o.name = {$this->connection->quote($table)} ")as$row){$row=(array)$row;$row['vendor']=$row;$row['unsigned']=(bool)$row['unsigned'];$row['nullable']=(bool)$row['nullable'];$row['autoincrement']=(bool)$row['autoincrement'];$row['primary']=(bool)$row['primary'];$columns[]=$row;}return$columns;}public function getIndexes($table){$indexes=array();foreach($this->connection->query(" SELECT i.name AS name, CASE WHEN i.is_unique = 1 OR i.is_unique_constraint = 1 THEN 1 ELSE 0 END AS [unique], i.is_primary_key AS [primary], c.name AS [column] FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id JOIN sys.tables t ON i.object_id = t.object_id WHERE t.name = {$this->connection->quote($table)} ORDER BY i.index_id, ic.index_column_id ")as$row){$indexes[$row->name]['name']=$row->name;$indexes[$row->name]['unique']=(bool)$row->unique;$indexes[$row->name]['primary']=(bool)$row->primary;$indexes[$row->name]['columns'][]=$row->column;}return array_values($indexes);}public function getForeignKeys($table){$keys=array();foreach($this->connection->query(" SELECT fk.name AS name, cl.name AS local, tf.name AS [table], cf.name AS [column] FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id JOIN sys.tables tl ON fkc.parent_object_id = tl.object_id JOIN sys.columns cl ON fkc.parent_object_id = cl.object_id AND fkc.parent_column_id = cl.column_id JOIN sys.tables tf ON fkc.referenced_object_id = tf.object_id JOIN sys.columns cf ON fkc.referenced_object_id = cf.object_id AND fkc.referenced_column_id = cf.column_id WHERE tl.name = {$this->connection->quote($table)} ")as$row){$keys[$row->name]=(array)$row;}return array_values($keys);}public function getColumnTypes(\PDOStatement$statement){$types=array();$count=$statement->columnCount();for($col=0;$col<$count;$col++){$meta=$statement->getColumnMeta($col);if(isset($meta['sqlsrv:decl_type'])&&$meta['sqlsrv:decl_type']!=='timestamp'){$types[$meta['name']]=Nette\Database\Helpers::detectType($meta['sqlsrv:decl_type']);}elseif(isset($meta['native_type'])){$types[$meta['name']]=Nette\Database\Helpers::detectType($meta['native_type']);}}return$types;}public function isSupported($item){return$item===self::SUPPORT_SUBSELECT;}}IReflection::FIELD_TEXT,'BYTEA|BLOB|BIN'=>IReflection::FIELD_BINARY,'TEXT|CHAR|POINT|INTERVAL'=>IReflection::FIELD_TEXT,'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT|^TINY$'=>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'=>IReflection::FIELD_BOOL);public static function dumpResult(ResultSet$result){echo"\n\n\n";if(!$result->getColumnCount()){echo"\t\n\t\t\n\t\t\n\t\n
".htmlSpecialChars($result->getQueryString())."
Affected rows:",$result->getRowCount(),"
\n";return;}$i=0;foreach($result as$row){if($i===0){echo"\n\t\n\t\t#row\n";foreach($row as$col=>$foo){echo"\t\t".htmlSpecialChars($col)."\n";}echo"\t\n\n\n";}echo"\t\n\t\t",$i,"\n";foreach($row as$col){echo"\t\t",htmlSpecialChars($col),"\n";}echo"\t\n";$i++;}if($i===0){echo"\t\n\t\tempty result set\n\t\n\n";}else{echo"\n\n";}}public static function dumpSql($sql,array$params=NULL){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|[RI]?LIKE|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''.$matches[1].'';}elseif(!empty($matches[2])){return''.$matches[2].'';}elseif(!empty($matches[3])){return''.$matches[3].'';}elseif(!empty($matches[4])){return''.$matches[4].'';}},$sql);$sql=preg_replace_callback('#\?#',function()use($params){static$i=0;if(!isset($params[$i])){return'?';}$param=$params[$i++];if(is_string($param)&&(preg_match('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u',$param)||preg_last_error())){return'<binary>';}elseif(is_string($param)){return'\''.htmlspecialchars(Nette\Utils\Strings::truncate($param,Helpers::$maxLength))."'";}elseif(is_resource($param)){$type=get_resource_type($param);if($type==='stream'){$info=stream_get_meta_data($param);}return'<'.htmlSpecialChars($type).' resource> ';}else{return htmlspecialchars($param);}},$sql);return'
'.trim($sql)."
\n";}public static function detectTypes(\PDOStatement$statement){$types=array();$count=$statement->columnCount();for($col=0;$col<$count;$col++){$meta=$statement->getColumnMeta($col);if(isset($meta['native_type'])){$types[$meta['name']]=self::detectType($meta['native_type']);}}return$types;}public static function detectType($type){static$cache;if(!isset($cache[$type])){$cache[$type]='string';foreach(self::$typePatterns as$s=>$val){if(preg_match("#$s#i",$type)){return$cache[$type]=$val;}}}return$cache[$type];}public static function loadFromFile(Connection$connection,$file){@set_time_limit(0);$handle=@fopen($file,'r');if(!$handle){throw new Nette\FileNotFoundException("Cannot open file '$file'.");}$count=0;$delimiter=';';$sql='';while(!feof($handle)){$s=rtrim(fgets($handle));if(!strncasecmp($s,'DELIMITER ',10)){$delimiter=substr($s,10);}elseif(substr($s,-strlen($delimiter))===$delimiter){$sql.=substr($s,0,-strlen($delimiter));$connection->query($sql);$sql='';$count++;}else{$sql.=$s."\n";}}if(trim($sql)!==''){$connection->query($sql);$count++;}fclose($handle);return$count;}public static function createDebugPanel($connection,$explain=TRUE,$name=NULL){$panel=new Nette\Bridges\DatabaseTracy\ConnectionPanel($connection);$panel->explain=$explain;$panel->name=$name;Tracy\Debugger::getBar()->addPanel($panel);return$panel;}public static function toPairs(array$rows,$key=NULL,$value=NULL){if(!$rows){return array();}$keys=array_keys((array)reset($rows));if(!count($keys)){throw new\LogicException('Result set does not contain any column.');}elseif($key===NULL&&$value===NULL){if(count($keys)===1){list($value)=$keys;}else{list($key,$value)=$keys;}}$return=array();if($key===NULL){foreach($rows as$row){$return[]=($value===NULL?$row:$row[$value]);}}else{foreach($rows as$row){$return[is_object($row[$key])?(string)$row[$key]:$row[$key]]=($value===NULL?$row:$row[$value]);}}return$return;}}primary=$primary;$this->foreign=$foreign;$this->table=$table;}public function getPrimary($table){return sprintf($this->primary,$this->getColumnFromTable($table));}public function getHasManyReference($table,$key){$table=$this->getColumnFromTable($table);return array(sprintf($this->table,$key,$table),sprintf($this->foreign,$table,$key));}public function getBelongsToReference($table,$key){$table=$this->getColumnFromTable($table);return array(sprintf($this->table,$key,$table),sprintf($this->foreign,$key,$table));}protected function getColumnFromTable($name){if($this->table!=='%s'&&preg_match('(^'.str_replace('%s','(.*)',preg_quote($this->table)).'\z)',$name,$match)){return$match[1];}return$name;}}connection=$connection;if($cacheStorage){$this->cache=new Nette\Caching\Cache($cacheStorage,'Nette.Database.'.md5($connection->getDsn()));$this->structure=$this->loadedStructure=$this->cache->load('structure')?:array();}}public function __destruct(){if($this->cache&&$this->structure!==$this->loadedStructure){$this->cache->save('structure',$this->structure);}}public function getPrimary($table){$primary=&$this->structure['primary'][strtolower($table)];if(isset($primary)){return empty($primary)?NULL:$primary;}$columns=$this->connection->getSupplementalDriver()->getColumns($table);$primary=array();foreach($columns as$column){if($column['primary']){$primary[]=$column['name'];}}if(count($primary)===0){return NULL;}elseif(count($primary)===1){$primary=reset($primary);}return$primary;}public function getHasManyReference($table,$key,$refresh=TRUE){if(isset($this->structure['hasMany'][strtolower($table)])){$candidates=$columnCandidates=array();foreach($this->structure['hasMany'][strtolower($table)]as$targetPair){list($targetColumn,$targetTable)=$targetPair;if(stripos($targetTable,$key)===FALSE){continue;}$candidates[]=array($targetTable,$targetColumn);if(stripos($targetColumn,$table)!==FALSE){$columnCandidates[]=$candidate=array($targetTable,$targetColumn);if(strtolower($targetTable)===strtolower($key)){return$candidate;}}}if(count($columnCandidates)===1){return reset($columnCandidates);}elseif(count($candidates)===1){return reset($candidates);}foreach($candidates as$candidate){if(strtolower($candidate[0])===strtolower($key)){return$candidate;}}}if($refresh){$this->reloadAllForeignKeys();return$this->getHasManyReference($table,$key,FALSE);}if(empty($candidates)){throw new MissingReferenceException("No reference found for \${$table}->related({$key}).");}else{throw new AmbiguousReferenceKeyException('Ambiguous joining column in related call.');}}public function getBelongsToReference($table,$key,$refresh=TRUE){if(isset($this->structure['belongsTo'][strtolower($table)])){foreach($this->structure['belongsTo'][strtolower($table)]as$column=>$targetTable){if(stripos($column,$key)!==FALSE){return array($targetTable,$column);}}}if($refresh){$this->reloadForeignKeys($table);return$this->getBelongsToReference($table,$key,FALSE);}throw new MissingReferenceException("No reference found for \${$table}->{$key}.");}protected function reloadAllForeignKeys(){$this->structure['hasMany']=$this->structure['belongsTo']=array();foreach($this->connection->getSupplementalDriver()->getTables()as$table){if($table['view']==FALSE){$this->reloadForeignKeys($table['name']);}}foreach($this->structure['hasMany']as&$table){uksort($table,function($a,$b){return strlen($a)-strlen($b);});}}protected function reloadForeignKeys($table){foreach($this->connection->getSupplementalDriver()->getForeignKeys($table)as$row){$this->structure['belongsTo'][strtolower($table)][$row['local']]=$row['table'];$this->structure['hasMany'][strtolower($row['table'])][$row['local'].$table]=array($row['local'],$table);}if(isset($this->structure['belongsTo'][$table])){uksort($this->structure['belongsTo'][$table],function($a,$b){return strlen($a)-strlen($b);});}}}connection=$connection;$this->supplementalDriver=$connection->getSupplementalDriver();$this->queryString=$queryString;$this->params=$params;if(substr($queryString,0,2)==='::'){$connection->getPdo()->{substr($queryString,2)}();}elseif($queryString!==NULL){$this->pdoStatement=$connection->getPdo()->prepare($queryString);$this->pdoStatement->setFetchMode(PDO::FETCH_ASSOC);$this->pdoStatement->execute($params);}$this->time=microtime(TRUE)-$time;}public function getConnection(){return$this->connection;}public function getPdoStatement(){return$this->pdoStatement;}public function getQueryString(){return$this->queryString;}public function getParameters(){return$this->params;}public function getColumnCount(){return$this->pdoStatement?$this->pdoStatement->columnCount():NULL;}public function getRowCount(){return$this->pdoStatement?$this->pdoStatement->rowCount():NULL;}public function getTime(){return$this->time;}public function normalizeRow($row){if($this->types===NULL){$this->types=(array)$this->supplementalDriver->getColumnTypes($this->pdoStatement);}foreach($this->types 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){if(($pos=strpos($value,'.'))!==FALSE){$value=rtrim(rtrim($pos===0?"0$value":$value,'0'),'.');}$float=(float)$value;$row[$key]=(string)$float===$value?$float:$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 Nette\Utils\DateTime($value);}elseif($type===IReflection::FIELD_TIME_INTERVAL){preg_match('#^(-?)(\d+)\D(\d+)\D(\d+)\z#',$value,$m);$row[$key]=new\DateInterval("PT$m[2]H$m[3]M$m[4]S");$row[$key]->invert=(int)(bool)$m[1];}elseif($type===IReflection::FIELD_UNIX_TIMESTAMP){$row[$key]=Nette\Utils\DateTime::from($value);}}return$this->supplementalDriver->normalizeRow($row);}public function dump(){Helpers::dumpResult($this);}public function rewind(){if($this->result===FALSE){throw new Nette\InvalidStateException('Nette\\Database\\ResultSet implements only one way iterator.');}}public function current(){return$this->result;}public function key(){return$this->resultKey;}public function next(){$this->result=FALSE;}public function valid(){if($this->result){return TRUE;}return$this->fetch()!==FALSE;}public function fetch(){$data=$this->pdoStatement?$this->pdoStatement->fetch():NULL;if(!$data){$this->pdoStatement->closeCursor();return FALSE;}$row=new Row;foreach($this->normalizeRow($data)as$key=>$value){if($key!==''){$row->$key=$value;}}if($this->result===NULL&&count($data)!==$this->pdoStatement->columnCount()){trigger_error('Found duplicate columns in database result set.',E_USER_NOTICE);}$this->resultKey++;return$this->result=$row;}public function fetchField($column=0){$row=$this->fetch();return$row?$row[$column]:FALSE;}public function fetchPairs($key=NULL,$value=NULL){return Helpers::toPairs($this->fetchAll(),$key,$value);}public function fetchAll(){if($this->results===NULL){$this->results=iterator_to_array($this);}return$this->results;}public function fetchAssoc($path){return Nette\Utils\Arrays::associate($this->fetchAll(),$path);}}$key;}public function offsetExists($key){if(is_int($key)){return(bool)current(array_slice((array)$this,$key,1));}return parent::offsetExists($key);}}value=(string)$value;$this->parameters=$parameters;}public function getParameters(){return$this->parameters;}public function __toString(){return$this->value;}}connection=$connection;$this->driver=$connection->getSupplementalDriver();$this->arrayModes=array('INSERT'=>$this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_INSERT_AS_SELECT)?'select':'values','REPLACE'=>'values','UPDATE'=>'assoc','WHERE'=>'and','HAVING'=>'and','ORDER BY'=>'order','GROUP BY'=>'order');}public function process($params){$this->params=$params;$this->counter=0;$this->remaining=array();$this->arrayMode='assoc';$res=array();while($this->countercounter++];if(($this->counter===2&&count($params)===2)||!is_scalar($param)){$res[]=$this->formatValue($param);}else{$res[]=Nette\Utils\Strings::replace($param,'~\'.*?\'|".*?"|\?|\b(?:INSERT|REPLACE|UPDATE|WHERE|HAVING|ORDER BY|GROUP BY)\b|/\*.*?\*/|--[^\n]*~si',array($this,'callback'));}}return array(implode(' ',$res),$this->remaining);}public function callback($m){$m=$m[0];if($m[0]==="'"||$m[0]==='"'||$m[0]==='/'||$m[0]==='-'){return$m;}elseif($m==='?'){if($this->counter>=count($this->params)){throw new Nette\InvalidArgumentException('There are more placeholders than passed parameters.');}return$this->formatValue($this->params[$this->counter++]);}else{$this->arrayMode=$this->arrayModes[strtoupper($m)];return$m;}}private function 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 rtrim(rtrim(number_format($value,10,'.',''),'0'),'.');}elseif(is_bool($value)){return$this->driver->formatBool($value);}elseif($value===NULL){return'NULL';}elseif($value instanceof Table\IRow){return$value->getPrimary();}elseif(is_array($value)||$value instanceof\Traversable){$vx=$kx=array();if($value instanceof\Traversable){$value=iterator_to_array($value);}if(isset($value[0])){foreach($value as$v){if(is_array($v)&&isset($v[0])){$vx[]='('.$this->formatValue($v).')';}else{$vx[]=$this->formatValue($v);}}if($this->arrayMode==='union'){return implode(' ',$vx);}return implode(', ',$vx);}elseif($this->arrayMode==='values'){$this->arrayMode='multi';foreach($value as$k=>$v){$kx[]=$this->driver->delimite($k);$vx[]=$this->formatValue($v);}return'('.implode(', ',$kx).') VALUES ('.implode(', ',$vx).')';}elseif($this->arrayMode==='select'){$this->arrayMode='union';foreach($value as$k=>$v){$kx[]=$this->driver->delimite($k);$vx[]=$this->formatValue($v);}return'('.implode(', ',$kx).') SELECT '.implode(', ',$vx);}elseif($this->arrayMode==='assoc'){foreach($value as$k=>$v){if(substr($k,-1)==='='){$k2=$this->driver->delimite(substr($k,0,-2));$vx[]=$k2.'='.$k2.' '.substr($k,-2,1).' '.$this->formatValue($v);}else{$vx[]=$this->driver->delimite($k).'='.$this->formatValue($v);}}return implode(', ',$vx);}elseif($this->arrayMode==='multi'){foreach($value as$v){$vx[]=$this->formatValue($v);}return'('.implode(', ',$vx).')';}elseif($this->arrayMode==='union'){foreach($value as$v){$vx[]=$this->formatValue($v);}return'UNION ALL SELECT '.implode(', ',$vx);}elseif($this->arrayMode==='and'){foreach($value as$k=>$v){$k=$this->driver->delimite($k);if(is_array($v)){$vx[]=$v?($k.' IN ('.$this->formatValue(array_values($v)).')'):'1=0';}else{$v=$this->formatValue($v);$vx[]=$k.($v==='NULL'?' IS ':' = ').$v;}}return$value?'('.implode(') AND (',$vx).')':'1=1';}elseif($this->arrayMode==='order'){foreach($value as$k=>$v){$vx[]=$this->driver->delimite($k).($v>0?'':' DESC');}return implode(', ',$vx);}}elseif($value instanceof\DateTime||$value instanceof\DateTimeInterface){return$this->driver->formatDateTime($value);}elseif($value instanceof SqlLiteral){$this->remaining=array_merge($this->remaining,$value->getParameters());return$value->__toString();}else{$this->remaining[]=$value;return'?';}}}data=$data;$this->table=$table;}public function setTable(Selection$table){$this->table=$table;}public function getTable(){return$this->table;}public function __toString(){try{return(string)$this->getPrimary();}catch(\Exception$e){if(func_num_args()){throw$e;}trigger_error("Exception in ".__METHOD__."(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}",E_USER_ERROR);}}public function toArray(){$this->accessColumn(NULL);return$this->data;}public function getPrimary($need=TRUE){$primary=$this->table->getPrimary($need);if($primary===NULL){return NULL;}elseif(!is_array($primary)){if(isset($this->data[$primary])){return$this->data[$primary];}elseif($need){throw new Nette\InvalidStateException("Row does not contain primary $primary column data.");}else{return NULL;}}else{$primaryVal=array();foreach($primary as$key){if(!isset($this->data[$key])){if($need){throw new Nette\InvalidStateException("Row does not contain primary $key column data.");}else{return NULL;}}$primaryVal[$key]=$this->data[$key];}return$primaryVal;}}public function getSignature($need=TRUE){return implode('|',(array)$this->getPrimary($need));}public function ref($key,$throughColumn=NULL){if(!$throughColumn){list($key,$throughColumn)=$this->table->getDatabaseReflection()->getBelongsToReference($this->table->getName(),$key);}return$this->getReference($key,$throughColumn);}public function related($key,$throughColumn=NULL){if(strpos($key,'.')!==FALSE){list($key,$throughColumn)=explode('.',$key);}elseif(!$throughColumn){list($key,$throughColumn)=$this->table->getDatabaseReflection()->getHasManyReference($this->table->getName(),$key);}return$this->table->getReferencingTable($key,$throughColumn,$this[$this->table->getPrimary()]);}public function update($data){$selection=$this->table->createSelectionInstance()->wherePrimary($this->getPrimary());if($selection->update($data)){$selection->select('*');if(($row=$selection->fetch())===FALSE){throw new Nette\InvalidStateException('Database refetch failed; row does not exist!');}$this->data=$row->data;return TRUE;}else{return FALSE;}}public function delete(){$res=$this->table->createSelectionInstance()->wherePrimary($this->getPrimary())->delete();if($res>0&&($signature=$this->getSignature(FALSE))){unset($this->table[$signature]);}return$res;}public function getIterator(){$this->accessColumn(NULL);return new\ArrayIterator($this->data);}public function offsetSet($key,$value){$this->__set($key,$value);}public function offsetGet($key){return$this->__get($key);}public function offsetExists($key){return$this->__isset($key);}public function offsetUnset($key){$this->__unset($key);}public function __set($key,$value){throw new Nette\DeprecatedException('ActiveRow is read-only; use update() method instead.');}public function&__get($key){$this->accessColumn($key);if(array_key_exists($key,$this->data)){return$this->data[$key];}try{list($table,$column)=$this->table->getDatabaseReflection()->getBelongsToReference($this->table->getName(),$key);$referenced=$this->getReference($table,$column);if($referenced!==FALSE){$this->accessColumn($key,FALSE);return$referenced;}}catch(MissingReferenceException$e){}$this->removeAccessColumn($key);throw new Nette\MemberAccessException("Cannot read an undeclared column '$key'.");}public function __isset($key){$this->accessColumn($key);if(array_key_exists($key,$this->data)){return isset($this->data[$key]);}$this->removeAccessColumn($key);return FALSE;}public function __unset($key){throw new Nette\DeprecatedException('ActiveRow is read-only.');}protected function accessColumn($key,$selectColumn=TRUE){$this->table->accessColumn($key,$selectColumn);if($this->table->getDataRefreshed()&&!$this->dataRefreshed){$this->data=$this->table[$this->getSignature()]->data;$this->dataRefreshed=TRUE;}}protected function removeAccessColumn($key){$this->table->removeAccessColumn($key);}protected function getReference($table,$column){$this->accessColumn($column);if(array_key_exists($column,$this->data)){$value=$this->data[$column];$referenced=$this->table->getReferencedTable($table,$column,$value);return isset($referenced[$value])?$referenced[$value]:NULL;}return FALSE;}}refTable=$refTable;$this->column=$column;parent::__construct($refTable->connection,$table,$refTable->reflection,$refTable->cache?$refTable->cache->getStorage():NULL);}public function setActive($active){$this->active=$active;return$this;}public function select($columns){if(!$this->sqlBuilder->getSelect()){$this->sqlBuilder->addSelect("$this->name.$this->column");}return call_user_func_array('parent::select',func_get_args());}public function order($columns){if(!$this->sqlBuilder->getOrder()){$this->sqlBuilder->addOrder("$this->name.$this->column".(preg_match('~\bDESC\z~i',$columns)?' DESC':''));}return call_user_func_array('parent::order',func_get_args());}public function aggregation($function){$aggregation=&$this->getRefTable($refPath)->aggregation[$refPath.$function.$this->getSql().json_encode($this->sqlBuilder->getParameters())];if($aggregation===NULL){$aggregation=array();$selection=$this->createSelectionInstance();$selection->getSqlBuilder()->importConditions($this->getSqlBuilder());$selection->select($function);$selection->select("$this->name.$this->column");$selection->group("$this->name.$this->column");foreach($selection as$row){$aggregation[$row[$this->column]]=$row;}}if(isset($aggregation[$this->active])){foreach($aggregation[$this->active]as$val){return$val;}}}public function count($column=NULL){$return=parent::count($column);return isset($return)?$return:0;}protected function execute(){if($this->rows!==NULL){$this->observeCache=$this;return;}$accessedColumns=$this->accessedColumns;$this->loadRefCache();if(!isset($this->refCacheCurrent['data'])){$this->accessedColumns=$accessedColumns;$limit=$this->sqlBuilder->getLimit();$rows=count($this->refTable->rows);if($limit&&$rows>1){$this->sqlBuilder->setLimit(NULL,NULL);}parent::execute();$this->sqlBuilder->setLimit($limit,NULL);$data=array();$offset=array();$this->accessColumn($this->column);foreach((array)$this->rows as$key=>$row){$ref=&$data[$row[$this->column]];$skip=&$offset[$row[$this->column]];if($limit===NULL||$rows<=1||(count($ref)<$limit&&$skip>=$this->sqlBuilder->getOffset())){$ref[$key]=$row;}else{unset($this->rows[$key]);}$skip++;unset($ref,$skip);}$this->refCacheCurrent['data']=$data;$this->data=&$this->refCacheCurrent['data'][$this->active];}$this->observeCache=$this;if($this->data===NULL){$this->data=array();}else{foreach($this->data as$row){$row->setTable($this);}reset($this->data);}}protected function getRefTable(&$refPath){$refObj=$this->refTable;$refPath=$this->name.'.';while($refObj instanceof GroupedSelection){$refPath.=$refObj->name.'.';$refObj=$refObj->refTable;}return$refObj;}protected function loadRefCache(){$hash=$this->getSpecificCacheKey();$referencing=&$this->refCache['referencing'][$this->getGeneralCacheKey()];$this->observeCache=&$referencing['observeCache'];$this->refCacheCurrent=&$referencing[$hash];$this->accessedColumns=&$referencing[$hash]['accessed'];$this->specificCacheKey=&$referencing[$hash]['specificCacheKey'];$this->rows=&$referencing[$hash]['rows'];if(isset($referencing[$hash]['data'][$this->active])){$this->data=&$referencing[$hash]['data'][$this->active];}}public function insert($data){if($data instanceof\Traversable&&!$data instanceof Selection){$data=iterator_to_array($data);}if(Nette\Utils\Arrays::isList($data)){foreach(array_keys($data)as$key){$data[$key][$this->column]=$this->active;}}else{$data[$this->column]=$this->active;}return parent::insert($data);}public function update($data){$builder=$this->sqlBuilder;$this->sqlBuilder=clone$this->sqlBuilder;$this->where($this->column,$this->active);$return=parent::update($data);$this->sqlBuilder=$builder;return$return;}public function delete(){$builder=$this->sqlBuilder;$this->sqlBuilder=clone$this->sqlBuilder;$this->where($this->column,$this->active);$return=parent::delete();$this->sqlBuilder=$builder;return$return;}}name=$table;$this->connection=$connection;$this->reflection=$reflection;$this->cache=$cacheStorage?new Nette\Caching\Cache($cacheStorage,'Nette.Database.'.md5($connection->getDsn())):NULL;$this->primary=$reflection->getPrimary($table);$this->sqlBuilder=new SqlBuilder($table,$connection,$reflection);$this->refCache=&$this->getRefTable($refPath)->globalRefCache[$refPath];}public function __destruct(){$this->saveCacheState();}public function __clone(){$this->sqlBuilder=clone$this->sqlBuilder;}public function getConnection(){return$this->connection;}public function getDatabaseReflection(){return$this->reflection;}public function getName(){return$this->name;}public function getPrimary($need=TRUE){if($this->primary===NULL&&$need){throw new\LogicException("Table '{$this->name}' does not have a primary key.");}return$this->primary;}public function getPrimarySequence(){if($this->primarySequence===FALSE){$this->primarySequence=NULL;$driver=$this->connection->getSupplementalDriver();if($driver->isSupported(ISupplementalDriver::SUPPORT_SEQUENCE)&&$this->primary!==NULL){foreach($driver->getColumns($this->name)as$column){if($column['name']===$this->primary){$this->primarySequence=$column['vendor']['sequence'];break;}}}}return$this->primarySequence;}public function setPrimarySequence($sequence){$this->primarySequence=$sequence;return$this;}public function getSql(){return$this->sqlBuilder->buildSelectQuery($this->getPreviousAccessedColumns());}public function getPreviousAccessedColumns(){if($this->cache&&$this->previousAccessedColumns===NULL){$this->accessedColumns=$this->previousAccessedColumns=$this->cache->load($this->getGeneralCacheKey());if($this->previousAccessedColumns===NULL){$this->previousAccessedColumns=array();}}return array_keys(array_filter((array)$this->previousAccessedColumns));}public function getSqlBuilder(){return$this->sqlBuilder;}public function get($key){$clone=clone$this;return$clone->wherePrimary($key)->fetch();}public function fetch(){$this->execute();$return=current($this->data);next($this->data);return$return;}public function fetchPairs($key=NULL,$value=NULL){return Nette\Database\Helpers::toPairs(iterator_to_array($this),$key,$value);}public function fetchAll(){return iterator_to_array($this);}public function select($columns){$this->emptyResultSet();call_user_func_array(array($this->sqlBuilder,'addSelect'),func_get_args());return$this;}public function wherePrimary($key){if(is_array($this->primary)&&Nette\Utils\Arrays::isList($key)){if(isset($key[0])&&is_array($key[0])){$this->where($this->primary,$key);}else{foreach($this->primary as$i=>$primary){$this->where($this->name.'.'.$primary,$key[$i]);}}}elseif(is_array($key)&&!Nette\Utils\Arrays::isList($key)){$this->where($key);}else{$this->where($this->name.'.'.$this->getPrimary(),$key);}return$this;}public function where($condition,$parameters=array()){if(is_array($condition)&&$parameters===array()){foreach($condition as$key=>$val){if(is_int($key)){$this->where($val);}else{$this->where($key,$val);}}return$this;}$this->emptyResultSet();call_user_func_array(array($this->sqlBuilder,'addWhere'),func_get_args());return$this;}public function order($columns){$this->emptyResultSet();call_user_func_array(array($this->sqlBuilder,'addOrder'),func_get_args());return$this;}public function limit($limit,$offset=NULL){$this->emptyResultSet();$this->sqlBuilder->setLimit($limit,$offset);return$this;}public function page($page,$itemsPerPage,&$numOfPages=NULL){if(func_num_args()>2){$numOfPages=(int)ceil($this->count('*')/$itemsPerPage);}return$this->limit($itemsPerPage,($page-1)*$itemsPerPage);}public function group($columns){$this->emptyResultSet();call_user_func_array(array($this->sqlBuilder,'setGroup'),func_get_args());return$this;}public function having($having){$this->emptyResultSet();call_user_func_array(array($this->sqlBuilder,'setHaving'),func_get_args());return$this;}public function aggregation($function){$selection=$this->createSelectionInstance();$selection->getSqlBuilder()->importConditions($this->getSqlBuilder());$selection->select($function);foreach($selection->fetch()as$val){return$val;}}public function count($column=NULL){if(!$column){$this->execute();return count($this->data);}return$this->aggregation("COUNT($column)");}public function min($column){return$this->aggregation("MIN($column)");}public function max($column){return$this->aggregation("MAX($column)");}public function sum($column){return$this->aggregation("SUM($column)");}protected function execute(){if($this->rows!==NULL){return;}$this->observeCache=$this;if($this->primary===NULL&&$this->sqlBuilder->getSelect()===NULL){throw new Nette\InvalidStateException('Table with no primary key requires an explicit select clause.');}try{$result=$this->query($this->getSql());}catch(\PDOException$exception){if(!$this->sqlBuilder->getSelect()&&$this->previousAccessedColumns){$this->previousAccessedColumns=FALSE;$this->accessedColumns=array();$result=$this->query($this->getSql());}else{throw$exception;}}$this->rows=array();$usedPrimary=TRUE;foreach($result->getPdoStatement()as$key=>$row){$row=$this->createRow($result->normalizeRow($row));$primary=$row->getSignature(FALSE);$usedPrimary=$usedPrimary&&$primary;$this->rows[$primary?:$key]=$row;}$this->data=$this->rows;if($usedPrimary&&$this->accessedColumns!==FALSE){foreach((array)$this->primary as$primary){$this->accessedColumns[$primary]=TRUE;}}}protected function createRow(array$row){return new ActiveRow($row,$this);}public function createSelectionInstance($table=NULL){return new Selection($this->connection,$table?:$this->name,$this->reflection,$this->cache?$this->cache->getStorage():NULL);}protected function createGroupedSelectionInstance($table,$column){return new GroupedSelection($this,$table,$column);}protected function query($query){return$this->connection->queryArgs($query,$this->sqlBuilder->getParameters());}protected function emptyResultSet($saveCache=TRUE){if($this->rows!==NULL&&$saveCache){$this->saveCacheState();}$this->rows=NULL;$this->specificCacheKey=NULL;$this->generalCacheKey=NULL;$this->refCache['referencingPrototype']=array();}protected function saveCacheState(){if($this->observeCache===$this&&$this->cache&&!$this->sqlBuilder->getSelect()&&$this->accessedColumns!==$this->previousAccessedColumns){$previousAccessed=$this->cache->load($this->getGeneralCacheKey());$accessed=$this->accessedColumns;$needSave=is_array($accessed)&&is_array($previousAccessed)?array_intersect_key($accessed,$previousAccessed)!==$accessed:$accessed!==$previousAccessed;if($needSave){$save=is_array($accessed)&&is_array($previousAccessed)?$previousAccessed+$accessed:$accessed;$this->cache->save($this->getGeneralCacheKey(),$save);$this->previousAccessedColumns=NULL;}}}protected function getRefTable(&$refPath){return$this;}protected function loadRefCache(){}protected function getGeneralCacheKey(){if($this->generalCacheKey){return$this->generalCacheKey;}return$this->generalCacheKey=md5(serialize(array(__CLASS__,$this->name,$this->sqlBuilder->getConditions())));}protected function getSpecificCacheKey(){if($this->specificCacheKey){return$this->specificCacheKey;}return$this->specificCacheKey=md5($this->getSql().json_encode($this->sqlBuilder->getParameters()));}public function accessColumn($key,$selectColumn=TRUE){if(!$this->cache){return;}if($key===NULL){$this->accessedColumns=FALSE;$currentKey=key((array)$this->data);}elseif($this->accessedColumns!==FALSE){$this->accessedColumns[$key]=$selectColumn;}if($selectColumn&&!$this->sqlBuilder->getSelect()&&$this->previousAccessedColumns&&($key===NULL||!isset($this->previousAccessedColumns[$key]))){$this->previousAccessedColumns=array();if($this->sqlBuilder->getLimit()){$generalCacheKey=$this->generalCacheKey;$sqlBuilder=$this->sqlBuilder;$primaryValues=array();foreach((array)$this->rows as$row){$primary=$row->getPrimary();$primaryValues[]=is_array($primary)?array_values($primary):$primary;}$this->emptyResultSet(FALSE);$this->sqlBuilder=clone$this->sqlBuilder;$this->sqlBuilder->setLimit(NULL,NULL);$this->wherePrimary($primaryValues);$this->generalCacheKey=$generalCacheKey;$this->execute();$this->sqlBuilder=$sqlBuilder;}else{$this->emptyResultSet(FALSE);$this->execute();}$this->dataRefreshed=TRUE;if(isset($currentKey)){while(key($this->data)!==$currentKey){next($this->data);}}}}public function removeAccessColumn($key){if($this->cache&&is_array($this->accessedColumns)){$this->accessedColumns[$key]=FALSE;}}public function getDataRefreshed(){return$this->dataRefreshed;}public function insert($data){if($data instanceof Selection){$data=new Nette\Database\SqlLiteral($data->getSql(),$data->getSqlBuilder()->getParameters());}elseif($data instanceof\Traversable){$data=iterator_to_array($data);}$return=$this->connection->query($this->sqlBuilder->buildInsertQuery(),$data);$this->loadRefCache();if($data instanceof Nette\Database\SqlLiteral||$this->primary===NULL){unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);return$return->getRowCount();}$primaryKey=$this->connection->getInsertId($this->getPrimarySequence());if($primaryKey===FALSE){unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);return$return->getRowCount();}if(is_array($this->getPrimary())){$primaryKey=array();foreach((array)$this->getPrimary()as$key){if(!isset($data[$key])){return$data;}$primaryKey[$key]=$data[$key];}if(count($primaryKey)===1){$primaryKey=reset($primaryKey);}}$row=$this->createSelectionInstance()->select('*')->wherePrimary($primaryKey)->fetch();if($this->rows!==NULL){if($signature=$row->getSignature(FALSE)){$this->rows[$signature]=$row;$this->data[$signature]=$row;}else{$this->rows[]=$row;$this->data[]=$row;}}return$row;}public function update($data){if($data instanceof\Traversable){$data=iterator_to_array($data);}elseif(!is_array($data)){throw new Nette\InvalidArgumentException;}if(!$data){return 0;}return$this->connection->queryArgs($this->sqlBuilder->buildUpdateQuery(),array_merge(array($data),$this->sqlBuilder->getParameters()))->getRowCount();}public function delete(){return$this->query($this->sqlBuilder->buildDeleteQuery())->getRowCount();}public function getReferencedTable($table,$column,$checkPrimaryKey){$referenced=&$this->refCache['referenced'][$this->getSpecificCacheKey()]["$table.$column"];$selection=&$referenced['selection'];$cacheKeys=&$referenced['cacheKeys'];if($selection===NULL||!isset($cacheKeys[$checkPrimaryKey])){$this->execute();$cacheKeys=array();foreach($this->rows as$row){if($row[$column]===NULL){continue;}$key=$row[$column];$cacheKeys[$key]=TRUE;}if($cacheKeys){$selection=$this->createSelectionInstance($table);$selection->where($selection->getPrimary(),array_keys($cacheKeys));}else{$selection=array();}}return$selection;}public function getReferencingTable($table,$column,$active=NULL){$prototype=&$this->refCache['referencingPrototype']["$table.$column"];if(!$prototype){$prototype=$this->createGroupedSelectionInstance($table,$column);$prototype->where("$table.$column",array_keys((array)$this->rows));}$clone=clone$prototype;$clone->setActive($active);return$clone;}public function rewind(){$this->execute();$this->keys=array_keys($this->data);reset($this->keys);}public function current(){if(($key=current($this->keys))!==FALSE){return$this->data[$key];}else{return FALSE;}}public function key(){return current($this->keys);}public function next(){next($this->keys);}public function valid(){return current($this->keys)!==FALSE;}public function offsetSet($key,$value){$this->execute();$this->rows[$key]=$value;}public function offsetGet($key){$this->execute();return$this->rows[$key];}public function offsetExists($key){$this->execute();return isset($this->rows[$key]);}public function offsetUnset($key){$this->execute();unset($this->rows[$key],$this->data[$key]);}}array(),'where'=>array(),'group'=>array(),'having'=>array(),'order'=>array());protected$order=array();protected$limit=NULL;protected$offset=NULL;protected$group='';protected$having='';public function __construct($tableName,Connection$connection,IReflection$reflection){$this->tableName=$tableName;$this->databaseReflection=$reflection;$this->driver=$connection->getSupplementalDriver();$this->delimitedTable=$this->tryDelimite($tableName);}public function buildInsertQuery(){return"INSERT INTO {$this->delimitedTable}";}public function buildUpdateQuery(){if($this->limit!==NULL||$this->offset){throw new Nette\NotSupportedException('LIMIT clause is not supported in UPDATE query.');}return$this->tryDelimite("UPDATE {$this->tableName} SET ?".$this->buildConditions());}public function buildDeleteQuery(){if($this->limit!==NULL||$this->offset){throw new Nette\NotSupportedException('LIMIT clause is not supported in DELETE query.');}return$this->tryDelimite("DELETE FROM {$this->tableName}".$this->buildConditions());}public function buildSelectQuery($columns=NULL){$queryCondition=$this->buildConditions();$queryEnd=$this->buildQueryEnd();$joins=array();$this->parseJoins($joins,$queryCondition);$this->parseJoins($joins,$queryEnd);if($this->select){$querySelect=$this->buildSelect($this->select);$this->parseJoins($joins,$querySelect);}elseif($columns){$prefix=$joins?"{$this->delimitedTable}.":'';$cols=array();foreach($columns as$col){$cols[]=$prefix.$col;}$querySelect=$this->buildSelect($cols);}elseif($this->group&&!$this->driver->isSupported(ISupplementalDriver::SUPPORT_SELECT_UNGROUPED_COLUMNS)){$querySelect=$this->buildSelect(array($this->group));$this->parseJoins($joins,$querySelect);}else{$prefix=$joins?"{$this->delimitedTable}.":'';$querySelect=$this->buildSelect(array($prefix.'*'));}$queryJoins=$this->buildQueryJoins($joins);$query="{$querySelect} FROM {$this->tableName}{$queryJoins}{$queryCondition}{$queryEnd}";if($this->limit!==NULL||$this->offset){$this->driver->applyLimit($query,$this->limit,$this->offset);}return$this->tryDelimite($query);}public function getParameters(){return array_merge($this->parameters['select'],$this->parameters['where'],$this->parameters['group'],$this->parameters['having'],$this->parameters['order']);}public function importConditions(SqlBuilder$builder){$this->where=$builder->where;$this->parameters['where']=$builder->parameters['where'];$this->conditions=$builder->conditions;}public function addSelect($columns){if(is_array($columns)){throw new Nette\InvalidArgumentException('Select column must be a string.');}$this->select[]=$columns;$this->parameters['select']=array_merge($this->parameters['select'],array_slice(func_get_args(),1));}public function getSelect(){return$this->select;}public function addWhere($condition,$parameters=array()){if(is_array($condition)&&is_array($parameters)&&!empty($parameters)){return$this->addWhereComposition($condition,$parameters);}$args=func_get_args();$hash=md5(json_encode($args));if(isset($this->conditions[$hash])){return FALSE;}$this->conditions[$hash]=$condition;$placeholderCount=substr_count($condition,'?');if($placeholderCount>1&&count($args)===2&&is_array($parameters)){$args=$parameters;}else{array_shift($args);}$condition=trim($condition);if($placeholderCount===0&&count($args)===1){$condition.=' ?';}elseif($placeholderCount!==count($args)){throw new Nette\InvalidArgumentException('Argument count does not match placeholder count.');}$replace=NULL;$placeholderNum=0;foreach($args as$arg){preg_match('#(?:.*?\?.*?){'.$placeholderNum.'}(((?:&|\||^|~|\+|-|\*|/|%|\(|,|<|>|=|(?<=\W|^)(?:REGEXP|ALL|AND|ANY|BETWEEN|EXISTS|IN|[IR]?LIKE|OR|NOT|SOME|INTERVAL))\s*)?(?:\(\?\)|\?))#s',$condition,$match,PREG_OFFSET_CAPTURE);$hasOperator=($match[1][0]==='?'&&$match[1][1]===0)?TRUE:!empty($match[2][0]);if($arg===NULL){$replace='IS NULL';if($hasOperator){if(trim($match[2][0])==='NOT'){$replace='IS NOT NULL';}else{throw new Nette\InvalidArgumentException('Column operator does not accept NULL argument.');}}}elseif(is_array($arg)||$arg instanceof Selection){if($hasOperator){if(trim($match[2][0])==='NOT'){$match[2][0]=rtrim($match[2][0]).' IN ';}elseif(trim($match[2][0])!=='IN'){throw new Nette\InvalidArgumentException('Column operator does not accept array argument.');}}else{$match[2][0]='IN ';}if($arg instanceof Selection){$clone=clone$arg;if(!$clone->getSqlBuilder()->select){try{$clone->select($clone->getPrimary());}catch(\LogicException$e){throw new Nette\InvalidArgumentException('Selection argument must have defined a select column.',0,$e);}}if($this->driver->isSupported(ISupplementalDriver::SUPPORT_SUBSELECT)){$arg=NULL;$replace=$match[2][0].'('.$clone->getSql().')';$this->parameters['where']=array_merge($this->parameters['where'],$clone->getSqlBuilder()->parameters['where']);}else{$arg=array();foreach($clone as$row){$arg[]=array_values(iterator_to_array($row));}}}if($arg!==NULL){if(!$arg){$hasBrackets=strpos($condition,'(')!==FALSE;$hasOperators=preg_match('#AND|OR#',$condition);$hasNot=strpos($condition,'NOT')!==FALSE;$hasPrefixNot=strpos($match[2][0],'NOT')!==FALSE;if(!$hasBrackets&&($hasOperators||($hasNot&&!$hasPrefixNot))){throw new Nette\InvalidArgumentException('Possible SQL query corruption. Add parentheses around operators.');}if($hasPrefixNot){$replace='IS NULL OR TRUE';}else{$replace='IS NULL AND FALSE';}$arg=NULL;}else{$replace=$match[2][0].'(?)';$this->parameters['where'][]=$arg;}}}elseif($arg instanceof SqlLiteral){$this->parameters['where'][]=$arg;}else{if(!$hasOperator){$replace='= ?';}$this->parameters['where'][]=$arg;}if($replace){$condition=substr_replace($condition,$replace,$match[1][1],strlen($match[1][0]));$replace=NULL;}if($arg!==NULL){$placeholderNum++;}}$this->where[]=$condition;return TRUE;}public function getConditions(){return array_values($this->conditions);}public function addOrder($columns){$this->order[]=$columns;$this->parameters['order']=array_merge($this->parameters['order'],array_slice(func_get_args(),1));}public function getOrder(){return$this->order;}public function setLimit($limit,$offset){$this->limit=$limit;$this->offset=$offset;}public function getLimit(){return$this->limit;}public function getOffset(){return$this->offset;}public function setGroup($columns){$this->group=$columns;$this->parameters['group']=array_slice(func_get_args(),1);}public function getGroup(){return$this->group;}public function setHaving($having){$this->having=$having;$this->parameters['having']=array_slice(func_get_args(),1);}public function getHaving(){return$this->having;}protected function buildSelect(array$columns){return'SELECT '.implode(', ',$columns);}protected function parseJoins(&$joins,&$query){$builder=$this;$query=preg_replace_callback('~ (?(DEFINE) (?P [a-z][\w_]* ) (?P [.:] ) (?P (?&del)? (?&word) (\((?&word)\))? ) ) (?P (?!\.) (?&node)*) \. (?P (?&word) | \* ) ~xi',function($match)use(&$joins,$builder){return$builder->parseJoinsCb($joins,$match);},$query);}public function parseJoinsCb(&$joins,$match){$chain=$match['chain'];if(!empty($chain[0])&&($chain[0]!=='.'||$chain[0]!==':')){$chain='.'.$chain;}$parent=$parentAlias=$this->tableName;if($chain==".{$parent}"){return"{$parent}.{$match['column']}";}preg_match_all('~ (?(DEFINE) (?P [a-z][\w_]* ) ) (?P [.:])?(?P (?&word))(\((?P (?&word))\))? ~xi',$chain,$keyMatches,PREG_SET_ORDER);foreach($keyMatches as$keyMatch){if($keyMatch['del']===':'){if(isset($keyMatch['throughColumn'])){$table=$keyMatch['key'];list(,$primary)=$this->databaseReflection->getBelongsToReference($table,$keyMatch['throughColumn']);}else{list($table,$primary)=$this->databaseReflection->getHasManyReference($parent,$keyMatch['key']);}$column=$this->databaseReflection->getPrimary($parent);}else{list($table,$column)=$this->databaseReflection->getBelongsToReference($parent,$keyMatch['key']);$primary=$this->databaseReflection->getPrimary($table);}$joins[$table.$column]=array($table,$keyMatch['key']?:$table,$parentAlias,$column,$primary);$parent=$table;$parentAlias=$keyMatch['key'];}return($keyMatch['key']?:$table).".{$match['column']}";}protected function buildQueryJoins(array$joins){$return='';foreach($joins as$join){list($joinTable,$joinAlias,$table,$tableColumn,$joinColumn)=$join;$return.=" LEFT JOIN {$joinTable}".($joinTable!==$joinAlias?" AS {$joinAlias}":'')." ON {$table}.{$tableColumn} = {$joinAlias}.{$joinColumn}";}return$return;}protected function buildConditions(){return$this->where?' WHERE ('.implode(') AND (',$this->where).')':'';}protected function buildQueryEnd(){$return='';if($this->group){$return.=' GROUP BY '.$this->group;}if($this->having){$return.=' HAVING '.$this->having;}if($this->order){$return.=' ORDER BY '.implode(', ',$this->order);}return$return;}protected function tryDelimite($s){$driver=$this->driver;return preg_replace_callback('#(?<=[^\w`"\[]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|\z)#i',function($m)use($driver){return strtoupper($m[0])===$m[0]?$m[0]:$driver->delimite($m[0]);},$s);}protected function addWhereComposition(array$columns,array$parameters){if($this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_COLUMN_AS_OR_COND)){$conditionFragment='('.implode(' = ? AND ',$columns).' = ?) OR ';$condition=substr(str_repeat($conditionFragment,count($parameters)),0,-4);return$this->addWhere($condition,Nette\Utils\Arrays::flatten($parameters));}else{return$this->addWhere('('.implode(', ',$columns).') IN',$parameters);}}}$meta[self::FILE],'handle'=>$meta[self::HANDLE]);}protected function getCacheFile($key){return parent::getCacheFile(substr_replace($key,trim(strtr($this->hint,'\\/@','.._'),'.').'-',strpos($key,Nette\Caching\Cache::NAMESPACE_SEPARATOR)+1,0)).'.php';}public function getDir(){return dirname(parent::getCacheFile(NULL));}}cb=$cb->cb;return;}if(!is_callable($cb,TRUE)){throw new InvalidArgumentException('Invalid callback.');}$this->cb=$cb;}public function __invoke(){if(!is_callable($this->cb)){throw new InvalidStateException("Callback '$this' is not callable.");}return call_user_func_array($this->cb,func_get_args());}public function invoke(){if(!is_callable($this->cb)){throw new InvalidStateException("Callback '$this' is not callable.");}return call_user_func_array($this->cb,func_get_args());}public function invokeArgs(array$args){if(!is_callable($this->cb)){throw new InvalidStateException("Callback '$this' is not callable.");}return call_user_func_array($this->cb,$args);}public function isCallable(){return is_callable($this->cb);}public function getNative(){return$this->cb;}public function toReflection(){if(is_string($this->cb)&&strpos($this->cb,'::')){return new Nette\Reflection\Method($this->cb);}elseif(is_array($this->cb)){return new Nette\Reflection\Method($this->cb[0],$this->cb[1]);}elseif(is_object($this->cb)&&!$this->cb instanceof\Closure){return new Nette\Reflection\Method($this->cb,'__invoke');}else{return new Nette\Reflection\GlobalFunction($this->cb);}}public function isStatic(){return is_array($this->cb)?is_string($this->cb[0]):is_string($this->cb);}public function bindTo($newthis){if(is_string($this->cb)&&strpos($this->cb,'::')){$this->cb=explode('::',$this->cb);}elseif(!is_array($this->cb)){throw new InvalidStateException("Callback '$this' have not any bound object.");}return new static($newthis,$this->cb[1]);}public function __toString(){if($this->cb instanceof\Closure){return'{closure}';}elseif(is_string($this->cb)&&$this->cb[0]==="\0"){return'{lambda}';}else{is_callable($this->cb,TRUE,$textual);return$textual;}}}addPanel($panel,$id);}}href(strtr(Debugger::$editor,array('%file'=>rawurlencode($file),'%line'=>$line)))->title("$file:$line")->setHtml(htmlSpecialChars(rtrim($dir,DIRECTORY_SEPARATOR),ENT_IGNORE).DIRECTORY_SEPARATOR.''.htmlSpecialChars(basename($file),ENT_IGNORE).''.($line?":$line":''));}else{return Nette\Utils\Html::el('span')->setText($file.($line?":$line":''));}}public static function htmlDump($var){trigger_error(__METHOD__.'() is deprecated; use Tracy\Dumper::toHtml() instead.',E_USER_DEPRECATED);return Tracy\Dumper::toHtml($var);}public static function clickableDump($var){trigger_error(__METHOD__.'() is deprecated; use Tracy\Dumper::toHtml() instead.',E_USER_DEPRECATED);return Tracy\Dumper::toHtml($var);}public static function textDump($var){trigger_error(__METHOD__.'() is deprecated; use Tracy\Dumper::toText() instead.',E_USER_DEPRECATED);return Tracy\Dumper::toText($var);}}expand($value);}self::getContext()->parameters[$name]=$value;}public static function getVariable($name,$default=NULL){if(isset(self::getContext()->parameters[$name])){return self::getContext()->parameters[$name];}elseif(func_num_args()>1){return$default;}else{throw new InvalidStateException("Unknown environment variable '$name'.");}}public static function getVariables(){return self::getContext()->parameters;}public static function expand($s){return self::getContext()->expand($s);}public static function setContext(DI\Container$context){if(self::$createdAt){throw new Nette\InvalidStateException('Configurator & SystemContainer has already been created automatically by Nette\Environment at '.self::$createdAt);}self::$context=$context;}public static function getContext(){if(self::$context===NULL){self::loadConfig();}return self::$context;}public static function getService($name){return self::getContext()->getService($name);}public static function __callStatic($name,$args){if(!$args&&strncasecmp($name,'get',3)===0){return self::getService(lcfirst(substr($name,3)));}else{throw new MemberAccessException("Call to undefined static method Nette\\Environment::$name().");}}public static function getHttpRequest(){return self::getContext()->getByType('Nette\Http\IRequest');}public static function getHttpContext(){return self::getContext()->getByType('Nette\Http\Context');}public static function getHttpResponse(){return self::getContext()->getByType('Nette\Http\IResponse');}public static function getApplication(){return self::getContext()->getByType('Nette\Application\Application');}public static function getUser(){return self::getContext()->getByType('Nette\Security\User');}public static function getRobotLoader(){return self::getContext()->getByType('Nette\Loaders\RobotLoader');}public static function getCache($namespace=''){return new Caching\Cache(self::getContext()->getByType('Nette\Caching\IStorage'),$namespace);}public static function getSession($namespace=NULL){return$namespace===NULL?self::getContext()->getByType('Nette\Http\Session'):self::getContext()->getByType('Nette\Http\Session')->getSection($namespace);}public static function loadConfig($file=NULL,$section=NULL){if(self::$createdAt){throw new Nette\InvalidStateException('Nette\Configurator has already been created automatically by Nette\Environment at '.self::$createdAt);}elseif(!defined('TEMP_DIR')){throw new Nette\InvalidStateException('Nette\Environment requires constant TEMP_DIR with path to temporary directory.');}$configurator=new Nette\Configurator;$configurator->setDebugMode(!self::isProduction())->setTempDirectory(TEMP_DIR)->addParameters(array('container'=>array('class'=>'EnvironmentContainer')));if($file){$configurator->addConfig($file,$section);}self::$context=$configurator->createContainer();self::$createdAt='?';foreach(debug_backtrace(FALSE)as$row){if(isset($row['file'])&&$row['file']!==__FILE__&&is_file($row['file'])){self::$createdAt="$row[file]:$row[line]";break;}}return self::getConfig();}public static function getConfig($key=NULL,$default=NULL){$params=Nette\Utils\ArrayHash::from(self::getContext()->parameters);if(func_num_args()){return isset($params[$key])?$params[$key]:$default;}else{return$params;}}}frozen=TRUE;}public function isFrozen(){return$this->frozen;}public function __clone(){$this->frozen=FALSE;}protected function updating(){if($this->frozen){$class=get_class($this);throw new InvalidStateException("Cannot modify a frozen object $class.");}}}getParser()->shortNoEscape=TRUE;$this->addFilter('url','rawurlencode');foreach(array('normalize','toAscii','webalize','padLeft','padRight','reverse')as$name){$this->addFilter($name,'Nette\Utils\Strings::'.$name);}}public function __invoke($s){trigger_error(__METHOD__.'() is deprecated; use compile() instead.',E_USER_DEPRECATED);return$this->setLoader(new Latte\Loaders\StringLoader)->compile($s);}public function getCompiler(){$compiler=parent::getCompiler();if(!$this->fixed){$this->fixed=TRUE;$compiler->addMacro('cache',new Nette\Bridges\CacheLatte\CacheMacro($compiler));Nette\Bridges\ApplicationLatte\UIMacros::install($compiler);Nette\Bridges\FormsLatte\FormMacros::install($compiler);}return$compiler;}public function&__get($name){switch(strtolower($name)){case'parser':case'compiler':$method='get'.ucfirst($name);trigger_error("Magic getters are deprecated. Use $method() method instead.",E_USER_DEPRECATED);$return=$this->$method();return$return;}return parent::__get($name);}}setFile($file);}}public function setFile($file){$this->file=realpath($file);if(!$this->file){throw new Nette\FileNotFoundException("Missing template file '$file'.");}return$this;}public function getFile(){return$this->file;}public function getSource(){return file_get_contents($this->file);}public function render(){if($this->file==NULL){throw new Nette\InvalidStateException('Template file name was not specified.');}if(!$this->getFilters()){$this->onPrepareFilters($this);}if($latte=$this->getLatte()){return$latte->setLoader(new Latte\Loaders\FileLoader)->render($this->file,$this->getParameters());}$cache=new Caching\Cache($storage=$this->getCacheStorage(),'Nette.FileTemplate');if($storage instanceof Caching\Storages\PhpFileStorage){$storage->hint=str_replace(dirname(dirname($this->file)),'',$this->file);}$cached=$compiled=$cache->load($this->file);if($compiled===NULL){try{$compiled="file\n\n?>".$this->compile();}catch(FilterException$e){throw$e->setSource(file_get_contents($this->file),$e->sourceLine,$this->file);}$cache->save($this->file,$compiled,array(Caching\Cache::FILES=>$this->file,Caching\Cache::CONSTS=>'Nette\Framework::REVISION'));$cached=$cache->load($this->file);}$isFile=$cached!==NULL&&$storage instanceof Caching\Storages\PhpFileStorage;self::load($isFile?$cached['file']:$compiled,$this->getParameters(),$isFile);}}'Nette\Utils\Strings::normalize','toascii'=>'Nette\Utils\Strings::toAscii','webalize'=>'Nette\Utils\Strings::webalize','padleft'=>'Nette\Utils\Strings::padLeft','padright'=>'Nette\Utils\Strings::padRight','reverse'=>'Nette\Utils\Strings::reverse','url'=>'rawurlencode');public static function loader($helper){if(method_exists(__CLASS__,$helper)){return array(__CLASS__,$helper);}elseif(isset(self::$helpers[$helper])){return self::$helpers[$helper];}}public static function modifyDate($time,$delta,$unit=NULL){return$time==NULL?NULL:Nette\Utils\DateTime::from($time)->modify($delta.$unit);}public static function length($var){return is_string($var)?Strings::length($var):count($var);}public static function null(){return'';}public static function optimizePhp($source,$lineLength=80){return Latte\Helpers::optimizePhp($source,$lineLength);}}source=$source;return$this;}public function getSource(){return$this->source;}public function render(){if(!$this->filters){$this->onPrepareFilters($this);}if($latte=$this->getLatte()){return$latte->setLoader(new Latte\Loaders\StringLoader)->render($this->source,$this->getParameters());}$cache=new Caching\Cache($storage=$this->getCacheStorage(),'Nette.Template');$cached=$compiled=$cache->load($this->source);if($compiled===NULL){$compiled=$this->compile();$cache->save($this->source,$compiled,array(Caching\Cache::CONSTS=>'Nette\Framework::REVISION'));$cached=$cache->load($this->source);}$isFile=$cached!==NULL&&$storage instanceof Caching\Storages\PhpFileStorage;self::load($isFile?$cached['file']:$compiled,$this->getParameters(),$isFile);}protected static function load(){foreach(func_get_arg(1)as$__k=>$__v)$$__k=$__v;unset($__k,$__v);if(func_get_arg(2)){include func_get_arg(0);}else{$res=eval('?>'.func_get_arg(0));if($res===FALSE&&($error=error_get_last())&&$error['type']===E_PARSE){throw new\ErrorException($error['message'],0,$error['type'],$error['file'],$error['line']);}}}public function save($file){if(file_put_contents($file,$this->__toString(TRUE))===FALSE){throw new Nette\IOException("Unable to save file '$file'.");}}public function __toString(){ob_start();try{$this->render();return ob_get_clean();}catch(\Exception$e){ob_end_clean();if(func_num_args()){throw$e;}trigger_error(sprintf('Exception in %s(): %s in %s:%i',__METHOD__,$e->getMessage(),$e->getFile(),$e->getLine()),E_USER_ERROR);}}public function compile(){if(!$this->filters){$this->onPrepareFilters($this);}$code=$this->getSource();foreach($this->filters as$filter){$code=self::extractPhp($code,$blocks);$code=call_user_func($filter,$code);$code=strtr($code,$blocks);}if($latte=$this->getLatte()){return$latte->setLoader(new Latte\Loaders\StringLoader)->compile($code);}return Helpers::optimizePhp($code);}public function setLatte(Latte\Engine$latte){$this->latte=$latte;}public function getLatte(){if(!$this->latte){return NULL;}$latte=$this->latte instanceof Latte\Engine?$this->latte:new Nette\Latte\Engine;foreach($this->helpers as$key=>$callback){$latte->addFilter($key,$callback);}foreach($this->helperLoaders as$callback){$latte->addFilter(NULL,function($name)use($callback,$latte){if($res=call_user_func($callback,$name)){$latte->addFilter($name,$res);}});}if($this->cacheStorage instanceof Nette\Caching\Storages\PhpFileStorage){$latte->setTempDirectory($this->cacheStorage->getDir());}return$latte;}public function registerFilter($callback){if($callback instanceof Latte\Engine){$this->latte=$callback;}elseif(is_array($callback)&&$callback[0]instanceof Latte\Engine){$this->latte=$callback[0];}elseif(strpos(Callback::toString($callback),'Latte\Engine')!==FALSE){$this->latte=TRUE;}elseif($this->latte){throw new Nette\DeprecatedException('Adding filters after Latte is not possible.');}else{$this->filters[]=Callback::check($callback);}return$this;}public function getFilters(){return$this->filters;}public function registerHelper($name,$callback){$this->helpers[strtolower($name)]=$callback;return$this;}public function registerHelperLoader($callback){array_unshift($this->helperLoaders,$callback);return$this;}public function getHelpers(){return$this->helpers;}public function getHelperLoaders(){return$this->helperLoaders;}public function __call($name,$args){$lname=strtolower($name);if(!isset($this->helpers[$lname])){foreach($this->helperLoaders as$loader){$helper=Callback::invoke($loader,$lname);if($helper){$this->registerHelper($lname,$helper);return Callback::invokeArgs($this->helpers[$lname],$args);}}return parent::__call($name,$args);}return Callback::invokeArgs($this->helpers[$lname],$args);}public function setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->registerHelper('translate',$translator===NULL?NULL:array($translator,'translate'));return$this;}public function add($name,$value){if(array_key_exists($name,$this->params)){throw new Nette\InvalidStateException("The variable '$name' already exists.");}$this->params[$name]=$value;return$this;}public function setParameters(array$params){$this->params=$params+$this->params;return$this;}public function getParameters(){$this->params['template']=$this;return$this->params;}public function __set($name,$value){$this->params[$name]=$value;}public function&__get($name){if(!array_key_exists($name,$this->params)){trigger_error("The variable '$name' does not exist in template.",E_USER_NOTICE);}return$this->params[$name];}public function __isset($name){return isset($this->params[$name]);}public function __unset($name){unset($this->params[$name]);}public function setCacheStorage(Caching\IStorage$storage){$this->cacheStorage=$storage;return$this;}public function getCacheStorage(){if($this->cacheStorage===NULL){return new Caching\Storages\DevNullStorage;}return$this->cacheStorage;}private static function extractPhp($source,&$blocks){$res='';$blocks=array();$tokens=token_get_all($source);foreach($tokens as$n=>$token){if(is_array($token)){if($token[0]===T_INLINE_HTML){$res.=$token[1];continue;}elseif($token[0]===T_CLOSE_TAG){if($php!==$res){$res.=str_repeat("\n",substr_count($php,"\n"));}$res.=$token[1];continue;}elseif($token[0]===T_OPEN_TAG&&$token[1]==='?';}elseif($token[0]===T_OPEN_TAG||$token[0]===T_OPEN_TAG_WITH_ECHO){$res.=$id="<@php:p".count($blocks)."@";$php=&$blocks[$id];}$php.=$token[1];}else{$php.=$token;}}return$res;}}1){foreach(func_get_arg(1)as$__k=>$__v)$$__k=$__v;unset($__k,$__v);}$res=eval('?>'.func_get_arg(0));if($res===FALSE&&($error=error_get_last())&&$error['type']===E_PARSE){throw new\ErrorException($error['message'],0,$error['type'],$error['file'],$error['line']);}return$res;}public static function load(){trigger_error(__METHOD__.'() is deprecated.',E_USER_DEPRECATED);if(func_num_args()>1&&is_array(func_get_arg(1))){foreach(func_get_arg(1)as$__k=>$__v)$$__k=$__v;unset($__k,$__v);}return include func_get_arg(0);}}1,'factories'=>1,'parameters'=>1);public function __construct(ContainerBuilder$builder=NULL){$this->builder=$builder?:new ContainerBuilder;}public function addExtension($name,CompilerExtension$extension){if(isset(self::$reserved[$name])){throw new Nette\InvalidArgumentException("Name '$name' is reserved.");}$this->extensions[$name]=$extension->setCompiler($this,$name);return$this;}public function getExtensions($type=NULL){return$type?array_filter($this->extensions,function($item)use($type){return$item instanceof$type;}):$this->extensions;}public function getContainerBuilder(){return$this->builder;}public function getConfig(){return$this->config;}public function compile(array$config,$className,$parentName){$this->config=$config;$this->processParameters();$this->processExtensions();$this->processServices();return$this->generateCode($className,$parentName);}public function processParameters(){if(isset($this->config['parameters'])){$this->builder->parameters=Helpers::expand($this->config['parameters'],$this->config['parameters'],TRUE);}}public function processExtensions(){for($i=0;$slice=array_slice($this->extensions,$i,1,TRUE);$i++){$name=key($slice);if(isset($this->config[$name])){$this->config[$name]=$this->builder->expand($this->config[$name]);}$this->extensions[$name]->loadConfiguration();}if($extra=array_diff_key($this->config,self::$reserved,$this->extensions)){$extra=implode("', '",array_keys($extra));throw new Nette\InvalidStateException("Found sections '$extra' in configuration, but corresponding extensions are missing.");}}public function processServices(){$this->parseServices($this->builder,$this->config);foreach($this->extensions as$name=>$extension){if(isset($this->config[$name])){$this->parseServices($this->builder,$this->config[$name],$name);}}}public function generateCode($className,$parentName){foreach($this->extensions as$extension){$extension->beforeCompile();$this->builder->addDependency(Nette\Reflection\ClassType::from($extension)->getFileName());}$classes=$this->builder->generateClasses($className,$parentName);$classes[0]->addMethod('initialize');foreach($this->extensions as$extension){$extension->afterCompile($classes[0]);}return implode("\n\n\n",$classes);}public static function parseServices(ContainerBuilder$builder,array$config,$namespace=NULL){if(!empty($config['factories'])){trigger_error("Section 'factories' is deprecated, move definitions to section 'services' and append key 'autowired: no'.",E_USER_DEPRECATED);}$services=isset($config['services'])?$config['services']:array();$factories=isset($config['factories'])?$config['factories']:array();$all=array_merge($services,$factories);$depths=array();foreach($all as$name=>$def){$path=array();while(Config\Helpers::isInheriting($def)){$path[]=$def;$def=isset($all[$def[Config\Helpers::EXTENDS_KEY]])?$all[$def[Config\Helpers::EXTENDS_KEY]]:array();if(in_array($def,$path,TRUE)){throw new ServiceCreationException("Circular reference detected for service '$name'.");}}$depths[$name]=count($path);}array_multisort($depths,$all);foreach($all as$origName=>$def){if((string)(int)$origName===(string)$origName){$name=count($builder->getDefinitions()).preg_replace('#\W+#','_',$def instanceof\stdClass?".$def->value":(is_scalar($def)?".$def":''));}elseif(array_key_exists($origName,$services)&&array_key_exists($origName,$factories)){throw new ServiceCreationException("It is not allowed to use services and factories with the same name: '$origName'.");}else{$name=($namespace?$namespace.'.':'').strtr($origName,'\\','_');}$params=$builder->parameters;if(is_array($def)&&isset($def['parameters'])){foreach((array)$def['parameters']as$k=>$v){$v=explode(' ',is_int($k)?$v:$k);$params[end($v)]=$builder::literal('$'.end($v));}}$def=Helpers::expand($def,$params);if(($parent=Config\Helpers::takeParent($def))&&$parent!==$name){$builder->removeDefinition($name);$definition=$builder->addDefinition($name,$parent===Config\Helpers::OVERWRITE?NULL:unserialize(serialize($builder->getDefinition($parent))));}elseif($builder->hasDefinition($name)){$definition=$builder->getDefinition($name);}else{$definition=$builder->addDefinition($name);}try{static::parseService($definition,$def);}catch(\Exception$e){throw new ServiceCreationException("Service '$name': ".$e->getMessage(),NULL,$e);}if($definition->class==='self'){$definition->class=$origName;trigger_error("Replace service definition '$origName: self' with '- $origName'.",E_USER_DEPRECATED);}if($definition->factory&&$definition->factory->entity==='self'){$definition->factory->entity=$origName;trigger_error("Replace service definition '$origName: self' with '- $origName'.",E_USER_DEPRECATED);}}}public static function parseService(ServiceDefinition$definition,$config){if($config===NULL){return;}elseif(is_string($config)&&interface_exists($config)){$config=array('class'=>NULL,'implement'=>$config);}elseif($config instanceof\stdClass&&interface_exists($config->value)){$config=array('class'=>NULL,'implement'=>$config->value,'factory'=>array_shift($config->attributes));}elseif(!is_array($config)){$config=array('class'=>NULL,'create'=>$config);}if(array_key_exists('factory',$config)){$config['create']=$config['factory'];unset($config['factory']);};$known=array('class','create','arguments','setup','autowired','inject','parameters','implement','run','tags');if($error=array_diff(array_keys($config),$known)){throw new Nette\InvalidStateException(sprintf("Unknown or deprecated key '%s' in definition of service.",implode("', '",$error)));}$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('create',$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('create',$config)){Validators::assertField($config,'create','callable|stdClass|null');if($config['create']instanceof\stdClass){$definition->setFactory($config['create']->value,self::filterArguments($config['create']->attributes));}else{$definition->setFactory($config['create'],$arguments);}}if(isset($config['setup'])){if(Config\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 instanceof\stdClass){Validators::assert($setup->value,'callable',"setup item #$id");$definition->addSetup($setup->value,self::filterArguments($setup->attributes));}else{$definition->addSetup($setup);}}}if(isset($config['parameters'])){Validators::assertField($config,'parameters','array');$definition->setParameters($config['parameters']);}if(isset($config['implement'])){Validators::assertField($config,'implement','string');$definition->setImplement($config['implement']);$definition->setAutowired(TRUE);}if(isset($config['autowired'])){Validators::assertField($config,'autowired','bool');$definition->setAutowired($config['autowired']);}if(isset($config['inject'])){Validators::assertField($config,'inject','bool');$definition->setInject($config['inject']);}if(isset($config['run'])){$config['tags']['run']=(bool)$config['run'];}if(isset($config['tags'])){Validators::assertField($config,'tags','array');if(Config\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);}}}}public static function filterArguments(array$args){foreach($args as$k=>$v){if($v==='...'){unset($args[$k]);}elseif(is_array($v)){$args[$k]=self::filterArguments($v);}elseif($v instanceof\stdClass&&isset($v->value,$v->attributes)){$args[$k]=new Statement($v->value,self::filterArguments($v->attributes));}}return$args;}}compiler=$compiler;$this->name=$name;return$this;}public function getConfig(array$defaults=NULL){$config=$this->compiler->getConfig();$config=isset($config[$this->name])?$config[$this->name]:array();unset($config['services'],$config['factories']);return Config\Helpers::merge($config,$this->compiler->getContainerBuilder()->expand($defaults));}public function getContainerBuilder(){return$this->compiler->getContainerBuilder();}public function loadFromFile($file){$loader=new Config\Loader;$res=$loader->load($file);$container=$this->compiler->getContainerBuilder();foreach($loader->getDependencies()as$file){$container->addDependency($file);}return$res;}public function prefix($id){return substr_replace($id,$this->name.'.',substr($id,0,1)==='@'?1:0,0);}public function loadConfiguration(){}public function beforeCompile(){}public function afterCompile(Nette\PhpGenerator\ClassType$class){}}$secData){if(is_array($secData)){if(substr($secName,-1)===self::RAW_SECTION){$secName=substr($secName,0,-1);}else{$tmp=array();foreach($secData 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 new 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 new Nette\InvalidStateException("Invalid section [$secName] in file '$file'.");}}if(is_array($secData)&&is_array($cursor)){$secData=Helpers::merge($secData,$cursor);}$cursor=$secData;}return$data;}public function dump(array$data){$output=array();foreach($data 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 static function build($input,&$output,$prefix){foreach($input 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 new Nette\InvalidArgumentException(sprintf("The '%s' item must be scalar or array, %s given.",$prefix.$key,gettype($val)));}}}}process((array)Neon\Neon::decode(file_get_contents($file)));}private function process(array$arr){$res=array();foreach($arr as$key=>$val){if(substr($key,-1)===self::PREVENT_MERGING){if(!is_array($val)&&$val!==NULL){throw new 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+)\z#',$key,$matches)){if(!is_array($val)&&$val!==NULL){throw new 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 new Nette\InvalidStateException("Duplicated key '$key'.");}}if(is_array($val)){$val=$this->process($val);}elseif($val instanceof Neon\Entity){$val=(object)array('value'=>$val->value,'attributes'=>$this->process($val->attributes));}$res[$key]=$val;}return$res;}public function dump(array$data){$tmp=array();foreach($data as$name=>$secData){if($parent=Helpers::takeParent($secData)){$name.=' '.self::INHERITING_SEPARATOR.' '.$parent;}$tmp[$name]=$secData;}return"# generated by Nette\n\n".Neon\Neon::encode($tmp,Neon\Neon::BLOCK);}}$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;}}public static function takeParent(&$data){if(is_array($data)&&isset($data[self::EXTENDS_KEY])){$parent=$data[self::EXTENDS_KEY];unset($data[self::EXTENDS_KEY]);return$parent;}}public static function isOverwriting(&$data){return is_array($data)&&isset($data[self::EXTENDS_KEY])&&$data[self::EXTENDS_KEY]===self::OVERWRITE;}public static function isInheriting(&$data){return is_array($data)&&isset($data[self::EXTENDS_KEY])&&$data[self::EXTENDS_KEY]!==self::OVERWRITE;}}'Nette\DI\Config\Adapters\PhpAdapter','ini'=>'Nette\DI\Config\Adapters\IniAdapter','neon'=>'Nette\DI\Config\Adapters\NeonAdapter');private$dependencies=array();public function load($file,$section=NULL){if(!is_file($file)||!is_readable($file)){throw new Nette\FileNotFoundException("File '$file' is missing or is not readable.");}$this->dependencies[]=realpath($file);$data=$this->getAdapter($file)->load($file);if($section){if(isset($data[self::INCLUDES_KEY])){throw new 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 Helpers::merge($data,$merged);}public function save($data,$file){if(file_put_contents($file,$this->getAdapter($file)->dump($data))===FALSE){throw new Nette\IOException("Cannot write file '$file'.");}}public function getDependencies(){return array_unique($this->dependencies);}public function addAdapter($extension,$adapter){$this->adapters[strtolower($extension)]=$adapter;return$this;}private function getAdapter($file){$extension=strtolower(pathinfo($file,PATHINFO_EXTENSION));if(!isset($this->adapters[$extension])){throw new Nette\InvalidArgumentException("Unknown file extension '$file'.");}return is_object($this->adapters[$extension])?$this->adapters[$extension]:new$this->adapters[$extension];}private function 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;}}parameters=$params+$this->parameters;}public function getParameters(){return$this->parameters;}public function addService($name,$service){if(func_num_args()>2){throw new Nette\DeprecatedException('Parameter $meta has been removed.');}elseif(!is_string($name)||!$name){throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.',gettype($name)));}elseif(isset($this->registry[$name])){throw new Nette\InvalidStateException("Service '$name' already exists.");}elseif(is_string($service)||is_array($service)||$service instanceof\Closure||$service instanceof Nette\Callback){trigger_error(sprintf('Passing factories to %s() is deprecated; pass the object itself.',__METHOD__),E_USER_DEPRECATED);$service=is_string($service)&&!preg_match('#\x00|:#',$service)?new$service:call_user_func($service,$this);}if(!is_object($service)){throw new Nette\InvalidArgumentException(sprintf('Service must be a object, %s given.',gettype($service)));}$this->registry[$name]=$service;return$this;}public function removeService($name){unset($this->registry[$name]);}public function getService($name){if(!isset($this->registry[$name])){$this->registry[$name]=$this->createService($name);}return$this->registry[$name];}public function hasService($name){return isset($this->registry[$name])||method_exists($this,$method=Container::getMethodName($name))&&$this->getReflection()->getMethod($method)->getName()===$method;}public function isCreated($name){if(!$this->hasService($name)){throw new MissingServiceException("Service '$name' not found.");}return isset($this->registry[$name]);}public function createService($name,array$args=array()){$method=Container::getMethodName($name);if(isset($this->creating[$name])){throw new Nette\InvalidStateException(sprintf('Circular reference detected for services: %s.',implode(', ',array_keys($this->creating))));}elseif(!method_exists($this,$method)||$this->getReflection()->getMethod($method)->getName()!==$method){throw new MissingServiceException("Service '$name' not found.");}$this->creating[$name]=TRUE;try{$service=call_user_func_array(array($this,$method),$args);}catch(\Exception$e){unset($this->creating[$name]);throw$e;}unset($this->creating[$name]);if(!is_object($service)){throw new Nette\UnexpectedValueException("Unable to create service '$name', value returned by method $method() is not object.");}return$service;}public function getByType($class,$need=TRUE){$names=$this->findByType($class);if(!$names){if($need){throw new MissingServiceException("Service of type $class not found.");}}elseif(count($names)>1){throw new MissingServiceException("Multiple services of type $class found: ".implode(', ',$names).'.');}else{return$this->getService($names[0]);}}public function findByType($class){$class=ltrim(strtolower($class),'\\');return isset($this->meta[self::TYPES][$class])?$this->meta[self::TYPES][$class]:array();}public function findByTag($tag){return isset($this->meta[self::TAGS][$tag])?$this->meta[self::TAGS][$tag]:array();}public function createInstance($class,array$args=array()){$rc=Nette\Reflection\ClassType::from($class);if(!$rc->isInstantiable()){throw new ServiceCreationException("Class $class is not instantiable.");}elseif($constructor=$rc->getConstructor()){return$rc->newInstanceArgs(Helpers::autowireArguments($constructor,$args,$this));}elseif($args){throw new ServiceCreationException("Unable to pass arguments, class $class has no constructor.");}return new$class;}public function callInjects($service){if(!is_object($service)){throw new Nette\InvalidArgumentException(sprintf('Service must be object, %s given.',gettype($service)));}foreach(array_reverse(get_class_methods($service))as$method){if(substr($method,0,6)==='inject'){$this->callMethod(array($service,$method));}}foreach(Helpers::getInjectProperties(Nette\Reflection\ClassType::from($service),$this)as$property=>$type){$service->$property=$this->getByType($type);}}public function callMethod($function,array$args=array()){return call_user_func_array($function,Helpers::autowireArguments(Nette\Utils\Callback::toReflection($function),$args,$this));}public function expand($s){return Helpers::expand($s,$this->parameters);}public function&__get($name){$this->error(__METHOD__,'getService');$tmp=$this->getService($name);return$tmp;}public function __set($name,$service){$this->error(__METHOD__,'addService');$this->addService($name,$service);}public function __isset($name){$this->error(__METHOD__,'hasService');return$this->hasService($name);}public function __unset($name){$this->error(__METHOD__,'removeService');$this->removeService($name);}private function error($oldName,$newName){if(empty($this->parameters['container']['accessors'])){trigger_error("$oldName() is deprecated; use $newName() or enable nette.container.accessors in configuration.",E_USER_DEPRECATED);}}public static function getMethodName($name){$uname=ucfirst($name);return'createService'.((string)$name===$uname?'__':'').str_replace('.','__',$uname);}}definitions[$name])){throw new Nette\InvalidStateException("Service '$name' has already been added.");}return$this->definitions[$name]=$definition?:new ServiceDefinition;}public function removeDefinition($name){unset($this->definitions[$name]);}public function getDefinition($name){if(!isset($this->definitions[$name])){throw new MissingServiceException("Service '$name' not found.");}return$this->definitions[$name];}public function getDefinitions(){return$this->definitions;}public function hasDefinition($name){return isset($this->definitions[$name]);}public function getByType($class){if($this->currentService!==NULL&&Reflection\ClassType::from($this->definitions[$this->currentService]->class)->is($class)){return$this->currentService;}$lower=ltrim(strtolower($class),'\\');if(!isset($this->classes[$lower])){return;}elseif(count($this->classes[$lower])===1){return$this->classes[$lower][0];}else{throw new ServiceCreationException("Multiple services of type $class found: ".implode(', ',$this->classes[$lower]));}}public function findByTag($tag){$found=array();foreach($this->definitions as$name=>$def){if(isset($def->tags[$tag])){$found[$name]=$def->tags[$tag];}}return$found;}public function autowireArguments($class,$method,array$arguments){$rc=Reflection\ClassType::from($class);if(!$rc->hasMethod($method)){if(!Nette\Utils\Arrays::isList($arguments)){throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");}return$arguments;}$rm=$rc->getMethod($method);if(!$rm->isPublic()){throw new ServiceCreationException("$rm is not callable.");}$this->addDependency($rm->getFileName());return Helpers::autowireArguments($rm,$arguments,$this);}public function prepareClassList(){unset($this->definitions[self::THIS_CONTAINER]);$this->addDefinition(self::THIS_CONTAINER)->setClass('Nette\DI\Container');$this->classes=FALSE;foreach($this->definitions as$name=>$def){if(!$def->implement){continue;}if(!interface_exists($def->implement)){throw new ServiceCreationException("Interface $def->implement used in service '$name' not found.");}$rc=Reflection\ClassType::from($def->implement);$method=$rc->hasMethod('create')?$rc->getMethod('create'):($rc->hasMethod('get')?$rc->getMethod('get'):NULL);if(count($rc->getMethods())!==1||!$method||$method->isStatic()){throw new ServiceCreationException("Interface $def->implement used in service '$name' must have just one non-static method create() or get().");}$def->implement=$rc->getName();$def->implementType=$rc->hasMethod('create')?'create':'get';if(!$def->class&&empty($def->factory->entity)){$returnType=$method->getAnnotation('return');if(!$returnType){throw new ServiceCreationException("Method $method used in service '$name' has no @return annotation.");}$returnType=Reflection\AnnotationsParser::expandClassName(preg_replace('#[|\s].*#','',$returnType),$rc);if(!class_exists($returnType)){throw new ServiceCreationException("Please check a @return annotation of the $method method. Class '$returnType' cannot be found.");}$def->setClass($returnType);}if($method->getName()==='get'){if($method->getParameters()){throw new ServiceCreationException("Method $method used in service '$name' must have no arguments.");}if(empty($def->factory->entity)){$def->setFactory('@\\'.ltrim($def->class,'\\'));}elseif(!$this->getServiceName($def->factory->entity)){throw new ServiceCreationException("Invalid factory in service '$name' definition.");}}if(!$def->parameters){foreach($method->getParameters()as$param){$paramDef=($param->isArray()?'array':$param->getClassName()).' '.$param->getName();if($param->isOptional()){$def->parameters[$paramDef]=$param->getDefaultValue();}else{$def->parameters[]=$paramDef;}}}}foreach($this->definitions as$name=>$def){if(!$def->factory||!$def->factory->entity){if(!$def->class){throw new ServiceCreationException("Class and factory are missing in service '$name' definition.");}if($def->factory){$def->factory->entity=$def->class;}else{$def->factory=new Statement($def->class);}}}foreach($this->definitions as$name=>$def){$factory=$def->factory->entity=$this->normalizeEntity($def->factory->entity);if(is_string($factory)&&preg_match('#^[\w\\\\]+\z#',$factory)&&$factory!==self::THIS_SERVICE){if(!class_exists($factory)||!Reflection\ClassType::from($factory)->isInstantiable()){throw new ServiceCreationException("Class $factory used in service '$name' not found or is not instantiable.");}}}foreach($this->definitions as$name=>$def){$this->resolveClass($name);if(!$def->class){continue;}elseif(!class_exists($def->class)&&!interface_exists($def->class)){throw new ServiceCreationException("Class or interface $def->class used in service '$name' not found.");}else{$def->class=Reflection\ClassType::from($def->class)->getName();}}$this->classes=array();foreach($this->definitions as$name=>$def){$class=$def->implement?:$def->class;if($def->autowired&&$class){foreach(class_parents($class)+class_implements($class)+array($class)as$parent){$this->classes[strtolower($parent)][]=(string)$name;}}}foreach($this->excludedClasses as$class){foreach(class_parents($class)+class_implements($class)+array($class)as$parent){unset($this->classes[strtolower($parent)]);}}foreach($this->classes as$class=>$foo){$this->addDependency(Reflection\ClassType::from($class)->getFileName());}}private function resolveClass($name,$recursive=array()){if(isset($recursive[$name])){throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.',implode(', ',array_keys($recursive))));}$recursive[$name]=TRUE;$def=$this->definitions[$name];$factory=$def->factory->entity;if($def->class){return$def->class;}elseif(is_array($factory)){if($service=$this->getServiceName($factory[0])){if(Strings::contains($service,'\\')){$factory[0]=$service;}else{$factory[0]=$this->resolveClass($service,$recursive);if(!$factory[0]){return;}if($this->definitions[$service]->implement&&$factory[1]==='create'){return$def->class=$factory[0];}}}try{$reflection=Nette\Utils\Callback::toReflection($factory);}catch(\ReflectionException$e){}if(isset($e)||!is_callable($factory)){throw new ServiceCreationException(sprintf("Factory '%s' used in service '%s' is not callable.",Nette\Utils\Callback::toString($factory),$name));}$def->class=preg_replace('#[|\s].*#','',$reflection->getAnnotation('return'));if($def->class&&$reflection instanceof\ReflectionMethod){$def->class=Reflection\AnnotationsParser::expandClassName($def->class,$reflection->getDeclaringClass());}}elseif($service=$this->getServiceName($factory)){if(!$def->implement){$def->autowired=FALSE;}if(Strings::contains($service,'\\')){return$def->class=$service;}if($this->definitions[$service]->implement){$def->autowired=FALSE;}return$def->class=$this->definitions[$service]->implement?:$this->resolveClass($service,$recursive);}else{return$def->class=$factory;}}public function addExcludedClasses(array$classes){$this->excludedClasses=array_merge($this->excludedClasses,$classes);return$this;}public function addDependency($file){$this->dependencies[$file]=TRUE;return$this;}public function getDependencies(){unset($this->dependencies[FALSE]);return array_keys($this->dependencies);}public function generateClasses($className='Container',$parentName='Nette\DI\Container'){$this->generatedClasses=array();$this->prepareClassList();$containerClass=$this->generatedClasses[]=new Nette\PhpGenerator\ClassType($className);$containerClass->setExtends($parentName);$containerClass->addMethod('__construct')->addBody('parent::__construct(?);',array($this->parameters));$definitions=$this->definitions;ksort($definitions);$meta=$containerClass->addProperty('meta',array())->setVisibility('protected')->setValue(array(Container::TYPES=>$this->classes));foreach($definitions as$name=>$def){foreach($def->tags as$tag=>$value){$meta->value[Container::TAGS][$tag][$name]=$value;}}foreach($definitions as$name=>$def){try{$name=(string)$name;$methodName=Container::getMethodName($name);if(!PhpHelpers::isIdentifier($methodName)){throw new ServiceCreationException('Name contains invalid characters.');}$containerClass->addMethod($methodName)->addDocument('@return '.($def->implement?:$def->class))->setBody($name===self::THIS_CONTAINER?'return $this;':$this->generateService($name))->setParameters($def->implement?array():$this->convertParameters($def->parameters));}catch(\Exception$e){throw new ServiceCreationException("Service '$name': ".$e->getMessage(),NULL,$e);}}return$this->generatedClasses;}private function generateService($name){$this->currentService=NULL;$def=$this->definitions[$name];$serviceRef=$this->getServiceName($def->factory->entity);$factory=$serviceRef&&!$def->factory->arguments&&!$def->setup&&$def->implementType!=='create'?new Statement(array('@'.ContainerBuilder::THIS_CONTAINER,'getService'),array($serviceRef)):$def->factory;$code='$service = '.$this->formatStatement($factory).";\n";$this->currentService=$name;if($def->class&&$def->class!==$def->factory->entity&&!$serviceRef){$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."));}$setups=(array)$def->setup;if($def->inject&&$def->class){$injects=array();foreach(Helpers::getInjectProperties(Reflection\ClassType::from($def->class),$this)as$property=>$type){$injects[]=new Statement('$'.$property,array('@\\'.ltrim($type,'\\')));}foreach(get_class_methods($def->class)as$method){if(substr($method,0,6)==='inject'){$injects[]=new Statement($method);}}foreach($injects as$inject){foreach($setups as$key=>$setup){if($setup->entity===$inject->entity){$inject=$setup;unset($setups[$key]);}}array_unshift($setups,$inject);}}foreach($setups as$setup){if(is_string($setup->entity)&&strpbrk($setup->entity,':@?')===FALSE){$setup->entity=array('@self',$setup->entity);}$code.=$this->formatStatement($setup).";\n";}$code.='return $service;';if(!$def->implement){return$code;}$factoryClass=$this->generatedClasses[]=new Nette\PhpGenerator\ClassType;$factoryClass->setName(str_replace(array('\\','.'),'_',"{$this->generatedClasses[0]->name}_{$def->implement}Impl_{$name}"))->addImplement($def->implement)->setFinal(TRUE);$factoryClass->addProperty('container')->setVisibility('private');$factoryClass->addMethod('__construct')->addBody('$this->container = $container;')->addParameter('container')->setTypeHint('Nette\DI\Container');$factoryClass->addMethod($def->implementType)->setParameters($this->convertParameters($def->parameters))->setBody(str_replace('$this','$this->container',$code));return"return new {$factoryClass->name}(\$this);";}private function convertParameters(array$parameters){$res=array();foreach($parameters as$k=>$v){$tmp=explode(' ',is_int($k)?$v:$k);$param=$res[]=new Nette\PhpGenerator\Parameter;$param->setName(end($tmp));if(!is_int($k)){$param=$param->setOptional(TRUE)->setDefaultValue($v);}if(isset($tmp[1])){$param->setTypeHint($tmp[0]);}}return$res;}public function formatStatement(Statement$statement){$entity=$this->normalizeEntity($statement->entity);$arguments=$statement->arguments;if(is_string($entity)&&Strings::contains($entity,'?')){return$this->formatPhp($entity,$arguments);}elseif($service=$this->getServiceName($entity)){$params=array();foreach($this->definitions[$service]->parameters as$k=>$v){$params[]=preg_replace('#\w+\z#','\$$0',(is_int($k)?$v:$k)).(is_int($k)?'':' = '.PhpHelpers::dump($v));}$rm=new Reflection\GlobalFunction(create_function(implode(', ',$params),''));$arguments=Helpers::autowireArguments($rm,$arguments,$this);return$this->formatPhp('$this->?(?*)',array(Container::getMethodName($service),$arguments));}elseif($entity==='not'){return$this->formatPhp('!?',array($arguments[0]));}elseif(is_string($entity)){if($constructor=Reflection\ClassType::from($entity)->getConstructor()){$this->addDependency($constructor->getFileName());$arguments=Helpers::autowireArguments($constructor,$arguments,$this);}elseif($arguments){throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");}return$this->formatPhp("new $entity".($arguments?'(?*)':''),array($arguments));}elseif(!Nette\Utils\Arrays::isList($entity)||count($entity)!==2){throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.',PhpHelpers::dump($entity)));}elseif($entity[0]===''){return$this->formatPhp("$entity[1](?*)",array($arguments));}elseif(Strings::contains($entity[1],'$')){Validators::assert($arguments,'list:1',"setup arguments for '".Nette\Utils\Callback::toString($entity)."'");if($this->getServiceName($entity[0])){return$this->formatPhp('?->? = ?',array($entity[0],substr($entity[1],1),$arguments[0]));}else{return$this->formatPhp($entity[0].'::$? = ?',array(substr($entity[1],1),$arguments[0]));}}elseif($service=$this->getServiceName($entity[0])){$class=$this->definitions[$service]->implement;if(!$class||!method_exists($class,$entity[1])){$class=$this->definitions[$service]->class;}if($class){$arguments=$this->autowireArguments($class,$entity[1],$arguments);}return$this->formatPhp('?->?(?*)',array($entity[0],$entity[1],$arguments));}else{$arguments=$this->autowireArguments($entity[0],$entity[1],$arguments);return$this->formatPhp("$entity[0]::$entity[1](?*)",array($arguments));}}public function formatPhp($statement,$args){$that=$this;array_walk_recursive($args,function(&$val)use($that){if($val instanceof Statement){$val=ContainerBuilder::literal($that->formatStatement($val));}elseif($val===$that){$val=ContainerBuilder::literal('$this');}elseif($val instanceof ServiceDefinition){$val='@'.current(array_keys($that->definitions,$val,TRUE));}elseif(is_string($val)&&preg_match('#^[\w\\\\]*::[A-Z][A-Z0-9_]*\z#',$val,$m)){$val=ContainerBuilder::literal(ltrim($val,':'));}if(is_string($val)&&substr($val,0,1)==='@'){$pair=explode('::',$val,2);$name=$that->getServiceName($pair[0]);if(isset($pair[1])&&preg_match('#^[A-Z][A-Z0-9_]*\z#',$pair[1],$m)){$val=$that->definitions[$name]->class.'::'.$pair[1];}else{if($name===ContainerBuilder::THIS_CONTAINER){$val='$this';}elseif($name===$that->currentService){$val='$service';}else{$val=$that->formatStatement(new Statement(array('@'.ContainerBuilder::THIS_CONTAINER,'getService'),array($name)));}$val.=(isset($pair[1])?PhpHelpers::formatArgs('->?',array($pair[1])):'');}$val=ContainerBuilder::literal($val);}});return PhpHelpers::formatArgs($statement,$args);}public function expand($value){return Helpers::expand($value,$this->parameters);}public static function literal($phpCode){return new Nette\PhpGenerator\PhpLiteral($phpCode);}public function normalizeEntity($entity){if(is_string($entity)&&Strings::contains($entity,'::')&&!Strings::contains($entity,'?')){$entity=explode('::',$entity);}if(is_array($entity)&&$entity[0]instanceof ServiceDefinition){$entity[0]='@'.current(array_keys($this->definitions,$entity[0],TRUE));}elseif($entity instanceof ServiceDefinition){$entity='@'.current(array_keys($this->definitions,$entity,TRUE));}elseif(is_array($entity)&&$entity[0]===$this){$entity[0]='@'.ContainerBuilder::THIS_CONTAINER;}return$entity;}public function getServiceName($arg){if(!is_string($arg)||!preg_match('#^@[\w\\\\.].*\z#',$arg)){return FALSE;}$service=substr($arg,1);if($service===self::THIS_SERVICE){$service=$this->currentService;}if(Strings::contains($service,'\\')){if($this->classes===FALSE){return$service;}$res=$this->getByType($service);if(!$res){throw new ServiceCreationException("Reference to missing service of type $service.");}return$res;}if(!isset($this->definitions[$service])){throw new ServiceCreationException("Reference to missing service '$service'.");}return$service;}}tempDirectory=$tempDirectory;}public function create(){if(!class_exists($this->class)){$this->loadClass();}return new$this->class;}protected function generateCode(){$compiler=$this->createCompiler();$config=$this->generateConfig();$this->onCompile($this,$compiler,$config);$code="configFiles as$info){$code.="// source: $info[0] $info[1]\n";}$code.="\n".$compiler->compile($config,$this->class,$this->parentClass);if($this->autoRebuild!=='compat'){$this->dependencies=array_merge($this->dependencies,$compiler->getContainerBuilder()->getDependencies());}return$code;}protected function generateConfig(){$config=array();$loader=$this->createLoader();foreach($this->configFiles as$info){$config=Config\Helpers::merge($loader->load($info[0],$info[1]),$config);}$this->dependencies=array_merge($this->dependencies,$loader->getDependencies());return Config\Helpers::merge($config,$this->config);}private function loadClass(){$key=md5(serialize(array($this->config,$this->configFiles,$this->class,$this->parentClass)));$handle=fopen($file="$this->tempDirectory/$key.php",'c+');if(!$handle){throw new Nette\IOException("Unable to open or create file '$file'.");}flock($handle,LOCK_SH);$stat=fstat($handle);if($stat['size']){if($this->autoRebuild){foreach((array)@unserialize(file_get_contents($file.'.meta'))as$f=>$time){if(@filemtime($f)!==$time){goto write;}}}}else{write:ftruncate($handle,0);flock($handle,LOCK_EX);$stat=fstat($handle);if(!$stat['size']){$this->dependencies=array();$code=$this->generateCode();if(fwrite($handle,$code,strlen($code))!==strlen($code)){ftruncate($handle,0);throw new Nette\IOException("Unable to write file '$file'.");}$tmp=array();foreach($this->dependencies as$f){$tmp[$f]=@filemtime($f);}file_put_contents($file.'.meta',serialize($tmp));}flock($handle,LOCK_SH);}require$file;}protected function createCompiler(){return new Compiler;}protected function createLoader(){return new Config\Loader;}}getConfig()as$name=>$value){$class->methods['initialize']->addBody('define(?, ?);',array($name,$value));}}}getConfig()as$name=>$class){$this->compiler->addExtension($name,new$class);}}}methods['initialize'];foreach($this->getConfig()as$name=>$value){if(!is_scalar($value)){throw new 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 new Nette\NotSupportedException('Required function ini_set() is disabled.');}}}}$val){$res[$key]=self::expand($val,$params,$recursive);}return$res;}elseif($var instanceof\stdClass||$var instanceof Statement){$res=clone$var;foreach($var as$key=>$val){$res->$key=self::expand($val,$params,$recursive);}return$res;}elseif(!is_string($var)){return$var;}$parts=preg_split('#%([\w.-]*)%#i',$var,-1,PREG_SPLIT_DELIM_CAPTURE);$res='';foreach($parts as$n=>$part){if($n % 2===0){$res.=$part;}elseif($part===''){$res.='%';}elseif(isset($recursive[$part])){throw new Nette\InvalidArgumentException(sprintf('Circular reference detected for variables: %s.',implode(', ',array_keys($recursive))));}else{try{$val=Nette\Utils\Arrays::get($params,explode('.',$part));}catch(Nette\InvalidArgumentException$e){throw new Nette\InvalidArgumentException("Missing parameter '$part'.",0,$e);}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 new Nette\InvalidArgumentException("Unable to concatenate non-scalar parameter '$part' into '$var'.");}$res.=$val;}}return$res;}public static function 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++;}elseif(class_exists($class)||interface_exists($class)){throw new ServiceCreationException("Service of type {$class} needed by $method not found. Did you register it in configuration file?");}else{throw new ServiceCreationException("Class {$class} needed by $method not found. Check type hint and 'use' statements.");}}else{if($container instanceof ContainerBuilder){$res[$num]='@'.$res[$num];}$optCount=0;}}elseif($parameter->isOptional()){$res[$num]=$parameter->isDefaultValueAvailable()?$parameter->getDefaultValue():NULL;$optCount++;}else{throw new ServiceCreationException("Parameter $parameter has no type hint, so its value must be specified.");}}while(array_key_exists(++$num,$arguments)){$res[$num]=$arguments[$num];unset($arguments[$num]);$optCount=0;}if($arguments){throw new ServiceCreationException("Unable to pass specified arguments to $method.");}return$optCount?array_slice($res,0,-$optCount):$res;}public static function getInjectProperties(Nette\Reflection\ClassType$class,$container=NULL){$res=array();foreach($class->getProperties(\ReflectionProperty::IS_PUBLIC)as$property){$type=$property->getAnnotation('var');if(!$property->getAnnotation('inject')){continue;}elseif(!$type){throw new Nette\InvalidStateException("Property $property has no @var annotation.");}$type=Nette\Reflection\AnnotationsParser::expandClassName($type,$property->getDeclaringClass());if(!class_exists($type)&&!interface_exists($type)){throw new Nette\InvalidStateException("Class or interface '$type' used in @var annotation at $property not found. Check annotation and 'use' statements.");}elseif($container&&!$container->getByType($type,FALSE)){throw new ServiceCreationException("Service of type {$type} used in @var annotation at $property not found. Did you register it in configuration file?");}$res[$property->getName()]=$type;}return$res;}}class=$class;if($args){$this->setFactory($class,$args);}return$this;}public function setFactory($factory,array$args=array()){$this->factory=$factory instanceof Statement?$factory:new Statement($factory,$args);return$this;}public function setArguments(array$args=array()){if($this->factory){$this->factory->arguments=$args;}else{$this->setClass($this->class,$args);}return$this;}public function addSetup($target,array$args=array()){$this->setup[]=new Statement($target,$args);return$this;}public function addTag($tag,$attrs=TRUE){$this->tags[$tag]=$attrs;return$this;}public function getTag($tag){return isset($this->tags[$tag])?$this->tags[$tag]:NULL;}public function setShared($on){trigger_error(__METHOD__.'() is deprecated.',E_USER_DEPRECATED);$this->autowired=$on?$this->autowired:FALSE;return$this;}public function isShared(){trigger_error(__METHOD__.'() is deprecated.',E_USER_DEPRECATED);}}entity=$entity;$this->arguments=$arguments;}}callback=$callback;}public function accept(){return call_user_func($this->callback,$this->current(),$this->key(),$this);}}select($mask,'isDir')->select($mask,'isFile');}public static function findFiles($mask){if(!is_array($mask)){$mask=func_get_args();}$finder=new static;return$finder->select($mask,'isFile');}public static function findDirectories($mask){if(!is_array($mask)){$mask=func_get_args();}$finder=new static;return$finder->select($mask,'isDir');}private function select($masks,$type){$this->cursor=&$this->groups[];$pattern=self::buildPattern($masks);if($type||$pattern){$this->filter(function($file)use($type,$pattern){return!$file->isDot()&&(!$type||$file->$type())&&(!$pattern||preg_match($pattern,'/'.strtr($file->getSubPathName(),'\\','/')));});}return$this;}public function in($path){if(!is_array($path)){$path=func_get_args();}$this->maxDepth=0;return$this->from($path);}public function from($path){if($this->paths){throw new Nette\InvalidStateException('Directory to search has already been specified.');}if(!is_array($path)){$path=func_get_args();}$this->paths=$path;$this->cursor=&$this->exclude;return$this;}public function childFirst(){$this->order=RecursiveIteratorIterator::CHILD_FIRST;return$this;}private static function buildPattern($masks){$pattern=array();foreach($masks as$mask){$mask=rtrim(strtr($mask,'\\','/'),'/');$prefix='';if($mask===''){continue;}elseif($mask==='*'){return NULL;}elseif($mask[0]==='/'){$mask=ltrim($mask,'/');$prefix='(?<=^/)';}$pattern[]=$prefix.strtr(preg_quote($mask,'#'),array('\*\*'=>'.*','\*'=>'[^/]*','\?'=>'[^/]','\[\!'=>'[^','\['=>'[','\]'=>']','\-'=>'-'));}return$pattern?'#/('.implode('|',$pattern).')\z#i':NULL;}public function getIterator(){if(!$this->paths){throw new Nette\InvalidStateException('Call in() or from() to specify directory to search.');}elseif(count($this->paths)===1){return$this->buildIterator($this->paths[0]);}else{$iterator=new\AppendIterator();$iterator->append($workaround=new\ArrayIterator(array('workaround PHP bugs #49104, #63077')));foreach($this->paths as$path){$iterator->append($this->buildIterator($path));}unset($workaround[0]);return$iterator;}}private function buildIterator($path){$iterator=new\RecursiveDirectoryIterator($path,\RecursiveDirectoryIterator::FOLLOW_SYMLINKS);if($this->exclude){$filters=$this->exclude;$iterator=new RecursiveCallbackFilterIterator($iterator,function($foo,$foo,$file)use($filters){if(!$file->isDot()&&!$file->isFile()){foreach($filters as$filter){if(!call_user_func($filter,$file)){return FALSE;}}}return TRUE;});}if($this->maxDepth!==0){$iterator=new RecursiveIteratorIterator($iterator,$this->order);$iterator->setMaxDepth($this->maxDepth);}if($this->groups){$groups=$this->groups;$iterator=new CallbackFilterIterator($iterator,function($foo,$foo,$file)use($groups){foreach($groups as$filters){foreach($filters as$filter){if(!call_user_func($filter,$file)){continue 2;}}return TRUE;}return FALSE;});}return$iterator;}public function exclude($masks){if(!is_array($masks)){$masks=func_get_args();}$pattern=self::buildPattern($masks);if($pattern){$this->filter(function($file)use($pattern){return!preg_match($pattern,'/'.strtr($file->getSubPathName(),'\\','/'));});}return$this;}public function filter($callback){$this->cursor[]=$callback;return$this;}public function limitDepth($depth){$this->maxDepth=$depth;return$this;}public function size($operator,$size=NULL){if(func_num_args()===1){if(!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?\z#i',$operator,$matches)){throw new Nette\InvalidArgumentException('Invalid size predicate format.');}list(,$operator,$size,$unit)=$matches;static$units=array(''=>1,'k'=>1e3,'m'=>1e6,'g'=>1e9);$size*=$units[strtolower($unit)];$operator=$operator?$operator:'=';}return$this->filter(function($file)use($operator,$size){return Finder::compare($file->getSize(),$operator,$size);});}public function date($operator,$date=NULL){if(func_num_args()===1){if(!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)\z#i',$operator,$matches)){throw new Nette\InvalidArgumentException('Invalid date predicate format.');}list(,$operator,$date)=$matches;$operator=$operator?$operator:'=';}$date=DateTime::from($date)->format('U');return$this->filter(function($file)use($operator,$date){return Finder::compare($file->getMTime(),$operator,$date);});}public static function compare($l,$operator,$r){switch($operator){case'>':return$l>$r;case'>=':return$l>=$r;case'<':return$l<$r;case'<=':return$l<=$r;case'=':case'==':return$l==$r;case'!':case'!=':case'<>':return$l!=$r;default:throw new Nette\InvalidArgumentException("Unknown operator $operator.");}}}getInnerIterator()->hasChildren();}public function getChildren(){return new static($this->getInnerIterator()->getChildren(),$this->callback);}}getForm(FALSE);if(!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValues($values,$erase);}return$this;}public function setValues($values,$erase=FALSE){if($values instanceof\Traversable){$values=iterator_to_array($values);}elseif(!is_array($values)){throw new Nette\InvalidArgumentException(sprintf('First parameter must be an array, %s given.',gettype($values)));}foreach($this->getComponents()as$name=>$control){if($control instanceof IControl){if(array_key_exists($name,$values)){$control->setValue($values[$name]);}elseif($erase){$control->setValue(NULL);}}elseif($control instanceof Container){if(array_key_exists($name,$values)){$control->setValues($values[$name],$erase);}elseif($erase){$control->setValues(array(),$erase);}}}return$this;}public function getValues($asArray=FALSE){$values=$asArray?array():new Nette\Utils\ArrayHash;foreach($this->getComponents()as$name=>$control){if($control instanceof IControl&&!$control->isOmitted()){$values[$name]=$control->getValue();}elseif($control instanceof Container){$values[$name]=$control->getValues($asArray);}}return$values;}public function isValid(){if(!$this->validated){if($this->getErrors()){return FALSE;}$this->validate();}return!$this->getErrors();}public function validate(array$controls=NULL){foreach($controls===NULL?$this->getControls():$controls as$control){$control->validate();}$this->onValidate($this);$this->validated=TRUE;}public function getErrors(){$errors=array();foreach($this->getControls()as$control){$errors=array_merge($errors,$control->getErrors());}return array_unique($errors);}public function setCurrentGroup(ControlGroup$group=NULL){$this->currentGroup=$group;return$this;}public function getCurrentGroup(){return$this->currentGroup;}public function addComponent(Nette\ComponentModel\IComponent$component,$name,$insertBefore=NULL){parent::addComponent($component,$name,$insertBefore);if($this->currentGroup!==NULL&&$component instanceof IControl){$this->currentGroup->add($component);}return$this;}public function getControls(){return$this->getComponents(TRUE,'Nette\Forms\IControl');}public function getForm($need=TRUE){return$this->lookup('Nette\Forms\Form',$need);}public function addText($name,$label=NULL,$cols=NULL,$maxLength=NULL){$control=new Controls\TextInput($label,$maxLength);$control->setAttribute('size',$cols);return$this[$name]=$control;}public function addPassword($name,$label=NULL,$cols=NULL,$maxLength=NULL){$control=new Controls\TextInput($label,$maxLength);$control->setAttribute('size',$cols);return$this[$name]=$control->setType('password');}public function addTextArea($name,$label=NULL,$cols=NULL,$rows=NULL){$control=new Controls\TextArea($label);$control->setAttribute('cols',$cols)->setAttribute('rows',$rows);return$this[$name]=$control;}public function addUpload($name,$label=NULL,$multiple=FALSE){return$this[$name]=new Controls\UploadControl($label,$multiple);}public function addHidden($name,$default=NULL){$control=new Controls\HiddenField;$control->setDefaultValue($default);return$this[$name]=$control;}public function addCheckbox($name,$caption=NULL){return$this[$name]=new Controls\Checkbox($caption);}public function addRadioList($name,$label=NULL,array$items=NULL){return$this[$name]=new Controls\RadioList($label,$items);}public function addCheckboxList($name,$label=NULL,array$items=NULL){return$this[$name]=new Controls\CheckboxList($label,$items);}public function addSelect($name,$label=NULL,array$items=NULL,$size=NULL){$control=new Controls\SelectBox($label,$items);if($size>1){$control->setAttribute('size',(int)$size);}return$this[$name]=$control;}public function addMultiSelect($name,$label=NULL,array$items=NULL,$size=NULL){$control=new Controls\MultiSelectBox($label,$items);if($size>1){$control->setAttribute('size',(int)$size);}return$this[$name]=$control;}public function addSubmit($name,$caption=NULL){return$this[$name]=new Controls\SubmitButton($caption);}public function addButton($name,$caption=NULL){return$this[$name]=new Controls\Button($caption);}public function addImage($name,$src=NULL,$alt=NULL){return$this[$name]=new Controls\ImageButton($src,$alt);}public function addContainer($name){$control=new Container;$control->currentGroup=$this->currentGroup;return$this[$name]=$control;}public function offsetSet($name,$component){$this->addComponent($component,$name);}public function offsetGet($name){return$this->getComponent($name,TRUE);}public function offsetExists($name){return$this->getComponent($name,FALSE)!==NULL;}public function offsetUnset($name){$component=$this->getComponent($name,FALSE);if($component!==NULL){$this->removeComponent($component);}}public function __clone(){throw new Nette\NotImplementedException('Form cloning is not supported yet.');}}controls=new\SplObjectStorage;}public function add(){foreach(func_get_args()as$num=>$item){if($item instanceof IControl){$this->controls->attach($item);}elseif($item instanceof\Traversable||is_array($item)){foreach($item as$control){$this->controls->attach($control);}}else{throw new Nette\InvalidArgumentException("Only IFormControl items are allowed, the #$num parameter is invalid.");}}return$this;}public function getControls(){return iterator_to_array($this->controls);}public function setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}public function getOption($key,$default=NULL){return isset($this->options[$key])?$this->options[$key]:$default;}public function getOptions(){return$this->options;}}monitor('Nette\Forms\Form');parent::__construct();$this->control=Html::el('input',array('type'=>NULL,'name'=>NULL));$this->label=Html::el('label');$this->caption=$caption;$this->rules=new Nette\Forms\Rules($this);$this->setValue(NULL);}protected function attached($form){if(!$this->isDisabled()&&$form instanceof Form&&$form->isAnchored()&&$form->isSubmitted()){$this->loadHttpData();}}public function getForm($need=TRUE){return$this->lookup('Nette\Forms\Form',$need);}public function loadHttpData(){$this->setValue($this->getHttpData(Form::DATA_TEXT));}public function getHttpData($type,$htmlTail=NULL){return$this->getForm()->getHttpData($type,$this->getHtmlName().$htmlTail);}public function getHtmlName(){return Nette\Forms\Helpers::generateHtmlName($this->lookupPath('Nette\Forms\Form'));}public function setValue($value){$this->value=$value;return$this;}public function getValue(){return$this->value;}public function isFilled(){$value=$this->getValue();return$value!==NULL&&$value!==array()&&$value!=='';}public function setDefaultValue($value){$form=$this->getForm(FALSE);if($this->isDisabled()||!$form||!$form->isAnchored()||!$form->isSubmitted()){$this->setValue($value);}return$this;}public function setDisabled($value=TRUE){if($this->disabled=(bool)$value){$this->omitted=TRUE;$this->setValue(NULL);}return$this;}public function isDisabled(){return$this->disabled===TRUE;}public function setOmitted($value=TRUE){$this->omitted=(bool)$value;return$this;}public function isOmitted(){return$this->omitted;}public function getControl(){$this->setOption('rendered',TRUE);$el=clone$this->control;return$el->addAttributes(array('name'=>$this->getHtmlName(),'id'=>$this->getHtmlId(),'required'=>$this->isRequired(),'disabled'=>$this->isDisabled(),'data-nette-rules'=>self::exportRules($this->rules)?:NULL));}public function getLabel($caption=NULL){$label=clone$this->label;$label->for=$this->getHtmlId();$label->setText($this->translate($caption===NULL?$this->caption:$caption));return$label;}public function getControlPrototype(){return$this->control;}public function getLabelPrototype(){return$this->label;}public function setHtmlId($id){$this->control->id=$id;return$this;}public function getHtmlId(){if(!isset($this->control->id)){$this->control->id=sprintf(self::$idMask,$this->lookupPath());}return$this->control->id;}public function setAttribute($name,$value=TRUE){$this->control->$name=$value;return$this;}public function setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->translator=$translator;return$this;}public function getTranslator(){if($this->translator===TRUE){return$this->getForm(FALSE)?$this->getForm()->getTranslator():NULL;}return$this->translator;}public function translate($value,$count=NULL){if($translator=$this->getTranslator()){$tmp=is_array($value)?array(&$value):array(array(&$value));foreach($tmp[0]as&$v){if($v!=NULL&&!$v instanceof Html){$v=$translator->translate((string)$v,$count);}}}return$value;}public function addRule($validator,$message=NULL,$arg=NULL){$this->rules->addRule($validator,$message,$arg);return$this;}public function addCondition($validator,$value=NULL){return$this->rules->addCondition($validator,$value);}public function addConditionOn(IControl$control,$validator,$value=NULL){return$this->rules->addConditionOn($control,$validator,$value);}public function getRules(){return$this->rules;}public function setRequired($value=TRUE){$this->rules->setRequired($value);return$this;}public function isRequired(){return$this->rules->isRequired();}public function validate(){if($this->isDisabled()){return;}$this->cleanErrors();$this->rules->validate();}public function addError($message){$this->errors[]=$message;}public function getError(){return$this->errors?implode(' ',array_unique($this->errors)):NULL;}public function getErrors(){return array_unique($this->errors);}public function hasErrors(){return(bool)$this->errors;}public function cleanErrors(){$this->errors=array();}protected static function exportRules($rules){$payload=array();foreach($rules as$rule){if(!is_string($op=$rule->validator)){if(!Nette\Utils\Callback::isStatic($op)){continue;}$op=Nette\Utils\Callback::toString($op);}if($rule->branch){$item=array('op'=>($rule->isNegative?'~':'').$op,'rules'=>static::exportRules($rule->branch,FALSE),'control'=>$rule->control->getHtmlName());if($rule->branch->getToggles()){$item['toggle']=$rule->branch->getToggles();}}else{$item=array('op'=>($rule->isNegative?'~':'').$op,'msg'=>$rules->formatMessage($rule,FALSE));}if(is_array($rule->arg)){foreach($rule->arg as$key=>$value){$item['arg'][$key]=$value instanceof IControl?array('control'=>$value->getHtmlName()):$value;}}elseif($rule->arg!==NULL){$item['arg']=$rule->arg instanceof IControl?array('control'=>$rule->arg->getHtmlName()):$rule->arg;}$payload[]=$item;}return$payload;}public static function 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){continue 2;}}return FALSE;}return TRUE;}public static function validateNotEqual(IControl$control,$arg){return!static::validateEqual($control,$arg);}public static function validateFilled(IControl$control){return$control->isFilled();}public static function validateBlank(IControl$control){return!$control->isFilled();}public static function validateValid(IControl$control){return$control->getRules()->validate();}public static function validateRange(IControl$control,$range){return Validators::isInRange($control->getValue(),$range);}public static function validateMin(IControl$control,$minimum){return Validators::isInRange($control->getValue(),array($minimum,NULL));}public static function validateMax(IControl$control,$maximum){return Validators::isInRange($control->getValue(),array(NULL,$maximum));}public static function validateLength(IControl$control,$range){if(!is_array($range)){$range=array($range,$range);}$value=$control->getValue();return Validators::isInRange(is_array($value)?count($value):Nette\Utils\Strings::length($value),$range);}public static function validateMinLength(IControl$control,$length){return static::validateLength($control,array($length,NULL));}public static function validateMaxLength(IControl$control,$length){return static::validateLength($control,array(NULL,$length));}public function setOption($key,$value){if($value===NULL){unset($this->options[$key]);}else{$this->options[$key]=$value;}return$this;}public function getOption($key,$default=NULL){return isset($this->options[$key])?$this->options[$key]:$default;}public function getOptions(){return$this->options;}}control->type='button';}public function isFilled(){$value=$this->getValue();return$value!==NULL&&$value!==array();}public function getLabel($caption=NULL){return NULL;}public function getControl($caption=NULL){$this->setOption('rendered',TRUE);$el=clone$this->control;return$el->addAttributes(array('name'=>$this->getHtmlName(),'id'=>$this->getHtmlId(),'disabled'=>$this->isDisabled(),'value'=>$this->translate($caption===NULL?$this->caption:$caption)));}}control->type='checkbox';$this->wrapper=Nette\Utils\Html::el();}public function setValue($value){if(!is_scalar($value)&&$value!==NULL){throw new Nette\InvalidArgumentException(sprintf("Value must be scalar or NULL, %s given in field '%s'.",gettype($value),$this->name));}$this->value=(bool)$value;return$this;}public function isFilled(){return$this->getValue()!==FALSE;}public function getControl(){return$this->wrapper->setHtml($this->getLabelPart()->insert(0,$this->getControlPart()));}public function getLabel($caption=NULL){return NULL;}public function getControlPart(){return parent::getControl()->checked($this->value);}public function getLabelPart(){return parent::getLabel();}public function getSeparatorPrototype(){return$this->wrapper;}}control->type='checkbox';$this->separator=Html::el('br');}public function getControl(){$items=$this->getItems();reset($items);$input=parent::getControl();return Nette\Forms\Helpers::createInputList($this->translate($items),array_merge($input->attrs,array('id'=>NULL,'checked?'=>$this->value,'disabled:'=>$this->disabled,'required'=>NULL,'data-nette-rules:'=>array(key($items)=>$input->attrs['data-nette-rules']))),$this->label->attrs,$this->separator);}public function getLabel($caption=NULL){return parent::getLabel($caption)->for(NULL);}public function getSeparatorPrototype(){return$this->separator;}public function getControlPart($key){return parent::getControl()->addAttributes(array('id'=>$this->getHtmlId().'-'.$key,'checked'=>in_array($key,(array)$this->value,TRUE),'disabled'=>is_array($this->disabled)?isset($this->disabled[$key]):$this->disabled,'required'=>NULL,'value'=>$key));}public function getLabelPart($key){return parent::getLabel($this->items[$key])->for($this->getHtmlId().'-'.$key);}}setItems($items);}}public function loadHttpData(){$this->value=$this->getHttpData(Nette\Forms\Form::DATA_TEXT);if($this->value!==NULL){if(is_array($this->disabled)&&isset($this->disabled[$this->value])){$this->value=NULL;}else{$this->value=key(array($this->value=>NULL));}}}public function setValue($value){if($value!==NULL&&!array_key_exists((string)$value,$this->items)){$range=Nette\Utils\Strings::truncate(implode(', ',array_map(function($s){return var_export($s,TRUE);},array_keys($this->items))),70,'...');throw new Nette\InvalidArgumentException("Value '$value' is out of allowed range [$range] in field '{$this->name}'.");}$this->value=$value===NULL?NULL:key(array((string)$value=>NULL));return$this;}public function getValue(){return array_key_exists($this->value,$this->items)?$this->value:NULL;}public function getRawValue(){return$this->value;}public function isFilled(){return$this->getValue()!==NULL;}public function setItems(array$items,$useKeys=TRUE){$this->items=$useKeys?$items:array_combine($items,$items);return$this;}public function getItems(){return$this->items;}public function getSelectedItem(){$value=$this->getValue();return$value===NULL?NULL:$this->items[$value];}public function setDisabled($value=TRUE){if(!is_array($value)){return parent::setDisabled($value);}parent::setDisabled(FALSE);$this->disabled=array_fill_keys($value,TRUE);if(isset($this->disabled[$this->value])){$this->value=NULL;}return$this;}}setOmitted()->addRule(self::PROTECTION,$message);$this->monitor('Nette\Application\UI\Presenter');}protected function attached($parent){parent::attached($parent);if(!$this->session&&$parent instanceof Nette\Application\UI\Presenter){$this->session=$parent->getSession();}}public function getToken(){$session=$this->getSession()->getSection(__CLASS__);if(!isset($session->token)){$session->token=Nette\Utils\Random::generate();}return$session->token;}private function generateToken($random=NULL){if($random===NULL){$random=Nette\Utils\Random::generate(10);}return$random.base64_encode(sha1($this->getToken().$random,TRUE));}public function getControl(){return parent::getControl()->value($this->generateToken());}public static function validateCsrf(CsrfProtection$control){$value=$control->getValue();return$control->generateToken(substr($value,0,10))===$value;}private function getSession(){if(!$this->session){$this->session=new Nette\Http\Session($this->getForm()->httpRequest,new Nette\Http\Response);}return$this->session;}}control->type='hidden';if($persistentValue!==NULL){$this->unmonitor('Nette\Forms\Form');$this->persistValue=TRUE;$this->value=(string)$persistentValue;}}public function setValue($value){if(!is_scalar($value)&&$value!==NULL&&!method_exists($value,'__toString')){throw new Nette\InvalidArgumentException(sprintf("Value must be scalar or NULL, %s given in field '%s'.",gettype($value),$this->name));}if(!$this->persistValue){$this->value=(string)$value;}return$this;}public function getControl(){$this->setOption('rendered',TRUE);$el=clone$this->control;return$el->addAttributes(array('name'=>$this->getHtmlName(),'id'=>$this->getHtmlId(),'disabled'=>$this->isDisabled(),'value'=>$this->value));}public function getLabel($caption=NULL){return NULL;}public function addError($message){$this->getForm()->addError($message);}}control->type='image';$this->control->src=$src;$this->control->alt=$alt;}public function loadHttpData(){parent::loadHttpData();$this->value=$this->value?array((int)array_shift($this->value),(int)array_shift($this->value)):NULL;}public function getHtmlName(){return parent::getHtmlName().'[]';}}setItems($items);}}public function loadHttpData(){$this->value=array_keys(array_flip($this->getHttpData(Nette\Forms\Form::DATA_TEXT)));if(is_array($this->disabled)){$this->value=array_diff($this->value,array_keys($this->disabled));}}public function setValue($values){if(is_scalar($values)||$values===NULL){$values=(array)$values;}elseif(!is_array($values)){throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.",gettype($values),$this->name));}$flip=array();foreach($values as$value){if(!is_scalar($value)&&!method_exists($value,'__toString')){throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.",gettype($value),$this->name));}$flip[(string)$value]=TRUE;}$values=array_keys($flip);if($diff=array_diff($values,array_keys($this->items))){$range=Nette\Utils\Strings::truncate(implode(', ',array_map(function($s){return var_export($s,TRUE);},array_keys($this->items))),70,'...');$vals=(count($diff)>1?'s':'')." '".implode("', '",$diff)."'";throw new Nette\InvalidArgumentException("Value$vals are out of allowed range [$range] in field '{$this->name}'.");}$this->value=$values;return$this;}public function getValue(){return array_values(array_intersect($this->value,array_keys($this->items)));}public function getRawValue(){return$this->value;}public function isFilled(){return$this->getValue()!==array();}public function setItems(array$items,$useKeys=TRUE){$this->items=$useKeys?$items:array_combine($items,$items);return$this;}public function getItems(){return$this->items;}public function getSelectedItems(){return array_intersect_key($this->items,array_flip($this->value));}public function setDisabled($value=TRUE){if(!is_array($value)){return parent::setDisabled($value);}parent::setDisabled(FALSE);$this->disabled=array_fill_keys($value,TRUE);$this->value=array_diff($this->value,$value);return$this;}public function getHtmlName(){return parent::getHtmlName().'[]';}}$value){unset($items[$key]);if(is_array($value)){foreach($value as$val){$res[$key][(string)$val]=$val;}}else{$res[(string)$value]=$value;}}$items=$res;}$this->options=$items;return parent::setItems(Nette\Utils\Arrays::flatten($items,TRUE));}public function getControl(){$items=array();foreach($this->options as$key=>$value){$items[is_array($value)?$this->translate($key):$key]=$this->translate($value);}return Nette\Forms\Helpers::createSelectBox($items,array('selected?'=>$this->value,'disabled:'=>is_array($this->disabled)?$this->disabled:NULL))->addAttributes(parent::getControl()->attrs)->multiple(TRUE);}function getSelectedItem(){trigger_error(__METHOD__.'(TRUE) is deprecated; use getSelectedItems() instead.',E_USER_DEPRECATED);return$this->getSelectedItems();}}control->type='radio';$this->container=Html::el();$this->separator=Html::el('br');}public function getValue(){return parent::getValue();}public function getSeparatorPrototype(){return$this->separator;}public function getContainerPrototype(){return$this->container;}public function getControl($key=NULL){if($key!==NULL){trigger_error(sprintf('Partial %s() is deprecated; use getControlPart() instead.',__METHOD__),E_USER_DEPRECATED);return$this->getControlPart($key);}$input=parent::getControl();$ids=array();foreach($this->getItems()as$value=>$label){$ids[$value]=$input->id.'-'.$value;}return$this->container->setHtml(Nette\Forms\Helpers::createInputList($this->translate($this->getItems()),array_merge($input->attrs,array('id:'=>$ids,'checked?'=>$this->value,'disabled:'=>$this->disabled,'data-nette-rules:'=>array(key($ids)=>$input->attrs['data-nette-rules']))),array('for:'=>$ids),$this->separator));}public function getLabel($caption=NULL,$key=NULL){if($key!==NULL){trigger_error(sprintf('Partial %s() is deprecated; use getLabelPart() instead.',__METHOD__),E_USER_DEPRECATED);return$this->getLabelPart($key);}return parent::getLabel($caption)->for(NULL);}public function getControlPart($key){return parent::getControl()->addAttributes(array('id'=>$this->getHtmlId().'-'.$key,'checked'=>in_array($key,(array)$this->value,TRUE),'disabled'=>is_array($this->disabled)?isset($this->disabled[$key]):$this->disabled,'value'=>$key));}public function getLabelPart($key){return parent::getLabel($this->items[$key])->for($this->getHtmlId().'-'.$key);}}prompt=$prompt;return$this;}public function getPrompt(){return$this->prompt;}public function setItems(array$items,$useKeys=TRUE){if(!$useKeys){$res=array();foreach($items as$key=>$value){unset($items[$key]);if(is_array($value)){foreach($value as$val){$res[$key][(string)$val]=$val;}}else{$res[(string)$value]=$value;}}$items=$res;}$this->options=$items;return parent::setItems(Nette\Utils\Arrays::flatten($items,TRUE));}public function getControl(){$items=$this->prompt===FALSE?array():array(''=>$this->translate($this->prompt));foreach($this->options as$key=>$value){$items[is_array($value)?$this->translate($key):$key]=$this->translate($value);}return Nette\Forms\Helpers::createSelectBox($items,array('selected?'=>$this->value,'disabled:'=>is_array($this->disabled)?$this->disabled:NULL))->addAttributes(parent::getControl()->attrs);}public function validate(){parent::validate();if(!$this->isDisabled()&&$this->prompt===FALSE&&$this->getValue()===NULL&&$this->options){$this->addError(Nette\Forms\Rules::$defaultMessages[self::VALID]);}}}control->type='submit';$this->setOmitted(TRUE);}public function loadHttpData(){parent::loadHttpData();if($this->isFilled()){$this->getForm()->setSubmittedBy($this);}}public function isSubmittedBy(){return$this->getForm()->isSubmitted()===$this;}public function setValidationScope($scope=NULL){if($scope===NULL||$scope===TRUE){$this->validationScope=NULL;}else{$this->validationScope=array();foreach($scope?:array()as$control){if(!$control instanceof Nette\Forms\Container&&!$control instanceof Nette\Forms\IControl){throw new Nette\InvalidArgumentException('Validation scope accepts only Nette\Forms\Container or Nette\Forms\IControl instances.');}$this->validationScope[]=$control;}}return$this;}public function getValidationScope(){return$this->validationScope;}public function click(){$this->onClick($this);}public function getControl($caption=NULL){$scope=array();foreach((array)$this->validationScope as$control){$scope[]=$control->lookupPath('Nette\Forms\Form');}return parent::getControl($caption)->addAttributes(array('formnovalidate'=>$this->validationScope!==NULL,'data-nette-validation-scope'=>$scope?:NULL));}public static function validateSubmitted(SubmitButton$control){return$control->isSubmittedBy();}}control->setName('textarea');}public function getControl(){$value=$this->getValue();if($value===''){$value=$this->translate($this->emptyValue);}return parent::getControl()->setText($value);}}name));}$this->rawValue=$this->value=$value;return$this;}public function getValue(){$value=$this->value;if(!empty($this->control->maxlength)){$value=Nette\Utils\Strings::substring($value,0,$this->control->maxlength);}foreach($this->filters as$filter){$value=(string)call_user_func($filter,$value);}return$value===$this->translate($this->emptyValue)?'':$value;}public function setEmptyValue($value){$this->emptyValue=(string)$value;return$this;}public function getEmptyValue(){return$this->emptyValue;}public function addFilter($filter){$this->filters[]=Nette\Utils\Callback::check($filter);return$this;}public function getControl(){$el=parent::getControl();if($this->emptyValue!==''){$el->attrs['data-nette-empty-value']=$this->translate($this->emptyValue);}if(isset($el->placeholder)){$el->placeholder=$this->translate($el->placeholder);}return$el;}public function addRule($validator,$message=NULL,$arg=NULL){if($validator===Form::LENGTH||$validator===Form::MAX_LENGTH){$tmp=is_array($arg)?$arg[1]:$arg;if(is_scalar($tmp)){$this->control->maxlength=isset($this->control->maxlength)?min($this->control->maxlength,$tmp):$tmp;}}return parent::addRule($validator,$message,$arg);}public static function validateEmail(TextBase$control){return Validators::isEmail($control->getValue());}public static function validateUrl(TextBase$control){if(Validators::isUrl($value=$control->getValue())){return TRUE;}elseif(Validators::isUrl($value="http://$value")){$control->setValue($value);return TRUE;}return FALSE;}public static function validateRegexp(TextBase$control,$regexp){trigger_error('Validator REGEXP is deprecated; use PATTERN instead (which is matched against the entire value and is case sensitive).',E_USER_DEPRECATED);return(bool)Strings::match($control->getValue(),$regexp);}public static function validatePattern(TextBase$control,$pattern){return(bool)Strings::match($control->getValue(),"\x01^($pattern)\\z\x01u");}public static function validateInteger(TextBase$control){if(Validators::isNumericInt($value=$control->getValue())){if(!is_float($tmp=$value*1)){$control->setValue($tmp);}return TRUE;}return FALSE;}public static function validateFloat(TextBase$control){$value=self::filterFloat($control->getValue());if(Validators::isNumeric($value)){$control->setValue((float)$value);return TRUE;}return FALSE;}public static function filterFloat($s){return str_replace(array(' ',','),array('','.'),$s);}}control->type='text';$this->control->maxlength=$maxLength;}public function loadHttpData(){$this->setValue($this->getHttpData(Form::DATA_LINE));}public function setType($type){$this->control->type=$type;return$this;}public function getControl(){$input=parent::getControl();foreach($this->getRules()as$rule){if($rule->isNegative||$rule->branch){}elseif(in_array($rule->validator,array(Form::MIN,Form::MAX,Form::RANGE),TRUE)&&in_array($input->type,array('number','range','datetime-local','datetime','date','month','week','time'),TRUE)){if($rule->validator===Form::MIN){$range=array($rule->arg,NULL);}elseif($rule->validator===Form::MAX){$range=array(NULL,$rule->arg);}else{$range=$rule->arg;}if(isset($range[0])&&is_scalar($range[0])){$input->min=isset($input->min)?max($input->min,$range[0]):$range[0];}if(isset($range[1])&&is_scalar($range[1])){$input->max=isset($input->max)?min($input->max,$range[1]):$range[1];}}elseif($rule->validator===Form::PATTERN&&is_scalar($rule->arg)&&in_array($input->type,array('text','search','tel','url','email','password'),TRUE)){$input->pattern=$rule->arg;}}if($input->type!=='password'){$input->value=$this->rawValue===''?$this->translate($this->emptyValue):$this->rawValue;}return$input;}}control->type='file';$this->control->multiple=(bool)$multiple;}protected function attached($form){if($form instanceof Nette\Forms\Form){if($form->getMethod()!==Nette\Forms\Form::POST){throw new Nette\InvalidStateException('File upload requires method POST.');}$form->getElementPrototype()->enctype='multipart/form-data';}parent::attached($form);}public function loadHttpData(){$this->value=$this->getHttpData(Nette\Forms\Form::DATA_FILE);if($this->value===NULL){$this->value=new FileUpload(NULL);}}public function getHtmlName(){return parent::getHtmlName().($this->control->multiple?'[]':'');}public function setValue($value){return$this;}public function isFilled(){return$this->value instanceof FileUpload?$this->value->isOk():(bool)$this->value;}public static function validateFileSize(UploadControl$control,$limit){foreach(static::toArray($control->getValue())as$file){if($file->getSize()>$limit||$file->getError()===UPLOAD_ERR_INI_SIZE){return FALSE;}}return TRUE;}public static function validateMimeType(UploadControl$control,$mimeType){$mimeTypes=is_array($mimeType)?$mimeType:explode(',',$mimeType);foreach(static::toArray($control->getValue())as$file){$type=strtolower($file->getContentType());if(!in_array($type,$mimeTypes,TRUE)&&!in_array(preg_replace('#/.*#','/*',$type),$mimeTypes,TRUE)){return FALSE;}}return TRUE;}public static function validateImage(UploadControl$control){foreach(static::toArray($control->getValue())as$file){if(!$file->isImage()){return FALSE;}}return TRUE;}private static function toArray($value){return$value instanceof FileUpload?array($value):(array)$value;}}getElementPrototype()->id='frm-'.$name;$tracker=new Controls\HiddenField($name);$tracker->setOmitted();$this[self::TRACKER_ID]=$tracker;}parent::__construct(NULL,$name);}protected function validateParent(Nette\ComponentModel\IContainer$parent){parent::validateParent($parent);$this->monitor(__CLASS__);}protected function attached($obj){if($obj instanceof self){throw new Nette\InvalidStateException('Nested forms are forbidden.');}}public function getForm($need=TRUE){return$this;}public function setAction($url){$this->getElementPrototype()->action=$url;return$this;}public function getAction(){return$this->getElementPrototype()->action;}public function setMethod($method){if($this->httpData!==NULL){throw new Nette\InvalidStateException(__METHOD__.'() must be called until the form is empty.');}$this->getElementPrototype()->method=strtolower($method);return$this;}public function getMethod(){return$this->getElementPrototype()->method;}public function addProtection($message=NULL){return$this[self::PROTECTOR_ID]=new Controls\CsrfProtection($message);}public function addGroup($caption=NULL,$setAsCurrent=TRUE){$group=new ControlGroup;$group->setOption('label',$caption);$group->setOption('visual',TRUE);if($setAsCurrent){$this->setCurrentGroup($group);}if(!is_scalar($caption)||isset($this->groups[$caption])){return$this->groups[]=$group;}else{return$this->groups[$caption]=$group;}}public function removeGroup($name){if(is_string($name)&&isset($this->groups[$name])){$group=$this->groups[$name];}elseif($name instanceof ControlGroup&&in_array($name,$this->groups,TRUE)){$group=$name;$name=array_search($group,$this->groups,TRUE);}else{throw new Nette\InvalidArgumentException("Group not found in form '$this->name'");}foreach($group->getControls()as$control){$control->getParent()->removeComponent($control);}unset($this->groups[$name]);}public function getGroups(){return$this->groups;}public function getGroup($name){return isset($this->groups[$name])?$this->groups[$name]:NULL;}public function setTranslator(Nette\Localization\ITranslator$translator=NULL){$this->translator=$translator;return$this;}public function getTranslator(){return$this->translator;}public function isAnchored(){return TRUE;}public function isSubmitted(){if($this->submittedBy===NULL){$this->getHttpData();}return$this->submittedBy;}public function isSuccess(){return$this->isSubmitted()&&$this->isValid();}public function setSubmittedBy(ISubmitterControl$by=NULL){$this->submittedBy=$by===NULL?FALSE:$by;return$this;}public function getHttpData($type=NULL,$htmlName=NULL){if($this->httpData===NULL){if(!$this->isAnchored()){throw new Nette\InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');}$data=$this->receiveHttpData();$this->httpData=(array)$data;$this->submittedBy=is_array($data);}if($htmlName===NULL){return$this->httpData;}return Helpers::extractHttpData($this->httpData,$htmlName,$type);}public function fireEvents(){if(!$this->isSubmitted()){return;}elseif(!$this->getErrors()){$this->validate();}if($this->submittedBy instanceof ISubmitterControl){if($this->isValid()){$this->submittedBy->onClick($this->submittedBy);}else{$this->submittedBy->onInvalidClick($this->submittedBy);}}if($this->onSuccess){foreach($this->onSuccess as$handler){if(!$this->isValid()){$this->onError($this);break;}$params=Nette\Utils\Callback::toReflection($handler)->getParameters();$values=isset($params[1])?$this->getValues($params[1]->isArray()):NULL;Nette\Utils\Callback::invoke($handler,$this,$values);}}elseif(!$this->isValid()){$this->onError($this);}$this->onSubmit($this);}protected function 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(!$data){return;}}if($tracker=$this->getComponent(self::TRACKER_ID,FALSE)){if(!isset($data[self::TRACKER_ID])||$data[self::TRACKER_ID]!==$tracker->getValue()){return;}}return$data;}public function validate(array$controls=NULL){$this->cleanErrors();if($controls===NULL&&$this->submittedBy instanceof ISubmitterControl){$controls=$this->submittedBy->getValidationScope();}$this->validateMaxPostSize();parent::validate($controls);}public function validateMaxPostSize(){if(!$this->submittedBy||strcasecmp($this->getMethod(),'POST')||empty($_SERVER['CONTENT_LENGTH'])){return;}$maxSize=ini_get('post_max_size');$units=array('k'=>10,'m'=>20,'g'=>30);if(isset($units[$ch=strtolower(substr($maxSize,-1))])){$maxSize<<=$units[$ch];}if($maxSize>0&&$maxSize<$_SERVER['CONTENT_LENGTH']){$this->addError(sprintf(Rules::$defaultMessages[self::MAX_FILE_SIZE],$maxSize));}}public function addError($message){$this->errors[]=$message;}public function getErrors(){return array_unique(array_merge($this->errors,parent::getErrors()));}public function hasErrors(){return(bool)$this->getErrors();}public function cleanErrors(){$this->errors=array();}public function getOwnErrors(){return array_unique($this->errors);}public function getAllErrors(){trigger_error(__METHOD__.'() is deprecated; use getErrors() instead.',E_USER_DEPRECATED);return$this->getErrors();}public function getElementPrototype(){if(!$this->element){$this->element=Nette\Utils\Html::el('form');$this->element->action='';$this->element->method=self::POST;}return$this->element;}public function setRenderer(IFormRenderer$renderer=NULL){$this->renderer=$renderer;return$this;}public function getRenderer(){if($this->renderer===NULL){$this->renderer=new Rendering\DefaultFormRenderer;}return$this->renderer;}public function render(){$args=func_get_args();array_unshift($args,$this);echo call_user_func_array(array($this->getRenderer(),'render'),$args);}public function __toString(){try{return$this->getRenderer()->render($this);}catch(\Exception$e){if(func_num_args()){throw$e;}trigger_error("Exception in ".__METHOD__."(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}",E_USER_ERROR);}}private function getHttpRequest(){if(!$this->httpRequest){$factory=new Nette\Http\RequestFactory;$this->httpRequest=$factory->createHttpRequest();}return$this->httpRequest;}public function getToggles(){$toggles=array();foreach($this->getControls()as$control){$toggles=$control->getRules()->getToggleStates($toggles);}return$toggles;}}$v){$data[$k]=$v=static::sanitize($itype,$v);if($v===NULL){unset($data[$k]);}}if($type&Form::DATA_KEYS){return$data;}return array_values($data);}else{return static::sanitize($itype,$data);}}private static function sanitize($type,$value){if($type===Form::DATA_TEXT){return is_scalar($value)?Strings::normalizeNewLines($value):NULL;}elseif($type===Form::DATA_LINE){return is_scalar($value)?Strings::trim(strtr($value,"\r\n",' ')):NULL;}elseif($type===Form::DATA_FILE){return$value instanceof Nette\Http\FileUpload?$value:NULL;}else{throw new Nette\InvalidArgumentException('Unknown data type');}}public static function generateHtmlName($id){$name=str_replace(Nette\ComponentModel\IComponent::NAME_SEPARATOR,'][',$id,$count);if($count){$name=substr_replace($name,'',strpos($name,']'),1).']';}if(is_numeric($name)||in_array($name,self::$unsafeNames,TRUE)){$name='_'.$name;}return$name;}public static function createInputList(array$items,array$inputAttrs=NULL,array$labelAttrs=NULL,$wrapper=NULL){list($inputAttrs,$inputTag)=self::prepareAttrs($inputAttrs,'input');list($labelAttrs,$labelTag)=self::prepareAttrs($labelAttrs,'label');$res='';$input=Html::el();$label=Html::el();list($wrapper,$wrapperEnd)=$wrapper instanceof Html?array($wrapper->startTag(),$wrapper->endTag()):array((string)$wrapper,'');foreach($items as$value=>$caption){foreach($inputAttrs as$k=>$v){$input->attrs[$k]=isset($v[$value])?$v[$value]:NULL;}foreach($labelAttrs as$k=>$v){$label->attrs[$k]=isset($v[$value])?$v[$value]:NULL;}$input->value=$value;$res.=($res===''&&$wrapperEnd===''?'':$wrapper).$labelTag.$label->attributes().'>'.$inputTag.$input->attributes().(Html::$xhtml?' />':'>').($caption instanceof Html?$caption:htmlspecialchars($caption)).''.$wrapperEnd;}return$res;}public static function createSelectBox(array$items,array$optionAttrs=NULL){list($optionAttrs,$optionTag)=self::prepareAttrs($optionAttrs,'option');$option=Html::el();$res=$tmp='';foreach($items as$group=>$subitems){if(is_array($subitems)){$res.=Html::el('optgroup')->label($group)->startTag();$tmp='';}else{$subitems=array($group=>$subitems);}foreach($subitems as$value=>$caption){$option->value=$value;foreach($optionAttrs as$k=>$v){$option->attrs[$k]=isset($v[$value])?$v[$value]:NULL;}if($caption instanceof Html){$caption=clone$caption;$res.=$caption->setName('option')->addAttributes($option->attrs);}else{$res.=$optionTag.$option->attributes().'>'.htmlspecialchars($caption).'';}}$res.=$tmp;$tmp='';}return Html::el('select')->setHtml($res);}private static function prepareAttrs($attrs,$name){$dynamic=array();foreach((array)$attrs as$k=>$v){$p=str_split($k,strlen($k)-1);if($p[1]==='?'||$p[1]===':'){unset($attrs[$k],$attrs[$p[0]]);if($p[1]==='?'){$dynamic[$p[0]]=array_fill_keys((array)$v,TRUE);}elseif(is_array($v)&&$v){$dynamic[$p[0]]=$v;}else{$attrs[$p[0]]=$v;}}}return array($dynamic,'<'.$name.Html::el(NULL,$attrs)->attributes());}}array('container'=>NULL),'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,'.error'=>NULL),'control'=>array('container'=>'td','.odd'=>NULL,'description'=>'small','requiredsuffix'=>'','errorcontainer'=>'span class=error','erroritem'=>'','.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;public function 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||strtolower($mode)==='ownerrors'){$s.=$this->renderErrors();}elseif($mode==='errors'){$s.=$this->renderErrors(NULL,FALSE);}if(!$mode||$mode==='body'){$s.=$this->renderBody();}if(!$mode||$mode==='end'){$s.=$this->renderEnd();}return$s;}protected function 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);}}}public function 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();$query=parse_url($el->action,PHP_URL_QUERY);$el->action=str_replace("?$query",'',$el->action);$s='';foreach(preg_split('#[;&]#',$query,NULL,PREG_SPLIT_NO_EMPTY)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])));}}return$el->startTag().($s?"\n\t".$this->getWrapper('hidden container')->setHtml($s):'');}else{return$this->form->getElementPrototype()->startTag();}}public function renderEnd(){$s='';foreach($this->form->getControls()as$control){if($control instanceof Nette\Forms\Controls\HiddenField&&!$control->getOption('rendered')){$s.=$control->getControl();}}if(iterator_count($this->form->getComponents(TRUE,'Nette\Forms\Controls\TextInput'))<2){$s.='';}if($s){$s=$this->getWrapper('hidden container')->setHtml($s)."\n";}return$s.$this->form->getElementPrototype()->endTag()."\n";}public function renderErrors(Nette\Forms\IControl$control=NULL,$own=TRUE){$errors=$control?$control->getErrors():($own?$this->form->getOwnErrors():$this->form->getErrors());if(!$errors){return;}$container=$this->getWrapper($control?'control errorcontainer':'error container');$item=$this->getWrapper($control?'control erroritem':'error item');foreach($errors as$error){$item=clone$item;if($error instanceof Html){$item->add($error);}else{$item->setText($error);}$container->add($item);}return"\n".$container->render($control?1:0);}public function 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 instanceof Html?clone$container:Html::el($container);$s.="\n".$container->startTag();$text=$group->getOption('label');if($text instanceof Html){$s.=$this->getWrapper('group label')->add($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 instanceof 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);}public function renderControls($parent){if(!($parent instanceof Nette\Forms\Container||$parent instanceof Nette\Forms\ControlGroup)){throw new 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 instanceof Nette\Forms\Controls\HiddenField||$control->getForm(FALSE)!==$this->form){}elseif($control instanceof 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;}public function 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->hasErrors()?$this->getValue('pair .error'):NULL,TRUE);$pair->class($control->getOption('class'),TRUE);if(++$this->counter % 2){$pair->class($this->getValue('pair .odd'),TRUE);}$pair->id=$control->getOption('id');return$pair->render(0);}public function renderPairMulti(array$controls){$s=array();foreach($controls as$control){if(!$control instanceof Nette\Forms\IControl){throw new Nette\InvalidArgumentException('Argument must be array of IFormControl instances.');}$description=$control->getOption('description');if($description instanceof Html){$description=' '.$control->getOption('description');}elseif(is_string($description)){$description=' '.$this->getWrapper('control description')->setText($control->translate($description));}else{$description='';}$s[]=$control->getControl().$description;}$pair=$this->getWrapper('pair container');$pair->add($this->renderLabel($control));$pair->add($this->getWrapper('control container')->setHtml(implode(' ',$s)));return$pair->render(0);}public function renderLabel(Nette\Forms\IControl$control){$suffix=$this->getValue('label suffix').($control->isRequired()?$this->getValue('label requiredsuffix'):'');$label=$control->getLabel();if($label instanceof Html){$label->add($suffix);}elseif($label!=NULL){$label.=$suffix;}return$this->getWrapper('label container')->setHtml($label);}public function renderControl(Nette\Forms\IControl$control){$body=$this->getWrapper('control container');if($this->counter % 2){$body->class($this->getValue('control .odd'),TRUE);}$description=$control->getOption('description');if($description instanceof Html){$description=' '.$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;}$el=$control->getControl();return$body->setHtml($el.$description.$this->renderErrors($control));}protected function getWrapper($name){$data=$this->getValue($name);return$data instanceof Html?clone$data:Html::el($data);}protected function getValue($name){$name=explode(' ',$name);$data=&$this->wrappers[$name[0]][$name[1]];return$data;}}'Please submit this form again (security token has expired).',Form::EQUAL=>'Please enter %s.',Form::NOT_EQUAL=>'This value should not be %s.',Form::FILLED=>'This field is required.',Form::BLANK=>'This field should be blank.',Form::MIN_LENGTH=>'Please enter at least %d characters.',Form::MAX_LENGTH=>'Please enter no more 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 valid integer.',Form::FLOAT=>'Please enter a valid number.',Form::MIN=>'Please enter a value greater than or equal to %d.',Form::MAX=>'Please enter a value less than or equal to %d.',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::MAX_POST_SIZE=>'The uploaded data exceeds the limit of %d bytes.',Form::IMAGE=>'The uploaded file must be image in format JPEG, GIF or PNG.',Form::MIME_TYPE=>'The uploaded file is not in the expected format.',Nette\Forms\Controls\SelectBox::VALID=>'Please select a valid option.');private$required;private$rules=array();private$parent;private$toggles=array();private$control;public function __construct(IControl$control){$this->control=$control;}public function setRequired($value=TRUE){if($value){$this->addRule(Form::REQUIRED,is_string($value)?$value:NULL);}else{$this->required=NULL;}return$this;}public function isRequired(){return$this->required instanceof Rule?!$this->required->isNegative:FALSE;}public function addRule($validator,$message=NULL,$arg=NULL){$rule=new Rule;$rule->control=$this->control;$rule->validator=$validator;$this->adjustOperation($rule);$rule->arg=$arg;$rule->message=$message;if($rule->validator===Form::REQUIRED){$this->required=$rule;}else{$this->rules[]=$rule;}return$this;}public function addCondition($validator,$arg=NULL){return$this->addConditionOn($this->control,$validator,$arg);}public function addConditionOn(IControl$control,$validator,$arg=NULL){$rule=new Rule;$rule->control=$control;$rule->validator=$validator;$this->adjustOperation($rule);$rule->arg=$arg;$rule->branch=new static($this->control);$rule->branch->parent=$this;$this->rules[]=$rule;return$rule->branch;}public function elseCondition(){$rule=clone end($this->parent->rules);$rule->isNegative=!$rule->isNegative;$rule->branch=new static($this->parent->control);$rule->branch->parent=$this->parent;$this->parent->rules[]=$rule;return$rule->branch;}public function endCondition(){return$this->parent;}public function toggle($id,$hide=TRUE){$this->toggles[$id]=$hide;return$this;}public function getToggles($actual=FALSE){return$actual?$this->getToggleStates():$this->toggles;}public function getToggleStates($toggles=array(),$success=TRUE){foreach($this->toggles as$id=>$hide){$toggles[$id]=($success xor!$hide)||!empty($toggles[$id]);}foreach($this as$rule){if($rule->branch){$toggles=$rule->branch->getToggleStates($toggles,$success&&static::validateRule($rule));}}return$toggles;}public function validate(){foreach($this as$rule){$success=$this->validateRule($rule);if($success&&$rule->branch&&!$rule->branch->validate()){return FALSE;}elseif(!$success&&!$rule->branch){$rule->control->addError($this->formatMessage($rule,TRUE));return FALSE;}}return TRUE;}public static function validateRule(Rule$rule){$args=is_array($rule->arg)?$rule->arg:array($rule->arg);foreach($args as&$val){$val=$val instanceof IControl?$val->getValue():$val;}return$rule->isNegative xor call_user_func(self::getCallback($rule),$rule->control,is_array($rule->arg)?$args:$args[0]);}public function getIterator(){$rules=$this->rules;if($this->required){array_unshift($rules,$this->required);}return new\ArrayIterator($rules);}private function adjustOperation($rule){if(is_string($rule->validator)&&ord($rule->validator[0])>127){$rule->isNegative=TRUE;$rule->validator=~$rule->validator;}if(!is_callable($this->getCallback($rule))){$validator=is_scalar($rule->validator)?" '$rule->validator'":'';throw new Nette\InvalidArgumentException("Unknown validator$validator for control '{$rule->control->name}'.");}}private static function getCallback($rule){$op=$rule->validator;if(is_string($op)&&strncmp($op,':',1)===0){return get_class($rule->control).'::'.self::VALIDATE_PREFIX.ltrim($op,':');}else{return$op;}}public static function formatMessage(Rule$rule,$withValue=TRUE){$message=$rule->message;if($message instanceof Nette\Utils\Html){return$message;}elseif($message===NULL&&is_string($rule->validator)&&isset(self::$defaultMessages[$rule->validator])){$message=self::$defaultMessages[$rule->validator];}elseif($message==NULL){trigger_error("Missing validation message for control '{$rule->control->getName()}'.",E_USER_WARNING);}if($translator=$rule->control->getForm()->getTranslator()){$message=$translator->translate($message,is_int($rule->arg)?$rule->arg:NULL);}$message=preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#',function($m)use($rule,$withValue){static$i=-1;switch($m[1]){case'name':return$rule->control->getName();case'label':return$rule->control->translate($rule->control->caption);case'value':return$withValue?$rule->control->getValue():$m[0];default:$args=is_array($rule->arg)?$rule->arg:array($rule->arg);$i=(int)$m[1]?$m[1]-1:$i+1;return isset($args[$i])?($args[$i]instanceof IControl?($withValue?$args[$i]->getValue():"%$i"):$args[$i]):'';}},$message);return$message;}}request=$request;$this->response=$response;}public function 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 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 TRUE;}}if(empty($match)){return TRUE;}$this->response->setCode(IResponse::S304_NOT_MODIFIED);return FALSE;}public function getRequest(){return$this->request;}public function getResponse(){return$this->response;}}error=UPLOAD_ERR_NO_FILE;return;}}$this->name=$value['name'];$this->size=$value['size'];$this->tmpName=$value['tmp_name'];$this->error=$value['error'];}public function getName(){return$this->name;}public function getSanitizedName(){return trim(Nette\Utils\Strings::webalize($this->name,'.',FALSE),'.-');}public function getContentType(){if($this->isOk()&&$this->type===NULL){$this->type=finfo_file(finfo_open(FILEINFO_MIME_TYPE),$this->tmpName);}return$this->type;}public function getSize(){return$this->size;}public function getTemporaryFile(){return$this->tmpName;}public function __toString(){return(string)$this->tmpName;}public function getError(){return$this->error;}public function isOk(){return$this->error===UPLOAD_ERR_OK;}public function move($dest){@mkdir(dirname($dest),0777,TRUE);@unlink($dest);if(!call_user_func(is_uploaded_file($this->tmpName)?'move_uploaded_file':'rename',$this->tmpName,$dest)){throw new Nette\InvalidStateException("Unable to move uploaded file '$this->tmpName' to '$dest'.");}chmod($dest,0666);$this->tmpName=$dest;return$this;}public function isImage(){return in_array($this->getContentType(),array('image/gif','image/png','image/jpeg'),TRUE);}public function toImage(){return Nette\Utils\Image::fromFile($this->tmpName);}public function getImageSize(){return$this->isOk()?@getimagesize($this->tmpName):NULL;}public function getContents(){return$this->isOk()?file_get_contents($this->tmpName):NULL;}}$max){return FALSE;}elseif($ipv4){$arr=array(ip2long($ip),ip2long($mask));}else{$arr=unpack('N*',inet_pton($ip).inet_pton($mask));$size=$size===''?0:$max-$size;}$bits=implode('',array_map(function($n){return sprintf('%032b',$n);},$arr));return substr($bits,0,$max-$size)===substr($bits,$max,$max-$size);}}url=$url;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;}public function getUrl(){return$this->url;}public function 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;}}public function 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;}}public function getFile($key){return Nette\Utils\Arrays::get($this->files,func_get_args(),NULL);}public function getFiles(){return$this->files;}public function getCookie($key,$default=NULL){return isset($this->cookies[$key])?$this->cookies[$key]:$default;}public function getCookies(){return$this->cookies;}public function getMethod(){return$this->method;}public function isMethod($method){return strcasecmp($this->method,$method)===0;}public function isPost(){return$this->isMethod('POST');}public function getHeader($header,$default=NULL){$header=strtolower($header);if(isset($this->headers[$header])){return$this->headers[$header];}else{return$default;}}public function getHeaders(){return$this->headers;}public function getReferer(){return isset($this->headers['referer'])?new Url($this->headers['referer']):NULL;}public function isSecured(){return$this->url->scheme==='https';}public function isAjax(){return$this->getHeader('X-Requested-With')==='XMLHttpRequest';}public function getRemoteAddress(){return$this->remoteAddress;}public function getRemoteHost(){if(!$this->remoteHost){$this->remoteHost=$this->remoteAddress?getHostByAddr($this->remoteAddress):NULL;}return$this->remoteHost;}public function getRawBody(){if(PHP_VERSION_ID>=50600){return file_get_contents('php://input');}elseif($this->rawBody===NULL){$this->rawBody=(string)file_get_contents('php://input');}return$this->rawBody;}public function detectLanguage(array$langs){$header=$this->getHeader('Accept-Language');if(!$header){return 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 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;}}array('#/{2,}#'=>'/'),'url'=>array());private$binary=FALSE;private$proxies=array();public function setBinary($binary=TRUE){$this->binary=(bool)$binary;return$this;}public function setProxy($proxy){$this->proxies=(array)$proxy;return$this;}public function createHttpRequest(){$url=new UrlScript;$url->scheme=!empty($_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[$tmp='HTTP_HOST'])||isset($_SERVER[$tmp='SERVER_NAME']))&&preg_match('#^([a-z0-9_.-]+|\[[a-f0-9:]+\])(:\d+)?\z#i',$_SERVER[$tmp],$pair)){$url->host=strtolower($pair[1]);if(isset($pair[2])){$url->port=(int)substr($pair[2],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();if($gpc||!$this->binary){$list=array(&$query,&$post,&$cookies);while(list($key,$val)=each($list)){foreach($val as$k=>$v){unset($list[$key][$k]);if($gpc){$k=stripslashes($k);}if(!$this->binary&&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->binary&&(preg_match(self::NONCHARS,$v)||preg_last_error())){$v='';}$list[$key][$k]=$v;}}}unset($list,$key,$val,$k,$v);}$files=array();$list=array();if(!empty($_FILES)){foreach($_FILES as$k=>$v){if(!$this->binary&&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->binary&&(preg_match(self::NONCHARS,$v['name'])||preg_last_error())){$v['name']='';}if($v['error']!==UPLOAD_ERR_NO_FILE){$v['@']=new FileUpload($v);}continue;}foreach($v['name']as$k=>$foo){if(!$this->binary&&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]);}}if(function_exists('apache_request_headers')){$headers=array_change_key_case(apache_request_headers(),CASE_LOWER);}else{$headers=array();foreach($_SERVER as$k=>$v){if(strncmp($k,'HTTP_',5)==0){$k=substr($k,5);}elseif(strncmp($k,'CONTENT_',8)){continue;}$headers[strtr(strtolower($k),'_','-')]=$v;}}$remoteAddr=isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:NULL;$remoteHost=isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:NULL;foreach($this->proxies as$proxy){if(Helpers::ipMatch($remoteAddr,$proxy)){if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){$remoteAddr=trim(current(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));}if(isset($_SERVER['HTTP_X_FORWARDED_HOST'])){$remoteHost=trim(current(explode(',',$_SERVER['HTTP_X_FORWARDED_HOST'])));}break;}}$method=isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:NULL;if($method==='POST'&&isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])&&preg_match('#^[A-Z]+\z#',$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])){$method=$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];}return new Request($url,$query,$post,$files,$cookies,$headers,$method,$remoteAddr,$remoteHost);}}=50400){if(is_int(http_response_code())){$this->code=http_response_code();}header_register_callback($this->removeDuplicateCookies);}}public function setCode($code){$code=(int)$code;if($code<100||$code>599){throw new Nette\InvalidArgumentException("Bad HTTP response '$code'.");}self::checkHeaders();$this->code=$code;$protocol=isset($_SERVER['SERVER_PROTOCOL'])?$_SERVER['SERVER_PROTOCOL']:'HTTP/1.1';header($protocol.' '.$code,TRUE,$code);return$this;}public function getCode(){return$this->code;}public function setHeader($name,$value){self::checkHeaders();if($value===NULL){header_remove($name);}elseif(strcasecmp($name,'Content-Length')===0&&ini_get('zlib.output_compression')){}else{header($name.': '.$value,TRUE,$this->code);}return$this;}public function addHeader($name,$value){self::checkHeaders();header($name.': '.$value,FALSE,$this->code);return$this;}public function setContentType($type,$charset=NULL){$this->setHeader('Content-Type',$type.($charset?'; charset='.$charset:''));return$this;}public function redirect($url,$code=self::S302_FOUND){$this->setCode($code);$this->setHeader('Location',$url);echo"

Redirect

\n\n

Please click here to continue.

";}public function 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=DateTime::from($time);$this->setHeader('Cache-Control','max-age='.($time->format('U')-time()));$this->setHeader('Expires',self::date($time));return$this;}public function isSent(){return headers_sent();}public function getHeader($header,$default=NULL){$header.=':';$len=strlen($header);foreach(headers_list()as$item){if(strncasecmp($item,$header,$len)===0){return ltrim(substr($item,$len));}}return$default;}public function getHeaders(){$headers=array();foreach(headers_list()as$header){$a=strpos($header,':');$headers[substr($header,0,$a)]=(string)substr($header,$a+2);}return$headers;}public static function date($time=NULL){$time=DateTime::from($time);$time->setTimezone(new\DateTimeZone('GMT'));return$time->format('D, d M Y H:i:s \G\M\T');}public function __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)&&preg_match('#^text/html(?:;|$)#',$this->getHeader('Content-Type','text/html'))){echo Nette\Utils\Random::generate(2e3," \t\r\n");self::$fixIE=FALSE;}}public function setCookie($name,$value,$time,$path=NULL,$domain=NULL,$secure=NULL,$httpOnly=NULL){self::checkHeaders();setcookie($name,$value,$time?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);$this->removeDuplicateCookies();return$this;}public function deleteCookie($name,$path=NULL,$domain=NULL,$secure=NULL){$this->setCookie($name,FALSE,0,$path,$domain,$secure);}public function removeDuplicateCookies(){if(headers_sent($file,$line)||ini_get('suhosin.cookie.encrypt')){return;}$flatten=array();foreach(headers_list()as$header){if(preg_match('#^Set-Cookie: .+?=#',$header,$m)){$flatten[$m[0]]=$header;header_remove('Set-Cookie');}}foreach(array_values($flatten)as$key=>$header){header($header,$key===0);}}private function checkHeaders(){if(headers_sent($file,$line)){throw new Nette\InvalidStateException('Cannot send header after HTTP headers have been sent'.($file?" (output started at $file:$line).":'.'));}elseif($this->warnOnBuffer&&ob_get_length()&&!array_filter(ob_get_status(TRUE),function($i){return!$i['chunk_size'];})){trigger_error('Possible problem: you are sending a HTTP header while already having some data in output buffer. Try OutputDebugger or start session earlier.',E_USER_NOTICE);}}}'','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;public function __construct(IRequest$request,IResponse$response){$this->request=$request;$this->response=$response;}public function start(){if(self::$started){return;}$this->configure($this->options);$id=&$_COOKIE[session_name()];if(!is_string($id)||!preg_match('#^[0-9a-zA-Z,-]{22,128}\z#i',$id)){unset($_COOKIE[session_name()]);}Nette\Utils\Callback::invokeSafe('session_start',array(),function($message)use(&$error){$error=$message;});$this->response->removeDuplicateCookies();if($error){@session_write_close();throw new Nette\InvalidStateException($error);}self::$started=TRUE;$nf=&$_SESSION['__NF'];if(empty($nf['Time'])){$nf['Time']=time();$this->regenerated=TRUE;}$browserKey=$this->request->getCookie('nette-browser');if(!is_string($browserKey)||!preg_match('#^[0-9a-z]{10}\z#',$browserKey)){$browserKey=Nette\Utils\Random::generate();}$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 as$variable=>$value){if((!empty($value['B'])&&$browserClosed)||(!empty($value['T'])&&$now>$value['T'])){if($variable===''){unset($nf['META'][$section],$nf['DATA'][$section]);continue 2;}unset($nf['META'][$section][$variable],$nf['DATA'][$section][$variable]);}}}}}if($this->regenerated){$this->regenerated=FALSE;$this->regenerateId();}register_shutdown_function(array($this,'clean'));}public function isStarted(){return(bool)self::$started;}public function close(){if(self::$started){$this->clean();session_write_close();self::$started=FALSE;}}public function destroy(){if(!self::$started){throw new 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']);}}public function exists(){return self::$started||$this->request->getCookie($this->getName())!==NULL;}public function regenerateId(){if(self::$started&&!$this->regenerated){if(headers_sent($file,$line)){throw new 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->response->removeDuplicateCookies();}$this->regenerated=TRUE;}public function getId(){return session_id();}public function setName($name){if(!is_string($name)||!preg_match('#[^0-9.][^.]*\z#A',$name)){throw new Nette\InvalidArgumentException('Session name must be a string and cannot contain dot.');}session_name($name);return$this->setOptions(array('name'=>$name));}public function getName(){return isset($this->options['name'])?$this->options['name']:session_name();}public function getSection($section,$class='Nette\Http\SessionSection'){return new$class($this,$section);}public function hasSection($section){if($this->exists()&&!self::$started){$this->start();}return!empty($_SESSION['__NF']['DATA'][$section]);}public function getIterator(){if($this->exists()&&!self::$started){$this->start();}if(isset($_SESSION['__NF']['DATA'])){return new\ArrayIterator(array_keys($_SESSION['__NF']['DATA']));}else{return new\ArrayIterator;}}public function 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']);}}public function setOptions(array$options){if(self::$started){$this->configure($options);}$this->options=$options+$this->options;if(!empty($options['auto_start'])){$this->start();}return$this;}public function getOptions(){return$this->options;}private function configure(array$config){$special=array('cache_expire'=>1,'cache_limiter'=>1,'save_path'=>1,'name'=>1);foreach($config 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 new 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(ini_get("session.$key")!=$value){throw new Nette\NotSupportedException("Unable to set 'session.$key' to '$value' because 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();}}}public function setExpiration($time){if(empty($time)){return$this->setOptions(array('gc_maxlifetime'=>self::DEFAULT_FILE_LIFETIME,'cookie_lifetime'=>0));}else{$time=Nette\Utils\DateTime::from($time)->format('U')-time();return$this->setOptions(array('gc_maxlifetime'=>$time,'cookie_lifetime'=>$time));}}public function setCookieParameters($path,$domain=NULL,$secure=NULL){return$this->setOptions(array('cookie_path'=>$path,'cookie_domain'=>$domain,'cookie_secure'=>$secure));}public function getCookieParameters(){return session_get_cookie_params();}public function setSavePath($path){return$this->setOptions(array('save_path'=>$path));}public function setStorage(ISessionStorage$storage){if(self::$started){throw new 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'));}public function setHandler(\SessionHandlerInterface$handler){if(self::$started){throw new Nette\InvalidStateException('Unable to set handler when session has been started.');}session_set_save_handler($handler);}private function sendCookie(){if(!headers_sent()&&ob_get_level()&&ob_get_length()){trigger_error('Possible problem: you are starting session while already having some data in output buffer. This may not work if the outputted data grows. Try starting the session earlier.',E_USER_NOTICE);}$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']);}}session=$session;$this->name=$name;}private function start(){if($this->meta===FALSE){$this->session->start();$this->data=&$_SESSION['__NF']['DATA'][$this->name];$this->meta=&$_SESSION['__NF']['META'][$this->name];}}public function getIterator(){$this->start();if(isset($this->data)){return new\ArrayIterator($this->data);}else{return new\ArrayIterator;}}public function __set($name,$value){$this->start();$this->data[$name]=$value;}public 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];}public function __isset($name){if($this->session->exists()){$this->start();}return isset($this->data[$name]);}public function __unset($name){$this->start();unset($this->data[$name],$this->meta[$name]);}public function offsetSet($name,$value){$this->__set($name,$value);}public function offsetGet($name){return$this->__get($name);}public function offsetExists($name){return$this->__isset($name);}public function offsetUnset($name){$this->__unset($name);}public function setExpiration($time,$variables=NULL){$this->start();if(empty($time)){$time=NULL;$whenBrowserIsClosed=TRUE;}else{$time=Nette\Utils\DateTime::from($time)->format('U');$max=ini_get('session.gc_maxlifetime');if($max!==0&&($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 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;}public function removeExpiration($variables=NULL){$this->start();if($variables===NULL){unset($this->meta['']['T'],$this->meta['']['B']);}elseif(is_array($variables)){foreach($variables as$variable){unset($this->meta[$variable]['T'],$this->meta[$variable]['B']);}}else{unset($this->meta[$variables]['T'],$this->meta[$variables]['B']);}}public function remove(){$this->start();$this->data=NULL;$this->meta=NULL;}}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='';public function __construct($url=NULL){if(is_string($url)){$parts=@parse_url($url);if($parts===FALSE){throw new Nette\InvalidArgumentException("Malformed or unsupported URI '$url'.");}foreach($parts 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 instanceof self){foreach($this as$key=>$val){$this->$key=$url->$key;}}}public function setScheme($value){$this->scheme=(string)$value;return$this;}public function getScheme(){return$this->scheme;}public function setUser($value){$this->user=(string)$value;return$this;}public function getUser(){return$this->user;}public function setPassword($value){$this->pass=(string)$value;return$this;}public function getPassword(){return$this->pass;}public function setHost($value){$this->host=(string)$value;return$this;}public function getHost(){return$this->host;}public function setPort($value){$this->port=(int)$value;return$this;}public function getPort(){return$this->port;}public function setPath($value){$this->path=(string)$value;return$this;}public function getPath(){return$this->path;}public function setQuery($value){$this->query=(string)(is_array($value)?http_build_query($value,'','&'):$value);return$this;}public function appendQuery($value){$value=(string)(is_array($value)?http_build_query($value,'','&'):$value);$this->query.=($this->query===''||$value==='')?$value:'&'.$value;return$this;}public function getQuery(){return$this->query;}public function getQueryParameter($name,$default=NULL){parse_str($this->query,$params);return isset($params[$name])?$params[$name]:$default;}public function setQueryParameter($name,$value){parse_str($this->query,$params);if($value===NULL){unset($params[$name]);}else{$params[$name]=$value;}$this->setQuery($params);return$this;}public function setFragment($value){$this->fragment=(string)$value;return$this;}public function getFragment(){return$this->fragment;}public function getAbsoluteUrl(){return$this->getHostUrl().$this->path.($this->query===''?'':'?'.$this->query).($this->fragment===''?'':'#'.$this->fragment);}public function 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;}public function getHostUrl(){return($this->scheme?$this->scheme.':':'').'//'.$this->getAuthority();}public function getBasePath(){$pos=strrpos($this->path,'/');return$pos===FALSE?'':substr($this->path,0,$pos+1);}public function getBaseUrl(){return$this->getHostUrl().$this->getBasePath();}public function getRelativeUrl(){return(string)substr($this->getAbsoluteUrl(),strlen($this->getBaseUrl()));}public function isEqual($url){$part=self::unescape(strtok($url,'?#'),'%/');if(strncmp($part,'//',2)===0){if($part!=='//'.$this->getAuthority().$this->path){return FALSE;}}elseif(strncmp($part,'/',1)===0){if($part!==$this->path){return FALSE;}}else{if($part!==$this->getHostUrl().$this->path){return FALSE;}}$part=preg_split('#[&;]#',self::unescape(strtr((string)strtok('?#'),'+',' '),'%&;=+'));sort($part);$query=preg_split('#[&;]#',$this->query);sort($query);return$part===$query;}public function canonicalize(){$this->path=$this->path===''?'/':self::unescape($this->path,'%/');$this->host=strtolower(rawurldecode($this->host));$this->query=self::unescape(strtr($this->query,'+',' '),'%&;=+');return$this;}public function __toString(){return$this->getAbsoluteUrl();}public static function 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;}}scriptPath=(string)$value;return$this;}public function getScriptPath(){return$this->scriptPath;}public function getBasePath(){$pos=strrpos($this->scriptPath,'/');return$pos===FALSE?'':substr($this->path,0,$pos+1);}public function getPathInfo(){return(string)substr($this->path,strlen($this->scriptPath));}}sessionHandler=$sessionHandler;}public function 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;}public function isAuthenticated(){$session=$this->getSessionSection(FALSE);return$session&&$session->authenticated;}public function setIdentity(IIdentity$identity=NULL){$this->getSessionSection(TRUE)->identity=$identity;return$this;}public function getIdentity(){$session=$this->getSessionSection(FALSE);return$session?$session->identity:NULL;}public function setNamespace($namespace){if($this->namespace!==$namespace){$this->namespace=(string)$namespace;$this->sessionSection=NULL;}return$this;}public function getNamespace(){return$this->namespace;}public function setExpiration($time,$flags=0){$section=$this->getSessionSection(TRUE);if($time){$time=Nette\Utils\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;}public function getLogoutReason(){$session=$this->getSessionSection(FALSE);return$session?$session->reason:NULL;}protected function getSessionSection($need){if($this->sessionSection!==NULL){return$this->sessionSection;}if(!$need&&!$this->sessionHandler->exists()){return NULL;}$this->sessionSection=$section=$this->sessionHandler->getSection('Nette.Http.UserStorage/'.$this->namespace);if(!$section->identity instanceof 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->expireTimereason=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;}}getIterator();}while($iterator instanceof\IteratorAggregate);}elseif($iterator instanceof\Traversable){if(!$iterator instanceof\Iterator){$iterator=new\IteratorIterator($iterator);}}else{throw new Nette\InvalidArgumentException(sprintf('Invalid argument passed to %s; array or Traversable expected, %s given.',__CLASS__,is_object($iterator)?get_class($iterator):gettype($iterator)));}parent::__construct($iterator,0);}public function isFirst($width=NULL){return$this->counter===1||($width&&$this->counter!==0&&(($this->counter-1)%$width)===0);}public function isLast($width=NULL){return!$this->hasNext()||($width&&($this->counter %$width)===0);}public function isEmpty(){return$this->counter===0;}public function isOdd(){return$this->counter % 2===1;}public function isEven(){return$this->counter % 2===0;}public function getCounter(){return$this->counter;}public function count(){$inner=$this->getInnerIterator();if($inner instanceof\Countable){return$inner->count();}else{throw new Nette\NotSupportedException('Iterator is not countable.');}}public function next(){parent::next();if(parent::valid()){$this->counter++;}}public function rewind(){parent::rewind();$this->counter=parent::valid()?1:0;}public function getNextKey(){return$this->getInnerIterator()->key();}public function getNextValue(){return$this->getInnerIterator()->current();}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}callback=Nette\Utils\Callback::check($callback);}public function accept(){return call_user_func($this->callback,$this->current(),$this->key(),$this);}}callback=Nette\Utils\Callback::check($callback);}public function current(){return call_user_func($this->callback,parent::current(),parent::key());}}getInnerIterator()->hasChildren();}public function getChildren(){return new static($this->getInnerIterator()->getChildren(),$this->callback);}}macroHandlers=new\SplObjectStorage;}public function addMacro($name,IMacro$macro){$this->macros[$name][]=$macro;$this->macroHandlers->attach($macro);return$this;}public function compile(array$tokens){$this->templateId=substr(lcg_value(),2,10);$this->tokens=$tokens;$output='';$this->output=&$output;$this->htmlNode=$this->macroNode=$this->context=NULL;foreach($this->macroHandlers as$handler){$handler->initialize($this);}foreach($tokens as$this->position=>$token){$this->{"process$token->type"}($token);}while($this->htmlNode){if(!empty($this->htmlNode->macroAttrs)){throw new CompileException('Missing '.self::printEndTag($this->macroNode));}$this->htmlNode=$this->htmlNode->parentNode;}$prologs=$epilogs='';foreach($this->macroHandlers as$handler){$res=$handler->finalize();$handlerName=get_class($handler);$prologs.=empty($res[0])?'':"";$epilogs=(empty($res[1])?'':"").$epilogs;}$output=($prologs?$prologs."\n":'').$output.$epilogs;if($this->macroNode){throw new CompileException('Missing '.self::printEndTag($this->macroNode));}$output=$this->expandTokens($output);return$output;}public function setContentType($type){$this->contentType=$type;$this->context=NULL;return$this;}public function getContentType(){return$this->contentType;}public function setContext($context,$sub=NULL){$this->context=array($context,$sub);return$this;}public function getContext(){return$this->context;}public function getTemplateId(){return$this->templateId;}public function getMacroNode(){return$this->macroNode;}public function getLine(){return$this->tokens?$this->tokens[$this->position]->line:NULL;}public function expandTokens($s){return strtr($s,$this->attrCodes);}private function processText(Token$token){if(in_array($this->context[0],array(self::CONTEXT_SINGLE_QUOTED_ATTR,self::CONTEXT_DOUBLE_QUOTED_ATTR),TRUE)&&$token->text===$this->context[0]){$this->setContext(self::CONTEXT_UNQUOTED_ATTR);}$this->output.=$token->text;}private function processMacroTag(Token$token){$isRightmost=!isset($this->tokens[$this->position+1])||substr($this->tokens[$this->position+1]->text,0,1)==="\n";if($token->name[0]==='/'){$this->closeMacro((string)substr($token->name,1),$token->value,$token->modifiers,$isRightmost);}else{$this->openMacro($token->name,$token->value,$token->modifiers,$isRightmost&&!$token->empty);if($token->empty){$this->closeMacro($token->name,NULL,NULL,$isRightmost);}}}private function processHtmlTagBegin(Token$token){if($token->closing){while($this->htmlNode){if(strcasecmp($this->htmlNode->name,$token->name)===0){break;}if($this->htmlNode->macroAttrs){throw new CompileException("Unexpected name>, expecting ".self::printEndTag($this->macroNode));}$this->htmlNode=$this->htmlNode->parentNode;}if(!$this->htmlNode){$this->htmlNode=new HtmlNode($token->name);}$this->htmlNode->closing=TRUE;$this->htmlNode->offset=strlen($this->output);$this->setContext(NULL);}elseif($token->text===''){$this->output.=$token->text;$this->setContext(NULL);return;}$htmlNode=$this->htmlNode;$isEmpty=!$htmlNode->closing&&(strpos($token->text,'/')!==FALSE||$htmlNode->isEmpty);$end='';if($isEmpty&&in_array($this->contentType,array(self::CONTENT_HTML,self::CONTENT_XHTML),TRUE)){$token->text=preg_replace('#^.*>#',$htmlNode->isEmpty&&$this->contentType===self::CONTENT_XHTML?' />':'>',$token->text);if(!$htmlNode->isEmpty){$end="name>";}}if(empty($htmlNode->macroAttrs)){$this->output.=$token->text.$end;}else{$code=substr($this->output,$htmlNode->offset).$token->text;$this->output=substr($this->output,0,$htmlNode->offset);$this->writeAttrsMacro($code);if($isEmpty){$htmlNode->closing=TRUE;$this->writeAttrsMacro($end);}}if($isEmpty){$htmlNode->closing=TRUE;}$lower=strtolower($htmlNode->name);if(!$htmlNode->closing&&($lower==='script'||$lower==='style')){$this->setContext($lower==='script'?self::CONTENT_JS:self::CONTENT_CSS);}else{$this->setContext(NULL);if($htmlNode->closing){$this->htmlNode=$this->htmlNode->parentNode;}}}private function processHtmlAttribute(Token$token){if(strncmp($token->name,Parser::N_PREFIX,strlen(Parser::N_PREFIX))===0){$name=substr($token->name,strlen(Parser::N_PREFIX));if(isset($this->htmlNode->macroAttrs[$name])){throw new CompileException("Found multiple attributes $token->name.");}elseif($this->macroNode&&$this->macroNode->htmlNode===$this->htmlNode){throw new CompileException("n:attributes must not appear inside macro; found $token->name inside {{$this->macroNode->name}}.");}$this->htmlNode->macroAttrs[$name]=$token->value;return;}$this->htmlNode->attrs[$token->name]=TRUE;$this->output.=$token->text;$contextMain=in_array($token->value,array(self::CONTEXT_SINGLE_QUOTED_ATTR,self::CONTEXT_DOUBLE_QUOTED_ATTR),TRUE)?$token->value:self::CONTEXT_UNQUOTED_ATTR;$context=NULL;if(in_array($this->contentType,array(self::CONTENT_HTML,self::CONTENT_XHTML),TRUE)){$lower=strtolower($token->name);if(substr($lower,0,2)==='on'){$context=self::CONTENT_JS;}elseif($lower==='style'){$context=self::CONTENT_CSS;}elseif(in_array($lower,array('href','src','action','formaction'),TRUE)||($lower==='data'&&strtolower($this->htmlNode->name)==='object')){$context=self::CONTENT_URL;}}$this->setContext($contextMain,$context);}private function processComment(Token$token){$isLeftmost=trim(substr($this->output,strrpos("\n$this->output","\n")))==='';if(!$isLeftmost){$this->output.=substr($token->text,strlen(rtrim($token->text,"\n")));}}public function openMacro($name,$args=NULL,$modifiers=NULL,$isRightmost=FALSE,$nPrefix=NULL){$node=$this->expandMacro($name,$args,$modifiers,$nPrefix);if($node->isEmpty){$this->writeCode($node->openingCode,$this->output,$node->replaced,$isRightmost);}else{$this->macroNode=$node;$node->saved=array(&$this->output,$isRightmost);$this->output=&$node->content;}return$node;}public function closeMacro($name,$args=NULL,$modifiers=NULL,$isRightmost=FALSE,$nPrefix=NULL){$node=$this->macroNode;if(!$node||($node->name!==$name&&''!==$name)||$modifiers||($args&&$node->args&&strncmp("$node->args ","$args ",strlen($args)+1))||$nPrefix!==$node->prefix){$name=$nPrefix?"htmlNode->name}> for ".Parser::N_PREFIX.implode(' and '.Parser::N_PREFIX,array_keys($this->htmlNode->macroAttrs)):'{/'.$name.($args?' '.$args:'').$modifiers.'}';throw new CompileException("Unexpected $name".($node?', expecting '.self::printEndTag($node):''));}$this->macroNode=$node->parentNode;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->replaced,$node->saved[1]);$this->writeCode($node->closingCode,$node->content,$node->replaced,$isRightmost,$isLeftmost);$this->output.=$node->content;return$node;}private function writeCode($code,&$output,$replaced,$isRightmost,$isLeftmost=NULL){if($isRightmost){$leftOfs=strrpos("\n$output","\n");if($isLeftmost===NULL){$isLeftmost=trim(substr($output,$leftOfs))==='';}if($replaced===NULL){$replaced=preg_match('#<\?php.*\secho\s#As',$code);}if($isLeftmost&&!$replaced){$output=substr($output,0,$leftOfs);}elseif(substr($code,-2)==='?>'){$code.="\n";}}$output.=$code;}public function writeAttrsMacro($code){$attrs=$this->htmlNode->macroAttrs;$left=$right=array();foreach($this->macros as$name=>$foo){$attrName=MacroNode::PREFIX_INNER."-$name";if(isset($attrs[$attrName])){if($this->htmlNode->closing){$left[]=array('closeMacro',$name,'',MacroNode::PREFIX_INNER);}else{array_unshift($right,array('openMacro',$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('openMacro',$name,$attrs[$attrName],MacroNode::PREFIX_TAG);array_unshift($right,array('closeMacro',$name,'',MacroNode::PREFIX_TAG));unset($attrs[$attrName]);}}foreach($this->macros as$name=>$foo){if(isset($attrs[$name])){if($this->htmlNode->closing){$right[]=array('closeMacro',$name,'',MacroNode::PREFIX_NONE);}else{array_unshift($left,array('openMacro',$name,$attrs[$name],MacroNode::PREFIX_NONE));}unset($attrs[$name]);}}if($attrs){throw new CompileException('Unknown attribute '.Parser::N_PREFIX.implode(' and '.Parser::N_PREFIX,array_keys($attrs)));}if(!$this->htmlNode->closing){$this->htmlNode->attrCode=&$this->attrCodes[$uniq=' n:'.substr(lcg_value(),2,10)];$code=substr_replace($code,$uniq,strrpos($code,'/>')?:strrpos($code,'>'),0);}foreach($left as$item){$node=$this->{$item[0]}($item[1],$item[2],NULL,NULL,$item[3]);if($node->closing||$node->isEmpty){$this->htmlNode->attrCode.=$node->attrCode;if($node->isEmpty){unset($this->htmlNode->macroAttrs[$node->name]);}}}$this->output.=$code;foreach($right as$item){$node=$this->{$item[0]}($item[1],$item[2],NULL,NULL,$item[3]);if($node->closing){$this->htmlNode->attrCode.=$node->attrCode;}}if($right&&substr($this->output,-2)==='?>'){$this->output.="\n";}}public function expandMacro($name,$args,$modifiers=NULL,$nPrefix=NULL){$inScript=in_array($this->context[0],array(self::CONTENT_JS,self::CONTENT_CSS),TRUE);if(empty($this->macros[$name])){throw new CompileException("Unknown macro {{$name}}".($inScript?' (in JavaScript or CSS, try to put a space after bracket.)':''));}if($this->context[1]===self::CONTENT_URL){$modifiers=preg_replace('#\|nosafeurl\s?(?=\||\z)#i','',$modifiers,-1,$found);if(!$found&&!preg_match('#\|datastream(?=\s|\||\z)#i',$modifiers)){$modifiers.='|safeurl';}}$modifiers=preg_replace('#\|noescape\s?(?=\||\z)#i','',$modifiers,-1,$found);if(!$found&&strpbrk($name,'=~%^&_')){$modifiers.='|escape';}if(!$found&&$inScript&&$name==='='&&preg_match('#["\'] *\z#',$this->tokens[$this->position-1]->text)){throw new CompileException("Do not place {$this->tokens[$this->position]->text} inside quotes.");}foreach(array_reverse($this->macros[$name])as$macro){$node=new MacroNode($macro,$name,$args,$modifiers,$this->macroNode,$this->htmlNode,$nPrefix);if($macro->nodeOpened($node)!==FALSE){return$node;}}throw new CompileException('Unknown '.($nPrefix?'attribute '.Parser::N_PREFIX.($nPrefix===MacroNode::PREFIX_NONE?'':"$nPrefix-").$name:'macro {'.$name.($args?" $args":'').'}'));}private static function printEndTag(MacroNode$node){if($node->prefix){return"htmlNode->name}> for ".Parser::N_PREFIX.implode(' and '.Parser::N_PREFIX,array_keys($node->htmlNode->macroAttrs));}else{return"{/$node->name}";}}}array(),'bytes'=>'Latte\Runtime\Filters::bytes','capitalize'=>'Latte\Runtime\Filters::capitalize','datastream'=>'Latte\Runtime\Filters::dataStream','date'=>'Latte\Runtime\Filters::date','escapecss'=>'Latte\Runtime\Filters::escapeCss','escapehtml'=>'Latte\Runtime\Filters::escapeHtml','escapehtmlcomment'=>'Latte\Runtime\Filters::escapeHtmlComment','escapeical'=>'Latte\Runtime\Filters::escapeICal','escapejs'=>'Latte\Runtime\Filters::escapeJs','escapeurl'=>'rawurlencode','escapexml'=>'Latte\Runtime\Filters::escapeXML','firstupper'=>'Latte\Runtime\Filters::firstUpper','implode'=>'implode','indent'=>'Latte\Runtime\Filters::indent','lower'=>'Latte\Runtime\Filters::lower','nl2br'=>'Latte\Runtime\Filters::nl2br','number'=>'number_format','repeat'=>'str_repeat','replace'=>'Latte\Runtime\Filters::replace','replacere'=>'Latte\Runtime\Filters::replaceRe','safeurl'=>'Latte\Runtime\Filters::safeUrl','strip'=>'Latte\Runtime\Filters::strip','striptags'=>'strip_tags','substr'=>'Latte\Runtime\Filters::substring','trim'=>'Latte\Runtime\Filters::trim','truncate'=>'Latte\Runtime\Filters::truncate','upper'=>'Latte\Runtime\Filters::upper');private$baseTemplateClass='Latte\Template';public function render($name,array$params=array()){$template=new$this->baseTemplateClass($params,$this->filters,$this,$name);$this->loadCacheFile($name,$template->getParameters());}public function renderToString($name,array$params=array()){ob_start();try{$this->render($name,$params);}catch(\Exception$e){ob_end_clean();throw$e;}return ob_get_clean();}public function compile($name){foreach($this->onCompile?:array()as$cb){call_user_func(Helpers::checkCallback($cb),$this);}$this->onCompile=array();$source=$this->getLoader()->getContent($name);try{$tokens=$this->getParser()->setContentType($this->contentType)->parse($source);$code=$this->getCompiler()->setContentType($this->contentType)->compile($tokens);if(preg_match('#^\S{5,100}\z#',$name)){$code="".$code;}}catch(\Exception$e){$e=$e instanceof CompileException?$e:new CompileException("Thrown exception '{$e->getMessage()}'",NULL,$e);throw$e->setSource($source,$this->getCompiler()->getLine(),$name);}$code=Helpers::optimizePhp($code);return$code;}private function loadCacheFile($name,$params){if(!$this->tempDirectory){return call_user_func(function(){foreach(func_get_arg(1)as$__k=>$__v){$$__k=$__v;}unset($__k,$__v);eval('?>'.func_get_arg(0));},$this->compile($name),$params);}$file=$this->getCacheFile($name);$handle=fopen($file,'c+');if(!$handle){throw new\RuntimeException("Unable to open or create file '$file'.");}flock($handle,LOCK_SH);$stat=fstat($handle);if(!$stat['size']||($this->autoRefresh&&$this->getLoader()->isExpired($name,$stat['mtime']))){ftruncate($handle,0);flock($handle,LOCK_EX);$stat=fstat($handle);if(!$stat['size']){$code=$this->compile($name);if(fwrite($handle,$code,strlen($code))!==strlen($code)){ftruncate($handle,0);throw new\RuntimeException("Unable to write file '$file'.");}}flock($handle,LOCK_SH);}call_user_func(function(){foreach(func_get_arg(1)as$__k=>$__v){$$__k=$__v;}unset($__k,$__v);include func_get_arg(0);},$file,$params);}public function getCacheFile($name){if(!$this->tempDirectory){throw new\RuntimeException('Set path to temporary directory using setTempDirectory().');}elseif(!is_dir($this->tempDirectory)){mkdir($this->tempDirectory);}$file=md5($name);if(preg_match('#\b\w.{10,50}$#',$name,$m)){$file=trim(preg_replace('#\W+#','-',$m[0]),'-').'-'.$file;}return$this->tempDirectory.'/'.$file.'.php';}public function addFilter($name,$callback){if($name==NULL){array_unshift($this->filters[NULL],$callback);}else{$this->filters[strtolower($name)]=$callback;}return$this;}public function getFilters(){return$this->filters;}public function invokeFilter($name,array$args){$lname=strtolower($name);if(!isset($this->filters[$lname])){$args2=$args;array_unshift($args2,$lname);foreach($this->filters[NULL]as$filter){$res=call_user_func_array(Helpers::checkCallback($filter),$args2);if($res!==NULL){return$res;}elseif(isset($this->filters[$lname])){return call_user_func_array(Helpers::checkCallback($this->filters[$lname]),$args);}}throw new\LogicException("Filter '$name' is not defined.");}return call_user_func_array(Helpers::checkCallback($this->filters[$lname]),$args);}public function addMacro($name,IMacro$macro){$this->getCompiler()->addMacro($name,$macro);return$this;}public function setContentType($type){$this->contentType=$type;return$this;}public function setTempDirectory($path){$this->tempDirectory=$path;return$this;}public function setAutoRefresh($on=TRUE){$this->autoRefresh=(bool)$on;return$this;}public function getParser(){if(!$this->parser){$this->parser=new Parser;}return$this->parser;}public function getCompiler(){if(!$this->compiler){$this->compiler=new Compiler;Macros\CoreMacros::install($this->compiler);Macros\BlockMacros::install($this->compiler);}return$this->compiler;}public function setLoader(ILoader$loader){$this->loader=$loader;return$this;}public function getLoader(){if(!$this->loader){$this->loader=new Loaders\FileLoader;}return$this->loader;}}sourceCode=(string)$code;$this->sourceLine=(int)$line;$this->sourceName=(string)$name;if(is_file($name)){$this->message=rtrim($this->message,'.').' in '.str_replace(dirname(dirname($name)),'...',$name).($line?":$line":'');}return$this;}}class RegexpException extends\Exception{static public$messages=array(PREG_INTERNAL_ERROR=>'Internal error',PREG_BACKTRACK_LIMIT_ERROR=>'Backtrack limit was exhausted',PREG_RECURSION_LIMIT_ERROR=>'Recursion limit was exhausted',PREG_BAD_UTF8_ERROR=>'Malformed UTF-8 data',5=>'Offset didn\'t correspond to the begin of a valid UTF-8 code point');public function __construct($message,$code=NULL){parent::__construct($message?:(isset(self::$messages[$code])?self::$messages[$code]:'Unknown error'),$code);}}class RuntimeException extends\Exception{}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,'track'=>1);public static function checkCallback($callable){if(!is_callable($callable,FALSE,$text)){throw new\InvalidArgumentException("Callback '$text' is not callable.");}return$callable;}public static function optimizePhp($source,$lineLength=80){$res=$php='';$lastChar=';';$tokens=new\ArrayIterator(token_get_all($source));foreach($tokens as$n=>$token){if(is_array($token)){if($token[0]===T_INLINE_HTML){$lastChar='';$res.=$token[1];}elseif($token[0]===T_CLOSE_TAG){$next=isset($tokens[$n+1])?$tokens[$n+1]:NULL;if(substr($res,-1)!=='<'&&preg_match('#^<\?php\s*\z#',$php)){$php='';}elseif(is_array($next)&&$next[0]===T_OPEN_TAG&&(!isset($tokens[$n+2][1])||$tokens[$n+2][1]!=='xml')){if(!strspn($lastChar,';{}:/')){$php.=$lastChar=';';}if(substr($next[1],-1)==="\n"){$php.="\n";}$tokens->next();}elseif($next){$res.=preg_replace('#;?(\s)*\z#','$1',$php).$token[1];if(strlen($res)-strrpos($res,"\n")>$lineLength&&(!is_array($next)||strpos($next[1],"\n")===FALSE)){$res.="\n";}$php='';}else{if(!strspn($lastChar,'};')){$php.=';';}}}elseif($token[0]===T_ELSE||$token[0]===T_ELSEIF){if($tokens[$n+1]===':'&&$lastChar==='}'){$php.=';';}$lastChar='';$php.=$token[1];}elseif($token[0]===T_OPEN_TAG&&$token[1]==='?';for($tokens->next();$tokens->valid();$tokens->next()){$token=$tokens->current();$res.=is_array($token)?$token[1]:$token;if($token[0]===T_CLOSE_TAG){break;}}}else{if(!in_array($token[0],array(T_WHITESPACE,T_COMMENT,T_DOC_COMMENT,T_OPEN_TAG),TRUE)){$lastChar='';}$php.=$token[1];}}else{$php.=$lastChar=$token;}}return$res.$php;}}name=$name;$this->parentNode=$parentNode;}}isExpired($file,time())){touch($file);}return file_get_contents($file);}public function isExpired($file,$time){return@filemtime($file)>$time;}public function getChildName($file,$parent=NULL){if($parent&&!preg_match('#/|\\\\|[a-z]:#iA',$file)){$file=dirname($parent).'/'.$file;}return$file;}}macro=$macro;$this->name=(string)$name;$this->modifiers=(string)$modifiers;$this->parentNode=$parentNode;$this->htmlNode=$htmlNode;$this->prefix=$prefix;$this->data=new\stdClass;$this->setArgs($args);}public function setArgs($args){$this->args=(string)$args;$this->tokenizer=new MacroTokens($this->args);}}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('snippetArea',array($me,'macroBlock'),array($me,'macroBlockEnd'));$me->addMacro('ifset',array($me,'macroIfset'),'}');}public function initialize(){$this->namedBlocks=array();$this->extends=NULL;}public function finalize(){$last=$this->getCompiler()->getMacroNode();if($last&&$last->name==='block'){$this->getCompiler()->closeMacro($last->name);}$epilog=$prolog=array();if($this->namedBlocks){foreach($this->namedBlocks 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(\$_b->blocks[".var_export($name,TRUE)."][] = '$func')) { "."function $func(\$_b, \$_args) { foreach (\$_args as \$__k => \$__v) \$\$__k = \$__v".($snippet?'; $_control->redrawControl('.var_export(substr($name,1),TRUE).', FALSE)':'')."\n?>$codenamedBlocks||$this->extends){$prolog[]='// template extending';$prolog[]='$_l->extends = '.($this->extends?$this->extends:'empty($_g->extended) && isset($_control) && $_control instanceof Nette\Application\UI\Presenter ? $_control->findLayoutTemplateFile() : NULL').'; $_g->extended = TRUE;';$prolog[]='if ($_l->extends) { '.($this->namedBlocks?'ob_start();':'return $template->renderChildTemplate($_l->extends, get_defined_vars());').'}';}return array(implode("\n\n",$prolog),implode("\n",$epilog));}public function macroInclude(MacroNode$node,PhpWriter$writer){$destination=$node->tokenizer->fetchWord();if(!preg_match('~#|[\w-]+\z~A',$destination)){return FALSE;}$destination=ltrim($destination,'#');$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 new CompileException("Cannot include $destination block outside of any block.");}$destination=$item->data->name;}$name=strpos($destination,'$')===FALSE?var_export($destination,TRUE):$destination;if(isset($this->namedBlocks[$destination])&&!$parent){$cmd="call_user_func(reset(\$_b->blocks[$name]), \$_b, %node.array? + get_defined_vars())";}else{$cmd='Latte\Macros\BlockMacros::callBlock'.($parent?'Parent':'')."(\$_b, $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);}}public function macroIncludeBlock(MacroNode$node,PhpWriter$writer){return$writer->write('ob_start(); $_b->templates[%var]->renderChildTemplate(%node.word, %node.array? + get_defined_vars()); echo rtrim(ob_get_clean())',$this->getCompiler()->getTemplateId());}public function macroExtends(MacroNode$node,PhpWriter$writer){if(!$node->args){throw new CompileException("Missing destination in {{$node->name}}");}if(!empty($node->parentNode)){throw new CompileException("{{$node->name}} must be placed outside any macro.");}if($this->extends!==NULL){throw new CompileException("Multiple {{$node->name}} 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;}public function macroBlock(MacroNode$node,PhpWriter$writer){$name=$node->tokenizer->fetchWord();if($node->name==='#'){trigger_error('Shortcut {#block} is deprecated.',E_USER_DEPRECATED);}elseif($node->name==='block'&&$name===FALSE){return$node->modifiers===''?'':'ob_start()';}$node->data->name=$name=ltrim($name,'#');if($name==NULL){if($node->name==='define'){throw new CompileException('Missing block name.');}}elseif(strpos($name,'$')!==FALSE){if($node->name==='snippet'){for($parent=$node->parentNode;$parent&&!($parent->name==='snippet'||$parent->name==='snippetArea');$parent=$parent->parentNode);if(!$parent){throw new CompileException('Dynamic snippets are allowed only inside static snippet/snippetArea.');}$parent->data->dynamic=TRUE;$node->data->leave=TRUE;$node->closingCode="dynSnippets[\$_l->dynSnippetId] = ob_get_flush() ?>";if($node->prefix){$node->attrCode=$writer->write("dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)})) . '\"' ?>");return$writer->write('ob_start()');}$tag=trim($node->tokenizer->fetchWord(),'<>');$tag=$tag?$tag:'div';$node->closingCode.="\n";return$writer->write("?>\n<$tag id=\"dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)}) ?>\">data->leave=TRUE;$fname=$writer->formatWord($name);$node->closingCode="name==='define'?'':"call_user_func(reset(\$_b->blocks[$fname]), \$_b, get_defined_vars())")." ?>";$func='_lb'.substr(md5($this->getCompiler()->getTemplateId().$name),0,10).'_'.preg_replace('#[^a-z0-9_]#i','_',$name);return"\n\n//\n// block $name\n//\n"."if (!function_exists(\$_b->blocks[$fname]['{$this->getCompiler()->getTemplateId()}'] = '$func')) { "."function $func(\$_b, \$_args) { foreach (\$_args as \$__k => \$__v) \$\$__k = \$__v";}}if($node->name==='snippet'||$node->name==='snippetArea'){if($node->prefix&&isset($node->htmlNode->attrs['id'])){throw new CompileException('Cannot combine HTML attribute id with n:snippet.');}$node->data->name=$name='_'.$name;}if(isset($this->namedBlocks[$name])){throw new CompileException("Cannot redeclare static {$node->name} '$name'");}$prolog=$this->namedBlocks?'':"if (\$_l->extends) { ob_end_clean(); return \$template->renderChildTemplate(\$_l->extends, get_defined_vars()); }\n";$this->namedBlocks[$name]=TRUE;$include='call_user_func(reset($_b->blocks[%var]), $_b, '.(($node->name==='snippet'||$node->name==='snippetArea')?'$template->getParameters()':'get_defined_vars()').')';if($node->modifiers){$include="ob_start(); $include; echo %modify(ob_get_clean())";}if($node->name==='snippet'){if($node->prefix){$node->attrCode=$writer->write('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=\"getSnippetId(%var) ?>\">\nname==='define'){return$prolog;}else{return$writer->write($prolog.$include,$name);}}public function macroBlockEnd(MacroNode$node,PhpWriter$writer){if(isset($node->data->name)){if($node->name==='snippet'&&$node->prefix===MacroNode::PREFIX_NONE&&preg_match('#^.*? n:\w+>\n?#s',$node->content,$m1)&&preg_match('#[ \t]*<[^<]+\z#s',$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($node->name==='snippetArea'){$node->content="snippetMode = isset(\$_snippetMode) && \$_snippetMode; ?>{$node->content}snippetMode = FALSE; ?>";}if(!empty($node->data->dynamic)){$node->content.='dynSnippets)) return $_l->dynSnippets; ?>';}if($node->name==='snippetArea'){$node->content.='';}$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='';}}elseif($node->modifiers){return$writer->write('echo %modify(ob_get_clean())');}}public function macroIfset(MacroNode$node,PhpWriter$writer){if(strpos($node->args,'#')===FALSE){return FALSE;}$list=array();while(($name=$node->tokenizer->fetchWord())!==FALSE){$list[]=$name[0]==='#'?'$_b->blocks["'.substr($name,1).'"]':$name;}return'if (isset('.implode(', ',$list).')) {';}public static function callBlock(\stdClass$context,$name,array$params){if(empty($context->blocks[$name])){throw new RuntimeException("Cannot include undefined block '$name'.");}$block=reset($context->blocks[$name]);$block($context,$params);}public static function callBlockParent(\stdClass$context,$name,array$params){if(empty($context->blocks[$name])||($block=next($context->blocks[$name]))===FALSE){throw new RuntimeException("Cannot include undefined parent block '$name'.");}$block($context,$params);prev($context->blocks[$name]);}}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)) {','}');$me->addMacro('elseifset','} elseif (isset(%node.args)) {');$me->addMacro('ifcontent',array($me,'macroIfContent'),array($me,'macroEndIfContent'));$me->addMacro('switch','$_l->switch[] = (%node.args); if (FALSE) {','} array_pop($_l->switch)');$me->addMacro('case','} elseif (end($_l->switch) === (%node.args)) {');$me->addMacro('foreach','',array($me,'macroEndForeach'));$me->addMacro('for','for (%node.args) {','}');$me->addMacro('while','while (%node.args) {','}');$me->addMacro('continueIf',array($me,'macroBreakContinueIf'));$me->addMacro('breakIf',array($me,'macroBreakContinueIf'));$me->addMacro('first','if ($iterator->isFirst(%node.args)) {','}');$me->addMacro('last','if ($iterator->isLast(%node.args)) {','}');$me->addMacro('sep','if (!$iterator->isLast(%node.args)) {','}');$me->addMacro('var',array($me,'macroVar'));$me->addMacro('default',array($me,'macroVar'));$me->addMacro('dump',array($me,'macroDump'));$me->addMacro('debugbreak',array($me,'macroDebugbreak'));$me->addMacro('l','?>{addMacro('r','?>}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('contentType',array($me,'macroContentType'));$me->addMacro('status',array($me,'macroStatus'));$me->addMacro('class',NULL,NULL,array($me,'macroClass'));$me->addMacro('attr',NULL,NULL,array($me,'macroAttr'));}public function finalize(){return array('list($_b, $_g, $_l) = $template->initialize('.var_export($this->getCompiler()->getTemplateId(),TRUE).', '.var_export($this->getCompiler()->getContentType(),TRUE).')');}public function 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) {');}public function macroEndIf(MacroNode$node,PhpWriter$writer){if($node->data->capture){if($node->args===''){throw new 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)?'{ $_l->else = ob_get_contents(); ob_end_clean(); ob_end_clean(); echo $_l->else; }':'ob_end_clean();'));}return'}';}public function macroElse(MacroNode$node,PhpWriter$writer){$ifNode=$node->parentNode;if($ifNode&&$ifNode->name==='if'&&$ifNode->data->capture){if(isset($ifNode->data->else)){throw new CompileException('Macro {if} supports only one {else}.');}$ifNode->data->else=TRUE;return'ob_start()';}return'} else {';}public function macroIfContent(MacroNode$node,PhpWriter$writer){if(!$node->prefix){throw new CompileException("Unknown macro {{$node->name}}, use n:{$node->name} attribute.");}elseif($node->prefix!==MacroNode::PREFIX_NONE){throw new CompileException("Unknown attribute n:{$node->prefix}-{$node->name}, use n:{$node->name} attribute.");}return$writer->write('ob_start()');}public function macroEndIfContent(MacroNode$node,PhpWriter$writer){preg_match('#(^.*?>)(.*)(<.*\z)#s',$node->content,$parts);$node->content=$parts[1].''.$parts[2].'ifcontent = ob_get_contents(); ob_end_flush() ?>'.$parts[3];return'rtrim($_l->ifcontent) === "" ? ob_end_clean() : ob_end_flush()';}public function 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()';}}public function macroInclude(MacroNode$node,PhpWriter$writer){$code=$writer->write('$_b->templates[%var]->renderChildTemplate(%node.word, %node.array? + $template->getParameters())',$this->getCompiler()->getTemplateId());if($node->modifiers){return$writer->write('ob_start(); %raw; echo %modify(ob_get_clean())',$code);}else{return$code;}}public function macroUse(MacroNode$node,PhpWriter$writer){call_user_func(Latte\Helpers::checkCallback(array($node->tokenizer->fetchWord(),'install')),$this->getCompiler())->initialize();}public function macroCapture(MacroNode$node,PhpWriter$writer){$variable=$node->tokenizer->fetchWord();if(substr($variable,0,1)!=='$'){throw new CompileException("Invalid capture block variable '$variable'");}$node->data->variable=$variable;return'ob_start()';}public function macroCaptureEnd(MacroNode$node,PhpWriter$writer){return$node->data->variable.$writer->write(' = %modify(ob_get_clean())');}public function macroEndForeach(MacroNode$node,PhpWriter$writer){if($node->modifiers!=='|noiterator'&&preg_match('#\W(\$iterator|include|require|get_defined_vars)\W#',$this->getCompiler()->expandTokens($node->content))){$node->openingCode='its[] = new Latte\Runtime\CachingIterator('.preg_replace('#(.*)\s+as\s+#i','$1) as ',$writer->formatArgs(),1).') { ?>';$node->closingCode='its); $iterator = end($_l->its) ?>';}else{$node->openingCode='formatArgs().') { ?>';$node->closingCode='';}}public function macroBreakContinueIf(MacroNode$node,PhpWriter$writer){$cmd=str_replace('If','',$node->name);if($node->parentNode&&$node->parentNode->prefix===$node::PREFIX_NONE){return$writer->write("if (%node.args) { echo \"parentNode->htmlNode->name}>\\n\"; $cmd; }");}return$writer->write("if (%node.args) $cmd");}public function macroClass(MacroNode$node,PhpWriter$writer){return$writer->write('if ($_l->tmp = array_filter(%node.array)) echo \' class="\' . %escape(implode(" ", array_unique($_l->tmp))) . \'"\'');}public function macroAttr(MacroNode$node,PhpWriter$writer){return$writer->write('echo Latte\Runtime\Filters::htmlAttributes(%node.array)');}public function macroDump(MacroNode$node,PhpWriter$writer){$args=$writer->formatArgs();return'Tracy\Debugger::barDump('.($node->args?$writer->write("array(%var => $args)",$args):'get_defined_vars()').', "Template " . str_replace(dirname(dirname($template->getName())), "\xE2\x80\xA6", $template->getName()))';}public function 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()');}public function macroVar(MacroNode$node,PhpWriter$writer){if($node->args===''&&$node->parentNode&&$node->parentNode->name==='switch'){return'} else {';}$var=TRUE;$tokens=$writer->preprocess();$res=new Latte\MacroTokens;while($tokens->nextToken()){if($var&&$tokens->isCurrent(Latte\MacroTokens::T_SYMBOL,Latte\MacroTokens::T_VARIABLE)){if($node->name==='default'){$res->append("'".ltrim($tokens->currentValue(),'$')."'");}else{$res->append('$'.ltrim($tokens->currentValue(),'$'));}$var=NULL;}elseif($tokens->isCurrent('=','=>')&&$tokens->depth===0){$res->append($node->name==='default'?'=>':'=');$var=FALSE;}elseif($tokens->isCurrent(',')&&$tokens->depth===0){if($var===NULL){$res->append($node->name==='default'?'=>NULL':'=NULL');}$res->append($node->name==='default'?',':';');$var=TRUE;}elseif($var===NULL&&$node->name==='default'&&!$tokens->isCurrent(Latte\MacroTokens::T_WHITESPACE)){throw new CompileException("Unexpected '{$tokens->currentValue()}' in {default $node->args}");}else{$res->append($tokens->currentToken());}}if($var===NULL){$res->append($node->name==='default'?'=>NULL':'=NULL');}$out=$writer->quoteFilter($res)->joinAll();return$node->name==='default'?"extract(array($out), EXTR_SKIP)":$out;}public function macroExpr(MacroNode$node,PhpWriter$writer){return$writer->write(($node->name==='?'?'':'echo ').'%modify(%node.args)');}public function macroContentType(MacroNode$node,PhpWriter$writer){if(strpos($node->args,'xhtml')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_XHTML);}elseif(strpos($node->args,'html')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_HTML);}elseif(strpos($node->args,'xml')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_XML);}elseif(strpos($node->args,'javascript')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_JS);}elseif(strpos($node->args,'css')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_CSS);}elseif(strpos($node->args,'calendar')!==FALSE){$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_ICAL);}else{$this->getCompiler()->setContentType(Latte\Compiler::CONTENT_TEXT);}if(strpos($node->args,'/')){return$writer->write('header(%var)',"Content-Type: $node->args");}}public function macroStatus(MacroNode$node,PhpWriter$writer){return$writer->write((substr($node->args,-1)==='?'?'if (!headers_sent()) ':'').'header((isset($_SERVER["SERVER_PROTOCOL"]) ? $_SERVER["SERVER_PROTOCOL"] : "HTTP/1.1") . " " . %0.var, TRUE, %0.var)',(int)$node->args);}}compiler=$compiler;}public function addMacro($name,$begin,$end=NULL,$attr=NULL){if(!$begin&&!$end&&!$attr){throw new\InvalidArgumentException("At least one argument must be specified for macro '$name'.");}foreach(array($begin,$end,$attr)as$arg){if($arg&&!is_string($arg)){Latte\Helpers::checkCallback($arg);}}$this->macros[$name]=array($begin,$end,$attr);$this->compiler->addMacro($name,$this);return$this;}public function initialize(){}public function finalize(){}public function nodeOpened(MacroNode$node){list($begin,$end,$attr)=$this->macros[$node->name];$node->isEmpty=!$end;if($attr&&$node->prefix===$node::PREFIX_NONE){$node->isEmpty=TRUE;$this->compiler->setContext(Latte\Compiler::CONTEXT_DOUBLE_QUOTED_ATTR);$res=$this->compile($node,$attr);if($res===FALSE){return FALSE;}elseif(!$node->attrCode){$node->attrCode="";}$this->compiler->setContext(NULL);}elseif($begin){$res=$this->compile($node,$begin);if($res===FALSE||($node->isEmpty&&$node->prefix)){return FALSE;}elseif(!$node->openingCode){$node->openingCode="";}}elseif(!$end){return FALSE;}}public function nodeClosed(MacroNode$node){if(isset($this->macros[$node->name][1])){$res=$this->compile($node,$this->macros[$node->name][1]);if(!$node->closingCode){$node->closingCode="";}}}private function compile(MacroNode$node,$def){$node->tokenizer->reset();$writer=Latte\PhpWriter::using($node,$this->compiler);if(is_string($def)){return$writer->write($def);}else{return call_user_func($def,$node,$writer);}}public function getCompiler(){return$this->compiler;}}parse($input));$this->ignored=array(self::T_COMMENT,self::T_WHITESPACE);}public function parse($s){self::$tokenizer=self::$tokenizer?:new Tokenizer(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');return self::$tokenizer->tokenize($s);}public function append($val,$position=NULL){if($val!=NULL){array_splice($this->tokens,$position===NULL?count($this->tokens):$position,0,is_array($val)?array($val):$this->parse($val));}return$this;}public function prepend($val){if($val!=NULL){array_splice($this->tokens,0,0,is_array($val)?array($val):$this->parse($val));}return$this;}public function fetchWord(){$words=$this->fetchWords();return$words?implode(':',$words):FALSE;}public function fetchWords(){do{$words[]=$this->joinUntil(self::T_WHITESPACE,',',':');}while($this->nextToken(':'));$this->nextToken(',');$this->nextAll(self::T_WHITESPACE,self::T_COMMENT);return$words===array('')?array():$words;}public function reset(){$this->depth=0;return parent::reset();}protected function next(){parent::next();if($this->isCurrent('[','(','{')){$this->depth++;}elseif($this->isCurrent(']',')','}')){$this->depth--;}}}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 CONTEXT_HTML_TEXT='htmlText',CONTEXT_CDATA='cdata',CONTEXT_HTML_TAG='htmlTag',CONTEXT_HTML_ATTRIBUTE='htmlAttribute',CONTEXT_RAW='raw',CONTEXT_HTML_COMMENT='htmlComment';public function parse($input){if(substr($input,0,3)==="\xEF\xBB\xBF"){$input=substr($input,3);}if(!preg_match('##u',$input)){throw new\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_HTML_TEXT);$this->lastHtmlTag=$this->syntaxEndTag=NULL;while($this->offset{"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,$token->empty)=$this->parseMacroTag($matches['macro']);}$this->filter();}if($this->offsetaddToken(Token::TEXT,substr($this->input,$this->offset));}return$this->output;}private function contextHtmlText(){$matches=$this->match('~ (?:(?<=\n|^)[ \t]*)?<(?P/?)(?P[a-z0-9:]+)| ## begin of HTML tag !--(?!>))| ## begin of HTML comment '.$this->macroRe.' ## macro tag ~xsi');if(!empty($matches['htmlcomment'])){$this->addToken(Token::HTML_TAG_BEGIN,$matches[0]);$this->setContext(self::CONTEXT_HTML_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_HTML_TAG);}return$matches;}private function contextCData(){$matches=$this->match('~ '.$this->lastHtmlTag.')(?![a-z0-9:])| ## end HTML tag macroRe.' ## macro tag ~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_HTML_TAG);}return$matches;}private function contextHtmlTag(){$matches=$this->match('~ (?P\ ?/?>)([ \t]*\n)?| ## end of HTML tag '.$this->macroRe.'| ## macro tag \s*(?P[^\s/>={]+)(?:\s*=\s*(?P["\']|[^\s/>{]+))? ## beginning of HTML attribute ~xsi');if(!empty($matches['end'])){$this->addToken(Token::HTML_TAG_END,$matches[0]);$this->setContext(!$this->xmlMode&&in_array($this->lastHtmlTag,array('script','style'),TRUE)?self::CONTEXT_CDATA:self::CONTEXT_HTML_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(strncmp($token->name,self::N_PREFIX,strlen(self::N_PREFIX))===0){$token->value='';if($m=$this->match('~(.*?)'.$matches['value'].'~xsi')){$token->value=$m[1];$token->text.=$m[0];}}else{$this->setContext(self::CONTEXT_HTML_ATTRIBUTE,$matches['value']);}}}return$matches;}private function contextHtmlAttribute(){$matches=$this->match('~ (?P'.$this->context[1].')| ## end of HTML attribute '.$this->macroRe.' ## macro tag ~xsi');if(!empty($matches['quote'])){$this->addToken(Token::TEXT,$matches[0]);$this->setContext(self::CONTEXT_HTML_TAG);}return$matches;}private function contextHtmlComment(){$matches=$this->match('~ (?P-->)| ## end of HTML comment '.$this->macroRe.' ## macro tag ~xsi');if(!empty($matches['htmlcomment'])){$this->addToken(Token::HTML_TAG_END,$matches[0]);$this->setContext(self::CONTEXT_HTML_TEXT);}return$matches;}private function contextRaw(){$matches=$this->match('~ '.$this->macroRe.' ## macro tag ~xsi');return$matches;}private function match($re){if(!preg_match($re,$this->input,$matches,PREG_OFFSET_CAPTURE,$this->offset)){if(preg_last_error()){throw new RegexpException(NULL,preg_last_error());}return array();}$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 as$k=>$v){$matches[$k]=$v[0];}return$matches;}public function setContentType($type){if(strpos($type,'html')!==FALSE){$this->xmlMode=FALSE;$this->setContext(self::CONTEXT_HTML_TEXT);}elseif(strpos($type,'xml')!==FALSE){$this->xmlMode=TRUE;$this->setContext(self::CONTEXT_HTML_TEXT);}else{$this->setContext(self::CONTEXT_RAW);}return$this;}public function setContext($context,$quote=NULL){$this->context=array($context,$quote);return$this;}public function setSyntax($type){$type=$type?:$this->defaultSyntax;if(isset($this->syntaxes[$type])){$this->setDelimiters($this->syntaxes[$type][0],$this->syntaxes[$type][1]);}else{throw new\InvalidArgumentException("Unknown syntax '$type'");}return$this;}public function setDelimiters($left,$right){$this->macroRe=' (?P'.$left.'\\*.*?\\*'.$right.'\n{0,2})| '.$left.' (?P(?: '.self::RE_STRING.'| \{(?:'.self::RE_STRING.'|[^\'"{}])*+\}| [^\'"{}] )+?) '.$right.' (?P[ \t]*(?=\n))? ';return$this;}public function parseMacroTag($tag){if(!preg_match('~^ ( (?P\?|/?[a-z]\w*+(?:[.:]\w+)*+(?!::|\(|\\\\))| ## ?, name, /name, but not function( or class:: or namespace\ (?P!?)(?P/?[=\~#%^&_]?) ## !expression, !=expression, ... )(?P.*?) (?P\|[a-z](?:'.Parser::RE_STRING.'|[^\'"])*(?/?\z) ()\z~isx',$tag,$match)){if(preg_last_error()){throw new RegexpException(NULL,preg_last_error());}return FALSE;}if($match['name']===''){$match['name']=$match['shortname']?:'=';if($match['noescape']){if(!$this->shortNoEscape){trigger_error("The noescape shortcut {!...} is deprecated, use {...|noescape} modifier on line {$this->getLine()}.",E_USER_DEPRECATED);}$match['modifiers'].='|noescape';}}return array($match['name'],trim($match['args']),$match['modifiers'],(bool)$match['empty']);}private function addToken($type,$text){$this->output[]=$token=new Token;$token->type=$type;$token->text=$text;$token->line=$this->getLine();return$token;}private function getLine(){return substr_count($this->input,"\n",0,max(1,$this->offset-1))+1;}protected function 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'){$this->setContentType($token->value);}}}tokenizer,$node->modifiers,$compiler);}public function __construct(MacroTokens$tokens,$modifiers=NULL,Compiler$compiler=NULL){$this->tokens=$tokens;$this->modifiers=$modifiers;$this->compiler=$compiler;}public function write($mask){$mask=preg_replace('#%(node|\d+)\.#','%$1_',$mask);$me=$this;$mask=preg_replace_callback('#%escape(\(([^()]*+|(?1))+\))#',function($m)use($me){return$me->escapeFilter(new MacroTokens(substr($m[1],1,-1)))->joinAll();},$mask);$mask=preg_replace_callback('#%modify(\(([^()]*+|(?1))+\))#',function($m)use($me){return$me->formatModifiers(substr($m[1],1,-1));},$mask);$args=func_get_args();$pos=$this->tokens->position;$word=strpos($mask,'%node_word')===FALSE?NULL:$this->tokens->fetchWord();$code=preg_replace_callback('#([,+]\s*)?%(node_|\d+_|)(word|var|raw|array|args)(\?)?(\s*\+\s*)?()#',function($m)use($me,$word,&$args){list(,$l,$source,$format,$cond,$r)=$m;switch($source){case'node_':$arg=$word;break;case'':$arg=next($args);break;default:$arg=$args[$source+1];break;}switch($format){case'word':$code=$me->formatWord($arg);break;case'args':$code=$me->formatArgs();break;case'array':$code=$me->formatArray();$code=$cond&&$code==='array()'?'':$code;break;case'var':$code=var_export($arg,TRUE);break;case'raw':$code=(string)$arg;break;}if($cond&&$code===''){return$r?$l:$r;}else{return$l.$code.$r;}},$mask);$this->tokens->position=$pos;return$code;}public function formatModifiers($var){$tokens=new MacroTokens(ltrim($this->modifiers,'|'));$tokens=$this->preprocess($tokens);$tokens=$this->modifiersFilter($tokens,$var);$tokens=$this->quoteFilter($tokens);return$tokens->joinAll();}public function formatArgs(MacroTokens$tokens=NULL){$tokens=$this->preprocess($tokens);$tokens=$this->quoteFilter($tokens);return$tokens->joinAll();}public function formatArray(MacroTokens$tokens=NULL){$tokens=$this->preprocess($tokens);$tokens=$this->expandFilter($tokens);$tokens=$this->quoteFilter($tokens);return$tokens->joinAll();}public function formatWord($s){return(is_numeric($s)||preg_match('#^\$|[\'"]|^true\z|^false\z|^null\z#i',$s))?$this->formatArgs(new MacroTokens($s)):'"'.$s.'"';}public function preprocess(MacroTokens$tokens=NULL){$tokens=$tokens===NULL?$this->tokens:$tokens;$tokens=$this->removeCommentsFilter($tokens);$tokens=$this->shortTernaryFilter($tokens);$tokens=$this->shortArraysFilter($tokens);return$tokens;}public function removeCommentsFilter(MacroTokens$tokens){$res=new MacroTokens;while($tokens->nextToken()){if(!$tokens->isCurrent(MacroTokens::T_COMMENT)){$res->append($tokens->currentToken());}}return$res;}public function shortTernaryFilter(MacroTokens$tokens){$res=new MacroTokens;$inTernary=array();while($tokens->nextToken()){if($tokens->isCurrent('?')){$inTernary[]=$tokens->depth;}elseif($tokens->isCurrent(':')){array_pop($inTernary);}elseif($tokens->isCurrent(',',')',']')&&end($inTernary)===$tokens->depth+!$tokens->isCurrent(',')){$res->append(' : NULL');array_pop($inTernary);}$res->append($tokens->currentToken());}if($inTernary){$res->append(' : NULL');}return$res;}public function shortArraysFilter(MacroTokens$tokens){$res=new MacroTokens;$arrays=array();while($tokens->nextToken()){if($tokens->isCurrent('[')){if($arrays[]=!$tokens->isPrev(']',')',MacroTokens::T_SYMBOL,MacroTokens::T_VARIABLE,MacroTokens::T_KEYWORD)){$res->append('array(');continue;}}elseif($tokens->isCurrent(']')){if(array_pop($arrays)===TRUE){$res->append(')');continue;}}$res->append($tokens->currentToken());}return$res;}public function expandFilter(MacroTokens$tokens){$res=new MacroTokens('array(');$expand=NULL;while($tokens->nextToken()){if($tokens->isCurrent('(expand)')&&$tokens->depth===0){$expand=TRUE;$res->append('),');}elseif($expand&&$tokens->isCurrent(',')&&!$tokens->depth){$expand=FALSE;$res->append(', array(');}else{$res->append($tokens->currentToken());}}if($expand!==NULL){$res->prepend('array_merge(')->append($expand?', array()':')');}return$res->append(')');}public function quoteFilter(MacroTokens$tokens){$res=new MacroTokens;while($tokens->nextToken()){$res->append($tokens->isCurrent(MacroTokens::T_SYMBOL)&&(!$tokens->isPrev()||$tokens->isPrev(',','(','[','=>',':','?','.','<','>','<=','>=','===','!==','==','!=','<>','&&','||','=','and','or','xor'))&&(!$tokens->isNext()||$tokens->isNext(',',';',')',']','=>',':','?','.','<','>','<=','>=','===','!==','==','!=','<>','&&','||','and','or','xor'))?"'".$tokens->currentValue()."'":$tokens->currentToken());}return$res;}public function modifiersFilter(MacroTokens$tokens,$var){$inside=FALSE;$res=new MacroTokens($var);while($tokens->nextToken()){if($tokens->isCurrent(MacroTokens::T_WHITESPACE)){$res->append(' ');}elseif($inside){if($tokens->isCurrent(':',',')){$res->append(', ');$tokens->nextAll(MacroTokens::T_WHITESPACE);}elseif($tokens->isCurrent('|')){$res->append(')');$inside=FALSE;}else{$res->append($tokens->currentToken());}}else{if($tokens->isCurrent(MacroTokens::T_SYMBOL)){if($this->compiler&&$tokens->isCurrent('escape')){$res=$this->escapeFilter($res);$tokens->nextToken('|');}elseif(!strcasecmp($tokens->currentValue(),'safeurl')){$res->prepend('Latte\Runtime\Filters::safeUrl(');$inside=TRUE;}else{$res->prepend('$template->'.$tokens->currentValue().'(');$inside=TRUE;}}else{throw new CompileException("Modifier name must be alphanumeric string, '{$tokens->currentValue()}' given.");}}}if($inside){$res->append(')');}return$res;}public function escapeFilter(MacroTokens$tokens){$tokens=clone$tokens;switch($this->compiler->getContentType()){case Compiler::CONTENT_XHTML:case Compiler::CONTENT_HTML:$context=$this->compiler->getContext();switch($context[0]){case Compiler::CONTEXT_SINGLE_QUOTED_ATTR:case Compiler::CONTEXT_DOUBLE_QUOTED_ATTR:case Compiler::CONTEXT_UNQUOTED_ATTR:if($context[1]===Compiler::CONTENT_JS){$tokens->prepend('Latte\Runtime\Filters::escapeJs(')->append(')');}elseif($context[1]===Compiler::CONTENT_CSS){$tokens->prepend('Latte\Runtime\Filters::escapeCss(')->append(')');}$tokens->prepend('Latte\Runtime\Filters::escapeHtml(')->append($context[0]===Compiler::CONTEXT_SINGLE_QUOTED_ATTR?', ENT_QUOTES)':', ENT_COMPAT)');if($context[0]===Compiler::CONTEXT_UNQUOTED_ATTR){$tokens->prepend("'\"' . ")->append(" . '\"'");}return$tokens;case Compiler::CONTEXT_COMMENT:return$tokens->prepend('Latte\Runtime\Filters::escapeHtmlComment(')->append(')');case Compiler::CONTENT_JS:case Compiler::CONTENT_CSS:return$tokens->prepend('Latte\Runtime\Filters::escape'.ucfirst($context[0]).'(')->append(')');default:return$tokens->prepend('Latte\Runtime\Filters::escapeHtml(')->append(', ENT_NOQUOTES)');}case Compiler::CONTENT_XML:$context=$this->compiler->getContext();switch($context[0]){case Compiler::CONTEXT_COMMENT:return$tokens->prepend('Latte\Runtime\Filters::escapeHtmlComment(')->append(')');default:$tokens->prepend('Latte\Runtime\Filters::escapeXml(')->append(')');if($context[0]===Compiler::CONTEXT_UNQUOTED_ATTR){$tokens->prepend("'\"' . ")->append(" . '\"'");}return$tokens;}case Compiler::CONTENT_JS:case Compiler::CONTENT_CSS:case Compiler::CONTENT_ICAL:return$tokens->prepend('Latte\Runtime\Filters::escape'.ucfirst($this->compiler->getContentType()).'(')->append(')');case Compiler::CONTENT_TEXT:return$tokens;default:return$tokens->prepend('$template->escape(')->append(')');}}}getIterator();}while($iterator instanceof\IteratorAggregate);}elseif($iterator instanceof\Traversable){if(!$iterator instanceof\Iterator){$iterator=new\IteratorIterator($iterator);}}else{throw new\InvalidArgumentException(sprintf('Invalid argument passed to foreach; array or Traversable expected, %s given.',is_object($iterator)?get_class($iterator):gettype($iterator)));}parent::__construct($iterator,0);}public function isFirst($width=NULL){return$this->counter===1||($width&&$this->counter!==0&&(($this->counter-1)%$width)===0);}public function isLast($width=NULL){return!$this->hasNext()||($width&&($this->counter %$width)===0);}public function isEmpty(){return$this->counter===0;}public function isOdd(){return$this->counter % 2===1;}public function isEven(){return$this->counter % 2===0;}public function getCounter(){return$this->counter;}public function count(){$inner=$this->getInnerIterator();if($inner instanceof\Countable){return$inner->count();}else{throw new\LogicException('Iterator is not countable.');}}public function next(){parent::next();if(parent::valid()){$this->counter++;}}public function rewind(){parent::rewind();$this->counter=parent::valid()?1:0;}public function getNextKey(){return$this->getInnerIterator()->key();}public function getNextValue(){return$this->getInnerIterator()->current();}public function __call($name,$args){throw new\LogicException(sprintf('Call to undefined method %s::%s().',get_class($this),$name));}public function&__get($name){if(method_exists($this,$m='get'.$name)||method_exists($this,$m='is'.$name)){$ret=$this->$m();return$ret;}throw new\LogicException(sprintf('Cannot read an undeclared property %s::$%s.',get_class($this),$name));}public function __set($name,$value){throw new\LogicException(sprintf('Cannot write to an undeclared property %s::$%s.',get_class($this),$name));}public function __isset($name){return method_exists($this,'get'.$name)||method_exists($this,'is'.$name);}public function __unset($name){throw new\LogicException(sprintf('Cannot unset the property %s::$%s.',get_class($this),$name));}}__toString(TRUE);}$s=(string)$s;if($quotes!==ENT_NOQUOTES&&strpos($s,'`')!==FALSE&&strpbrk($s,' <>"\'')===FALSE){$s.=' ';}return htmlSpecialChars($s,$quotes);}public static function escapeHtmlComment($s){$s=(string)$s;if($s&&($s[0]==='-'||$s[0]==='>'||$s[0]==='!')){$s=' '.$s;}return str_replace('-','- ',$s);}public static function escapeXML($s){return htmlSpecialChars(preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]+#','',$s),ENT_QUOTES);}public static function escapeCss($s){return addcslashes($s,"\x00..\x1F!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~");}public static function escapeJs($s){if($s instanceof IHtmlString||$s instanceof\Nette\Utils\IHtmlString){$s=$s->__toString(TRUE);}$json=json_encode($s,PHP_VERSION_ID>=50400?JSON_UNESCAPED_UNICODE:0);if($error=json_last_error()){throw new\RuntimeException(PHP_VERSION_ID>=50500?json_last_error_msg():'JSON encode error',$error);}return str_replace(array("\xe2\x80\xa8","\xe2\x80\xa9",']]>','=1){$s=preg_replace_callback('#<(textarea|pre).*?format($format);}elseif(is_numeric($time)){$time=new\DateTime('@'.$time);$time->setTimeZone(new\DateTimeZone(date_default_timezone_get()));}elseif(!$time instanceof\DateTime&&!$time instanceof\DateTimeInterface){$time=new\DateTime($time);}return strpos($format,'%')===FALSE?$time->format($format):strftime($format,$time->format('U'));}public static function bytes($bytes,$precision=2){$bytes=round($bytes);$units=array('B','kB','MB','GB','TB','PB');foreach($units as$unit){if(abs($bytes)<1024||$unit===end($units)){break;}$bytes=$bytes/1024;}return round($bytes,$precision).' '.$unit;}public static function replace($subject,$search,$replacement=''){return str_replace($search,$replacement,$subject);}public static function replaceRe($subject,$pattern,$replacement=''){$res=preg_replace($pattern,$replacement,$subject);if(preg_last_error()){throw new Latte\RegexpException(NULL,preg_last_error());}return$res;}public static function dataStream($data,$type=NULL){if($type===NULL){$type=finfo_buffer(finfo_open(FILEINFO_MIME_TYPE),$data);}return'data:'.($type?"$type;":'').'base64,'.base64_encode($data);}public static function nl2br($value){return nl2br($value,self::$xhtml);}public static function substring($s,$start,$length=NULL){if($length===NULL){$length=self::length($s);}if(function_exists('mb_substr')){return mb_substr($s,$start,$length,'UTF-8');}return iconv_substr($s,$start,$length,'UTF-8');}public static function truncate($s,$maxLen,$append="\xE2\x80\xA6"){if(self::length($s)>$maxLen){$maxLen=$maxLen-self::length($append);if($maxLen<1){return$append;}elseif(preg_match('#^.{1,'.$maxLen.'}(?=[\s\x00-/:-@\[-`{-~])#us',$s,$matches)){return$matches[0].$append;}else{return self::substring($s,0,$maxLen).$append;}}return$s;}public static function lower($s){return mb_strtolower($s,'UTF-8');}public static function upper($s){return mb_strtoupper($s,'UTF-8');}public static function firstUpper($s){return self::upper(self::substring($s,0,1)).self::substring($s,1);}public static function capitalize($s){return mb_convert_case($s,MB_CASE_TITLE,'UTF-8');}public static function length($s){return strlen(utf8_decode($s));}public static function trim($s,$charlist=" \t\n\r\0\x0B\xC2\xA0"){$charlist=preg_quote($charlist,'#');$s=preg_replace('#^['.$charlist.']+|['.$charlist.']+\z#u','',$s);if(preg_last_error()){throw new Latte\RegexpException(NULL,preg_last_error());}return$s;}public static function htmlAttributes($attrs){if(!is_array($attrs)){return'';}$s='';foreach($attrs 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)){$tmp=NULL;foreach($value 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;}$q=strpos($value,'"')===FALSE?'"':"'";$s.=' '.$key.'='.$q.str_replace(array('&',$q),array('&',$q==='"'?'"':'''),$value).(strpos($value,'`')!==FALSE&&strpbrk($value,' <>"\'')===FALSE?' ':'').$q;}return$s;}}value=(string)$value;}public function __toString(){return$this->value;}}array());public function __construct(array$params,array&$filters,Engine$engine,$name){$params['template']=$this;$this->setParameters($params);$this->filters=&$filters;$this->engine=$engine;$this->name=$name;}public function getEngine(){return$this->engine;}public function getName(){return$this->name;}public function initialize($templateId,$contentType){Runtime\Filters::$xhtml=(bool)preg_match('#xml|xhtml#',$contentType);$this->params['_l']=new\stdClass;if(isset($this->params['_b'])){$block=$this->params['_b'];unset($this->params['_b']);}else{$block=new\stdClass;}$block->templates[$templateId]=$this;if(!isset($this->params['_g'])){$this->params['_g']=new\stdClass;}return array($block,$this->params['_g'],$this->params['_l']);}public function renderChildTemplate($name,array$params=array()){$name=$this->engine->getLoader()->getChildName($name,$this->name);$this->engine->render($name,$params);}public function __call($name,$args){return$this->engine->invokeFilter($name,$args);}public function setParameters(array$params){$this->params=$params;$this->params['template']=$this;return$this;}public function getParameters(){return$this->params;}public function __set($name,$value){$this->params[$name]=$value;}public function&__get($name){if(!array_key_exists($name,$this->params)){trigger_error("The variable '$name' does not exist in template.",E_USER_NOTICE);}return$this->params[$name];}public function __isset($name){return isset($this->params[$name]);}public function __unset($name){unset($this->params[$name]);}}tokens=$tokens;}public function currentToken(){return isset($this->tokens[$this->position])?$this->tokens[$this->position]:NULL;}public function currentValue(){return isset($this->tokens[$this->position])?$this->tokens[$this->position][Tokenizer::VALUE]:NULL;}public function nextToken(){return$this->scan(func_get_args(),TRUE,TRUE);}public function nextValue(){return$this->scan(func_get_args(),TRUE,TRUE,TRUE);}public function nextAll(){return$this->scan(func_get_args(),FALSE,TRUE);}public function nextUntil($arg){return$this->scan(func_get_args(),FALSE,TRUE,FALSE,TRUE);}public function joinAll(){return$this->scan(func_get_args(),FALSE,TRUE,TRUE);}public function joinUntil($arg){return$this->scan(func_get_args(),FALSE,TRUE,TRUE,TRUE);}public function isCurrent($arg){if(!isset($this->tokens[$this->position])){return FALSE;}$args=func_get_args();$token=$this->tokens[$this->position];return in_array($token[Tokenizer::VALUE],$args,TRUE)||(isset($token[Tokenizer::TYPE])&&in_array($token[Tokenizer::TYPE],$args,TRUE));}public function isNext(){return(bool)$this->scan(func_get_args(),TRUE,FALSE);}public function isPrev(){return(bool)$this->scan(func_get_args(),TRUE,FALSE,FALSE,FALSE,TRUE);}public function reset(){$this->position=-1;return$this;}protected function next(){$this->position++;}protected function scan($wanted,$onlyFirst,$advance,$strings=FALSE,$until=FALSE,$prev=FALSE){$res=$onlyFirst?NULL:($strings?'':array());$pos=$this->position+($prev?-1:1);do{if(!isset($this->tokens[$pos])){if(!$wanted&&$advance&&!$prev&&$pos<=count($this->tokens)){$this->next();}return$res;}$token=$this->tokens[$pos];$type=isset($token[Tokenizer::TYPE])?$token[Tokenizer::TYPE]:NULL;if(!$wanted||(in_array($token[Tokenizer::VALUE],$wanted,TRUE)||in_array($type,$wanted,TRUE))^$until){while($advance&&!$prev&&$pos>$this->position){$this->next();}if($onlyFirst){return$strings?$token[Tokenizer::VALUE]:$token;}elseif($strings){$res.=$token[Tokenizer::VALUE];}else{$res[]=$token;}}elseif($until||!in_array($type,$this->ignored,TRUE)){return$res;}$pos+=$prev?-1:1;}while(TRUE);}}re='~('.implode(')|(',$patterns).')~A'.$flags;$this->types=array_keys($patterns);}public function tokenize($input){preg_match_all($this->re,$input,$tokens,PREG_SET_ORDER);if(preg_last_error()){throw new RegexpException(NULL,preg_last_error());}$len=0;$count=count($this->types);foreach($tokens 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=array(self::VALUE=>$match[0],self::OFFSET=>$len,self::TYPE=>$type);$len+=strlen($match[self::VALUE]);}if($len!==strlen($input)){list($line,$col)=$this->getCoordinates($input,$len);$token=str_replace("\n",'\n',substr($input,$len,10));throw new CompileException("Unexpected '$token' on line $line, column $col.");}return$tokens;}public static function getCoordinates($text,$offset){$text=substr($text,0,$offset);return array(substr_count($text,"\n")+1,$offset-strrpos("\n".$text,"\n")+1);}}register();array_walk(new ArrayIterator(array('Nette\Config\Configurator'=>'Nette\Configurator','Nette\Config\CompilerExtension'=>'Nette\DI\CompilerExtension','Nette\Diagnostics\Bar'=>'Tracy\Bar','Nette\Diagnostics\BlueScreen'=>'Tracy\BlueScreen','Nette\Diagnostics\Dumper'=>'Tracy\Dumper','Nette\Latte\CompileException'=>'Latte\CompileException','Nette\Latte\IMacro'=>'Latte\IMacro','Nette\Latte\Macros\MacroSet'=>'Latte\Macros\MacroSet','Nette\ArrayHash'=>'Nette\Utils\ArrayHash','Nette\ArrayList'=>'Nette\Utils\ArrayList','Nette\DateTime'=>'Nette\Utils\DateTime','Nette\Image'=>'Nette\Utils\Image','Nette\ObjectMixin'=>'Nette\Utils\ObjectMixin','Nette\Utils\NeonException'=>'Nette\Neon\Exception','Nette\Utils\NeonEntity'=>'Nette\Neon\Entity','Nette\Utils\Neon'=>'Nette\Neon\Neon')),'class_alias');require_once __DIR__.'/shortcuts.php';'Nette\Configurator','Nette\Config\CompilerExtension'=>'Nette\DI\CompilerExtension','Nette\Http\User'=>'Nette\Security\User','Nette\Templating\DefaultHelpers'=>'Nette\Templating\Helpers','Nette\Templating\FilterException'=>'Latte\CompileException','Nette\Utils\PhpGenerator\ClassType'=>'Nette\PhpGenerator\ClassType','Nette\Utils\PhpGenerator\Helpers'=>'Nette\PhpGenerator\Helpers','Nette\Utils\PhpGenerator\Method'=>'Nette\PhpGenerator\Method','Nette\Utils\PhpGenerator\Parameter'=>'Nette\PhpGenerator\Parameter','Nette\Utils\PhpGenerator\PhpLiteral'=>'Nette\PhpGenerator\PhpLiteral','Nette\Utils\PhpGenerator\Property'=>'Nette\PhpGenerator\Property','Nette\Diagnostics\Bar'=>'Tracy\Bar','Nette\Diagnostics\BlueScreen'=>'Tracy\BlueScreen','Nette\Diagnostics\DefaultBarPanel'=>'Tracy\DefaultBarPanel','Nette\Diagnostics\Dumper'=>'Tracy\Dumper','Nette\Diagnostics\FireLogger'=>'Tracy\FireLogger','Nette\Diagnostics\Logger'=>'Tracy\Logger','Nette\Diagnostics\OutputDebugger'=>'Tracy\OutputDebugger','Nette\Latte\ParseException'=>'Latte\CompileException','Nette\Latte\CompileException'=>'Latte\CompileException','Nette\Latte\Compiler'=>'Latte\Compiler','Nette\Latte\HtmlNode'=>'Latte\HtmlNode','Nette\Latte\IMacro'=>'Latte\IMacro','Nette\Latte\MacroNode'=>'Latte\MacroNode','Nette\Latte\MacroTokens'=>'Latte\MacroTokens','Nette\Latte\Parser'=>'Latte\Parser','Nette\Latte\PhpWriter'=>'Latte\PhpWriter','Nette\Latte\Token'=>'Latte\Token','Nette\Latte\Macros\CoreMacros'=>'Latte\Macros\CoreMacros','Nette\Latte\Macros\MacroSet'=>'Latte\Macros\MacroSet','Nette\Latte\Macros\CacheMacro'=>'Nette\Bridges\CacheLatte\CacheMacro','Nette\Latte\Macros\FormMacros'=>'Nette\Bridges\FormsLatte\FormMacros','Nette\Latte\Macros\UIMacros'=>'Nette\Bridges\ApplicationLatte\UIMacros','Nette\ArrayHash'=>'Nette\Utils\ArrayHash','Nette\ArrayList'=>'Nette\Utils\ArrayList','Nette\DateTime'=>'Nette\Utils\DateTime','Nette\Image'=>'Nette\Utils\Image','Nette\ObjectMixin'=>'Nette\Utils\ObjectMixin','Nette\Utils\NeonException'=>'Nette\Neon\Exception','Nette\Utils\NeonEntity'=>'Nette\Neon\Entity','Nette\Utils\Neon'=>'Nette\Neon\Neon');public$list=array('Latte\CompileException'=>'Latte/exceptions','Latte\Compiler'=>'Latte/Compiler','Latte\Engine'=>'Latte/Engine','Latte\Helpers'=>'Latte/Helpers','Latte\HtmlNode'=>'Latte/HtmlNode','Latte\ILoader'=>'Latte/ILoader','Latte\IMacro'=>'Latte/IMacro','Latte\Loaders\FileLoader'=>'Latte/Loaders/FileLoader','Latte\Loaders\StringLoader'=>'Latte/Loaders/StringLoader','Latte\MacroNode'=>'Latte/MacroNode','Latte\MacroTokens'=>'Latte/MacroTokens','Latte\Macros\BlockMacros'=>'Latte/Macros/BlockMacros','Latte\Macros\CoreMacros'=>'Latte/Macros/CoreMacros','Latte\Macros\MacroSet'=>'Latte/Macros/MacroSet','Latte\Object'=>'Latte/Object','Latte\Parser'=>'Latte/Parser','Latte\PhpWriter'=>'Latte/PhpWriter','Latte\RegexpException'=>'Latte/exceptions','Latte\RuntimeException'=>'Latte/exceptions','Latte\Runtime\CachingIterator'=>'Latte/Runtime/CachingIterator','Latte\Runtime\Filters'=>'Latte/Runtime/Filters','Latte\Runtime\Html'=>'Latte/Runtime/Html','Latte\Runtime\IHtmlString'=>'Latte/Runtime/IHtmlString','Latte\Template'=>'Latte/Template','Latte\Token'=>'Latte/Token','Latte\TokenIterator'=>'Latte/TokenIterator','Latte\Tokenizer'=>'Latte/Tokenizer','NetteModule\ErrorPresenter'=>'Application/ErrorPresenter','NetteModule\MicroPresenter'=>'Application/MicroPresenter','Nette\Application\AbortException'=>'Application/exceptions','Nette\Application\ApplicationException'=>'Application/exceptions','Nette\Application\BadRequestException'=>'Application/exceptions','Nette\Application\ForbiddenRequestException'=>'Application/exceptions','Nette\Application\InvalidPresenterException'=>'Application/exceptions','Nette\ArgumentOutOfRangeException'=>'Utils/exceptions','Nette\Caching\Storages\PhpFileStorage'=>'deprecated/Caching/PhpFileStorage','Nette\Callback'=>'deprecated/Callback','Nette\Configurator'=>'Bootstrap/Configurator','Nette\DI\MissingServiceException'=>'DI/exceptions','Nette\DI\ServiceCreationException'=>'DI/exceptions','Nette\Database\Reflection\AmbiguousReferenceKeyException'=>'Database/Reflection/exceptions','Nette\Database\Reflection\MissingReferenceException'=>'Database/Reflection/exceptions','Nette\DeprecatedException'=>'Utils/exceptions','Nette\Diagnostics\Debugger'=>'deprecated/Diagnostics/Debugger','Nette\Diagnostics\Helpers'=>'deprecated/Diagnostics/Helpers','Nette\Diagnostics\IBarPanel'=>'deprecated/Diagnostics/IBarPanel','Nette\DirectoryNotFoundException'=>'Utils/exceptions','Nette\Environment'=>'deprecated/Environment','Nette\FileNotFoundException'=>'Utils/exceptions','Nette\FreezableObject'=>'deprecated/FreezableObject','Nette\IFreezable'=>'deprecated/IFreezable','Nette\IOException'=>'Utils/exceptions','Nette\InvalidArgumentException'=>'Utils/exceptions','Nette\InvalidStateException'=>'Utils/exceptions','Nette\Latte\Engine'=>'deprecated/Latte/Engine','Nette\Loaders\RobotLoader'=>'RobotLoader/RobotLoader','Nette\Localization\ITranslator'=>'Utils/ITranslator','Nette\Mail\SmtpException'=>'Mail/SmtpMailer','Nette\MemberAccessException'=>'Utils/exceptions','Nette\NotImplementedException'=>'Utils/exceptions','Nette\NotSupportedException'=>'Utils/exceptions','Nette\Object'=>'Utils/Object','Nette\OutOfRangeException'=>'Utils/exceptions','Nette\StaticClassException'=>'Utils/exceptions','Nette\Templating\FileTemplate'=>'deprecated/Templating/FileTemplate','Nette\Templating\Helpers'=>'deprecated/Templating/Helpers','Nette\Templating\IFileTemplate'=>'deprecated/Templating/IFileTemplate','Nette\Templating\ITemplate'=>'deprecated/Templating/ITemplate','Nette\Templating\Template'=>'deprecated/Templating/Template','Nette\UnexpectedValueException'=>'Utils/exceptions','Nette\Utils\AssertionException'=>'Utils/Validators','Nette\Utils\CallbackFilterIterator'=>'Finder/CallbackFilterIterator','Nette\Utils\Finder'=>'Finder/Finder','Nette\Utils\JsonException'=>'Utils/Json','Nette\Utils\LimitedScope'=>'deprecated/Utils/LimitedScope','Nette\Utils\MimeTypeDetector'=>'deprecated/Utils/MimeTypeDetector','Nette\Utils\RecursiveCallbackFilterIterator'=>'Finder/RecursiveCallbackFilterIterator','Nette\Utils\RegexpException'=>'Utils/Strings','Nette\Utils\SafeStream'=>'SafeStream/SafeStream','Nette\Utils\TokenIterator'=>'Tokenizer/TokenIterator','Nette\Utils\Tokenizer'=>'Tokenizer/Tokenizer','Nette\Utils\TokenizerException'=>'Tokenizer/TokenizerException','Nette\Utils\UnknownImageFileException'=>'Utils/Image','Tracy\Bar'=>'Tracy/Bar','Tracy\BlueScreen'=>'Tracy/BlueScreen','Tracy\Debugger'=>'Tracy/Debugger','Tracy\DefaultBarPanel'=>'Tracy/DefaultBarPanel','Tracy\Dumper'=>'Tracy/Dumper','Tracy\FireLogger'=>'Tracy/FireLogger','Tracy\Helpers'=>'Tracy/Helpers','Tracy\IBarPanel'=>'Tracy/IBarPanel','Tracy\Logger'=>'Tracy/Logger','Tracy\OutputDebugger'=>'Tracy/OutputDebugger');public static function getInstance(){if(self::$instance===NULL){self::$instance=new static;}return self::$instance;}public function register($prepend=FALSE){spl_autoload_register(array($this,'tryLoad'),TRUE,(bool)$prepend);}public function tryLoad($type){$type=ltrim($type,'\\');if(isset($this->renamed[$type])){class_alias($this->renamed[$type],$type);trigger_error("Class $type has been renamed to {$this->renamed[$type]}.",E_USER_WARNING);}elseif(isset($this->list[$type])){require __DIR__.'/../'.$this->list[$type].'.php';}elseif(substr($type,0,6)==='Nette\\'&&is_file($file=__DIR__.'/../'.strtr(substr($type,5),'\\','/').'.php')){require$file;}}}'1.0','X-Mailer'=>'Nette Framework');private$attachments=array();private$inlines=array();private$html;public function __construct(){foreach(static::$defaultHeaders as$name=>$value){$this->setHeader($name,$value);}$this->setHeader('Date',date('r'));}public function setFrom($email,$name=NULL){$this->setHeader('From',$this->formatEmail($email,$name));return$this;}public function getFrom(){return$this->getHeader('From');}public function addReplyTo($email,$name=NULL){$this->setHeader('Reply-To',$this->formatEmail($email,$name),TRUE);return$this;}public function setSubject($subject){$this->setHeader('Subject',$subject);return$this;}public function getSubject(){return$this->getHeader('Subject');}public function addTo($email,$name=NULL){$this->setHeader('To',$this->formatEmail($email,$name),TRUE);return$this;}public function addCc($email,$name=NULL){$this->setHeader('Cc',$this->formatEmail($email,$name),TRUE);return$this;}public function addBcc($email,$name=NULL){$this->setHeader('Bcc',$this->formatEmail($email,$name),TRUE);return$this;}private function formatEmail($email,$name){if(!$name&&preg_match('#^(.+) +<(.*)>\z#',$email,$matches)){return array($matches[2]=>$matches[1]);}else{return array($email=>$name);}}public function setReturnPath($email){$this->setHeader('Return-Path',$email);return$this;}public function getReturnPath(){return$this->getHeader('Return-Path');}public function setPriority($priority){$this->setHeader('X-Priority',(int)$priority);return$this;}public function getPriority(){return$this->getHeader('X-Priority');}public function setHtmlBody($html,$basePath=NULL){if($html instanceof Nette\Templating\ITemplate||$html instanceof Nette\Application\UI\ITemplate){$html->mail=$this;if($basePath===NULL&&($html instanceof Nette\Templating\IFileTemplate||$html instanceof Nette\Application\UI\ITemplate)){$basePath=dirname($html->getFile());}$html=$html->__toString(TRUE);}if($basePath!==FALSE){$cids=array();$matches=Strings::matchAll($html,'#(src\s*=\s*|background\s*=\s*|url\()(["\']?)(?![a-z]+:|[/\\#])([^"\')\s]+)#i',PREG_OFFSET_CAPTURE);foreach(array_reverse($matches)as$m){$file=rtrim($basePath,'/\\').'/'.urldecode($m[3][0]);if(!isset($cids[$file])){$cids[$file]=substr($this->addEmbeddedFile($file)->getHeader('Content-ID'),1,-1);}$html=substr_replace($html,"{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",$m[0][1],strlen($m[0][0]));}}$this->html=$html;if($this->getSubject()==NULL&&$matches=Strings::match($html,'#(.+?)#is')){$this->setSubject(html_entity_decode($matches[1],ENT_QUOTES,'UTF-8'));}if($this->getBody()==NULL&&$html!=NULL){$this->setBody($this->buildText($html));}return$this;}public function getHtmlBody(){return$this->html;}public function addEmbeddedFile($file,$content=NULL,$contentType=NULL){return$this->inlines[$file]=$this->createAttachment($file,$content,$contentType,'inline')->setHeader('Content-ID',$this->getRandomId());}public function addAttachment($file,$content=NULL,$contentType=NULL){return$this->attachments[]=$this->createAttachment($file,$content,$contentType,'attachment');}private function createAttachment($file,$content,$contentType,$disposition){$part=new MimePart;if($content===NULL){$content=@file_get_contents($file);if($content===FALSE){throw new Nette\FileNotFoundException("Unable to read file '$file'.");}}else{$content=(string)$content;}$part->setBody($content);$part->setContentType($contentType?$contentType:finfo_buffer(finfo_open(FILEINFO_MIME_TYPE),$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;}public function generateMessage(){return$this->build()->getEncodedMessage();}protected function build(){$mail=clone$this;$mail->setHeader('Message-ID',$this->getRandomId());$cursor=$mail;if($mail->attachments){$tmp=$cursor->setContentType('multipart/mixed');$cursor=$cursor->addPart();foreach($mail->attachments 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 as$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 function buildText($html){$text=Strings::replace($html,array('#<(style|script|head).*#Uis'=>'','#]#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]+#',' ');return trim($text);}private function getRandomId(){return'<'.Nette\Utils\Random::generate().'@'.preg_replace('#[^\w.-]+#','',isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:php_uname('n')).'>';}}headers[$name]);}}elseif(is_array($value)){$tmp=&$this->headers[$name];if(!$append||!is_array($tmp)){$tmp=array();}foreach($value as$email=>$recipient){if($recipient!==NULL&&!Strings::checkEncoding($recipient)){Nette\Utils\Validators::assert($recipient,'unicode',"header '$name'");}if(preg_match('#[\r\n]#',$recipient)){throw new 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 new Nette\InvalidArgumentException('Header is not valid UTF-8 string.');}$this->headers[$name]=preg_replace('#[\r\n]+#',' ',$value);}return$this;}public function getHeader($name){return isset($this->headers[$name])?$this->headers[$name]:NULL;}public function clearHeader($name){unset($this->headers[$name]);return$this;}public function getEncodedHeader($name){$offset=strlen($name)+2;if(!isset($this->headers[$name])){return NULL;}elseif(is_array($this->headers[$name])){$s='';foreach($this->headers[$name]as$email=>$name){if($name!=NULL){$s.=self::encodeHeader($name,$offset,TRUE);$email=" <$email>";}$s.=self::append($email.',',$offset);}return ltrim(substr($s,0,-1));}elseif(preg_match('#^(\S+; (?:file)?name=)"(.*)"\z#',$this->headers[$name],$m)){$offset+=strlen($m[1]);return$m[1].'"'.self::encodeHeader($m[2],$offset).'"';}else{return ltrim(self::encodeHeader($this->headers[$name],$offset));}}public function getHeaders(){return$this->headers;}public function setContentType($contentType,$charset=NULL){$this->setHeader('Content-Type',$contentType.($charset?"; charset=$charset":''));return$this;}public function setEncoding($encoding){$this->setHeader('Content-Transfer-Encoding',$encoding);return$this;}public function getEncoding(){return$this->getHeader('Content-Transfer-Encoding');}public function addPart(MimePart$part=NULL){return$this->parts[]=$part===NULL?new self:$part;}public function setBody($body){if($body instanceof Nette\Templating\ITemplate||$body instanceof Nette\Application\UI\ITemplate){$body->mail=$this;$body=$body->__toString(TRUE);}$this->body=$body;return$this;}public function getBody(){return$this->body;}public function getEncodedMessage(){$output='';$boundary='--------'.Nette\Utils\Random::generate();foreach($this->headers 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 self::ENCODING_QUOTED_PRINTABLE:$output.=quoted_printable_encode($body);break;case self::ENCODING_BASE64:$output.=rtrim(chunk_split(base64_encode($body),self::LINE_LENGTH,self::EOL));break;case self::ENCODING_7BIT:$body=preg_replace('#[\x80-\xFF]+#','',$body);case self::ENCODING_8BIT:$body=str_replace(array("\x00","\r"),'',$body);$body=str_replace("\n",self::EOL,$body);$output.=$body;break;default:throw new Nette\InvalidStateException('Unknown encoding.');}}if($this->parts){if(substr($output,-strlen(self::EOL))!==self::EOL){$output.=self::EOL;}foreach($this->parts as$part){$output.='--'.$boundary.self::EOL.$part->getEncodedMessage().self::EOL;}$output.='--'.$boundary.'--';}return$output;}private static function encodeHeader($s,&$offset=0,$quotes=FALSE){if(strspn($s,"!\"#$%&\'()*+,-./0123456789:;<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`abcdefghijklmnopqrstuvwxyz{|}~=? _\r\n\t")===strlen($s)){if($quotes&&preg_match('#[^ a-zA-Z0-9!\#$%&\'*+/?^_`{|}~-]#',$s)){return self::append('"'.addcslashes($s,'"\\').'"',$offset);}return self::append($s,$offset);}$o='';if($offset>=55){$o=self::EOL."\t";$offset=1;}$s=iconv_mime_encode(str_repeat(' ',$old=$offset),$s,array('scheme'=>'B','input-charset'=>'UTF-8','output-charset'=>'UTF-8'));$offset=strlen($s)-strrpos($s,"\n");$s=str_replace("\n ","\n\t",substr($s,$old+2));return$o.$s;}private static function append($s,&$offset=0){if($offset+strlen($s)>self::LINE_LENGTH){$offset=1;$s=self::EOL."\t".$s;}$offset+=strlen($s);return$s;}}setHeader('Subject',NULL);$tmp->setHeader('To',NULL);$parts=explode(Message::EOL.Message::EOL,$tmp->generateMessage(),2);$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=Nette\Utils\Callback::invokeSafe('mail',$args,function($message)use(&$info){$info=": $message";});if($res===FALSE){throw new Nette\InvalidStateException("Unable to send email$info.");}}}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;}$this->persistent=!empty($options['persistent']);}public function send(Message$mail){$mail=clone$mail;try{if(!$this->connection){$this->connect();}if(($from=$mail->getHeader('Return-Path'))||($from=key($mail->getHeader('From')))){$this->write("MAIL FROM:<$from>",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));}$mail->setHeader('Bcc',NULL);$data=$mail->generateMessage();$this->write('DATA',354);$data=preg_replace('#^\.#m','..',$data);$this->write($data);$this->write('.',250);if(!$this->persistent){$this->write('QUIT',221);$this->disconnect();}}catch(SmtpException$e){if($this->connection){$this->disconnect();}throw$e;}}protected function connect(){$this->connection=@fsockopen(($this->secure==='ssl'?'ssl://':'').$this->host,$this->port,$errno,$error,$this->timeout);if(!$this->connection){throw new SmtpException($error,$errno);}stream_set_timeout($this->connection,$this->timeout,0);$this->read();$self=isset($_SERVER['HTTP_HOST'])&&preg_match('#^[\w.-]+\z#',$_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'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 new 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');}}protected function disconnect(){fclose($this->connection);$this->connection=NULL;}protected function write($line,$expectedCode=NULL,$message=NULL){fwrite($this->connection,$line.Message::EOL);if($expectedCode&&!in_array((int)$this->read(),(array)$expectedCode,TRUE)){throw new SmtpException('SMTP server did not accept '.($message?$message:$line));}}protected function read(){$s='';while(($line=fgets($this->connection,1e3))!=NULL){$s.=$line;if(substr($line,3,1)===' '){break;}}return$s;}}class SmtpException extends\Exception{}']','{'=>'}','('=>')');private$input;private$tokens;private$pos;public function decode($input){if(!is_string($input)){throw new\InvalidArgumentException(sprintf('Argument must be a string, %s given.',gettype($input)));}elseif(substr($input,0,3)==="\xEF\xBB\xBF"){$input=substr($input,3);}$this->input="\n".str_replace("\r",'',$input);$pattern='~('.implode(')|(',self::$patterns).')~Amix';$this->tokens=preg_split($pattern,$this->input,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE|PREG_SPLIT_DELIM_CAPTURE);$last=end($this->tokens);if($this->tokens&&!preg_match($pattern,$last[0])){$this->pos=count($this->tokens)-1;$this->error();}$this->pos=0;$res=$this->parse(NULL);while(isset($this->tokens[$this->pos])){if($this->tokens[$this->pos][0][0]==="\n"){$this->pos++;}else{$this->error();}}return$res;}private function parse($indent,$result=NULL,$key=NULL,$hasKey=FALSE){$inlineParser=$indent===FALSE;$value=NULL;$hasValue=FALSE;$tokens=$this->tokens;$n=&$this->pos;$count=count($tokens);$mainResult=&$result;for(;$n<$count;$n++){$t=$tokens[$n][0];if($t===','){if((!$hasKey&&!$hasValue)||!$inlineParser){$this->error();}$this->addValue($result,$hasKey,$key,$hasValue?$value:NULL);$hasKey=$hasValue=FALSE;}elseif($t===':'||$t==='='){if($hasValue&&(is_array($value)||is_object($value))){$this->error('Unacceptable key');}elseif($hasKey&&$key===NULL&&$hasValue&&!$inlineParser){$n++;$result[]=$this->parse($indent.' ',array(),$value,TRUE);$newIndent=isset($tokens[$n],$tokens[$n+1])?(string)substr($tokens[$n][0],1):'';if(strlen($newIndent)>strlen($indent)){$n++;$this->error('Bad indentation');}elseif(strlen($newIndent)error();}else{$key=(string)$value;$hasKey=TRUE;$hasValue=FALSE;$result=&$mainResult;}}elseif($t==='-'){if($hasKey||$hasValue||$inlineParser){$this->error();}$key=NULL;$hasKey=TRUE;}elseif(isset(self::$brackets[$t])){if($hasValue){if($t!=='('){$this->error();}$n++;$value=new Entity($value,$this->parse(FALSE,array()));}else{$n++;$value=$this->parse(FALSE,array());}$hasValue=TRUE;if(!isset($tokens[$n])||$tokens[$n][0]!==self::$brackets[$t]){$this->error();}}elseif($t===']'||$t==='}'||$t===')'){if(!$inlineParser){$this->error();}break;}elseif($t[0]==="\n"){if($inlineParser){if($hasKey||$hasValue){$this->addValue($result,$hasKey,$key,$hasValue?$value:NULL);$hasKey=$hasValue=FALSE;}}else{while(isset($tokens[$n+1])&&$tokens[$n+1][0][0]==="\n"){$n++;}if(!isset($tokens[$n+1])){break;}$newIndent=(string)substr($tokens[$n][0],1);if($indent===NULL){$indent=$newIndent;}$minlen=min(strlen($newIndent),strlen($indent));if($minlen&&(string)substr($newIndent,0,$minlen)!==(string)substr($indent,0,$minlen)){$n++;$this->error('Invalid combination of tabs and spaces');}if(strlen($newIndent)>strlen($indent)){if($hasValue||!$hasKey){$n++;$this->error('Bad indentation');}$this->addValue($result,$key!==NULL,$key,$this->parse($newIndent));$newIndent=isset($tokens[$n],$tokens[$n+1])?(string)substr($tokens[$n][0],1):'';if(strlen($newIndent)>strlen($indent)){$n++;$this->error('Bad indentation');}$hasKey=FALSE;}else{if($hasValue&&!$hasKey){break;}elseif($hasKey){$this->addValue($result,$key!==NULL,$key,$hasValue?$value:NULL);if($key!==NULL&&!$hasValue&&$newIndent===$indent){$result=&$result[$key];}$hasKey=$hasValue=FALSE;}}if(strlen($newIndent)error();}static$consts=array('true'=>TRUE,'True'=>TRUE,'TRUE'=>TRUE,'yes'=>TRUE,'Yes'=>TRUE,'YES'=>TRUE,'on'=>TRUE,'On'=>TRUE,'ON'=>TRUE,'false'=>FALSE,'False'=>FALSE,'FALSE'=>FALSE,'no'=>FALSE,'No'=>FALSE,'NO'=>FALSE,'off'=>FALSE,'Off'=>FALSE,'OFF'=>FALSE);if($t[0]==='"'){$value=preg_replace_callback('#\\\\(?:u[0-9a-f]{4}|x[0-9a-f]{2}|.)#i',array($this,'cbString'),substr($t,1,-1));}elseif($t[0]==="'"){$value=substr($t,1,-1);}elseif(isset($consts[$t])&&(!isset($tokens[$n+1][0])||($tokens[$n+1][0]!==':'&&$tokens[$n+1][0]!=='='))){$value=$consts[$t];}elseif($t==='null'||$t==='Null'||$t==='NULL'){$value=NULL;}elseif(is_numeric($t)){$value=$t*1;}elseif(preg_match('#\d\d\d\d-\d\d?-\d\d?(?:(?:[Tt]| +)\d\d?:\d\d:\d\d(?:\.\d*)? *(?:Z|[-+]\d\d?(?::\d\d)?)?)?\z#A',$t)){$value=new\DateTime($t);}else{$value=$t;}$hasValue=TRUE;}}if($inlineParser){if($hasKey||$hasValue){$this->addValue($result,$hasKey,$key,$hasValue?$value:NULL);}}else{if($hasValue&&!$hasKey){if($result===NULL){$result=$value;}else{$this->error();}}elseif($hasKey){$this->addValue($result,$key!==NULL,$key,$hasValue?$value:NULL);}}return$mainResult;}private function addValue(&$result,$hasKey,$key,$value){if($hasKey){if($result&&array_key_exists($key,$result)){$this->error("Duplicated key '$key'");}$result[$key]=$value;}else{$result[]=$value;}}private function cbString($m){static$mapping=array('t'=>"\t",'n'=>"\n",'r'=>"\r",'f'=>"\x0C",'b'=>"\x08",'"'=>'"','\\'=>'\\','/'=>'/','_'=>"\xc2\xa0");$sq=$m[0];if(isset($mapping[$sq[1]])){return$mapping[$sq[1]];}elseif($sq[1]==='u'&&strlen($sq)===6){return iconv('UTF-32BE','UTF-8//IGNORE',pack('N',hexdec(substr($sq,2))));}elseif($sq[1]==='x'&&strlen($sq)===4){return chr(hexdec(substr($sq,2)));}else{$this->error("Invalid escaping sequence $sq");}}private function error($message="Unexpected '%s'"){$last=isset($this->tokens[$this->pos])?$this->tokens[$this->pos]:NULL;$offset=$last?$last[1]:strlen($this->input);$text=substr($this->input,0,$offset);$line=substr_count($text,"\n");$col=$offset-strrpos("\n".$text,"\n")+1;$token=$last?str_replace("\n",'',substr($last[0],0,40)):'end';throw new Exception(str_replace('%s',$token,$message)." on line $line, column $col.");}}format('Y-m-d H:i:s O');}elseif($var instanceof Entity){return self::encode($var->value).'('.(is_array($var->attributes)?substr(self::encode($var->attributes),1,-1):'').')';}if(is_object($var)){$obj=$var;$var=array();foreach($obj as$k=>$v){$var[$k]=$v;}}if(is_array($var)){$isList=!$var||array_keys($var)===range(0,count($var)-1);$s='';if($options&self::BLOCK){if(count($var)===0){return'[]';}foreach($var as$k=>$v){$v=self::encode($v,self::BLOCK);$s.=($isList?'-':self::encode($k).':').(strpos($v,"\n")===FALSE?' '.$v:"\n\t".str_replace("\n","\n\t",$v))."\n";continue;}return$s;}else{foreach($var as$k=>$v){$s.=($isList?'':self::encode($k).': ').self::encode($v).', ';}return($isList?'[':'{').substr($s,0,-2).($isList?']':'}');}}elseif(is_string($var)&&!is_numeric($var)&&!preg_match('~[\x00-\x1F]|^\d{4}|^(true|false|yes|no|on|off|null)\z~i',$var)&&preg_match('~^'.Decoder::$patterns[1].'\z~x',$var)){return$var;}elseif(is_float($var)){$var=json_encode($var);return strpos($var,'.')===FALSE?$var.'.0':$var;}else{return json_encode($var);}}}value=$value;$this->attributes=(array)$attrs;}}encode($var,$options);}public static function decode($input){$decoder=new Decoder;return$decoder->decode($input);}}getShortName());$class->type=$from->isInterface()?'interface':(PHP_VERSION_ID>=50400&&$from->isTrait()?'trait':'class');$class->final=$from->isFinal();$class->abstract=$from->isAbstract()&&$class->type==='class';$class->implements=$from->getInterfaceNames();$class->documents=preg_replace('#^\s*\* ?#m','',trim($from->getDocComment(),"/* \r\n"));$namespace=$from->getNamespaceName();if($from->getParentClass()){$class->extends=$from->getParentClass()->getName();if($namespace){$class->extends=Strings::startsWith($class->extends,"$namespace\\")?substr($class->extends,strlen($namespace)+1):'\\'.$class->extends;}$class->implements=array_diff($class->implements,$from->getParentClass()->getInterfaceNames());}if($namespace){foreach($class->implements as&$interface){$interface=Strings::startsWith($interface,"$namespace\\")?substr($interface,strlen($namespace)+1):'\\'.$interface;}}foreach($from->getProperties()as$prop){if($prop->getDeclaringClass()==$from){$class->properties[$prop->getName()]=Property::from($prop);}}foreach($from->getMethods()as$method){if($method->getDeclaringClass()==$from){$class->methods[$method->getName()]=Method::from($method);}}return$class;}public function __construct($name=NULL){$this->name=$name;}public function addConst($name,$value){$this->consts[$name]=$value;return$this;}public function addProperty($name,$value=NULL){$property=new Property;return$this->properties[$name]=$property->setName($name)->setValue($value);}public function addMethod($name){$method=new Method;if($this->type==='interface'){$method->setVisibility('')->setBody(FALSE);}else{$method->setVisibility('public');}return$this->methods[$name]=$method->setName($name);}public function __toString(){$consts=array();foreach($this->consts as$name=>$value){$consts[]="const $name = ".Helpers::dump($value).";\n";}$properties=array();foreach($this->properties as$property){$properties[]=($property->documents?str_replace("\n","\n * ","/**\n".implode("\n",(array)$property->documents))."\n */\n":'').$property->visibility.($property->static?' static':'').' $'.$property->name.($property->value===NULL?'':' = '.Helpers::dump($property->value)).";\n";}return Strings::normalize(($this->documents?str_replace("\n","\n * ","/**\n".implode("\n",(array)$this->documents))."\n */\n":'').($this->abstract?'abstract ':'').($this->final?'final ':'').$this->type.' '.$this->name.' '.($this->extends?'extends '.implode(', ',(array)$this->extends).' ':'').($this->implements?'implements '.implode(', ',(array)$this->implements).' ':'')."\n{\n\n".Strings::indent(($this->traits?"use ".implode(', ',(array)$this->traits).";\n\n":'').($this->consts?implode('',$consts)."\n\n":'').($this->properties?implode("\n",$properties)."\n\n":'').implode("\n\n\n",$this->methods),1)."\n\n}")."\n";}}50||isset($var[$marker])){throw new Nette\InvalidArgumentException('Nesting level too deep or recursive dependency.');}else{$out='';$outAlt="\n$space";$var[$marker]=TRUE;$counter=0;foreach($var as$k=>&$v){if($k!==$marker){$item=($k===$counter?'':self::_dump($k,$level+1).' => ').self::_dump($v,$level+1);$counter=is_int($k)?max($k+1,$counter):$counter;$out.=($out===''?'':', ').$item;$outAlt.="\t$item,\n$space";}}unset($var[$marker]);}return'array('.(strpos($out,"\n")===FALSE&&strlen($out)<40?$out:$outAlt).')';}elseif($var instanceof\Serializable){$var=serialize($var);return'unserialize('.self::_dump($var,$level).')';}elseif(is_object($var)){$arr=(array)$var;$space=str_repeat("\t",$level);$class=get_class($var);static$list=array();if($level>50||in_array($var,$list,TRUE)){throw new Nette\InvalidArgumentException('Nesting level too deep or recursive dependency.');}else{$out="\n";$list[]=$var;if(method_exists($var,'__sleep')){foreach($var->__sleep()as$v){$props[$v]=$props["\x00*\x00$v"]=$props["\x00$class\x00$v"]=TRUE;}}foreach($arr as$k=>&$v){if(!isset($props)||isset($props[$k])){$out.="$space\t".self::_dump($k,$level+1)." => ".self::_dump($v,$level+1).",\n";}}array_pop($list);$out.=$space;}return$class==='stdClass'?"(object) array($out)":__CLASS__."::createObject('$class', array($out))";}elseif(is_resource($var)){throw new Nette\InvalidArgumentException('Cannot dump resource.');}else{return var_export($var,TRUE);}}public static function format($statement){$args=func_get_args();return self::formatArgs(array_shift($args),$args);}public static function formatArgs($statement,array$args){$a=strpos($statement,'?');while($a!==FALSE){if(!$args){throw new Nette\InvalidArgumentException('Insufficient number of arguments.');}$arg=array_shift($args);if(substr($statement,$a+1,1)==='*'){if(!is_array($arg)){throw new Nette\InvalidArgumentException('Argument must be an array.');}$arg=implode(', ',array_map(array(__CLASS__,'dump'),$arg));$statement=substr_replace($statement,$arg,$a,2);}else{$arg=substr($statement,$a-1,1)==='$'||in_array(substr($statement,$a-2,2),array('->','::'),TRUE)?self::formatMember($arg):self::_dump($arg);$statement=substr_replace($statement,$arg,$a,1);}$a=strpos($statement,'?',$a+strlen($arg));}return$statement;}public static function formatMember($name){return$name instanceof PhpLiteral||!self::isIdentifier($name)?'{'.self::_dump($name).'}':$name;}public static function isIdentifier($value){return is_string($value)&&preg_match('#^'.self::PHP_IDENT.'\z#',$value);}public static function createObject($class,array$props){return unserialize('O'.substr(serialize((string)$class),1,-1).substr(serialize($props),1));}}name=$from->getName();foreach($from->getParameters()as$param){$method->parameters[$param->getName()]=Parameter::from($param);}$method->static=$from->isStatic();$method->visibility=$from->isPrivate()?'private':($from->isProtected()?'protected':'');$method->final=$from->isFinal();$method->abstract=$from->isAbstract()&&!$from->getDeclaringClass()->isInterface();$method->body=$from->isAbstract()?FALSE:'';$method->returnReference=$from->returnsReference();$method->variadic=PHP_VERSION_ID>=50600&&$from->isVariadic();$method->documents=preg_replace('#^\s*\* ?#m','',trim($from->getDocComment(),"/* \r\n"));return$method;}public function addParameter($name,$defaultValue=NULL){$param=new Parameter;if(func_num_args()>1){$param->setOptional(TRUE)->setDefaultValue($defaultValue);}return$this->parameters[$name]=$param->setName($name);}public function addUse($name){$param=new Parameter;return$this->uses[]=$param->setName($name);}public function setBody($statement,array$args=NULL){$this->body=func_num_args()>1?Helpers::formatArgs($statement,$args):$statement;return$this;}public function addBody($statement,array$args=NULL){$this->body.=(func_num_args()>1?Helpers::formatArgs($statement,$args):$statement)."\n";return$this;}public function __toString(){$parameters=array();foreach($this->parameters as$param){$variadic=$this->variadic&&$param===end($this->parameters);$parameters[]=($param->typeHint?$param->typeHint.' ':'').($param->reference?'&':'').($variadic?'...':'').'$'.$param->name.($param->optional&&!$variadic?' = '.Helpers::dump($param->defaultValue):'');}$uses=array();foreach($this->uses as$param){$uses[]=($param->reference?'&':'').'$'.$param->name;}return($this->documents?str_replace("\n","\n * ","/**\n".implode("\n",(array)$this->documents))."\n */\n":'').($this->abstract?'abstract ':'').($this->final?'final ':'').($this->visibility?$this->visibility.' ':'').($this->static?'static ':'').'function'.($this->returnReference?' &':'').($this->name?' '.$this->name:'').'('.implode(', ',$parameters).')'.($this->uses?' use ('.implode(', ',$uses).')':'').($this->abstract||$this->body===FALSE?';':($this->name?"\n":' ')."{\n".Nette\Utils\Strings::indent(trim($this->body),1)."\n}");}}name=$from->getName();$param->reference=$from->isPassedByReference();try{$param->typeHint=$from->isArray()?'array':($from->getClass()?'\\'.$from->getClass()->getName():'');}catch(\ReflectionException$e){if(preg_match('#Class (.+) does not exist#',$e->getMessage(),$m)){$param->typeHint='\\'.$m[1];}else{throw$e;}}$param->optional=PHP_VERSION_ID<50407?$from->isOptional()||($param->typeHint&&$from->allowsNull()):$from->isDefaultValueAvailable();$param->defaultValue=(PHP_VERSION_ID===50316?$from->isOptional():$from->isDefaultValueAvailable())?$from->getDefaultValue():NULL;$namespace=$from->getDeclaringClass()->getNamespaceName();$namespace=$namespace?"\\$namespace\\":"\\";if(Nette\Utils\Strings::startsWith($param->typeHint,$namespace)){$param->typeHint=substr($param->typeHint,strlen($namespace));}return$param;}}value=(string)$value;}public function __toString(){return$this->value;}}name=$from->getName();$defaults=$from->getDeclaringClass()->getDefaultProperties();$prop->value=isset($defaults[$from->name])?$defaults[$from->name]:NULL;$prop->static=$from->isStatic();$prop->visibility=$from->isPrivate()?'private':($from->isProtected()?'protected':'public');$prop->documents=preg_replace('#^\s*\* ?#m','',trim($from->getDocComment(),"/* \r\n"));return$prop;}}$v){$this->$k=$v;}}public function __toString(){return$this->value;}}getName();$member='class';$file=$r->getFileName();}elseif($r instanceof\ReflectionMethod){$type=$r->getDeclaringClass()->getName();$member=$r->getName();$file=$r->getFileName();}elseif($r instanceof\ReflectionFunction){$type=NULL;$member=$r->getName();$file=$r->getFileName();}else{$type=$r->getDeclaringClass()->getName();$member='$'.$r->getName();$file=$r->getDeclaringClass()->getFileName();}if(!self::$useReflection){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 self::$cache[$type][$member];}if(self::$useReflection===NULL){self::$useReflection=(bool)ClassType::from(__CLASS__)->getDocComment();}if(self::$useReflection){$annotations=self::parseComment($r->getDocComment());}else{$outerCache=self::getCache();if(self::$cache===NULL){self::$cache=(array)$outerCache->load('list');self::$timestamps=isset(self::$cache['*'])?self::$cache['*']:array();}if(!isset(self::$cache[$type])&&$file){self::$cache['*'][$file]=filemtime($file);foreach(static::parsePhp(file_get_contents($file))as$class=>$info){foreach($info as$prop=>$comment){if($prop!=='use'){self::$cache[$class][$prop]=self::parseComment($comment);}}}$outerCache->save('list',self::$cache);}if(isset(self::$cache[$type][$member])){$annotations=self::$cache[$type][$member];}else{$annotations=array();}}if($r 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 self::$cache[$type][$member]=$annotations;}public static function expandClassName($name,\ReflectionClass$reflector){if(empty($name)){throw new Nette\InvalidArgumentException('Class name must not be empty.');}if($name[0]==='\\'){return ltrim($name,'\\');}$filename=$reflector->getFileName();$parsed=static::getCache()->load($filename,function(&$dp)use($filename){if(AnnotationsParser::$autoRefresh){$dp[Nette\Caching\Cache::FILES]=$filename;}return AnnotationsParser::parsePhp(file_get_contents($filename));});$uses=array_change_key_case((array)$tmp=&$parsed[$reflector->getName()]['use']);$parts=explode('\\',$name,2);$parts[0]=strtolower($parts[0]);if(isset($uses[$parts[0]])){$parts[0]=$uses[$parts[0]];return implode('\\',$parts);}elseif($reflector->inNamespace()){return$reflector->getNamespaceName().'\\'.$name;}else{return$name;}}private static function 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]:'','~ (?<=\s|^)@('.self::RE_IDENTIFIER.')[ \t]* ## annotation ( \((?>'.self::RE_STRING.'|[^\'")@]+)+\)| ## (value) [^(@\r\n][^@\r\n]*|) ## value ~xi');foreach($matches 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;$val=rtrim($val);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;}}$res[$name][]=is_array($value)?Nette\Utils\ArrayHash::from($value):$value;}return$res;}public static function parsePhp($code){if(Strings::match($code,'#//nette'.'loader=(\S*)#')){return;}$tokens=@token_get_all($code);$namespace=$class=$classLevel=$level=$docComment=NULL;$res=$uses=array();while(list($key,$token)=each($tokens)){switch(is_array($token)?$token[0]:$token){case T_DOC_COMMENT:$docComment=$token[1];break;case T_NAMESPACE:$namespace=self::fetch($tokens,array(T_STRING,T_NS_SEPARATOR)).'\\';$uses=array();break;case T_CLASS:case T_INTERFACE:case PHP_VERSION_ID<50400?-1:T_TRAIT:if($name=self::fetch($tokens,T_STRING)){$class=$namespace.$name;$classLevel=$level+1;if($docComment){$res[$class]['class']=$docComment;}if($uses){$res[$class]['use']=$uses;}}break;case T_FUNCTION:self::fetch($tokens,'&');if($level===$classLevel&&$docComment&&($name=self::fetch($tokens,T_STRING))){$res[$class][$name]=$docComment;}break;case T_VAR:case T_PUBLIC:case T_PROTECTED:self::fetch($tokens,T_STATIC);if($level===$classLevel&&$docComment&&($name=self::fetch($tokens,T_VARIABLE))){$res[$class][$name]=$docComment;}break;case T_USE:while(!$class&&($name=self::fetch($tokens,array(T_STRING,T_NS_SEPARATOR)))){if(self::fetch($tokens,T_AS)){$uses[self::fetch($tokens,T_STRING)]=ltrim($name,'\\');}else{$tmp=explode('\\',$name);$uses[end($tmp)]=$name;}if(!self::fetch($tokens,',')){break;}}break;case T_CURLY_OPEN:case T_DOLLAR_OPEN_CURLY_BRACES:case'{':$level++;break;case'}':if($level===$classLevel){$class=$classLevel=NULL;}$level--;case';':$docComment=NULL;}}return$res;}private static function fetch(&$tokens,$take){$res=NULL;while($token=current($tokens)){list($token,$s)=is_array($token)?$token:array($token,$token);if(in_array($token,(array)$take,TRUE)){$res.=$s;}elseif(!in_array($token,array(T_DOC_COMMENT,T_WHITESPACE,T_COMMENT),TRUE)){break;}next($tokens);}return$res;}public static function setCacheStorage(Nette\Caching\IStorage$storage){self::$cacheStorage=$storage;}public static function getCacheStorage(){if(!self::$cacheStorage){self::$cacheStorage=new Nette\Caching\Storages\MemoryStorage();}return self::$cacheStorage;}private static function getCache(){return new Nette\Caching\Cache(static::getCacheStorage(),'Nette.Reflection.Annotations');}}getName();}public function is($type){return$this->isSubclassOf($type)||strcasecmp($this->getName(),ltrim($type,'\\'))===0;}public function getConstructor(){return($ref=parent::getConstructor())?Method::from($this->getName(),$ref->getName()):NULL;}public function getExtension(){return($name=$this->getExtensionName())?new Extension($name):NULL;}public function getInterfaces(){$res=array();foreach(parent::getInterfaceNames()as$val){$res[$val]=new static($val);}return$res;}public function getMethod($name){return new Method($this->getName(),$name);}public function getMethods($filter=-1){foreach($res=parent::getMethods($filter)as$key=>$val){$res[$key]=new Method($this->getName(),$val->getName());}return$res;}public function getParentClass(){return($ref=parent::getParentClass())?new static($ref->getName()):NULL;}public function getProperties($filter=-1){foreach($res=parent::getProperties($filter)as$key=>$val){$res[$key]=new Property($this->getName(),$val->getName());}return$res;}public function getProperty($name){return new Property($this->getName(),$name);}public function hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}public function getAnnotation($name){$res=AnnotationsParser::getAll($this);return isset($res[$name])?end($res[$name]):NULL;}public function getAnnotations(){return AnnotationsParser::getAll($this);}public function getDescription(){return$this->getAnnotation('description');}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}getName();}public function getClasses(){$res=array();foreach(parent::getClassNames()as$val){$res[$val]=new ClassType($val);}return$res;}public function getFunctions(){foreach($res=parent::getFunctions()as$key=>$val){$res[$key]=new GlobalFunction($key);}return$res;}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}value=$name);}public function toCallback(){return new Nette\Callback($this->value);}public function __toString(){return$this->getName().'()';}public function getClosure(){return PHP_VERSION_ID<50400?Nette\Utils\Callback::closure($this->value):parent::getClosure();}public function getExtension(){return($name=$this->getExtensionName())?new Extension($name):NULL;}public function getParameters(){foreach($res=parent::getParameters()as$key=>$val){$res[$key]=new Parameter($this->value,$val->getName());}return$res;}public function hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}public function getAnnotation($name){$res=AnnotationsParser::getAll($this);return isset($res[$name])?end($res[$name]):NULL;}public function getAnnotations(){return AnnotationsParser::getAll($this);}public function getDescription(){return$this->getAnnotation('description');}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}getName(),$this->getName());}public function __toString(){return parent::getDeclaringClass()->getName().'::'.$this->getName().'()';}public function getClosure($object=NULL){return PHP_VERSION_ID<50400?Nette\Utils\Callback::closure($object?:parent::getDeclaringClass()->getName(),$this->getName()):parent::getClosure($object);}public function getDeclaringClass(){return new ClassType(parent::getDeclaringClass()->getName());}public function getPrototype(){$prototype=parent::getPrototype();return new Method($prototype->getDeclaringClass()->getName(),$prototype->getName());}public function getExtension(){return($name=$this->getExtensionName())?new Extension($name):NULL;}public function getParameters(){$me=array(parent::getDeclaringClass()->getName(),$this->getName());foreach($res=parent::getParameters()as$key=>$val){$res[$key]=new Parameter($me,$val->getName());}return$res;}public function hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}public function getAnnotation($name){$res=AnnotationsParser::getAll($this);return isset($res[$name])?end($res[$name]):NULL;}public function getAnnotations(){return AnnotationsParser::getAll($this);}public function getDescription(){return$this->getAnnotation('description');}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}function=$function,$parameter);}public function getClass(){return($ref=parent::getClass())?new ClassType($ref->getName()):NULL;}public function 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;}}public function getDeclaringClass(){return($ref=parent::getDeclaringClass())?new ClassType($ref->getName()):NULL;}public function getDeclaringFunction(){return is_array($this->function)?new Method($this->function[0],$this->function[1]):new GlobalFunction($this->function);}public function isDefaultValueAvailable(){if(PHP_VERSION_ID===50316){try{$this->getDefaultValue();return TRUE;}catch(\ReflectionException$e){return FALSE;}}return parent::isDefaultValueAvailable();}public function __toString(){return'$'.parent::getName().' in '.$this->getDeclaringFunction();}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}getName().'::$'.$this->getName();}public function getDeclaringClass(){return new ClassType(parent::getDeclaringClass()->getName());}public function hasAnnotation($name){$res=AnnotationsParser::getAll($this);return!empty($res[$name]);}public function getAnnotation($name){$res=AnnotationsParser::getAll($this);return isset($res[$name])?end($res[$name]):NULL;}public function getAnnotations(){return AnnotationsParser::getAll($this);}public function getDescription(){return$this->getAnnotation('description');}public function __call($name,$args){return ObjectMixin::call($this,$name,$args);}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}classes=$this->getCache()->load($this->getKey(),array($this,'_rebuildCallback'));spl_autoload_register(array($this,'tryLoad'),TRUE,(bool)$prepend);return$this;}public function tryLoad($type){$type=ltrim(strtolower($type),'\\');$info=&$this->classes[$type];if(isset($this->missing[$type])||(is_int($info)&&$info>=self::RETRY_LIMIT)){return;}if($this->autoRebuild){if(!is_array($info)||!is_file($info['file'])){$info=is_int($info)?$info+1:0;if($this->rebuilt){$this->getCache()->save($this->getKey(),$this->classes);}else{$this->rebuild();}}elseif(!$this->rebuilt&&filemtime($info['file'])!==$info['time']){$this->updateFile($info['file']);if(!isset($this->classes[$type])){$this->classes[$type]=0;}$this->getCache()->save($this->getKey(),$this->classes);}}if(isset($this->classes[$type]['file'])){call_user_func(function($file){require$file;},$this->classes[$type]['file']);}else{$this->missing[$type]=TRUE;}}public function addDirectory($path){foreach((array)$path as$val){$real=realpath($val);if($real===FALSE){throw new Nette\DirectoryNotFoundException("Directory '$val' not found.");}$this->scanDirs[]=$real;}return$this;}public function getIndexedClasses(){$res=array();foreach($this->classes as$info){if(is_array($info)){$res[$info['orig']]=$info['file'];}}return$res;}public function rebuild(){$this->rebuilt=TRUE;$this->getCache()->save($this->getKey(),Nette\Utils\Callback::closure($this,'_rebuildCallback'));}public function _rebuildCallback(){$files=$missing=array();foreach($this->classes as$class=>$info){if(is_array($info)){$files[$info['file']]['time']=$info['time'];$files[$info['file']]['classes'][]=$info['orig'];}else{$missing[$class]=$info;}}$this->classes=array();foreach(array_unique($this->scanDirs)as$dir){foreach($this->createFileIterator($dir)as$file){$file=$file->getPathname();if(isset($files[$file])&&$files[$file]['time']==filemtime($file)){$classes=$files[$file]['classes'];}else{$classes=$this->scanPhp(file_get_contents($file));}foreach($classes as$class){$info=&$this->classes[strtolower($class)];if(isset($info['file'])){throw new Nette\InvalidStateException("Ambiguous class $class resolution; defined in {$info['file']} and in $file.");}$info=array('file'=>$file,'time'=>filemtime($file),'orig'=>$class);}}}$this->classes+=$missing;return$this->classes;}private function createFileIterator($dir){if(!is_dir($dir)){return new\ArrayIterator(array(new\SplFileInfo($dir)));}$ignoreDirs=is_array($this->ignoreDirs)?$this->ignoreDirs:preg_split('#[,\s]+#',$this->ignoreDirs);$disallow=array();foreach($ignoreDirs as$item){if($item=realpath($item)){$disallow[$item]=TRUE;}}$iterator=Nette\Utils\Finder::findFiles(is_array($this->acceptFiles)?$this->acceptFiles:preg_split('#[,\s]+#',$this->acceptFiles))->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(preg_match('#^(?:disallow\\s*:)?\\s*(\\S+)#i',$s,$matches)){$disallow[$path.str_replace('/',DIRECTORY_SEPARATOR,rtrim('/'.ltrim($matches[1],'/'),'/'))]=TRUE;}}}return!isset($disallow[$path]);});$filter(new\SplFileInfo($dir));return$iterator;}private function updateFile($file){foreach($this->classes as$class=>$info){if(isset($info['file'])&&$info['file']===$file){unset($this->classes[$class]);}}if(is_file($file)){foreach($this->scanPhp(file_get_contents($file))as$class){$info=&$this->classes[strtolower($class)];if(isset($info['file'])&&@filemtime($info['file'])!==$info['time']){$this->updateFile($info['file']);$info=&$this->classes[strtolower($class)];}if(isset($info['file'])){throw new Nette\InvalidStateException("Ambiguous class $class resolution; defined in {$info['file']} and in $file.");}$info=array('file'=>$file,'time'=>filemtime($file),'orig'=>$class);}}}private function scanPhp($code){$T_TRAIT=PHP_VERSION_ID<50400?-1:T_TRAIT;$expected=FALSE;$namespace='';$level=$minLevel=0;$classes=array();if(preg_match('#//nette'.'loader=(\S*)#',$code,$matches)){foreach(explode(',',$matches[1])as$name){$classes[]=$name;}return$classes;}foreach(@token_get_all($code)as$token){if(is_array($token)){switch($token[0]){case T_COMMENT:case T_DOC_COMMENT:case T_WHITESPACE:continue 2;case T_NS_SEPARATOR:case T_STRING:if($expected){$name.=$token[1];}continue 2;case T_NAMESPACE:case T_CLASS:case T_INTERFACE:case$T_TRAIT:$expected=$token[0];$name='';continue 2;case T_CURLY_OPEN:case T_DOLLAR_OPEN_CURLY_BRACES:$level++;}}if($expected){switch($expected){case T_CLASS:case T_INTERFACE:case$T_TRAIT:if($name&&$level===$minLevel){$classes[]=$namespace.$name;}break;case T_NAMESPACE:$namespace=$name?$name.'\\':'';$minLevel=$token==='{'?1:0;}$expected=NULL;}if($token==='{'){$level++;}elseif($token==='}'){$level--;}}return$classes;}public function setCacheStorage(Nette\Caching\IStorage$storage){$this->cacheStorage=$storage;return$this;}public function getCacheStorage(){return$this->cacheStorage;}protected function getCache(){if(!$this->cacheStorage){trigger_error('Missing cache storage.',E_USER_WARNING);$this->cacheStorage=new Nette\Caching\Storages\DevNullStorage;}return new Cache($this->cacheStorage,'Nette.RobotLoader');}protected function getKey(){return array($this->ignoreDirs,$this->acceptFiles,$this->scanDirs);}}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 FALSE;}}elseif($mode[0]==='x'){if(!$this->checkAndLock($this->handle=fopen($path,'x'.$flag,$use_path),LOCK_EX)){return 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 FALSE;}}else{trigger_error("Unknown mode $mode",E_USER_WARNING);return FALSE;}$tmp='~~'.lcg_value().'.tmp';if(!$this->tempHandle=fopen($path.$tmp,(strpos($mode,'+')?'x+':'x').$flag,$use_path)){$this->clean();return 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(stream_copy_to_stream($this->handle,$this->tempHandle)!==$stat['size']){$this->clean();return FALSE;}if($mode[0]==='a'){fseek($this->tempHandle,0,SEEK_END);}}return TRUE;}private function checkAndLock($handle,$lock){if(!$handle){return FALSE;}elseif(!flock($handle,$lock)){fclose($handle);return FALSE;}return TRUE;}private function clean(){flock($this->handle,LOCK_UN);fclose($this->handle);if($this->deleteFile){unlink($this->file);}if($this->tempHandle){fclose($this->tempHandle);unlink($this->tempFile);}}public function 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);}}}public function stream_read($length){return fread($this->tempHandle,$length);}public function stream_write($data){$len=strlen($data);$res=fwrite($this->tempHandle,$data,$len);if($res!==$len){$this->writeError=TRUE;}return$res;}public function stream_truncate($size){return ftruncate($this->tempHandle,$size);}public function stream_tell(){return ftell($this->tempHandle);}public function stream_eof(){return feof($this->tempHandle);}public function stream_seek($offset,$whence){return fseek($this->tempHandle,$offset,$whence)===0;}public function stream_stat(){return fstat($this->tempHandle);}public function url_stat($path,$flags){$path=substr($path,strlen(self::PROTOCOL)+3);return($flags&STREAM_URL_STAT_LINK)?@lstat($path):@stat($path);}public function unlink($path){$path=substr($path,strlen(self::PROTOCOL)+3);return unlink($path);}}setId($id);$this->setRoles((array)$roles);$this->data=$data instanceof\Traversable?iterator_to_array($data):(array)$data;}public function setId($id){$this->id=is_numeric($id)?1*$id:$id;return$this;}public function getId(){return$this->id;}public function setRoles(array$roles){$this->roles=$roles;return$this;}public function getRoles(){return$this->roles;}public function getData(){return$this->data;}public function __set($key,$value){if(parent::__isset($key)){parent::__set($key,$value);}else{$this->data[$key]=$value;}}public function&__get($key){if(parent::__isset($key)){return parent::__get($key);}else{return$this->data[$key];}}public function __isset($key){return isset($this->data[$key])||parent::__isset($key);}public function __unset($name){Nette\Utils\ObjectMixin::remove($this,$name);}}= 5.3.7.');}elseif(($len=strlen($salt))<22){throw new Nette\InvalidArgumentException("Salt must be 22 characters long, $len given.");}elseif($cost<4||$cost>31){throw new Nette\InvalidArgumentException("Cost must be in range 4-31, $cost given.");}$password=substr($password,0,self::PASSWORD_MAX_LENGTH);$hash=crypt($password,'$2y$'.($cost<10?0:'').$cost.'$'.$salt);if(strlen($hash)<60){throw new Nette\InvalidStateException('Hash returned by crypt is invalid.');}return$hash;}public static function verify($password,$hash){return preg_match('#^\$2y\$(?P\d\d)\$(?P.{22})#',$hash,$m)&&$m['cost']>3&&$m['cost']<31&&self::hash($password,$m)===$hash;}public static function needsRehash($hash,array$options=NULL){$cost=isset($options['cost'])?(int)$options['cost']:self::BCRYPT_COST;return!preg_match('#^\$2y\$(?P\d\d)\$(?P.{22})#',$hash,$m)||$m['cost']<$cost;}}array('allRoles'=>array('allPrivileges'=>array('type'=>self::DENY,'assert'=>NULL),'byPrivilege'=>array()),'byRole'=>array()),'byResource'=>array());private$queriedRole,$queriedResource;public function addRole($role,$parents=NULL){$this->checkRole($role,FALSE);if(isset($this->roles[$role])){throw new Nette\InvalidStateException("Role '$role' already exists in the list.");}$roleParents=array();if($parents!==NULL){if(!is_array($parents)){$parents=array($parents);}foreach($parents as$parent){$this->checkRole($parent);$roleParents[$parent]=TRUE;$this->roles[$parent]['children'][$role]=TRUE;}}$this->roles[$role]=array('parents'=>$roleParents,'children'=>array());return$this;}public function hasRole($role){$this->checkRole($role,FALSE);return isset($this->roles[$role]);}private function checkRole($role,$need=TRUE){if(!is_string($role)||$role===''){throw new Nette\InvalidArgumentException('Role must be a non-empty string.');}elseif($need&&!isset($this->roles[$role])){throw new Nette\InvalidStateException("Role '$role' does not exist.");}}public function getRoles(){return array_keys($this->roles);}public function getRoleParents($role){$this->checkRole($role);return array_keys($this->roles[$role]['parents']);}public function 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 TRUE;}}return FALSE;}public function 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;}public function 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;}public function addResource($resource,$parent=NULL){$this->checkResource($resource,FALSE);if(isset($this->resources[$resource])){throw new 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;}public function hasResource($resource){$this->checkResource($resource,FALSE);return isset($this->resources[$resource]);}private function checkResource($resource,$need=TRUE){if(!is_string($resource)||$resource===''){throw new Nette\InvalidArgumentException('Resource must be a non-empty string.');}elseif($need&&!isset($this->resources[$resource])){throw new Nette\InvalidStateException("Resource '$resource' does not exist.");}}public function getResources(){return array_keys($this->resources);}public function resourceInheritsFrom($resource,$inherit,$onlyParent=FALSE){$this->checkResource($resource);$this->checkResource($inherit);if($this->resources[$resource]['parent']===NULL){return FALSE;}$parent=$this->resources[$resource]['parent'];if($inherit===$parent){return TRUE;}elseif($onlyParent){return FALSE;}while($this->resources[$parent]['parent']!==NULL){$parent=$this->resources[$parent]['parent'];if($inherit===$parent){return TRUE;}}return FALSE;}public function 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 as$resourceRemoved){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resourceRemoved===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}unset($this->resources[$resource]);return$this;}public function removeAllResources(){foreach($this->resources as$resource=>$foo){foreach($this->rules['byResource']as$resourceCurrent=>$rules){if($resource===$resourceCurrent){unset($this->rules['byResource'][$resourceCurrent]);}}}$this->resources=array();return$this;}public function allow($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=NULL){$this->setRule(TRUE,self::ALLOW,$roles,$resources,$privileges,$assertion);return$this;}public function deny($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL,$assertion=NULL){$this->setRule(TRUE,self::DENY,$roles,$resources,$privileges,$assertion);return$this;}public function removeAllow($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL){$this->setRule(FALSE,self::ALLOW,$roles,$resources,$privileges);return$this;}public function removeDeny($roles=self::ALL,$resources=self::ALL,$privileges=self::ALL){$this->setRule(FALSE,self::DENY,$roles,$resources,$privileges);return$this;}protected function setRule($toAdd,$type,$roles,$resources,$privileges,$assertion=NULL){if($roles===self::ALL){$roles=array(self::ALL);}else{if(!is_array($roles)){$roles=array($roles);}foreach($roles as$role){$this->checkRole($role);}}if($resources===self::ALL){$resources=array(self::ALL);}else{if(!is_array($resources)){$resources=array($resources);}foreach($resources as$resource){$this->checkResource($resource);}}if($privileges===self::ALL){$privileges=array();}elseif(!is_array($privileges)){$privileges=array($privileges);}if($toAdd){foreach($resources as$resource){foreach($roles as$role){$rules=&$this->getRules($resource,$role,TRUE);if(count($privileges)===0){$rules['allPrivileges']['type']=$type;$rules['allPrivileges']['assert']=$assertion;if(!isset($rules['byPrivilege'])){$rules['byPrivilege']=array();}}else{foreach($privileges as$privilege){$rules['byPrivilege'][$privilege]['type']=$type;$rules['byPrivilege'][$privilege]['assert']=$assertion;}}}}}else{foreach($resources as$resource){foreach($roles as$role){$rules=&$this->getRules($resource,$role);if($rules===NULL){continue;}if(count($privileges)===0){if($resource===self::ALL&&$role===self::ALL){if($type===$rules['allPrivileges']['type']){$rules=array('allPrivileges'=>array('type'=>self::DENY,'assert'=>NULL),'byPrivilege'=>array());}continue;}if($type===$rules['allPrivileges']['type']){unset($rules['allPrivileges']);}}else{foreach($privileges as$privilege){if(isset($rules['byPrivilege'][$privilege])&&$type===$rules['byPrivilege'][$privilege]['type']){unset($rules['byPrivilege'][$privilege]);}}}}}}return$this;}public function isAllowed($role=self::ALL,$resource=self::ALL,$privilege=self::ALL){$this->queriedRole=$role;if($role!==self::ALL){if($role instanceof IRole){$role=$role->getRoleId();}$this->checkRole($role);}$this->queriedResource=$resource;if($resource!==self::ALL){if($resource instanceof IResource){$resource=$resource->getResourceId();}$this->checkResource($resource);}do{if($role!==NULL&&NULL!==($result=$this->searchRolePrivileges($privilege===self::ALL,$role,$resource,$privilege))){break;}if($privilege===self::ALL){if($rules=$this->getRules($resource,self::ALL)){foreach($rules['byPrivilege']as$privilege=>$rule){if(self::DENY===($result=$this->getRuleType($resource,NULL,$privilege))){break 2;}}if(NULL!==($result=$this->getRuleType($resource,NULL,NULL))){break;}}}else{if(NULL!==($result=$this->getRuleType($resource,NULL,$privilege))){break;}elseif(NULL!==($result=$this->getRuleType($resource,NULL,NULL))){break;}}$resource=$this->resources[$resource]['parent'];}while(TRUE);$this->queriedRole=$this->queriedResource=NULL;return$result;}public function getQueriedRole(){return$this->queriedRole;}public function getQueriedResource(){return$this->queriedResource;}private function searchRolePrivileges($all,$role,$resource,$privilege){$dfs=array('visited'=>array(),'stack'=>array($role));while(NULL!==($role=array_pop($dfs['stack']))){if(isset($dfs['visited'][$role])){continue;}if($all){if($rules=$this->getRules($resource,$role)){foreach($rules['byPrivilege']as$privilege2=>$rule){if(self::DENY===$this->getRuleType($resource,$role,$privilege2)){return self::DENY;}}if(NULL!==($type=$this->getRuleType($resource,$role,NULL))){return$type;}}}else{if(NULL!==($type=$this->getRuleType($resource,$role,$privilege))){return$type;}elseif(NULL!==($type=$this->getRuleType($resource,$role,NULL))){return$type;}}$dfs['visited'][$role]=TRUE;foreach($this->roles[$role]['parents']as$roleParent=>$foo){$dfs['stack'][]=$roleParent;}}return NULL;}private function getRuleType($resource,$role,$privilege){if(!$rules=$this->getRules($resource,$role)){return NULL;}if($privilege===self::ALL){if(isset($rules['allPrivileges'])){$rule=$rules['allPrivileges'];}else{return NULL;}}elseif(!isset($rules['byPrivilege'][$privilege])){return NULL;}else{$rule=$rules['byPrivilege'][$privilege];}if($rule['assert']===NULL||Nette\Utils\Callback::invoke($rule['assert'],$this,$role,$resource,$privilege)){return$rule['type'];}elseif($resource!==self::ALL||$role!==self::ALL||$privilege!==self::ALL){return NULL;}elseif(self::ALLOW===$rule['type']){return self::DENY;}else{return self::ALLOW;}}private function&getRules($resource,$role,$create=FALSE){$null=NULL;if($resource===self::ALL){$visitor=&$this->rules['allResources'];}else{if(!isset($this->rules['byResource'][$resource])){if(!$create){return$null;}$this->rules['byResource'][$resource]=array();}$visitor=&$this->rules['byResource'][$resource];}if($role===self::ALL){if(!isset($visitor['allRoles'])){if(!$create){return$null;}$visitor['allRoles']['byPrivilege']=array();}return$visitor['allRoles'];}if(!isset($visitor['byRole'][$role])){if(!$create){return$null;}$visitor['byRole'][$role]['byPrivilege']=array();}return$visitor['byRole'][$role];}}userlist=$userlist;$this->usersRoles=$usersRoles;}public function authenticate(array$credentials){list($username,$password)=$credentials;foreach($this->userlist as$name=>$pass){if(strcasecmp($name,$username)===0){if((string)$pass===(string)$password){return new Identity($name,isset($this->usersRoles[$name])?$this->usersRoles[$name]:NULL);}else{throw new AuthenticationException('Invalid password.',self::INVALID_CREDENTIAL);}}}throw new AuthenticationException("User '$username' not found.",self::IDENTITY_NOT_FOUND);}}storage=$storage;$this->authenticator=$authenticator;$this->authorizator=$authorizator;}public function getStorage(){return$this->storage;}public function login($id=NULL,$password=NULL){$this->logout(TRUE);if(!$id instanceof IIdentity){$id=$this->getAuthenticator()->authenticate(func_get_args());}$this->storage->setIdentity($id);$this->storage->setAuthenticated(TRUE);$this->onLoggedIn($this);}public function logout($clearIdentity=FALSE){if($this->isLoggedIn()){$this->onLoggedOut($this);$this->storage->setAuthenticated(FALSE);}if($clearIdentity){$this->storage->setIdentity(NULL);}}public function isLoggedIn(){return$this->storage->isAuthenticated();}public function getIdentity(){return$this->storage->getIdentity();}public function getId(){$identity=$this->getIdentity();return$identity?$identity->getId():NULL;}public function setAuthenticator(IAuthenticator$handler){$this->authenticator=$handler;return$this;}public function getAuthenticator($need=TRUE){if($need&&!$this->authenticator){throw new Nette\InvalidStateException('Authenticator has not been set.');}return$this->authenticator;}public function setExpiration($time,$whenBrowserIsClosed=TRUE,$clearIdentity=FALSE){$flags=($whenBrowserIsClosed?IUserStorage::BROWSER_CLOSED:0)|($clearIdentity?IUserStorage::CLEAR_IDENTITY:0);$this->storage->setExpiration($time,$flags);return$this;}public function getLogoutReason(){return$this->storage->getLogoutReason();}public function getRoles(){if(!$this->isLoggedIn()){return array($this->guestRole);}$identity=$this->getIdentity();return$identity&&$identity->getRoles()?$identity->getRoles():array($this->authenticatedRole);}public function isInRole($role){return in_array($role,$this->getRoles(),TRUE);}public function isAllowed($resource=IAuthorizator::ALL,$privilege=IAuthorizator::ALL){foreach($this->getRoles()as$role){if($this->getAuthorizator()->isAllowed($role,$resource,$privilege)){return TRUE;}}return FALSE;}public function setAuthorizator(IAuthorizator$handler){$this->authorizator=$handler;return$this;}public function getAuthorizator($need=TRUE){if($need&&!$this->authorizator){throw new Nette\InvalidStateException('Authorizator has not been set.');}return$this->authorizator;}}tokens=$tokens;}public function currentToken(){return isset($this->tokens[$this->position])?$this->tokens[$this->position]:NULL;}public function currentValue(){return isset($this->tokens[$this->position])?$this->tokens[$this->position][Tokenizer::VALUE]:NULL;}public function nextToken(){return$this->scan(func_get_args(),TRUE,TRUE);}public function nextValue(){return$this->scan(func_get_args(),TRUE,TRUE,TRUE);}public function nextAll(){return$this->scan(func_get_args(),FALSE,TRUE);}public function nextUntil($arg){return$this->scan(func_get_args(),FALSE,TRUE,FALSE,TRUE);}public function joinAll(){return$this->scan(func_get_args(),FALSE,TRUE,TRUE);}public function joinUntil($arg){return$this->scan(func_get_args(),FALSE,TRUE,TRUE,TRUE);}public function isCurrent($arg){if(!isset($this->tokens[$this->position])){return FALSE;}$args=func_get_args();$token=$this->tokens[$this->position];return in_array($token[Tokenizer::VALUE],$args,TRUE)||(isset($token[Tokenizer::TYPE])&&in_array($token[Tokenizer::TYPE],$args,TRUE));}public function isNext(){return(bool)$this->scan(func_get_args(),TRUE,FALSE);}public function isPrev(){return(bool)$this->scan(func_get_args(),TRUE,FALSE,FALSE,FALSE,TRUE);}public function reset(){$this->position=-1;return$this;}protected function next(){$this->position++;}protected function scan($wanted,$onlyFirst,$advance,$strings=FALSE,$until=FALSE,$prev=FALSE){$res=$onlyFirst?NULL:($strings?'':array());$pos=$this->position+($prev?-1:1);do{if(!isset($this->tokens[$pos])){if(!$wanted&&$advance&&!$prev&&$pos<=count($this->tokens)){$this->next();}return$res;}$token=$this->tokens[$pos];$type=isset($token[Tokenizer::TYPE])?$token[Tokenizer::TYPE]:NULL;if(!$wanted||(in_array($token[Tokenizer::VALUE],$wanted,TRUE)||in_array($type,$wanted,TRUE))^$until){while($advance&&!$prev&&$pos>$this->position){$this->next();}if($onlyFirst){return$strings?$token[Tokenizer::VALUE]:$token;}elseif($strings){$res.=$token[Tokenizer::VALUE];}else{$res[]=$token;}}elseif($until||!in_array($type,$this->ignored,TRUE)){return$res;}$pos+=$prev?-1:1;}while(TRUE);}}re='~('.implode(')|(',$patterns).')~A'.$flags;$keys=array_keys($patterns);$this->types=$keys===range(0,count($patterns)-1)?FALSE:$keys;}public function tokenize($input){if($this->types){preg_match_all($this->re,$input,$tokens,PREG_SET_ORDER);$len=0;$count=count($this->types);foreach($tokens 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=array(self::VALUE=>$match[0],self::OFFSET=>$len,self::TYPE=>$type);$len+=strlen($match[self::VALUE]);}if($len!==strlen($input)){$errorOffset=$len;}}else{$tokens=preg_split($this->re,$input,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_OFFSET_CAPTURE|PREG_SPLIT_DELIM_CAPTURE);$last=end($tokens);if($tokens&&!preg_match($this->re,$last[0])){$errorOffset=$last[1];}}if(isset($errorOffset)){list($line,$col)=$this->getCoordinates($input,$errorOffset);$token=str_replace("\n",'\n',substr($input,$errorOffset,10));throw new TokenizerException("Unexpected '$token' on line $line, column $col.");}return$tokens;}public static function getCoordinates($text,$offset){$text=substr($text,0,$offset);return array(substr_count($text,"\n")+1,$offset-strrpos("\n".$text,"\n")+1);}}panels[$id]));}$this->panels[$id]=$panel;return$this;}public function getPanel($id){return isset($this->panels[$id])?$this->panels[$id]:NULL;}public function render(){$obLevel=ob_get_level();$panels=array();foreach($this->panels as$id=>$panel){$idHtml=preg_replace('#[^a-z0-9]+#i','-',$id);try{$tab=(string)$panel->getTab();$panelHtml=$tab?(string)$panel->getPanel():NULL;if($tab&&$panel instanceof\Nette\Diagnostics\IBarPanel){$panelHtml=preg_replace('~(["\'.\s#])nette-(debug|inner|collapsed|toggle|toggle-collapsed)(["\'\s])~','$1tracy-$2$3',$panelHtml);$panelHtml=str_replace('tracy-toggle-collapsed','tracy-toggle tracy-collapsed',$panelHtml);}$panels[]=array('id'=>$idHtml,'tab'=>$tab,'panel'=>$panelHtml);}catch(\Exception$e){$panels[]=array('id'=>"error-$idHtml",'tab'=>"Error in $id",'panel'=>'

Error: '.$id.'

'.nl2br(htmlSpecialChars($e,ENT_IGNORE)).'
');while(ob_get_level()>$obLevel){ob_end_clean();}}}@session_start();$session=&$_SESSION['__NF']['debuggerbar'];if(preg_match('#^Location:#im',implode("\n",headers_list()))){$session[]=$panels;return;}foreach(array_reverse((array)$session)as$reqId=>$oldpanels){$panels[]=array('tab'=>'previous','panel'=>NULL,'previous'=>TRUE);foreach($oldpanels as$panel){$panel['id'].='-'.$reqId;$panels[]=$panel;}}$session=NULL;$info=array_filter($this->info);require __DIR__.'/templates/bar.phtml';}}panels,TRUE)){$this->panels[]=$panel;}return$this;}public function render(\Exception$exception){$panels=$this->panels;$info=array_filter($this->info);require __DIR__.'/templates/bluescreen.phtml';}public static function highlightFile($file,$line,$lines=15,array$vars=NULL){$source=@file_get_contents($file);if($source){$source=static::highlightPhp($source,$line,$lines,$vars);if($editor=Helpers::editorUri($file,$line)){$source=substr_replace($source,' data-tracy-href="'.htmlspecialchars($editor).'"',4,0);}return$source;}}public static function highlightPhp($source,$line,$lines=15,array$vars=NULL){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));$out=$source[0];$source=str_replace('
',"\n",$source[1]);$out.=static::highlightLine($source,$line,$lines);if($vars){$out=preg_replace_callback('#">\$(\w+)( )?#',function($m)use($vars){return array_key_exists($m[1],$vars)?'" title="'.str_replace('"','"',trim(strip_tags(Dumper::toHtml($vars[$m[1]])))).$m[0]:$m[0];},$out);}return"
$out
";}public static function highlightLine($html,$line,$lines=15){$source=explode("\n","\n".str_replace("\r\n","\n",$html));$out='';$spans=1;$start=$i=max(1,$line-floor($lines*2/3));while(--$i>=1){if(preg_match('#.*(]*>)#',$source[$i],$m)){if($m[1]!==''){$spans++;$out.=$m[1];}break;}}$source=array_slice($source,$start,$lines,TRUE);end($source);$numWidth=strlen((string)key($source));foreach($source as$n=>$s){$spans+=substr_count($s,']+>#',$s,$tags);if($n==$line){$out.=sprintf("%{$numWidth}s: %s\n%s",$n,strip_tags($s),implode('',$tags[0]));}else{$out.=sprintf("%{$numWidth}s: %s\n",$n,$s);}}$out.=str_repeat('',$spans).'';return$out;}public function isCollapsed($file){foreach($this->collapsePaths as$path){if(strpos(strtr($file,'\\','/'),strtr("$path/",'\\','/'))===0){return TRUE;}}return FALSE;}}'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 standards',E_DEPRECATED=>'Deprecated',E_USER_DEPRECATED=>'User Deprecated');private static$logger;private static$fireLogger;public static$logDirectory;public static$logSeverity=0;public static$email;public static$mailer=array('Tracy\Logger','defaultMailer');public static$emailSnooze=172800;const DEBUG='debug',INFO='info',WARNING='warning',ERROR='error',EXCEPTION='exception',CRITICAL='critical';private static$bar;final public function __construct(){throw new\LogicException;}public static function enable($mode=NULL,$logDirectory=NULL,$email=NULL){self::$enabled=TRUE;self::$time=isset($_SERVER['REQUEST_TIME_FLOAT'])?$_SERVER['REQUEST_TIME_FLOAT']:microtime(TRUE);if(isset($_SERVER['REQUEST_URI'])){self::$source=(!empty($_SERVER['HTTPS'])&&strcasecmp($_SERVER['HTTPS'],'off')?'https://':'http://').(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'').$_SERVER['REQUEST_URI'];}else{self::$source=empty($_SERVER['argv'])?'CLI':'CLI: '.implode(' ',$_SERVER['argv']);}error_reporting(E_ALL|E_STRICT);if(is_bool($mode)){self::$productionMode=$mode;}elseif($mode!==self::DETECT||self::$productionMode===NULL){$list=is_string($mode)?preg_split('#[,\s]+#',$mode):(array)$mode;if(!isset($_SERVER['HTTP_X_FORWARDED_FOR'])){$list[]='127.0.0.1';$list[]='::1';}self::$productionMode=!in_array(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:php_uname('n'),$list,TRUE);}if($email!==NULL){self::$email=$email;}if(is_string($logDirectory)){self::$logDirectory=realpath($logDirectory);if(self::$logDirectory===FALSE){self::_exceptionHandler(new\RuntimeException("Log directory is not found or is not directory."));}}elseif($logDirectory===FALSE){self::$logDirectory=NULL;}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')){self::_exceptionHandler(new\RuntimeException("Unable to set 'display_errors' because function ini_set() is disabled."));}register_shutdown_function(array(__CLASS__,'_shutdownHandler'));set_exception_handler(array(__CLASS__,'_exceptionHandler'));set_error_handler(array(__CLASS__,'_errorHandler'));foreach(array('Tracy\Bar','Tracy\BlueScreen','Tracy\DefaultBarPanel','Tracy\Dumper','Tracy\FireLogger','Tracy\Helpers','Tracy\Logger')as$class){class_exists($class);}}public static function getBlueScreen(){if(!self::$blueScreen){self::$blueScreen=new BlueScreen;self::$blueScreen->info=array('PHP '.PHP_VERSION,isset($_SERVER['SERVER_SOFTWARE'])?$_SERVER['SERVER_SOFTWARE']:NULL,'Tracy '.self::$version);}return self::$blueScreen;}public static function getBar(){if(!self::$bar){self::$bar=new Bar;self::$bar->addPanel(new DefaultBarPanel('time'));self::$bar->addPanel(new DefaultBarPanel('memory'));self::$bar->addPanel(new DefaultBarPanel('errors'),__CLASS__.':errors');self::$bar->addPanel(new DefaultBarPanel('dumps'),__CLASS__.':dumps');self::$bar->info=array('PHP '.PHP_VERSION,isset($_SERVER['SERVER_SOFTWARE'])?$_SERVER['SERVER_SOFTWARE']:NULL,'Tracy '.self::$version);}return self::$bar;}public static function setLogger($logger){self::$logger=$logger;}public static function getLogger(){if(!self::$logger){self::$logger=new Logger;self::$logger->directory=&self::$logDirectory;self::$logger->email=&self::$email;self::$logger->mailer=&self::$mailer;self::$logger->emailSnooze=&self::$emailSnooze;}return self::$logger;}public static function getFireLogger(){if(!self::$fireLogger){self::$fireLogger=new FireLogger;}return self::$fireLogger;}public static function isEnabled(){return self::$enabled;}public static function log($message,$priority=self::INFO){if(!self::$logDirectory){return;}$exceptionFilename=NULL;if($message instanceof\Exception){$exception=$message;while($exception){$tmp[]=($exception instanceof ErrorException?'Fatal error: '.$exception->getMessage():get_class($exception).': '.$exception->getMessage()).' in '.$exception->getFile().':'.$exception->getLine();$exception=$exception->getPrevious();}$exception=$message;$message=implode($tmp,"\ncaused by ");$hash=md5(preg_replace('~(Resource id #)\d+~','$1',$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;}}}elseif(!is_string($message)){$message=Dumper::toText($message);}if($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::getBlueScreen()->render($exception);ob_end_flush();ob_end_clean();fclose($logHandle);}}self::getLogger()->log(array(@date('[Y-m-d H-i-s]'),trim($message),self::$source?' @ '.self::$source:NULL,$exceptionFilename?' @@ '.basename($exceptionFilename):NULL),$priority);return$exceptionFilename?strtr($exceptionFilename,'\\/',DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR):NULL;}public static function _shutdownHandler(){if(!self::$enabled){return;}$error=error_get_last();if(in_array($error['type'],array(E_ERROR,E_CORE_ERROR,E_COMPILE_ERROR,E_PARSE),TRUE)){self::_exceptionHandler(Helpers::fixStack(new ErrorException($error['message'],0,$error['type'],$error['file'],$error['line'])),FALSE);}elseif(!connection_aborted()&&!self::$productionMode&&self::isHtmlMode()){self::getBar()->render();}}public static function _exceptionHandler(\Exception$exception,$exit=TRUE){if(!self::$enabled){return;}self::$enabled=FALSE;if(!headers_sent()){$protocol=isset($_SERVER['SERVER_PROTOCOL'])?$_SERVER['SERVER_PROTOCOL']:'HTTP/1.1';$code=isset($_SERVER['HTTP_USER_AGENT'])&&strpos($_SERVER['HTTP_USER_AGENT'],'MSIE ')!==FALSE?503:500;header("$protocol $code",TRUE,$code);if(self::isHtmlMode()){header('Content-Type: text/html; charset=UTF-8');}}$logMsg='Unable to log error. Check if directory is writable and path is absolute.';if(self::$productionMode){try{self::log($exception,self::EXCEPTION);}catch(\Exception$e){}$error=isset($e)?$logMsg:NULL;if(self::isHtmlMode()){require __DIR__.'/templates/error.phtml';}else{echo"ERROR: application encountered an error and can not continue.\n$error\n";}}elseif(!connection_aborted()&&self::isHtmlMode()){self::getBlueScreen()->render($exception);self::getBar()->render();}elseif(connection_aborted()||!self::fireLog($exception)){try{$file=self::log($exception,self::EXCEPTION);if($file&&!headers_sent()){header("X-Tracy-Error-Log: $file");}echo"$exception\n".($file?"(stored in $file)\n":'');if($file&&self::$browser){exec(self::$browser.' '.escapeshellarg($file));}}catch(\Exception$e){echo"$exception\n$logMsg {$e->getMessage()}\n";}}try{foreach(self::$onFatalError as$handler){call_user_func($handler,$exception);}}catch(\Exception$e){try{self::log($e,self::EXCEPTION);}catch(\Exception$e){}}if($exit){exit(254);}}public static function _errorHandler($severity,$message,$file,$line,$context){if(self::$scream){error_reporting(E_ALL|E_STRICT);}if($severity===E_RECOVERABLE_ERROR||$severity===E_USER_ERROR){if(Helpers::findTrace(debug_backtrace(PHP_VERSION_ID>=50306?DEBUG_BACKTRACE_IGNORE_ARGS:FALSE),'*::__toString')){$previous=isset($context['e'])&&$context['e']instanceof\Exception?$context['e']:NULL;$e=new ErrorException($message,0,$severity,$file,$line,$previous);$e->context=$context;self::_exceptionHandler($e);}$e=new ErrorException($message,0,$severity,$file,$line);$e->context=$context;throw$e;}elseif(($severity&error_reporting())!==$severity){return FALSE;}elseif(($severity&self::$logSeverity)===$severity){$e=new ErrorException($message,0,$severity,$file,$line);$e->context=$context;self::log($e,self::ERROR);return NULL;}elseif(!self::$productionMode&&(is_bool(self::$strictMode)?self::$strictMode:((self::$strictMode&$severity)===$severity))){$e=new ErrorException($message,0,$severity,$file,$line);$e->context=$context;self::_exceptionHandler($e);}$message='PHP '.(isset(self::$errorTypes[$severity])?self::$errorTypes[$severity]:'Unknown error').": $message";$count=&self::getBar()->getPanel(__CLASS__.':errors')->data["$file|$line|$message"];if($count++){return NULL;}elseif(self::$productionMode){self::log("$message in $file:$line",self::ERROR);return NULL;}else{self::fireLog(new ErrorException($message,0,$severity,$file,$line));return self::isHtmlMode()?NULL:FALSE;}}public static function dump($var,$return=FALSE){if($return){ob_start();Dumper::dump($var,array(Dumper::DEPTH=>self::$maxDepth,Dumper::TRUNCATE=>self::$maxLen));return ob_get_clean();}elseif(!self::$productionMode){Dumper::dump($var,array(Dumper::DEPTH=>self::$maxDepth,Dumper::TRUNCATE=>self::$maxLen,Dumper::LOCATION=>self::$showLocation));}return$var;}public static function timer($name=NULL){static$time=array();$now=microtime(TRUE);$delta=isset($time[$name])?$now-$time[$name]:0;$time[$name]=$now;return$delta;}public static function barDump($var,$title=NULL,array$options=NULL){if(!self::$productionMode){self::getBar()->getPanel(__CLASS__.':dumps')->data[]=array('title'=>$title,'dump'=>Dumper::toHtml($var,(array)$options+array(Dumper::DEPTH=>self::$maxDepth,Dumper::TRUNCATE=>self::$maxLen,Dumper::LOCATION=>self::$showLocation)));}return$var;}public static function fireLog($message){if(!self::$productionMode){return self::getFireLogger()->log($message);}}private static function isHtmlMode(){return empty($_SERVER['HTTP_X_REQUESTED_WITH'])&&PHP_SAPI!=='cli'&&!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list()));}}id=$id;}public function getTab(){ob_start();require __DIR__."/templates/bar.{$this->id}.tab.phtml";return ob_get_clean();}public function getPanel(){ob_start();if(is_file(__DIR__."/templates/bar.{$this->id}.panel.phtml")){require __DIR__."/templates/bar.{$this->id}.panel.phtml";}return ob_get_clean();}}'1;33','null'=>'1;33','number'=>'1;32','string'=>'1;36','array'=>'1;31','key'=>'1;37','object'=>'1;31','visibility'=>'1;30','resource'=>'1;37','indent'=>'1;30');public static$resources=array('stream'=>'stream_get_meta_data','stream-context'=>'stream_context_get_options','curl'=>'curl_getinfo');public static function dump($var,array$options=NULL){if(PHP_SAPI!=='cli'&&!preg_match('#^Content-Type: (?!text/html)#im',implode("\n",headers_list()))){echo self::toHtml($var,$options);}elseif(self::detectColors()){echo self::toTerminal($var,$options);}else{echo self::toText($var,$options);}return$var;}public static function toHtml($var,array$options=NULL){$options=(array)$options+array(self::DEPTH=>4,self::TRUNCATE=>150,self::COLLAPSE=>FALSE,self::COLLAPSE_COUNT=>7,self::LOCATION=>FALSE);list($file,$line,$code)=$options[self::LOCATION]?self::findLocation():NULL;return'
':'>').self::dumpVar($var,$options).($file?'in '.Helpers::editorLink($file,$line).'':'')."
\n";}public static function toText($var,array$options=NULL){return htmlspecialchars_decode(strip_tags(self::toHtml($var,$options)),ENT_QUOTES);}public static function toTerminal($var,array$options=NULL){return htmlspecialchars_decode(strip_tags(preg_replace_callback('#|#',function($m){return"\033[".(isset($m[1],Dumper::$terminalColors[$m[1]])?Dumper::$terminalColors[$m[1]]:'0').'m';},self::toHtml($var,$options))),ENT_QUOTES);}private static function dumpVar(&$var,array$options,$level=0){if(method_exists(__CLASS__,$m='dump'.gettype($var))){return self::$m($var,$options,$level);}else{return"unknown type\n";}}private static function dumpNull(){return"NULL\n";}private static function dumpBoolean(&$var){return''.($var?'TRUE':'FALSE')."\n";}private static function dumpInteger(&$var){return"$var\n";}private static function dumpDouble(&$var){$var=is_finite($var)?($tmp=json_encode($var)).(strpos($tmp,'.')===FALSE?'.0':''):var_export($var,TRUE);return"$var\n";}private static function dumpString(&$var,$options){return''.self::encodeString($options[self::TRUNCATE]&&strlen($var)>$options[self::TRUNCATE]?substr($var,0,$options[self::TRUNCATE]).' ... ':$var).''.(strlen($var)>1?' ('.strlen($var).')':'')."\n";}private static function dumpArray(&$var,$options,$level){static$marker;if($marker===NULL){$marker=uniqid("\x00",TRUE);}$out='array (';if(empty($var)){return$out.")\n";}elseif(isset($var[$marker])){return$out.(count($var)-1).") [ RECURSION ]\n";}elseif(!$options[self::DEPTH]||$level<$options[self::DEPTH]){$collapsed=$level?count($var)>=$options[self::COLLAPSE_COUNT]:$options[self::COLLAPSE];$out=''.$out.count($var).")\n';$var[$marker]=TRUE;foreach($var as$k=>&$v){if($k!==$marker){$out.=' '.str_repeat('| ',$level).''.''.(preg_match('#^\w+\z#',$k)?$k:self::encodeString($k)).' => '.self::dumpVar($v,$options,$level+1);}}unset($var[$marker]);return$out.'';}else{return$out.count($var).") [ ... ]\n";}}private static function dumpObject(&$var,$options,$level){if($var instanceof\Closure){$rc=new\ReflectionFunction($var);$fields=array();foreach($rc->getParameters()as$param){$fields[]='$'.$param->getName();}$fields=array('file'=>$rc->getFileName(),'line'=>$rc->getStartLine(),'variables'=>$rc->getStaticVariables(),'parameters'=>implode(', ',$fields));}elseif($var instanceof\SplFileInfo){$fields=array('path'=>$var->getPathname());}elseif($var instanceof\SplObjectStorage){$fields=array();foreach(clone$var as$obj){$fields[]=array('object'=>$obj,'data'=>$var[$obj]);}}else{$fields=(array)$var;}static$list=array();$rc=$var instanceof\Closure?new\ReflectionFunction($var):new\ReflectionClass($var);$out='getFileName(),$rc->getStartLine()))?' data-tracy-href="'.htmlspecialchars($editor).'"':'').'>'.get_class($var).' #'.substr(md5(spl_object_hash($var)),0,4).'';if(empty($fields)){return$out."\n";}elseif(in_array($var,$list,TRUE)){return$out." { RECURSION }\n";}elseif(!$options[self::DEPTH]||$level<$options[self::DEPTH]||$var instanceof\Closure){$collapsed=$level?count($fields)>=$options[self::COLLAPSE_COUNT]:$options[self::COLLAPSE];$out=''.$out."\n';$list[]=$var;foreach($fields as$k=>&$v){$vis='';if($k[0]==="\x00"){$vis=' '.($k[1]==='*'?'protected':'private').'';$k=substr($k,strrpos($k,"\x00")+1);}$out.=' '.str_repeat('| ',$level).''.''.(preg_match('#^\w+\z#',$k)?$k:self::encodeString($k))."$vis => ".self::dumpVar($v,$options,$level+1);}array_pop($list);return$out.'';}else{return$out." { ... }\n";}}private static function dumpResource(&$var,$options,$level){$type=get_resource_type($var);$out=''.htmlSpecialChars($type).' resource';if(isset(self::$resources[$type])){$out="$out\n
";foreach(call_user_func(self::$resources[$type],$var)as$k=>$v){$out.=' '.str_repeat('| ',$level).''.''.htmlSpecialChars($k)." => ".self::dumpVar($v,$options,$level+1);}return$out.'
';}return"$out\n";}private static function encodeString($s){static$table;if($table===NULL){foreach(array_merge(range("\x00","\x1F"),range("\x7F","\xFF"))as$ch){$table[$ch]='\x'.str_pad(dechex(ord($ch)),2,'0',STR_PAD_LEFT);}$table["\\"]='\\\\';$table["\r"]='\r';$table["\n"]='\n';$table["\t"]='\t';}if(preg_match('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u',$s)||preg_last_error()){$s=strtr($s,$table);}return'"'.htmlSpecialChars($s,ENT_NOQUOTES).'"';}private static function findLocation(){foreach(debug_backtrace(PHP_VERSION_ID>=50306?DEBUG_BACKTRACE_IGNORE_ARGS:FALSE)as$item){if(isset($item['class'])&&$item['class']===__CLASS__){$location=$item;continue;}elseif(isset($item['function'])){try{$reflection=isset($item['class'])?new\ReflectionMethod($item['class'],$item['function']):new\ReflectionFunction($item['function']);if(preg_match('#\s@tracySkipLocation\s#',$reflection->getDocComment())){$location=$item;continue;}}catch(\ReflectionException$e){}}break;}if(isset($location['file'],$location['line'])&&is_file($location['file'])){$lines=file($location['file']);$line=$lines[$location['line']-1];return array($location['file'],$location['line'],trim(preg_match('#\w*dump(er::\w+)?\(.*\)#i',$line,$m)?$m[0]:$line));}}private static function detectColors(){return self::$terminalColors&&(getenv('ConEmuANSI')==='ON'||getenv('ANSICON')!==FALSE||(defined('STDOUT')&&function_exists('posix_isatty')&&posix_isatty(STDOUT)));}}array());public static function log($message,$priority=self::DEBUG){if(!isset($_SERVER['HTTP_X_FIRELOGGER'])||headers_sent()){return 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']==='Tracy\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 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']==='Tracy\Debugger'&&($trace[1]['function']==='fireLog')){unset($trace[0]);}foreach($trace 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 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 TRUE;}private static function 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 Helpers::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&$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'(object) '.get_class($var));foreach($arr 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';}}}%%%',$editor,"$file:$line",rtrim($dir,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR,basename($file),$line?":$line":'');}else{return self::createHtml('%',$file.($line?":$line":''));}}public static function editorUri($file,$line){if(Debugger::$editor&&$file&&is_file($file)){return strtr(Debugger::$editor,array('%file'=>rawurlencode($file),'%line'=>(int)$line));}}public static function createHtml($mask){$args=func_get_args();return preg_replace_callback('#%#',function()use(&$args,&$count){return htmlspecialchars($args[++$count],ENT_IGNORE|ENT_QUOTES);},$mask);}public static function findTrace(array$trace,$method,&$index=NULL){$m=explode('::',$method);foreach($trace as$i=>$item){if(isset($item['function'])&&$item['function']===end($m)&&isset($item['class'])===isset($m[1])&&(!isset($item['class'])||$item['class']===$m[0]||$m[0]==='*'||is_subclass_of($item['class'],$m[0]))){$index=$i;return$item;}}}public static function fixStack($exception){if(function_exists('xdebug_get_function_stack')){$stack=array();foreach(array_slice(array_reverse(xdebug_get_function_stack()),2,-1)as$row){$frame=array('file'=>$row['file'],'line'=>$row['line'],'function'=>isset($row['function'])?$row['function']:'*unknown*','args'=>array());if(!empty($row['class'])){$frame['type']=isset($row['type'])&&$row['type']==='dynamic'?'->':'::';$frame['class']=$row['class'];}$stack[]=$frame;}$ref=new\ReflectionProperty('Exception','trace');$ref->setAccessible(TRUE);$ref->setValue($exception,$stack);}return$exception;}public static function fixEncoding($s){if(PHP_VERSION_ID<50400){return@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$s));}else{return htmlspecialchars_decode(htmlspecialchars($s,ENT_NOQUOTES|ENT_IGNORE,'UTF-8'),ENT_NOQUOTES);}}}directory)){throw new\RuntimeException("Directory '$this->directory' is not found or is not directory.");}if(is_array($message)){$message=implode(' ',$message);}$message=preg_replace('#\s*\r?\n\s*#',' ',trim($message));$file=$this->directory.'/'.strtolower($priority?:self::INFO).'.log';if(!@file_put_contents($file,$message.PHP_EOL,FILE_APPEND|LOCK_EX)){throw new\RuntimeException("Unable to write to log file '$file'. Is directory writable?");}if(in_array($priority,array(self::ERROR,self::EXCEPTION,self::CRITICAL),TRUE)&&$this->email&&$this->mailer&&@filemtime($this->directory.'/email-sent')+$this->emailSnoozedirectory.'/email-sent','sent')){call_user_func($this->mailer,$message,implode(', ',(array)$this->email));}}public static function defaultMailer($message,$email){$host=preg_replace('#[^\w.-]+#','',isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:php_uname('n'));$parts=str_replace(array("\r\n","\n"),array("\n",PHP_EOL),array('headers'=>implode("\n",array("From: noreply@$host",'X-Mailer: Tracy','Content-Type: text/plain; charset=UTF-8','Content-Transfer-Encoding: 8bit'))."\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']);}}start();}public function start(){foreach(get_included_files()as$file){if(fread(fopen($file,'r'),3)===self::BOM){$this->list[]=array($file,1,self::BOM);}}ob_start(array($this,'handler'),PHP_VERSION_ID>=50400?1:2);}public function handler($s,$phase){$trace=debug_backtrace(FALSE);if(isset($trace[0]['file'],$trace[0]['line'])){if($this->lastFile===$trace[0]['file']){$this->list[count($this->list)-1][2].=$s;}else{$this->list[]=array($this->lastFile=$trace[0]['file'],$trace[0]['line'],$s);}}if($phase===PHP_OUTPUT_HANDLER_FINAL){return$this->renderHtml();}}private function renderHtml(){$res='';foreach($this->list as$item){$res.=Helpers::editorLink($item[0],$item[1]).' '.str_replace(self::BOM,'BOM',Dumper::toHtml($item[2]))."
\n";}return$res.'
';}}/** * Debugger Bar * * This file is part of the Tracy (http://tracy.nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ /* common styles */ #tracy-debug { display: none; direction: ltr; } body#tracy-debug { margin: 5px 5px 0; display: block; } body #tracy-debug { position: absolute; bottom: 0; right: 0; } #tracy-debug * { font: inherit; color: inherit; background: transparent; margin: 0; padding: 0; border: none; text-align: inherit; list-style: inherit; opacity: 1; border-radius: 0; box-shadow: none; } #tracy-debug b, #tracy-debug strong { font-weight: bold; } #tracy-debug i, #tracy-debug em { font-style: italic; } #tracy-debug a { color: #125EAE; text-decoration: none; } #tracy-debug .tracy-panel a { color: #125EAE; text-decoration: none; } #tracy-debug a:hover, #tracy-debug a:active, #tracy-debug a:focus { background-color: #125EAE; color: white; } #tracy-debug .tracy-panel h2, #tracy-debug .tracy-panel h3, #tracy-debug .tracy-panel p { margin: .4em 0; } #tracy-debug .tracy-panel table { border-collapse: collapse; background: #FDF5CE; } #tracy-debug .tracy-panel tr:nth-child(2n) td { background: #F7F0CB; } #tracy-debug .tracy-panel td, #tracy-debug .tracy-panel th { border: 1px solid #E6DFBF; padding: 2px 5px; vertical-align: top; text-align: left; } #tracy-debug .tracy-panel th { background: #F4F3F1; color: #655E5E; font-size: 90%; font-weight: bold; } #tracy-debug .tracy-panel pre, #tracy-debug .tracy-panel code { font: 9pt/1.5 Consolas, monospace; } #tracy-debug table .tracy-right { text-align: right; } /* bar */ #tracy-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: fixed; right: 0; bottom: 0; overflow: auto; min-height: 21px; min-width: 50px; white-space: nowrap; z-index: 30000; opacity: .9; transition: opacity 0.2s; border-radius: 3px; box-shadow: 1px 1px 10px rgba(0, 0, 0, .15); } #tracy-debug-bar:hover { opacity: 1; transition: opacity 0.1s; } #tracy-debug-bar ul { list-style: none none; margin-left: 4px; clear: left; } #tracy-debug-bar li { float: left; } #tracy-debug-bar ul.tracy-previous li { font-size: 90%; opacity: .6; background: #F5F3EE; } #tracy-debug-bar ul.tracy-previous li:first-child { width: 45px; } #tracy-debug-bar img { vertical-align: middle; position: relative; top: -1px; margin-right: 3px; } #tracy-debug-bar li a { color: #000; display: block; padding: 0 4px; } #tracy-debug-bar li a:hover { color: black; background: #c3c1b8; } #tracy-debug-bar li .tracy-warning { color: #D32B2B; font-weight: bold; } #tracy-debug-bar li > span { padding: 0 4px; } #tracy-debug-logo { background: url('data:image/gif;base64,R0lGODlhLgALANU/AO3r4v7+/P79+pSSjeTi2vDu5ysrKllYVvPx6razraqoovr49YqJhJyalN3b1Pz69fb07oSCfdTRyaWinPf17/799kZFQ8bEvWRjYfTy6+3r57y6s4aFgfr48W5safTy7Xp4daGfmejl2peVkODd1cvJwXZ0cZCOio2Mh2ppZvLx7Ovo3vj28Xh2c317eIF/e4iGgbGvqHBvbOnn4HJxbZ+dmF9dWvLw6Pj27/z79/38+lJRT/379OTi1////////yH5BAEAAD8ALAAAAAAuAAsAAAb/QFZmSMxAhEQEy/dr/gQLRMD5CwQoiOEiN8s5dR1NgPQaoBo184CgGLhRp9K0ChhFSoJmoBAbnAYwEyoDI1M+NyhrMyMNCmk1IxMaE2cNEyMmJV4BCi4jIA5TGScmIyGQNTcSGBc+nB4bRhkFD309BSwUDDE8PAE4HDUZPgURMT0vCTk+GyYJIjcFBTcLAjEpFAQeCgBzTw0nAE0QDAozDgQXLRNLJbAVIRwIAiEwJHlUPxQwbyQ6VDkGcFghakALGS8i0IAhQYCAEyBE+JBwQIKPEwy65ftBTIYLCR3y5eAAguCPDy44uDiAgkQFAT5I7NjA40GBFCN8NKBBYaOenYQImABskUKjChtrTlgw4YCjAgspMNjAcADDAw0GSPhw5coJixQgMmzUccCCxg8GUlTgUcKGgQkLLBwg2SICh7cBDhjwCCJFBApM4toQmy9AChsrAu9oAVhABgYnLhgI0YEFhAcIDth4AOCFhc8GDiT+QTZFgY0LABC40YTCCgIQ9FQAQEIEgH9NchRwUEAADwA9CAhn/YOFasI/ggAAOw==') 0 50% no-repeat; min-width: 47px; cursor: move; } #tracy-debug-logo span { display: none; } /* panels */ #tracy-debug .tracy-panel { font: normal normal 12px/1.5 sans-serif; background: white; color: #333; text-align: left; } #tracy-debug h1 { font: normal normal 23px/1.4 Tahoma, sans-serif; color: #575753; margin: -5px -5px 5px; padding: 0 25px 5px 5px; } #tracy-debug .tracy-mode-peek .tracy-inner, #tracy-debug .tracy-mode-float .tracy-inner { max-width: 700px; max-height: 500px; overflow: auto; } #tracy-debug .tracy-panel .tracy-icons { display: none; } #tracy-debug .tracy-mode-peek { display: none; position: fixed; right: 0; bottom: 0; padding: 10px; min-width: 150px; min-height: 50px; border-radius: 5px; box-shadow: 1px 1px 20px rgba(102, 102, 102, 0.36); border: 1px solid rgba(0, 0, 0, 0.1); } #tracy-debug .tracy-mode-peek h1 { cursor: move; } #tracy-debug .tracy-mode-float { position: fixed; right: 0; bottom: 0; padding: 10px; min-width: 150px; min-height: 50px; border-radius: 5px; opacity: .95; transition: opacity 0.2s; box-shadow: 1px 1px 30px rgba(102, 102, 102, 0.36); border: 1px solid rgba(0, 0, 0, 0.1); } #tracy-debug .tracy-focused { opacity: 1; transition: opacity 0.1s; } #tracy-debug .tracy-mode-float h1 { cursor: move; } #tracy-debug .tracy-mode-float .tracy-icons { display: block; position: absolute; top: 0; right: 5px; font-size: 18px; } #tracy-debug .tracy-icons a { color: #575753; } #tracy-debug .tracy-icons a:hover { color: white; } /* dump */ #tracy-debug pre.tracy-dump div { padding-left: 3ex; } #tracy-debug pre.tracy-dump div div { border-left: 1px solid rgba(0, 0, 0, .1); margin-left: .5ex; } #tracy-debug pre.tracy-dump { background: #FDF5CE; padding: .4em .7em; border: 1px dotted silver; overflow: auto; } #tracy-debug table pre.tracy-dump { padding: 0; margin: 0; border: none; } #tracy-debug .tracy-dump-array, #tracy-debug .tracy-dump-object { color: #C22; } #tracy-debug .tracy-dump-string { color: #35D; } #tracy-debug .tracy-dump-number { color: #090; } #tracy-debug .tracy-dump-null, #tracy-debug .tracy-dump-bool { color: #850; } #tracy-debug .tracy-dump-visibility, #tracy-debug .tracy-dump-hash { font-size: 85%; color: #999; } #tracy-debug .tracy-dump-indent { display: none; } @media print { #tracy-debug * { display: none; } }

Dumped variables

data as$item):?>

data)){return;}?> variables

Errors

data as$item=>$count):list($file,$line,$message)=explode('|',$item,3)?>
data)){return;}?> data),$sum>1?' errors':' error'?>/** * Debugger Bar * * This file is part of the Tracy (http://tracy.nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ (function(){ var $ = Tracy.Query.factory; var Panel = Tracy.DebugPanel = function(id) { this.id = 'tracy-debug-panel-' + id; this.elem = $('#' + this.id); }; Panel.PEEK = 'tracy-mode-peek'; Panel.FLOAT = 'tracy-mode-float'; Panel.WINDOW = 'tracy-mode-window'; Panel.FOCUSED = 'tracy-focused'; Panel.zIndex = 20000; Panel.prototype.init = function() { var _this = this; this.elem.data().onmove = function(coords) { _this.moveConstrains(this, coords); }; this.elem.draggable({ rightEdge: true, bottomEdge: true, handle: this.elem.find('h1'), stop: function() { _this.toFloat(); } }).bind('mouseenter', function() { _this.focus(); }).bind('mouseleave', function() { _this.blur(); }); this.elem.find('.tracy-icons').find('a').bind('click', function(e) { if (this.rel === 'close') { _this.toPeek(); } else { _this.toWindow(); } e.preventDefault(); }); this.restorePosition(); }; Panel.prototype.is = function(mode) { return this.elem.hasClass(mode); }; Panel.prototype.focus = function(callback) { var elem = this.elem; if (this.is(Panel.WINDOW)) { elem.data().win.focus(); } else { clearTimeout(elem.data().displayTimeout); elem.data().displayTimeout = setTimeout(function() { elem.addClass(Panel.FOCUSED).show(); elem[0].style.zIndex = Panel.zIndex++; if (callback) { callback(); } }, 50); } }; Panel.prototype.blur = function() { var elem = this.elem; elem.removeClass(Panel.FOCUSED); if (this.is(Panel.PEEK)) { clearTimeout(elem.data().displayTimeout); elem.data().displayTimeout = setTimeout(function() { elem.hide(); }, 50); } }; Panel.prototype.toFloat = function() { this.elem.removeClass(Panel.WINDOW). removeClass(Panel.PEEK). addClass(Panel.FLOAT). show(); this.reposition(); }; Panel.prototype.toPeek = function() { this.elem.removeClass(Panel.WINDOW). removeClass(Panel.FLOAT). addClass(Panel.PEEK). hide(); document.cookie = this.id + '=; path=/'; // delete position }; Panel.prototype.toWindow = function() { var offset = this.elem.offset(); offset.left += typeof window.screenLeft === 'number' ? window.screenLeft : (window.screenX + 10); offset.top += typeof window.screenTop === 'number' ? window.screenTop : (window.screenY + 50); var win = window.open('', this.id.replace(/-/g, '_'), 'left='+offset.left+',top='+offset.top+',width='+offset.width+',height='+(offset.height+15)+',resizable=yes,scrollbars=yes'); if (!win) { return; } var doc = win.document; doc.write('
¤ ×
      ';?>
    • ',trim($panel['tab']),'';endif?>
    • ×
ms/** * Debugger Bluescreen * * This file is part of the Tracy (http://tracy.nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ html { overflow-y: scroll; } #tracyBluescreen { font: 9pt/1.5 Verdana, sans-serif; background: white; color: #333; position: absolute; z-index: 20000; left: 0; top: 0; width: 100%; text-align: left; } #tracyBluescreen * { font: inherit; color: inherit; background: transparent; border: none; margin: 0; padding: 0; text-align: inherit; text-indent: 0; } #tracyBluescreen b { font-weight: bold; } #tracyBluescreen i { font-style: italic; } #tracyBluescreen a { text-decoration: none; color: #328ADC; padding: 2px 4px; margin: -2px -4px; } #tracyBluescreen a:hover, #tracyBluescreen a:active, #tracyBluescreen a:focus { color: #085AA3; } #tracyBluescreenIcon { position: absolute; right: .5em; top: .5em; text-decoration: none; background: #CD1818; color: white !important; padding: 3px; } #tracyBluescreenError { background: #CD1818; color: white; font: 13pt/1.5 Verdana, sans-serif !important; display: block; } #tracyBluescreenError #tracyBsSearch { color: #CD1818; font-size: .7em; } #tracyBluescreenError:hover #tracyBsSearch { color: #ED8383; } #tracyBluescreen h1 { font-size: 18pt; font-weight: normal; text-shadow: 1px 1px 0 rgba(0, 0, 0, .4); margin: .7em 0; } #tracyBluescreen h2 { font: 14pt/1.5 sans-serif !important; color: #888; margin: .6em 0; } #tracyBluescreen h3 { font: bold 10pt/1.5 Verdana, sans-serif !important; margin: 1em 0; padding: 0; } #tracyBluescreen p, #tracyBluescreen pre { margin: .8em 0 } #tracyBluescreen pre, #tracyBluescreen code, #tracyBluescreen table { font: 9pt/1.5 Consolas, monospace !important; } #tracyBluescreen pre, #tracyBluescreen table { background: #FDF5CE; padding: .4em .7em; border: 1px dotted silver; overflow: auto; } #tracyBluescreen table pre { padding: 0; margin: 0; border: none; } #tracyBluescreen table { border-collapse: collapse; width: 100%; } #tracyBluescreen td, #tracyBluescreen th { vertical-align: top; text-align: left; padding: 2px 6px; border: 1px solid #e6dfbf; } #tracyBluescreen th { font-weight: bold; } #tracyBluescreen tr > :first-child { width: 20%; } #tracyBluescreen tr:nth-child(2n), #tracyBluescreen tr:nth-child(2n) pre { background-color: #F7F0CB; } #tracyBluescreen ol { margin: 1em 0; padding-left: 2.5em; } #tracyBluescreen ul { font: 7pt/1.5 Verdana, sans-serif !important; padding: 2em 4em; margin: 1em 0 0; color: #777; background: #F6F5F3; border-top: 1px solid #DDD; } #tracyBluescreenLogo a { position: absolute; bottom: 0; right: 0; width: 100px; height: 50px; background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAUBAMAAAD/1DctAAAAMFBMVEWupZzj39rEvbTy8O3X0sz9/PvGwLu8tavQysHq6OS0rKP5+Pbd2dT29fPMxbzPx8DKErMJAAAACXBIWXMAAAsTAAALEwEAmpwYAAACGUlEQVQoFX3TQWgTQRQA0MWLIJJDYehBTykhG5ERTx56K1u8eEhCYtomE7x5L4iLh0ViF7egewuFFqSIYE6hIHsIYQ6CQSg9CDKn4QsNCRlB59C74J/ZNHW1+An5+bOPyf6/s46oz2P+A0yIeZZ2ieEHi6TOnLKTxvWq+b52mxlVO3xnM1s7xLX1504XQH65OnW2dBqn7cCkYsFsfYsWpyY/2salmFTpEyzeR8zosYqMdiPDXdyU52K1wgEa/SjGpdEwUAxqvRfckQCDOyFearsEHe2grvkh/cFAHKvdtI3lcVceKQIOFpv+FOZaNPQBwJZLPp+hfrvT5JZXaUFsR8zqQc9qSgAharkfS5M/5F6nGJJAtXq/eLr3ucZpHccSxOOIPaQhtHohpCH2Xu6rLmQ0djnr4/+J3C6v+AW8/XWYxwYNdlhWj/P5fPSTQwVr0T9lGxdaBCqErNZaqYnEwbkjEB3NasGF3lPdrHa1nnxNOMgj0+neePUPjd2v/qVvUv29ifvc19huQ48qwXShy/9o8o3OSk0cs37mOFd0Ydgvsf/oZEnPVtggfd66lORn9mDyyzXU13SRtH2L6aR5T/snGAcZPfAXz5J1YlJWBEuxdMYqQecpBrlM49xAbmqyHA+xlA1FxBtqT2xmJoNXZlIt74ZBLeJ9ZGDqByNI7p543idzJ23vXEv7IgnsxiS+eNtwNbFdLq7+Bi4wQ0I4SVb9AAAAAElFTkSuQmCC') no-repeat; opacity: .6; padding: 0; margin: 0; } #tracyBluescreenLogo a:hover, #tracyBluescreenLogo a:active, #tracyBluescreenLogo a:focus { opacity: 1; transition: opacity 0.1s; } #tracyBluescreen div.panel { padding: 1px 25px; } #tracyBluescreen div.inner { background: #F4F3F1; padding: .1em 1em 1em; border-radius: 8px; } #tracyBluescreen .outer { overflow: auto; } /* source code */ #tracyBluescreen pre.php div { min-width: 100%; float: left; white-space: pre; } #tracyBluescreen .highlight { background: #CD1818; color: white; font-weight: bold; font-style: normal; display: block; padding: 0 .4em; margin: 0 -.4em; } #tracyBluescreen .line { color: #9F9C7F; font-weight: normal; font-style: normal; } #tracyBluescreen a[href^=editor\:] { color: inherit; border-bottom: 1px dotted rgba(0, 0, 0, .2); } #tracyBluescreen span[data-tracy-href] { border-bottom: 1px dotted rgba(0, 0, 0, .2); } /* toggle */ html.js #tracyBluescreen .tracy-collapsed { display: none; } html.js #tracyBluescreen .tracy-toggle.tracy-collapsed { display: inline; } #tracyBluescreen .tracy-toggle { cursor: pointer; } #tracyBluescreen .tracy-toggle:after { content: " ▼"; opacity: .4; } #tracyBluescreen .tracy-toggle.tracy-collapsed:after { content: " ►"; opacity: .4; } /* dump */ #tracyBluescreen .tracy-dump-array, #tracyBluescreen .tracy-dump-object { color: #C22; } #tracyBluescreen .tracy-dump-string { color: #35D; } #tracyBluescreen .tracy-dump-number { color: #090; } #tracyBluescreen .tracy-dump-null, #tracyBluescreen .tracy-dump-bool { color: #850; } #tracyBluescreen .tracy-dump-visibility, #tracyBluescreen .tracy-dump-hash { font-size: 85%; color: #998; } #tracyBluescreen .tracy-dump-indent { display: none; } #tracyBluescreen pre.tracy-dump div { padding-left: 3ex; } #tracyBluescreen pre.tracy-dump div div { border-left: 1px solid rgba(0, 0, 0, .1); margin-left: .5ex; } #tracyBluescreen .caused { float: right; padding: .3em .6em; background: #df8075; border-radius: 0 0 0 8px; white-space: nowrap; } #tracyBluescreen .caused a { color: white; }getSeverity()]))?Debugger::$errorTypes[$exception->getSeverity()]:get_class($exception);$counter=0;?>
<?php echo htmlspecialchars($title)?>

getCode()?' #'.$exception->getCode():'')?>

getMessage(),ENT_IGNORE)?> getMessage()))?>" id="tracyBsSearch" rel="noreferrer">search►

getPrevious()):?>
>

Caused by

getCode()?' #'.$ex->getCode():''))?>

getMessage(),ENT_IGNORE)?>

getTrace();$expanded=NULL?> getSeverity(),array(E_USER_NOTICE,E_USER_WARNING,E_USER_DEPRECATED)))&&$this->isCollapsed($ex->getFile())){foreach($stack as$key=>$row){if(isset($row['file'])&&!$this->isCollapsed($row['file'])){$expanded=$key;break;}}}?>

Source file

File: getFile(),$ex->getLine())?>

getFile())):?>getFile(),$ex->getLine(),15,$ex instanceof\ErrorException&&isset($ex->context)?$ex->context:NULL)?>

Call stack

    $row):?>
  1. inner-code " class="tracy-toggle">source  "?> '?> (" class="tracy-toggle tracy-collapsed">arguments)

    id="tracyBsSrc">
    ">
    "> getParameters();}catch(\Exception$e){$params=array();}foreach($row['args']as$k=>$v){echo'\n";}?>
    ',htmlspecialchars(isset($params[$k])?'$'.$params[$k]->name:"#$k"),'';echo Dumper::toHtml($v);echo"
context)&&is_array($ex->context)):?>

Variables

context as$k=>$v){echo'\n";}?>
$',htmlspecialchars($k),'',Dumper::toHtml($v),"
getPrevious());?>
'?>

Environment

$_SERVER

$v)echo'\n";?>
',htmlspecialchars($k),'',Dumper::toHtml($v),"

$_SESSION

empty

$v)echo'\n";?>
',htmlspecialchars($k),'',$k==='__NF'?'Nette Session':Dumper::toHtml($v),"

Nette Session

$v)echo'\n";?>
',htmlspecialchars($k),'',Dumper::toHtml($v),"

Constants

$v){echo'';echo'\n";}?>
',htmlspecialchars($k),'',Dumper::toHtml($v),"

Included files ()

\n";}?>
',htmlspecialchars($v,ENT_IGNORE),"

Configuration options

|.+\z#s','',ob_get_clean())?>

HTTP request

Headers

$v)echo'\n";?>
',htmlspecialchars($k),'',htmlspecialchars($v),"

$

empty

$v)echo'\n";?>
',htmlspecialchars($k),'',Dumper::toHtml($v),"

HTTP response

Headers

';?>

no headers

  • Report generated at
/** * Dumper * * This file is part of the Tracy (http://tracy.nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ /* toggle */ .tracy-collapsed { display: none; } .tracy-toggle.tracy-collapsed { display: inline; } .tracy-toggle { cursor: pointer; } .tracy-toggle:after { content: " ▼"; opacity: .4; } .tracy-toggle.tracy-collapsed:after { content: " ►"; } /* dump */ pre.tracy-dump { text-align: left; color: #444; background: white; } pre.tracy-dump div { padding-left: 3ex; } pre.tracy-dump div div { border-left: 1px solid rgba(0, 0, 0, .1); margin-left: .5ex; } .tracy-dump-array, .tracy-dump-object { color: #C22; } .tracy-dump-string { color: #35D; } .tracy-dump-number { color: #090; } .tracy-dump-null, .tracy-dump-bool { color: #850; } .tracy-dump-visibility, .tracy-dump-hash { font-size: 85%; color: #999; } .tracy-dump-indent { display: none; } span[data-tracy-href] { border-bottom: 1px dotted rgba(0, 0, 0, .2); }/** * Dumper * * This file is part of the Tracy (http://tracy.nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ (function(){ var $ = Tracy.Query.factory; var Dumper = Tracy.Dumper = {}; Dumper.init = function() { $(document.body).bind('click', function(e) { var link; // enables & ctrl key for (link = e.target; link && (!link.getAttribute || !link.getAttribute('data-tracy-href')); link = link.parentNode) {} if (e.ctrlKey && link) { location.href = link.getAttribute('data-tracy-href'); return false; } if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) { return; } // enables or toggling link = $(e.target).closest('.tracy-toggle'); if (!link.length) { return; } var collapsed = link.hasClass('tracy-collapsed'), ref = link[0].getAttribute('data-ref') || link[0].getAttribute('href', 2), dest = ref && ref !== '#' ? $(ref) : link.next(''), panel = link.closest('.tracy-panel'), oldPosition = panel.position(); link[collapsed ? 'removeClass' : 'addClass']('tracy-collapsed'); dest[collapsed ? 'removeClass' : 'addClass']('tracy-collapsed'); e.preventDefault(); if (panel.length) { var newPosition = panel.position(); panel.position({ right: newPosition.right - newPosition.width + oldPosition.width, bottom: newPosition.bottom - newPosition.height + oldPosition.height }); } }); }; })(); Server Error

Server Error

We're sorry! The server encountered an internal error and was unable to complete your request. Please try again later.

error 500Tracy says: ",htmlspecialchars($error)?>

/** * tracyQ * * This file is part of the Tracy. * Copyright (c) 2004, 2014 David Grudl (http://davidgrudl.com) */ var Tracy = Tracy || {}; (function(){ // supported cross-browser selectors: #id | div | div.class | .class var Query = Tracy.Query = function(selector) { if (typeof selector === "string") { selector = this._find(document, selector); } else if (!selector || selector.nodeType || selector.length === undefined || selector === window) { selector = [selector]; } for (var i = 0, len = selector.length; i < len; i++) { if (selector[i]) { this[this.length++] = selector[i]; } } }; Query.factory = function(selector) { return new Query(selector); }; Query.prototype.length = 0; Query.prototype.find = function(selector) { return new Query(this._find(this[0], selector)); }; Query.prototype._find = function(context, selector) { if (!context || !selector) { return []; } else if (document.querySelectorAll) { return context.querySelectorAll(selector); } else if (selector.charAt(0) === '#') { // #id return [document.getElementById(selector.substring(1))]; } else { // div | div.class | .class selector = selector.split('.'); var elms = context.getElementsByTagName(selector[0] || '*'); if (selector[1]) { var list = [], pattern = new RegExp('(^|\\s)' + selector[1] + '(\\s|$)'); for (var i = 0, len = elms.length; i < len; i++) { if (pattern.test(elms[i].className)) { list.push(elms[i]); } } return list; } else { return elms; } } }; Query.prototype.dom = function() { return this[0]; }; Query.prototype.each = function(callback) { for (var i = 0; i < this.length; i++) { if (callback.apply(this[i]) === false) { break; } } return this; }; // cross-browser event attach Query.prototype.bind = function(event, handler) { if (document.addEventListener && (event === 'mouseenter' || event === 'mouseleave')) { // simulate mouseenter & mouseleave using mouseover & mouseout var old = handler; event = event === 'mouseenter' ? 'mouseover' : 'mouseout'; handler = function(e) { for (var target = e.relatedTarget; target; target = target.parentNode) { if (target === this) { return; } // target must not be inside this } old.call(this, e); }; } return this.each(function() { var elem = this, // fixes 'this' in iE data = elem.tracy ? elem.tracy : elem.tracy = {}, events = data.events = data.events || {}; // use own handler queue if (!events[event]) { var handlers = events[event] = [], generic = function(e) { // dont worry, 'e' is passed in IE if (!e.target) { e.target = e.srcElement; } if (!e.preventDefault) { e.preventDefault = function() { e.returnValue = false; }; } if (!e.stopPropagation) { e.stopPropagation = function() { e.cancelBubble = true; }; } e.stopImmediatePropagation = function() { this.stopPropagation(); i = handlers.length; }; for (var i = 0; i < handlers.length; i++) { handlers[i].call(elem, e); } }; if (document.addEventListener) { // non-IE elem.addEventListener(event, generic, false); } else if (document.attachEvent) { // IE < 9 elem.attachEvent('on' + event, generic); } } events[event].push(handler); }); }; // adds class to element Query.prototype.addClass = function(className) { return this.each(function() { this.className = (this.className.replace(/^|\s+|$/g, ' ').replace(' '+className+' ', ' ') + ' ' + className).replace(/^\s+|\s+$/g,''); }); }; // removes class from element Query.prototype.removeClass = function(className) { return this.each(function() { this.className = this.className.replace(/^|\s+|$/g, ' ').replace(' '+className+' ', ' ').replace(/^\s+|\s+$/g,''); }); }; // tests whether element has given class Query.prototype.hasClass = function(className) { return this[0] && this[0].className && this[0].className.replace(/^|\s+|$/g, ' ').indexOf(' '+className+' ') > -1; }; Query.prototype.show = function() { Query.displays = Query.displays || {}; return this.each(function() { var tag = this.tagName; if (!Query.displays[tag]) { Query.displays[tag] = (new Query(document.body.appendChild(document.createElement(tag)))).css('display'); } this.style.display = Query.displays[tag]; }); }; Query.prototype.hide = function() { return this.each(function() { this.style.display = 'none'; }); }; Query.prototype.css = function(property) { if (this[0] && this[0].currentStyle) { return this[0].currentStyle[property]; } else if (this[0] && window.getComputedStyle) { return document.defaultView.getComputedStyle(this[0], null).getPropertyValue(property) } }; Query.prototype.data = function() { if (this[0]) { return this[0].tracy ? this[0].tracy : this[0].tracy = {}; } }; Query.prototype._trav = function(elem, selector, fce) { selector = selector.split('.'); while (elem && !(elem.nodeType === 1 && (!selector[0] || elem.tagName.toLowerCase() === selector[0]) && (!selector[1] || (new Query(elem)).hasClass(selector[1])))) { elem = elem[fce]; } return new Query(elem || []); }; Query.prototype.closest = function(selector) { return this._trav(this[0], selector, 'parentNode'); }; Query.prototype.prev = function(selector) { return this._trav(this[0] && this[0].previousSibling, selector, 'previousSibling'); }; Query.prototype.next = function(selector) { return this._trav(this[0] && this[0].nextSibling, selector, 'nextSibling'); }; // returns total offset for element Query.prototype.offset = function(coords) { if (coords) { return this.each(function() { var elem = this, ofs = {left: -coords.left || 0, top: -coords.top || 0}; while (elem = elem.offsetParent) { ofs.left += elem.offsetLeft; ofs.top += elem.offsetTop; } this.style.left = -ofs.left + 'px'; this.style.top = -ofs.top + 'px'; }); } else if (this[0]) { var elem = this[0], res = {left: elem.offsetLeft, top: elem.offsetTop}; while (elem = elem.offsetParent) { res.left += elem.offsetLeft; res.top += elem.offsetTop; } return res; } }; // returns current position or move to new position Query.prototype.position = function(coords) { if (coords) { return this.each(function() { if (this.tracy && this.tracy.onmove) { this.tracy.onmove.call(this, coords); } for (var item in coords) { this.style[item] = coords[item] + 'px'; } }); } else if (this[0]) { return { left: this[0].offsetLeft, top: this[0].offsetTop, right: this[0].style.right ? parseInt(this[0].style.right, 10) : 0, bottom: this[0].style.bottom ? parseInt(this[0].style.bottom, 10) : 0, width: this[0].offsetWidth, height: this[0].offsetHeight }; } }; // makes element draggable Query.prototype.draggable = function(options) { var elem = this[0], dE = document.documentElement, started; options = options || {}; (options.handle ? new Query(options.handle) : this).bind('mousedown', function(e) { var $el = new Query(options.handle ? elem : this); e.preventDefault(); e.stopPropagation(); if (Query.dragging) { // missed mouseup out of window? return dE.onmouseup(e); } var pos = $el.position(), deltaX = options.rightEdge ? pos.right + e.clientX : pos.left - e.clientX, deltaY = options.bottomEdge ? pos.bottom + e.clientY : pos.top - e.clientY; Query.dragging = true; started = false; dE.onmousemove = function(e) { e = e || window.event; if (!started) { if (options.draggedClass) { $el.addClass(options.draggedClass); } if (options.start) { options.start(e, $el); } started = true; } var pos = {}; pos[options.rightEdge ? 'right' : 'left'] = options.rightEdge ? deltaX - e.clientX : e.clientX + deltaX; pos[options.bottomEdge ? 'bottom' : 'top'] = options.bottomEdge ? deltaY - e.clientY : e.clientY + deltaY; $el.position(pos); return false; }; dE.onmouseup = function(e) { if (started) { if (options.draggedClass) { $el.removeClass(options.draggedClass); } if (options.stop) { options.stop(e || window.event, $el); } } Query.dragging = dE.onmousemove = dE.onmouseup = null; return false; }; }).bind('click', function(e) { if (started) { e.stopImmediatePropagation(); } }); return this; }; })();$value){if($recursive&&is_array($value)){$obj->$key=static::from($value,TRUE);}else{$obj->$key=$value;}}return$obj;}public function getIterator(){return new\RecursiveArrayIterator($this);}public function count(){return count((array)$this);}public function offsetSet($key,$value){if(!is_scalar($key)){throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.',gettype($key)));}$this->$key=$value;}public function offsetGet($key){return$this->$key;}public function offsetExists($key){return isset($this->$key);}public function offsetUnset($key){unset($this->$key);}}list);}public function count(){return count($this->list);}public function offsetSet($index,$value){if($index===NULL){$this->list[]=$value;}elseif($index<0||$index>=count($this->list)){throw new Nette\OutOfRangeException('Offset invalid or out of range');}else{$this->list[(int)$index]=$value;}}public function offsetGet($index){if($index<0||$index>=count($this->list)){throw new Nette\OutOfRangeException('Offset invalid or out of range');}return$this->list[(int)$index];}public function offsetExists($index){return$index>=0&&$indexlist);}public function offsetUnset($index){if($index<0||$index>=count($this->list)){throw new Nette\OutOfRangeException('Offset invalid or out of range');}array_splice($this->list,(int)$index,1);}}$v){if(is_array($v)&&is_array($arr2[$k])){$res[$k]=self::mergeTree($v,$arr2[$k]);}}return$res;}public static function searchKey($arr,$key){$foo=array($key=>NULL);return array_search(key($foo),array_keys($arr),TRUE);}public static function insertBefore(array&$arr,$key,array$inserted){$offset=self::searchKey($arr,$key);$arr=array_slice($arr,0,$offset,TRUE)+$inserted+array_slice($arr,$offset,count($arr),TRUE);}public static function insertAfter(array&$arr,$key,array$inserted){$offset=self::searchKey($arr,$key);$offset=$offset===FALSE?count($arr):$offset+1;$arr=array_slice($arr,0,$offset,TRUE)+$inserted+array_slice($arr,$offset,count($arr),TRUE);}public static function renameKey(array&$arr,$oldKey,$newKey){$offset=self::searchKey($arr,$oldKey);if($offset!==FALSE){$keys=array_keys($arr);$keys[$offset]=$newKey;$arr=array_combine($keys,$arr);}}public static function grep(array$arr,$pattern,$flags=0){return Strings::pcre('preg_grep',array($pattern,$arr,$flags));}public static function flatten(array$arr,$preserveKeys=FALSE){$res=array();$cb=$preserveKeys?function($v,$k)use(&$res){$res[$k]=$v;}:function($v)use(&$res){$res[]=$v;};array_walk_recursive($arr,$cb);return$res;}public static function isList($value){return is_array($value)&&(!$value||array_keys($value)===range(0,count($value)-1));}public static function associate(array$arr,$path){$parts=is_array($path)?$path:preg_split('#(\[\]|->|=|\|)#',$path,NULL,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);if(!$parts||$parts[0]==='='||$parts[0]==='|'||$parts===array('->')){throw new Nette\InvalidArgumentException("Invalid path '$path'.");}$res=$parts[0]==='->'?new\stdClass:array();foreach($arr as$rowOrig){$row=(array)$rowOrig;$x=&$res;for($i=0;$i'){if(isset($parts[++$i])){$x=&$x->{$row[$parts[$i]]};}else{$row=is_object($rowOrig)?$rowOrig:(object)$row;}}elseif($part!=='|'){$x=&$x[(string)$row[$part]];}}if($x===NULL){$x=$row;}}return$res;}}getNative();}$class=class_exists('Nette\Reflection\Method')?'Nette\Reflection\Method':'ReflectionMethod';if(is_string($callable)&&strpos($callable,'::')){return new$class($callable);}elseif(is_array($callable)){return new$class($callable[0],$callable[1]);}elseif(is_object($callable)&&!$callable instanceof\Closure){return new$class($callable,'__invoke');}else{$class=class_exists('Nette\Reflection\GlobalFunction')?'Nette\Reflection\GlobalFunction':'ReflectionFunction';return new$class($callable);}}public static function isStatic($callable){return is_array($callable)?is_string($callable[0]):is_string($callable);}public static function unwrap(\Closure$closure){$rm=new\ReflectionFunction($closure);$vars=$rm->getStaticVariables();return isset($vars['_callable_'])?$vars['_callable_']:NULL;}}format('Y-m-d H:i:s'),$time->getTimezone());}elseif(is_numeric($time)){if($time<=self::YEAR){$time+=time();}$tmp=new static('@'.$time);return$tmp->setTimeZone(new\DateTimeZone(date_default_timezone_get()));}else{return new static($time);}}public function __toString(){return$this->format('Y-m-d H:i:s');}public function modifyClone($modify=''){$dolly=clone$this;return$modify?$dolly->modify($modify):$dolly;}public function setTimestamp($timestamp){$zone=$this->getTimezone();$this->__construct('@'.$timestamp);return$this->setTimeZone($zone);}public function getTimestamp(){$ts=$this->format('U');return is_float($tmp=$ts*1)?$ts:$tmp;}public static function createFromFormat($format,$time,$timezone=NULL){if($timezone===NULL){$timezone=new\DateTimeZone(date_default_timezone_get());}elseif(is_string($timezone)){$timezone=new\DateTimeZone($timezone);}elseif(!$timezone instanceof\DateTimeZone){throw new Nette\InvalidArgumentException('Invalid timezone given');}return static::from(parent::createFromFormat($format,$time,$timezone));}}isDir()){static::createDir($dest.'/'.$iterator->getSubPathName());}else{static::copy($item,$dest.'/'.$iterator->getSubPathName());}}}else{static::createDir(dirname($dest));if(@stream_copy_to_stream(fopen($source,'r'),fopen($dest,'w'))===FALSE){throw new Nette\IOException("Unable to copy file '$source' to '$dest'.");}}}public static function delete($path){if(is_file($path)||is_link($path)){$func=DIRECTORY_SEPARATOR==='\\'&&is_dir($path)?'rmdir':'unlink';if(!@$func($path)){throw new Nette\IOException("Unable to delete '$path'.");}}elseif(is_dir($path)){foreach(new\FilesystemIterator($path)as$item){static::delete($item);}if(!@rmdir($path)){throw new Nette\IOException("Unable to delete directory '$path'.");}}}public static function rename($name,$newName,$overwrite=TRUE){if(!$overwrite&&file_exists($newName)){throw new Nette\InvalidStateException("File or directory '$newName' already exists.");}elseif(!file_exists($name)){throw new Nette\IOException("File or directory '$name' not found.");}else{static::createDir(dirname($newName));static::delete($newName);if(!@rename($name,$newName)){throw new Nette\IOException("Unable to rename file or directory '$name' to '$newName'.");}}}public static function write($file,$content,$mode=0666){static::createDir(dirname($file));if(@file_put_contents($file,$content)===FALSE){throw new Nette\IOException("Unable to write file '$file'.");}if($mode!==NULL&&!@chmod($file,$mode)){throw new Nette\IOException("Unable to chmod file '$file'.");}}public static function isAbsolute($path){return(bool)preg_match('#([a-z]:)?[/\\\\]|[a-z][a-z0-9+.-]*://#Ai',$path);}}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,'track'=>1);public static function el($name=NULL,$attrs=NULL){$el=new 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;}public function setName($name,$isEmpty=NULL){if($name!==NULL&&!is_string($name)){throw new Nette\InvalidArgumentException(sprintf('Name must be string or NULL, %s given.',gettype($name)));}$this->name=$name;$this->isEmpty=$isEmpty===NULL?isset(static::$emptyElements[$name]):(bool)$isEmpty;return$this;}public function getName(){return$this->name;}public function isEmpty(){return$this->isEmpty;}public function addAttributes(array$attrs){$this->attrs=array_merge($this->attrs,$attrs);return$this;}public function __set($name,$value){$this->attrs[$name]=$value;}public function&__get($name){return$this->attrs[$name];}public function __isset($name){return isset($this->attrs[$name]);}public function __unset($name){unset($this->attrs[$name]);}public function __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 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;}public function href($path,$query=NULL){if($query){$query=http_build_query($query,NULL,'&');if($query!==''){$path.='?'.$query;}}$this->attrs['href']=$path;return$this;}public function setHtml($html){if(is_array($html)){throw new Nette\InvalidArgumentException(sprintf('Textual content must be a scalar, %s given.',gettype($html)));}$this->removeChildren();$this->children[]=(string)$html;return$this;}public function getHtml(){$s='';foreach($this->children as$child){if(is_object($child)){$s.=$child->render();}else{$s.=$child;}}return$s;}public function setText($text){if(!is_array($text)&&!$text instanceof self){$text=htmlspecialchars((string)$text,ENT_NOQUOTES);}return$this->setHtml($text);}public function getText(){return html_entity_decode(strip_tags($this->getHtml()),ENT_QUOTES,'UTF-8');}public function add($child){return$this->insert(NULL,$child);}public function create($name,$attrs=NULL){$this->insert(NULL,$child=static::el($name,$attrs));return$child;}public function insert($index,$child,$replace=FALSE){if($child instanceof Html||is_scalar($child)){if($index===NULL){$this->children[]=$child;}else{array_splice($this->children,(int)$index,$replace?1:0,array($child));}}else{throw new Nette\InvalidArgumentException(sprintf('Child node must be scalar or Html object, %s given.',is_object($child)?get_class($child):gettype($child)));}return$this;}public function offsetSet($index,$child){$this->insert($index,$child,TRUE);}public function offsetGet($index){return$this->children[$index];}public function offsetExists($index){return isset($this->children[$index]);}public function offsetUnset($index){if(isset($this->children[$index])){array_splice($this->children,(int)$index,1);}}public function count(){return count($this->children);}public function removeChildren(){$this->children=array();}public function getIterator(){if(func_num_args()&&func_get_arg(0)){throw new Nette\DeprecatedException(__METHOD__." doesn't support deep iterator any more.");}return new\ArrayIterator($this->children);}public function getChildren(){return$this->children;}public function render($indent=NULL){$s=$this->startTag();if(!$this->isEmpty){if($indent!==NULL){$indent++;}foreach($this->children 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;}public function __toString(){return$this->render();}public function startTag(){if($this->name){return'<'.$this->name.$this->attributes().(static::$xhtml&&$this->isEmpty?' />':'>');}else{return'';}}public function endTag(){return$this->name&&!$this->isEmpty?'name.'>':'';}public function attributes(){if(!is_array($this->attrs)){return'';}$s='';foreach($this->attrs 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 as$k=>$v){if($v!==NULL&&$v!==FALSE){if(is_array($v)){$v=Json::encode($v);}$q=strpos($v,'"')===FALSE?'"':"'";$s.=' data-'.$k.'='.$q.str_replace(array('&',$q),array('&',$q==='"'?'"':'''),$v).(strpos($v,'`')!==FALSE&&strpbrk($v,' <>"\'')===FALSE?' ':'').$q;}}continue;}elseif(strncmp($key,'data-',5)===0){$value=Json::encode($value);}else{$tmp=NULL;foreach($value 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;}$q=strpos($value,'"')===FALSE?'"':"'";$s.=' '.$key.'='.$q.str_replace(array('&',$q),array('&',$q==='"'?'"':'''),$value).(strpos($value,'`')!==FALSE&&strpbrk($value,' <>"\'')===FALSE?' ':'').$q;}$s=str_replace('@','@',$s);return$s;}public function __clone(){foreach($this->children as$key=>$value){if(is_object($value)){$this->children[$key]=clone$value;}}}} * $image = Image::fromFile('nette.jpg'); * $image->resize(150, 100); * $image->sharpen(); * $image->send(); * * * @author David Grudl * * @method void alphaBlending(bool $on) * @method void antialias(bool $on) * @method void arc($x, $y, $w, $h, $s, $e, $color) * @method void char($font, $x, $y, $char, $color) * @method void charUp($font, $x, $y, $char, $color) * @method int colorAllocate($red, $green, $blue) * @method int colorAllocateAlpha($red, $green, $blue, $alpha) * @method int colorAt($x, $y) * @method int colorClosest($red, $green, $blue) * @method int colorClosestAlpha($red, $green, $blue, $alpha) * @method int colorClosestHWB($red, $green, $blue) * @method void colorDeallocate($color) * @method int colorExact($red, $green, $blue) * @method int colorExactAlpha($red, $green, $blue, $alpha) * @method void colorMatch(Image $image2) * @method int colorResolve($red, $green, $blue) * @method int colorResolveAlpha($red, $green, $blue, $alpha) * @method void colorSet($index, $red, $green, $blue) * @method array colorsForIndex($index) * @method int colorsTotal() * @method int colorTransparent([$color]) * @method void convolution(array $matrix, float $div, float $offset) * @method void copy(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH) * @method void copyMerge(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity) * @method void copyMergeGray(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity) * @method void copyResampled(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) * @method void copyResized(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) * @method void dashedLine($x1, $y1, $x2, $y2, $color) * @method void ellipse($cx, $cy, $w, $h, $color) * @method void fill($x, $y, $color) * @method void filledArc($cx, $cy, $w, $h, $s, $e, $color, $style) * @method void filledEllipse($cx, $cy, $w, $h, $color) * @method void filledPolygon(array $points, $numPoints, $color) * @method void filledRectangle($x1, $y1, $x2, $y2, $color) * @method void fillToBorder($x, $y, $border, $color) * @method void filter($filtertype [, ...]) * @method int fontHeight($font) * @method int fontWidth($font) * @method array ftBBox($size, $angle, string $fontFile, string $text [, array $extrainfo]) * @method array ftText($size, $angle, $x, $y, $col, string $fontFile, string $text [, array $extrainfo]) * @method void gammaCorrect(float $inputgamma, float $outputgamma) * @method int interlace([$interlace]) * @method bool isTrueColor() * @method void layerEffect($effect) * @method void line($x1, $y1, $x2, $y2, $color) * @method int loadFont(string $file) * @method void paletteCopy(Image $source) * @method void polygon(array $points, $numPoints, $color) * @method array psBBox(string $text, $font, $size [, $space] [, $tightness] [, float $angle]) * @method void psEncodeFont($fontIndex, string $encodingfile) * @method void psExtendFont($fontIndex, float $extend) * @method void psFreeFont($fontindex) * @method resource psLoadFont(string $filename) * @method void psSlantFont($fontIndex, float $slant) * @method array psText(string $text, $font, $size, $color, $backgroundColor, $x, $y [, $space] [, $tightness] [, float $angle] [, $antialiasSteps]) * @method void rectangle($x1, $y1, $x2, $y2, $col) * @method Image rotate(float $angle, $backgroundColor) * @method void saveAlpha(bool $saveflag) * @method void setBrush(Image $brush) * @method void setPixel($x, $y, $color) * @method void setStyle(array $style) * @method void setThickness($thickness) * @method void setTile(Image $tile) * @method void string($font, $x, $y, string $s, $col) * @method void stringUp($font, $x, $y, string $s, $col) * @method void trueColorToPalette(bool $dither, $ncolors) * @method array ttfBBox($size, $angle, string $fontfile, string $text) * @method array ttfText($size, $angle, $x, $y, $color, string $fontfile, string $text) * @method int types() * @property-read int $width * @property-read int $height * @property-read resource $imageResource */class Image extends Nette\Object{const SHRINK_ONLY=1;const STRETCH=2;const FIT=0;const FILL=4;const EXACT=8;const JPEG=IMAGETYPE_JPEG,PNG=IMAGETYPE_PNG,GIF=IMAGETYPE_GIF;const 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 ENLARGE=0;private$image;public static function rgb($red,$green,$blue,$transparency=0){return 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)));}public static function fromFile($file,&$format=NULL){if(!extension_loaded('gd')){throw new Nette\NotSupportedException('PHP extension GD is not loaded.');}$info=@getimagesize($file);switch($format=$info[2]){case self::JPEG:return new static(imagecreatefromjpeg($file));case self::PNG:return new static(imagecreatefrompng($file));case self::GIF:return new static(imagecreatefromgif($file));default:throw new UnknownImageFileException("Unknown image type or file '$file' not found.");}}public static function getFormatFromString($s){$types=array('image/jpeg'=>self::JPEG,'image/gif'=>self::GIF,'image/png'=>self::PNG);$type=finfo_buffer(finfo_open(FILEINFO_MIME_TYPE),$s);return isset($types[$type])?$types[$type]:NULL;}public static function fromString($s,&$format=NULL){if(!extension_loaded('gd')){throw new Nette\NotSupportedException('PHP extension GD is not loaded.');}$format=static::getFormatFromString($s);return new static(imagecreatefromstring($s));}public static function fromBlank($width,$height,$color=NULL){if(!extension_loaded('gd')){throw new Nette\NotSupportedException('PHP extension GD is not loaded.');}$width=(int)$width;$height=(int)$height;if($width<1||$height<1){throw new Nette\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 new static($image);}public function __construct($image){$this->setImageResource($image);imagesavealpha($image,TRUE);}public function getWidth(){return imagesx($this->image);}public function getHeight(){return imagesy($this->image);}protected function setImageResource($image){if(!is_resource($image)||get_resource_type($image)!=='gd'){throw new Nette\InvalidArgumentException('Image is not valid.');}$this->image=$image;return$this;}public function getImageResource(){return$this->image;}public function 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->image,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->image,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;}public static function 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 new Nette\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 new Nette\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 array(max((int)$newWidth,1),max((int)$newHeight,1));}public function 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->image,0,0,$left,$top,$width,$height);$this->image=$newImage;return$this;}public static function 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 array($left,$top,$newWidth,$newHeight);}public function sharpen(){imageconvolution($this->image,array(array(-1,-1,-1),array(-1,24,-1),array(-1,-1,-1)),16,0);return$this;}public function 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->image,$image->getImageResource(),$left,$top,0,0,$image->getWidth(),$image->getHeight());}elseif($opacity<>0){imagecopymerge($this->image,$image->getImageResource(),$left,$top,0,0,$image->getWidth(),$image->getHeight(),$opacity);}return$this;}public function 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 self::JPEG:$quality=$quality===NULL?85:max(0,min(100,(int)$quality));return imagejpeg($this->image,$file,$quality);case self::PNG:$quality=$quality===NULL?9:max(0,min(9,(int)$quality));return imagepng($this->image,$file,$quality);case self::GIF:return imagegif($this->image,$file);default:throw new Nette\InvalidArgumentException('Unsupported image type.');}}public function toString($type=self::JPEG,$quality=NULL){ob_start();$this->save(NULL,$quality,$type);return ob_get_clean();}public function __toString(){try{return$this->toString();}catch(\Exception$e){if(func_num_args()){throw$e;}trigger_error("Exception in ".__METHOD__."(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}",E_USER_ERROR);}}public function send($type=self::JPEG,$quality=NULL){if($type!==self::GIF&&$type!==self::PNG&&$type!==self::JPEG){throw new Nette\InvalidArgumentException('Unsupported image type.');}header('Content-Type: '.image_type_to_mime_type($type));return$this->save(NULL,$quality,$type);}public function __call($name,$args){$function='image'.$name;if(function_exists($function)){foreach($args as$key=>$value){if($value instanceof self){$args[$key]=$value->getImageResource();}elseif(is_array($value)&&isset($value['red'])){$args[$key]=imagecolorallocatealpha($this->image,$value['red'],$value['green'],$value['blue'],$value['alpha']);}}array_unshift($args,$this->image);$res=call_user_func_array($function,$args);return is_resource($res)&&get_resource_type($res)==='gd'?$this->setImageResource($res):$res;}return parent::__call($name,$args);}public function __clone(){ob_start();imagegd2($this->image);$this->setImageResource(imagecreatefromstring(ob_get_clean()));}}class UnknownImageFileException extends\Exception{}'The maximum stack depth has been exceeded',JSON_ERROR_STATE_MISMATCH=>'Syntax error, malformed JSON',JSON_ERROR_CTRL_CHAR=>'Unexpected control character found',JSON_ERROR_SYNTAX=>'Syntax error, malformed JSON',5=>'Invalid UTF-8 sequence');final public function __construct(){throw new Nette\StaticClassException;}public static function encode($value,$options=0){$flags=PHP_VERSION_ID>=50400?(JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|($options&self::PRETTY?JSON_PRETTY_PRINT:0)):0;if(PHP_VERSION_ID<50500){$json=Callback::invokeSafe('json_encode',array($value,$flags),function($message){throw new JsonException($message);});}else{$json=json_encode($value,$flags);}if($error=json_last_error()){$message=isset(static::$messages[$error])?static::$messages[$error]:(PHP_VERSION_ID>=50500?json_last_error_msg():'Unknown error');throw new JsonException($message,$error);}$json=str_replace(array("\xe2\x80\xa8","\xe2\x80\xa9"),array('\u2028','\u2029'),$json);return$json;}public static function decode($json,$options=0){$json=(string)$json;if(!preg_match('##u',$json)){throw new JsonException('Invalid UTF-8 sequence',5);}$args=array($json,(bool)($options&self::FORCE_ARRAY));$args[]=512;if(PHP_VERSION_ID>=50400&&!(defined('JSON_C_VERSION')&&PHP_INT_SIZE>4)){$args[]=JSON_BIGINT_AS_STRING;}$value=call_user_func_array('json_decode',$args);if($value===NULL&&$json!==''&&strcasecmp($json,'null')){$error=json_last_error();throw new JsonException(isset(static::$messages[$error])?static::$messages[$error]:'Unknown error',$error);}return$value;}}class JsonException extends\Exception{}getName();}if($callback===NULL){return ObjectMixin::getExtensionMethod($class,$name);}else{ObjectMixin::setExtensionMethod($class,$name,$callback);}}public function&__get($name){return ObjectMixin::get($this,$name);}public function __set($name,$value){ObjectMixin::set($this,$name,$value);}public function __isset($name){return ObjectMixin::has($this,$name);}public function __unset($name){ObjectMixin::remove($this,$name);}}$name instanceof\Closure){return call_user_func_array($_this->$name,$args);}elseif($isProp==='event'){if(is_array($_this->$name)||$_this->$name instanceof\Traversable){foreach($_this->$name as$handler){Callback::invokeArgs($handler,$args);}}elseif($_this->$name!==NULL){throw new Nette\UnexpectedValueException("Property $class::$$name must be array or NULL, ".gettype($_this->$name)." given.");}}elseif(isset($methods[$name])&&is_array($methods[$name])){list($op,$rp,$type)=$methods[$name];if(count($args)!==($op==='get'?0:1)){throw new Nette\InvalidArgumentException("$class::$name() expects ".($op==='get'?'no':'1').' argument, '.count($args).' given.');}elseif($type&&$args&&!self::checkType($args[0],$type)){throw new Nette\InvalidArgumentException("Argument passed to $class::$name() must be $type, ".gettype($args[0]).' given.');}if($op==='get'){return$rp->getValue($_this);}elseif($op==='set'){$rp->setValue($_this,$args[0]);}elseif($op==='add'){$val=$rp->getValue($_this);$val[]=$args[0];$rp->setValue($_this,$val);}return$_this;}elseif($cb=self::getExtensionMethod($class,$name)){array_unshift($args,$_this);return Callback::invokeArgs($cb,$args);}else{if(method_exists($class,$name)){$class='parent';}throw new MemberAccessException("Call to undefined method $class::$name().");}}public static function callStatic($class,$method,$args){throw new MemberAccessException("Call to undefined static method $class::$method().");}public static function&get($_this,$name){$class=get_class($_this);$uname=ucfirst($name);$methods=&self::getMethods($class);if($name===''){throw new MemberAccessException("Cannot read a class '$class' property without name.");}elseif(isset($methods[$m='get'.$uname])||isset($methods[$m='is'.$uname])){if($methods[$m]===0){$rm=new\ReflectionMethod($class,$m);$methods[$m]=$rm->returnsReference();}if($methods[$m]===TRUE){return$_this->$m();}else{$val=$_this->$m();return$val;}}elseif(isset($methods[$name])){if(PHP_VERSION_ID>=50400){$rm=new\ReflectionMethod($class,$name);$val=$rm->getClosure($_this);}else{$val=Callback::closure($_this,$name);}return$val;}else{$type=isset($methods['set'.$uname])?'a write-only':'an undeclared';throw new MemberAccessException("Cannot read $type property $class::\$$name.");}}public static function set($_this,$name,$value){$class=get_class($_this);$uname=ucfirst($name);$methods=&self::getMethods($class);if($name===''){throw new MemberAccessException("Cannot write to a class '$class' property without name.");}elseif(self::hasProperty($class,$name)){$_this->$name=$value;}elseif(isset($methods[$m='set'.$uname])){$_this->$m($value);}else{$type=isset($methods['get'.$uname])||isset($methods['is'.$uname])?'a read-only':'an undeclared';throw new MemberAccessException("Cannot write to $type property $class::\$$name.");}}public static function remove($_this,$name){$class=get_class($_this);if(!self::hasProperty($class,$name)){throw new MemberAccessException("Cannot unset the property $class::\$$name.");}}public static function has($_this,$name){$name=ucfirst($name);$methods=&self::getMethods(get_class($_this));return$name!==''&&(isset($methods['get'.$name])||isset($methods['is'.$name]));}private static function hasProperty($class,$name){$prop=&self::$props[$class][$name];if($prop===NULL){$prop=FALSE;try{$rp=new\ReflectionProperty($class,$name);if($rp->isPublic()&&!$rp->isStatic()){$prop=preg_match('#^on[A-Z]#',$name)?'event':TRUE;}}catch(\ReflectionException$e){}}return$prop;}private static function&getMethods($class){if(!isset(self::$methods[$class])){self::$methods[$class]=array_fill_keys(get_class_methods($class),0)+self::getMagicMethods($class);if($parent=get_parent_class($class)){self::$methods[$class]+=self::getMethods($parent);}}return self::$methods[$class];}/** * Returns array of magic methods defined by annotation @method. * @return array */public static function getMagicMethods($class){$rc=new\ReflectionClass($class);preg_match_all('~^ [ \t*]* @method [ \t]+ (?: [^\s(]+ [ \t]+ )? (set|get|is|add) ([A-Z]\w*) [ \t]* (?: \( [ \t]* ([^)$\s]+) )? ()~mx',$rc->getDocComment(),$matches,PREG_SET_ORDER);$methods=array();foreach($matches as$m){list(,$op,$prop,$type)=$m;$name=$op.$prop;$prop=strtolower($prop[0]).substr($prop,1).($op==='add'?'s':'');if($rc->hasProperty($prop)&&($rp=$rc->getProperty($prop))&&!$rp->isStatic()){$rp->setAccessible(TRUE);if($op==='get'||$op==='is'){$type=NULL;$op='get';}elseif(!$type&&preg_match('#@var[ \t]+(\S+)'.($op==='add'?'\[\]#':'#'),$rp->getDocComment(),$m)){$type=$m[1];}if($rc->inNamespace()&&preg_match('#^[A-Z]\w+(\[|\||\z)#',$type)){$type=$rc->getNamespaceName().'\\'.$type;}$methods[$name]=array($op,$rp,$type);}}return$methods;}public static function checkType(&$val,$type){if(strpos($type,'|')!==FALSE){$found=NULL;foreach(explode('|',$type)as$type){$tmp=$val;if(self::checkType($tmp,$type)){if($val===$tmp){return TRUE;}$found[]=$tmp;}}if($found){$val=$found[0];return TRUE;}return FALSE;}elseif(substr($type,-2)==='[]'){if(!is_array($val)){return FALSE;}$type=substr($type,0,-2);$res=array();foreach($val as$k=>$v){if(!self::checkType($v,$type)){return FALSE;}$res[$k]=$v;}$val=$res;return TRUE;}switch(strtolower($type)){case NULL:case'mixed':return TRUE;case'bool':case'boolean':return($val===NULL||is_scalar($val))&&settype($val,'bool');case'string':return($val===NULL||is_scalar($val)||(is_object($val)&&method_exists($val,'__toString')))&&settype($val,'string');case'int':case'integer':return($val===NULL||is_bool($val)||is_numeric($val))&&((float)(int)$val===(float)$val)&&settype($val,'int');case'float':return($val===NULL||is_bool($val)||is_numeric($val))&&settype($val,'float');case'scalar':case'array':case'object':case'callable':case'resource':case'null':return call_user_func("is_$type",$val);default:return$val instanceof$type;}}public static function setExtensionMethod($class,$name,$callback){$name=strtolower($name);self::$extMethods[$name][$class]=Callback::closure($callback);self::$extMethods[$name]['']=NULL;}public static function getExtensionMethod($class,$name){$list=&self::$extMethods[strtolower($name)];$cache=&$list[''][$class];if(isset($cache)){return$cache;}foreach(array($class)+class_parents($class)+class_implements($class)as$cl){if(isset($list[$cl])){return$cache=$list[$cl];}}return$cache=FALSE;}}page=(int)$page;return$this;}public function getPage(){return$this->base+$this->getPageIndex();}public function getFirstPage(){return$this->base;}public function getLastPage(){return$this->itemCount===NULL?NULL:$this->base+max(0,$this->getPageCount()-1);}public function setBase($base){$this->base=(int)$base;return$this;}public function getBase(){return$this->base;}protected function getPageIndex(){$index=max(0,$this->page-$this->base);return$this->itemCount===NULL?$index:min($index,max(0,$this->getPageCount()-1));}public function isFirst(){return$this->getPageIndex()===0;}public function isLast(){return$this->itemCount===NULL?FALSE:$this->getPageIndex()>=$this->getPageCount()-1;}public function getPageCount(){return$this->itemCount===NULL?NULL:(int)ceil($this->itemCount/$this->itemsPerPage);}public function setItemsPerPage($itemsPerPage){$this->itemsPerPage=max(1,(int)$itemsPerPage);return$this;}public function getItemsPerPage(){return$this->itemsPerPage;}public function setItemCount($itemCount){$this->itemCount=($itemCount===FALSE||$itemCount===NULL)?NULL:max(0,(int)$itemCount);return$this;}public function getItemCount(){return$this->itemCount;}public function getOffset(){return$this->getPageIndex()*$this->itemsPerPage;}public function getCountdownOffset(){return$this->itemCount===NULL?NULL:max(0,$this->itemCount-($this->getPageIndex()+1)*$this->itemsPerPage);}public function getLength(){return$this->itemCount===NULL?$this->itemsPerPage:min($this->itemsPerPage,$this->itemCount-$this->getPageIndex()*$this->itemsPerPage);}}=50400||!defined('PHP_WINDOWS_VERSION_BUILD'))){$rand3=openssl_random_pseudo_bytes($length);}if(empty($rand3)&&function_exists('mcrypt_create_iv')&&(PHP_VERSION_ID>=50307||!defined('PHP_WINDOWS_VERSION_BUILD'))){$rand3=mcrypt_create_iv($length,MCRYPT_DEV_URANDOM);}if(empty($rand3)&&@is_readable('/dev/urandom')){$rand3=file_get_contents('/dev/urandom',FALSE,NULL,-1,$length);}if(empty($rand3)){static$cache;$rand3=$cache?:$cache=md5(serialize($_SERVER),TRUE);}$s='';for($i=0;$i<$length;$i++){if($i % 5===0){list($rand,$rand2)=explode(' ',microtime());$rand+=lcg_value();}$rand*=$chLen;$s.=$charlist[($rand+$rand2+ord($rand3[$i % strlen($rand3)]))%$chLen];$rand-=(int)$rand;}return$s;}}1&&strcasecmp(func_get_arg(1),'UTF-8')){trigger_error(__METHOD__.' supports only UTF-8 encoding.',E_USER_DEPRECATED);}return$s===self::fixEncoding($s);}public static function fixEncoding($s){if(func_num_args()>1&&strcasecmp(func_get_arg(1),'UTF-8')){trigger_error(__METHOD__.' supports only UTF-8 encoding.',E_USER_DEPRECATED);}if(PHP_VERSION_ID<50400){return@iconv('UTF-16','UTF-8//IGNORE',iconv('UTF-8','UTF-16//IGNORE',$s));}else{return htmlspecialchars_decode(htmlspecialchars($s,ENT_NOQUOTES|ENT_IGNORE,'UTF-8'),ENT_NOQUOTES);}}public static function chr($code){if(func_num_args()>1&&strcasecmp(func_get_arg(1),'UTF-8')){trigger_error(__METHOD__.' supports only UTF-8 encoding.',E_USER_DEPRECATED);}return iconv('UTF-32BE','UTF-8//IGNORE',pack('N',$code));}public static function startsWith($haystack,$needle){return strncmp($haystack,$needle,strlen($needle))===0;}public static function endsWith($haystack,$needle){return strlen($needle)===0||substr($haystack,-strlen($needle))===$needle;}public static function contains($haystack,$needle){return strpos($haystack,$needle)!==FALSE;}public static function substring($s,$start,$length=NULL){if($length===NULL){$length=self::length($s);}if(function_exists('mb_substr')){return mb_substr($s,$start,$length,'UTF-8');}return iconv_substr($s,$start,$length,'UTF-8');}public static function normalize($s){$s=self::normalizeNewLines($s);$s=preg_replace('#[\x00-\x08\x0B-\x1F\x7F]+#','',$s);$s=preg_replace('#[\t ]+$#m','',$s);$s=trim($s,"\n");return$s;}public static function normalizeNewLines($s){return str_replace(array("\r\n","\r"),"\n",$s);}public static function toAscii($s){$s=preg_replace('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u','',$s);$s=strtr($s,'`\'"^~',"\x01\x02\x03\x04\x05");$s=str_replace(array("\xE2\x80\x9E","\xE2\x80\x9C","\xE2\x80\x9D","\xE2\x80\x9A","\xE2\x80\x98","\xE2\x80\x99","\xC2\xBB","\xC2\xAB"),array("\x03","\x03","\x03","\x02","\x02","\x02",">>","<<"),$s);if(ICONV_IMPL==='glibc'){$s=@iconv('UTF-8','WINDOWS-1250//TRANSLIT',$s);$s=strtr($s,"\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e"."\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"."\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8"."\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96","ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt-");}else{$s=@iconv('UTF-8','ASCII//TRANSLIT',$s);}$s=str_replace(array('`',"'",'"','^','~'),'',$s);return strtr($s,"\x01\x02\x03\x04\x05",'`\'"^~');}public static function webalize($s,$charlist=NULL,$lower=TRUE){$s=self::toAscii($s);if($lower){$s=strtolower($s);}$s=preg_replace('#[^a-z0-9'.preg_quote($charlist,'#').']+#i','-',$s);$s=trim($s,'-');return$s;}public static function truncate($s,$maxLen,$append="\xE2\x80\xA6"){if(self::length($s)>$maxLen){$maxLen=$maxLen-self::length($append);if($maxLen<1){return$append;}elseif($matches=self::match($s,'#^.{1,'.$maxLen.'}(?=[\s\x00-/:-@\[-`{-~])#us')){return$matches[0].$append;}else{return self::substring($s,0,$maxLen).$append;}}return$s;}public static function indent($s,$level=1,$chars="\t"){if($level>0){$s=self::replace($s,'#(?:^|[\r\n]+)(?=[^\r\n])#','$0'.str_repeat($chars,$level));}return$s;}public static function lower($s){return mb_strtolower($s,'UTF-8');}public static function upper($s){return mb_strtoupper($s,'UTF-8');}public static function firstUpper($s){return self::upper(self::substring($s,0,1)).self::substring($s,1);}public static function capitalize($s){return mb_convert_case($s,MB_CASE_TITLE,'UTF-8');}public static function compare($left,$right,$len=NULL){if($len<0){$left=self::substring($left,$len,-$len);$right=self::substring($right,$len,-$len);}elseif($len!==NULL){$left=self::substring($left,0,$len);$right=self::substring($right,0,$len);}return self::lower($left)===self::lower($right);}public static function findPrefix($strings){if(!is_array($strings)){$strings=func_get_args();}$first=array_shift($strings);for($i=0;$i="\x80"&&$first[$i]>="\x80"&&$first[$i]<"\xC0"){$i--;}return substr($first,0,$i);}}}return$first;}public static function length($s){return strlen(utf8_decode($s));}public static function trim($s,$charlist=" \t\n\r\0\x0B\xC2\xA0"){$charlist=preg_quote($charlist,'#');return self::replace($s,'#^['.$charlist.']+|['.$charlist.']+\z#u','');}public static function padLeft($s,$length,$pad=' '){$length=max(0,$length-self::length($s));$padLen=self::length($pad);return str_repeat($pad,$length/$padLen).self::substring($pad,0,$length %$padLen).$s;}public static function padRight($s,$length,$pad=' '){$length=max(0,$length-self::length($s));$padLen=self::length($pad);return$s.str_repeat($pad,$length/$padLen).self::substring($pad,0,$length %$padLen);}public static function reverse($s){return@iconv('UTF-32LE','UTF-8',strrev(@iconv('UTF-8','UTF-32BE',$s)));}public static function random($length=10,$charlist='0-9a-z'){return Random::generate($length,$charlist);}public static function split($subject,$pattern,$flags=0){return self::pcre('preg_split',array($pattern,$subject,-1,$flags|PREG_SPLIT_DELIM_CAPTURE));}public static function match($subject,$pattern,$flags=0,$offset=0){if($offset>strlen($subject)){return NULL;}return self::pcre('preg_match',array($pattern,$subject,&$m,$flags,$offset))?$m:NULL;}public static function matchAll($subject,$pattern,$flags=0,$offset=0){if($offset>strlen($subject)){return array();}self::pcre('preg_match_all',array($pattern,$subject,&$m,($flags&PREG_PATTERN_ORDER)?$flags:($flags|PREG_SET_ORDER),$offset));return$m;}public static function replace($subject,$pattern,$replacement=NULL,$limit=-1){if(is_object($replacement)||is_array($replacement)){if($replacement instanceof Nette\Callback){$replacement=$replacement->getNative();}if(!is_callable($replacement,FALSE,$textual)){throw new Nette\InvalidStateException("Callback '$textual' is not callable.");}return self::pcre('preg_replace_callback',array($pattern,$replacement,$subject,$limit));}elseif($replacement===NULL&&is_array($pattern)){$replacement=array_values($pattern);$pattern=array_keys($pattern);}return self::pcre('preg_replace',array($pattern,$replacement,$subject,$limit));}public static function pcre($func,$args){$res=Callback::invokeSafe($func,$args,function($message)use($args){throw new RegexpException($message.' in pattern: '.implode(' or ',(array)$args[0]));});if(($code=preg_last_error())&&($res===NULL||!in_array($func,array('preg_filter','preg_replace_callback','preg_replace')))){throw new RegexpException(NULL,$code,implode(' or ',(array)$args[0]));}return$res;}}class RegexpException extends\Exception{static public$messages=array(PREG_INTERNAL_ERROR=>'Internal error',PREG_BACKTRACK_LIMIT_ERROR=>'Backtrack limit was exhausted',PREG_RECURSION_LIMIT_ERROR=>'Recursion limit was exhausted',PREG_BAD_UTF8_ERROR=>'Malformed UTF-8 data',5=>'Offset didn\'t correspond to the begin of a valid UTF-8 code point');public function __construct($message,$code=NULL,$pattern=NULL){if(!$message){$message=(isset(self::$messages[$code])?self::$messages[$code]:'Unknown error').($pattern?" (pattern: $pattern)":'');}parent::__construct($message,$code);}}'is_bool','boolean'=>'is_bool','int'=>'is_int','integer'=>'is_int','float'=>'is_float','number'=>NULL,'numeric'=>array(__CLASS__,'isNumeric'),'numericint'=>array(__CLASS__,'isNumericInt'),'string'=>'is_string','unicode'=>array(__CLASS__,'isUnicode'),'array'=>'is_array','list'=>array('Nette\Utils\Arrays','isList'),'object'=>'is_object','resource'=>'is_resource','scalar'=>'is_scalar','callable'=>array(__CLASS__,'isCallable'),'null'=>'is_null','email'=>array(__CLASS__,'isEmail'),'url'=>array(__CLASS__,'isUrl'),'uri'=>array(__CLASS__,'isUri'),'none'=>array(__CLASS__,'isNone'),'type'=>array(__CLASS__,'isType'),'identifier'=>array(__CLASS__,'isPhpIdentifier'),'pattern'=>NULL,'alnum'=>'ctype_alnum','alpha'=>'ctype_alpha','digit'=>'ctype_digit','lower'=>'ctype_lower','upper'=>'ctype_upper','space'=>'ctype_space','xdigit'=>'ctype_xdigit');protected static$counters=array('string'=>'strlen','unicode'=>array('Nette\Utils\Strings','length'),'array'=>'count','list'=>'count','alnum'=>'strlen','alpha'=>'strlen','digit'=>'strlen','lower'=>'strlen','space'=>'strlen','upper'=>'strlen','xdigit'=>'strlen');public static function assert($value,$expected,$label='variable'){if(!static::is($value,$expected)){$expected=str_replace(array('|',':'),array(' or ',' in range '),$expected);if(is_array($value)){$type='array('.count($value).')';}elseif(is_object($value)){$type='object '.get_class($value);}elseif(is_string($value)&&strlen($value)<40){$type="string '$value'";}else{$type=gettype($value);}throw new AssertionException("The $label expects to be $expected, $type given.");}}public static function assertField($arr,$field,$expected=NULL,$label="item '%' in array"){self::assert($arr,'array','first argument');if(!array_key_exists($field,$arr)){throw new AssertionException('Missing '.str_replace('%',$field,$label).'.');}elseif($expected){static::assert($arr[$field],$expected,str_replace('%',$field,$label));}}public static function is($value,$expected){foreach(explode('|',$expected)as$item){list($type)=$item=explode(':',$item,2);if(isset(static::$validators[$type])){if(!call_user_func(static::$validators[$type],$value)){continue;}}elseif($type==='number'){if(!is_int($value)&&!is_float($value)){continue;}}elseif($type==='pattern'){if(preg_match('|^'.(isset($item[1])?$item[1]:'').'\z|',$value)){return TRUE;}continue;}elseif(!$value instanceof$type){continue;}if(isset($item[1])){if(isset(static::$counters[$type])){$value=call_user_func(static::$counters[$type],$value);}$range=explode('..',$item[1]);if(!isset($range[1])){$range[1]=$range[0];}if(($range[0]!==''&&$value<$range[0])||($range[1]!==''&&$value>$range[1])){continue;}}return TRUE;}return FALSE;}public static function isNumericInt($value){return is_int($value)||is_string($value)&&preg_match('#^-?[0-9]+\z#',$value);}public static function isNumeric($value){return is_float($value)||is_int($value)||is_string($value)&&preg_match('#^-?[0-9]*[.]?[0-9]+\z#',$value);}public static function isCallable($value){return$value&&is_callable($value,TRUE);}public static function isUnicode($value){return is_string($value)&&preg_match('##u',$value);}public static function isNone($value){return$value==NULL;}public static function isList($value){return Arrays::isList($value);}public static function isInRange($value,$range){return(!isset($range[0])||$range[0]===''||$value>=$range[0])&&(!isset($range[1])||$range[1]===''||$value<=$range[1]);}public static function isEmail($value){$atom="[-a-z0-9!#$%&'*+/=?^_`{|}~]";$localPart="(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)";$alpha="a-z\x80-\xFF";$domain="[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?";$topDomain="[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";return(bool)preg_match("(^$localPart@(?:$domain\\.)+$topDomain\\z)i",$value);}public static function isUrl($value){$alpha="a-z\x80-\xFF";$domain="[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?";$topDomain="[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";return(bool)preg_match("(^https?://(?:(?:$domain\\.)*$topDomain|\\d{1,3}\.\\d{1,3}\.\\d{1,3}\.\\d{1,3}|\[[0-9a-f:]{3,39}\])(:\\d{1,5})?(/\\S*)?\\z)i",$value);}public static function isUri($value){return(bool)preg_match('#^[a-z\d+\.-]+:\S+\z#i',$value);}public static function isType($type){return class_exists($type)||interface_exists($type)||(PHP_VERSION_ID>=50400&&trait_exists($type));}public static function isPhpIdentifier($value){return is_string($value)&&preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\z#',$value);}}class AssertionException extends\Exception{}x\ X}e 0GBMB