Пример #1
1
	/**
	 * @param  Exception
	 * @return void
	 */
	public function renderDefault($exception)
	{
		if ($this->isAjax()) { // AJAX request? Just note this error in payload.
			$this->payload->error = TRUE;
			$this->terminate();

		} elseif ($exception instanceof BadRequestException) {
			$code = $exception->getCode();
			$this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx'); // load template 403.latte or 404.latte or ... 4xx.latte

		} else {
			$this->setView('500'); // load template 500.latte
			Debug::log($exception, Debug::ERROR); // and log exception
		}
	}
Пример #2
1
	/**
	 * Processes request.
	 *
	 * @author   Jan Tvrdík
	 * @param    PresenterRequest
	 * @return   void
	 * @throws   Nette\Applicationy\AbortException|\InvalidStateException
	 */
	public function processRequest(PresenterRequest $request)
	{
		$params = $request->getParams();
		$exception = & $params['exception'];
		if (!isset($exception)) {
			throw new \InvalidStateException('Missing required parameter - exception.');
		}

		if ($exception instanceof BadRequestException) {
			$code = $exception->getCode();
			$name = in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx';

		} else {
			Debug::log($exception, Debug::ERROR);
			$name = '500';
		}

		$this->page = '@errors/' . $name;
		$this->sendTemplate();
	}
Пример #3
0
 /**
  * Converts link to URL.
  * @return string
  */
 public function __toString()
 {
     try {
         return $this->component->link($this->destination, $this->params);
     } catch (\Exception $e) {
         Nette\Debug::toStringException($e);
     }
 }
Пример #4
0
 public function __construct($host = 'localhost', $port = 11211, $prefix = '', Nette\Context $context = NULL)
 {
     if (!self::isAvailable()) {
         throw new \NotSupportedException("PHP extension 'memcache' is not loaded.");
     }
     $this->prefix = $prefix;
     $this->context = $context;
     $this->memcache = new \Memcache();
     Nette\Debug::tryError();
     $this->memcache->connect($host, $port);
     if (Nette\Debug::catchError($msg)) {
         throw new \InvalidStateException($msg);
     }
 }
Пример #5
0
 /**
  * Sends e-mail.
  * @param  Mail
  * @return void
  */
 public function send(Mail $mail)
 {
     $tmp = clone $mail;
     $tmp->setHeader('Subject', NULL);
     $tmp->setHeader('To', NULL);
     $parts = explode(Mail::EOL . Mail::EOL, $tmp->generateMessage(), 2);
     Nette\Debug::tryError();
     $res = mail(str_replace(Mail::EOL, PHP_EOL, $mail->getEncodedHeader('To')), str_replace(Mail::EOL, PHP_EOL, $mail->getEncodedHeader('Subject')), str_replace(Mail::EOL, PHP_EOL, $parts[1]), str_replace(Mail::EOL, PHP_EOL, $parts[0]));
     if (Nette\Debug::catchError($msg)) {
         throw new \InvalidStateException($msg);
     } elseif (!$res) {
         throw new \InvalidStateException('Unable to send email.');
     }
 }
Пример #6
0
 public function __construct($host = 'localhost', $port = 11211, $prefix = '', ICacheJournal $journal = NULL)
 {
     if (!self::isAvailable()) {
         throw new \NotSupportedException("PHP extension 'memcache' is not loaded.");
     }
     $this->prefix = $prefix;
     $this->journal = $journal;
     $this->memcache = new \Memcache();
     Nette\Debug::tryError();
     $this->memcache->connect($host, $port);
     if (Nette\Debug::catchError($e)) {
         throw new \InvalidStateException($e->getMessage());
     }
 }
Пример #7
0
 /**
  * Renders template to string.
  * @param  bool  can throw exceptions? (hidden parameter)
  * @return string
  */
 public function __toString()
 {
     ob_start();
     try {
         $this->render();
         return ob_get_clean();
     } catch (\Exception $e) {
         ob_end_clean();
         if (func_num_args() && func_get_arg(0)) {
             throw $e;
         } else {
             Nette\Debug::toStringException($e);
         }
     }
 }
Пример #8
0
	/**
	 * Returns the JSON representation of a value.
	 * @param  mixed
	 * @return string
	 */
	public static function encode($value)
	{
		Debug::tryError();
		if (function_exists('ini_set')) {
			$old = ini_set('display_errors', 0); // needed to receive 'Invalid UTF-8 sequence' error
			$json = json_encode($value);
			ini_set('display_errors', $old);
		} else {
			$json = json_encode($value);
		}
		if (Debug::catchError($e)) { // needed to receive 'recursion detected' error
			throw new JsonException($e->getMessage());
		}
		return $json;
	}
Пример #9
0
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($this->isAjax()) {
         // AJAX request? Just note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     } elseif ($exception instanceof BadRequestException) {
         $this->setView('404');
         // load template 404.phtml
     } else {
         $this->setView('500');
         // load template 500.phtml
         Debug::processException($exception);
         // and handle error by Nette\Debug
     }
 }
Пример #10
0
 public function __construct($dsn, $username = NULL, $password = NULL, array $options = NULL)
 {
     parent::__construct($dsn, $username, $password, $options);
     $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Nette\\Database\\Statement', array($this)));
     $class = 'Nette\\Database\\Drivers\\Pdo' . $this->getAttribute(PDO::ATTR_DRIVER_NAME) . 'Driver';
     if (class_exists($class)) {
         $this->driver = new $class($this, (array) $options);
     }
     $this->preprocessor = new SqlPreprocessor($this);
     $this->databaseReflection = new Nette\Database\Reflection\DatabaseReflection();
     // TODO
     if (!Nette\Debug::$productionMode) {
         Nette\Debug::addPanel($panel = new DatabasePanel($dsn));
         $this->onQuery[] = callback($panel, 'logQuery');
     }
 }
Пример #11
0
<?php

namespace ActiveMapperTests;

require_once __DIR__ . "/../libs/Nette/loader.php";
\Nette\Debug::enable(\Nette\Debug::DEVELOPMENT);
\Nette\Environment::setVariable("tempDir", __DIR__ . "/_temp");
$loader = new \Nette\Loaders\RobotLoader();
$loader->addDirectory(__DIR__ . "/../libs");
$loader->addDirectory(__DIR__ . "/../ActiveMapper");
$loader->addDirectory(__DIR__ . "/../examples/Models");
$loader->register();
\dibi::connect(array('driver' => "sqlite3", 'database' => ":memory:", 'formatDateTime' => "'Y-m-d H:i:s'", 'lazy' => TRUE, 'profiler' => TRUE));
\dibi::loadFile(__DIR__ . "/db.structure.sql");
\dibi::loadFile(__DIR__ . "/db.data.sql");
Пример #12
0
	/** @internal */
	public static function catchPregError($pattern)
	{
		if (Debug::catchError($e)) { // compile error
			throw new RegexpException($e->getMessage() . " in pattern: $pattern");

		} elseif (preg_last_error()) { // run-time error
			static $messages = array(
				PREG_INTERNAL_ERROR => 'Internal error',
				PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
				PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
				PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data',
				5 => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point', // PREG_BAD_UTF8_OFFSET_ERROR
			);
			$code = preg_last_error();
			throw new RegexpException((isset($messages[$code]) ? $messages[$code] : 'Unknown error') . " (pattern: $pattern)", $code);
		}
	}
Пример #13
0
 /**
  * Reads configuration from INI file.
  * @param  string  file name
  * @param  string  section to load
  * @return array
  * @throws \InvalidStateException
  */
 public static function load($file, $section = NULL)
 {
     if (!is_file($file) || !is_readable($file)) {
         throw new \FileNotFoundException("File '{$file}' is missing or is not readable.");
     }
     Nette\Debug::tryError();
     $ini = parse_ini_file($file, TRUE);
     if (Nette\Debug::catchError($e)) {
         throw $e;
     }
     $separator = trim(self::$sectionSeparator);
     $data = array();
     foreach ($ini as $secName => $secData) {
         // is section?
         if (is_array($secData)) {
             if (substr($secName, -1) === self::$rawSection) {
                 $secName = substr($secName, 0, -1);
             } elseif (self::$keySeparator) {
                 // process key separators (key1> key2> key3)
                 $tmp = array();
                 foreach ($secData as $key => $val) {
                     $cursor =& $tmp;
                     foreach (explode(self::$keySeparator, $key) as $part) {
                         if (!isset($cursor[$part]) || is_array($cursor[$part])) {
                             $cursor =& $cursor[$part];
                         } else {
                             throw new \InvalidStateException("Invalid key '{$key}' in section [{$secName}] in '{$file}'.");
                         }
                     }
                     $cursor = $val;
                 }
                 $secData = $tmp;
             }
             // process extends sections like [staging < production] (with special support for separator ':')
             $parts = $separator ? explode($separator, strtr($secName, ':', $separator)) : array($secName);
             if (count($parts) > 1) {
                 $parent = trim($parts[1]);
                 $cursor =& $data;
                 foreach (self::$keySeparator ? explode(self::$keySeparator, $parent) : array($parent) as $part) {
                     if (isset($cursor[$part]) && is_array($cursor[$part])) {
                         $cursor =& $cursor[$part];
                     } else {
                         throw new \InvalidStateException("Missing parent section [{$parent}] in '{$file}'.");
                     }
                 }
                 $secData = Nette\ArrayTools::mergeTree($secData, $cursor);
             }
             $secName = trim($parts[0]);
             if ($secName === '') {
                 throw new \InvalidStateException("Invalid empty section name in '{$file}'.");
             }
         }
         if (self::$keySeparator) {
             $cursor =& $data;
             foreach (explode(self::$keySeparator, $secName) as $part) {
                 if (!isset($cursor[$part]) || is_array($cursor[$part])) {
                     $cursor =& $cursor[$part];
                 } else {
                     throw new \InvalidStateException("Invalid section [{$secName}] in '{$file}'.");
                 }
             }
         } else {
             $cursor =& $data[$secName];
         }
         if (is_array($secData) && is_array($cursor)) {
             $secData = Nette\ArrayTools::mergeTree($secData, $cursor);
         }
         $cursor = $secData;
     }
     if ($section === NULL) {
         return $data;
     } elseif (!isset($data[$section]) || !is_array($data[$section])) {
         throw new \InvalidStateException("There is not section [{$section}] in '{$file}'.");
     } else {
         return $data[$section];
     }
 }
Пример #14
0
 /**
  * Return array entries that match the pattern.
  * @param  array
  * @param  string
  * @param  int
  * @return array
  */
 public static function grep(array $arr, $pattern, $flags = 0)
 {
     Debug::tryError();
     $res = preg_grep($pattern, $arr, $flags);
     String::catchPregError($pattern);
     return $res;
 }
Пример #15
0
 /**
  * Dispatch a HTTP request to a front controller.
  * @return void
  */
 public function run()
 {
     $httpRequest = $this->getHttpRequest();
     $httpResponse = $this->getHttpResponse();
     $httpRequest->setEncoding('UTF-8');
     if (Environment::getVariable('baseUri') === NULL) {
         Environment::setVariable('baseUri', $httpRequest->getUri()->getBasePath());
     }
     // autostarts session
     $session = $this->getSession();
     if (!$session->isStarted() && $session->exists()) {
         $session->start();
     }
     // enable routing debuggger
     Nette\Debug::addPanel(new RoutingDebugger($this->getRouter(), $httpRequest));
     // check HTTP method
     if ($this->allowedMethods) {
         $method = $httpRequest->getMethod();
         if (!in_array($method, $this->allowedMethods, TRUE)) {
             $httpResponse->setCode(Nette\Web\IHttpResponse::S501_NOT_IMPLEMENTED);
             $httpResponse->setHeader('Allow', implode(',', $this->allowedMethods));
             echo '<h1>Method ' . htmlSpecialChars($method) . ' is not implemented</h1>';
             return;
         }
     }
     // dispatching
     $request = NULL;
     $repeatedError = FALSE;
     do {
         try {
             if (count($this->requests) > self::$maxLoop) {
                 throw new ApplicationException('Too many loops detected in application life cycle.');
             }
             if (!$request) {
                 $this->onStartup($this);
                 // default router
                 $router = $this->getRouter();
                 if ($router instanceof MultiRouter && !count($router)) {
                     $router[] = new SimpleRouter(array('presenter' => 'Default', 'action' => 'default'));
                 }
                 // routing
                 $request = $router->match($httpRequest);
                 if (!$request instanceof PresenterRequest) {
                     $request = NULL;
                     throw new BadRequestException('No route for HTTP request.');
                 }
                 if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
                     throw new BadRequestException('Invalid request.');
                 }
             }
             $this->requests[] = $request;
             $this->onRequest($this, $request);
             // Instantiate presenter
             $presenter = $request->getPresenterName();
             try {
                 $class = $this->getPresenterLoader()->getPresenterClass($presenter);
                 $request->setPresenterName($presenter);
             } catch (InvalidPresenterException $e) {
                 throw new BadRequestException($e->getMessage(), 404, $e);
             }
             $request->freeze();
             // Execute presenter
             $this->presenter = new $class();
             $response = $this->presenter->run($request);
             // Send response
             if ($response instanceof ForwardingResponse) {
                 $request = $response->getRequest();
                 continue;
             } elseif ($response instanceof IPresenterResponse) {
                 $response->send();
             }
             break;
         } catch (\Exception $e) {
             // fault barrier
             if ($this->catchExceptions === NULL) {
                 $this->catchExceptions = Environment::isProduction();
             }
             $this->onError($this, $e);
             if (!$this->catchExceptions) {
                 $this->onShutdown($this, $e);
                 throw $e;
             }
             if ($repeatedError) {
                 $e = new ApplicationException('An error occured while executing error-presenter', 0, $e);
             }
             if (!$httpResponse->isSent()) {
                 $httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
             }
             if (!$repeatedError && $this->errorPresenter) {
                 $repeatedError = TRUE;
                 $request = new PresenterRequest($this->errorPresenter, PresenterRequest::FORWARD, array('exception' => $e));
                 // continue
             } else {
                 // default error handler
                 echo "<!DOCTYPE html><meta name=robots content=noindex>\n\n";
                 echo "<style>body{color:black;background:white;width:500px;margin:100px auto}h1{font:bold 47px/1.5 sans-serif;margin:.6em 0}p{font:21px/1.5 Georgia,serif;margin:1.5em 0}small{font-size:70%;color:gray}</style>\n\n";
                 if ($e instanceof BadRequestException) {
                     echo "<title>404 Not Found</title>\n\n<h1>Not Found</h1>\n\n<p>The requested URL was not found on this server.</p>";
                 } else {
                     Nette\Debug::processException($e, FALSE);
                     echo "<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n", "<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";
                 }
                 echo "\n\n<hr>\n<small><i>Nette Framework</i></small>";
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : NULL);
 }
Пример #16
0
namespace App;

require_once __DIR__ . "/bootstrap.php";
use Nette\Debug, Nette\Framework, dibi;
Debug::timer('benchmark');
$memory = memory_get_peak_usage();
echoBeginHtml();
/********************************************************************************************************************************/
// Setum entity manager
$em = new \ActiveMapper\Manager(\dibi::getConnection());
echo "<h1>All authors</h1>";
// Get all authors
$authors = $em->findAll('App\\Models\\Author');
foreach ($authors as $author) {
    Debug::dump($author->name);
    Debug::dump($author->blog->name);
}
echo "<h1>Author by ID #3</h1>";
// Get author by id
$author = $em->find('App\\Models\\Author', 3);
Debug::dump($author->name);
Debug::dump($author->blog->name);
/********************************************************************************************************************************/
// Benchmark data
Debug::barDump(Framework::NAME . " " . Framework::VERSION . " " . Framework::REVISION);
Debug::barDump("dibi " . dibi::VERSION . " " . dibi::REVISION);
Debug::barDump($mappingTime = number_format(Debug::timer('benchmark') * 1000, 1, '.', ' ') . "ms", "Mapping Time");
Debug::barDump($mappingMemory = number_format((memory_get_peak_usage() - $memory) / 1000, 1, '.', ' ') . "kB", "Mapping Memory");
echo '<p><a href="http://github.com/Vrtak-CZ/ActiveMapper/blob/master/examples/index.php" target="_blank">' . 'Show code on GitHub</a> - <a href="http://am.vrtak-cz.net/coverage">Show coverage</a></p>';
$benchMarkData = "mapping time: {$mappingTime} mapping memory: {$mappingMemory} " . "total time: " . number_format((microtime(TRUE) - Debug::$time) * 1000, 1, '.', ' ') . "ms " . "total memory: " . number_format(memory_get_peak_usage() / 1000, 1, '.', ' ') . "kB";
file_put_contents(__DIR__ . "/benchmark.log", date("r") . " # " . $benchMarkData . PHP_EOL, FILE_APPEND);
Пример #17
0
 /**
  * Outputs image to string.
  * @return string
  */
 public function __toString()
 {
     try {
         return $this->toString();
     } catch (\Exception $e) {
         Debug::toStringException($e);
     }
 }
Пример #18
0
 /**
  * Starts and initializes session data.
  * @throws \InvalidStateException
  * @return void
  */
 public function start()
 {
     if (self::$started) {
         return;
     } elseif (self::$started === NULL && defined('SID')) {
         throw new \InvalidStateException('A session had already been started by session.auto-start or session_start().');
     }
     $this->configure($this->options);
     Nette\Debug::tryError();
     session_start();
     if (Nette\Debug::catchError($e)) {
         @session_write_close();
         // this is needed
         throw new \InvalidStateException($e->getMessage());
     }
     self::$started = TRUE;
     if ($this->regenerationNeeded) {
         session_regenerate_id(TRUE);
         $this->regenerationNeeded = FALSE;
     }
     /* structure:
     			__NF: Counter, BrowserKey, Data, Meta
     				DATA: namespace->variable = data
     				META: namespace->variable = Timestamp, Browser, Version
     		*/
     unset($_SESSION['__NT'], $_SESSION['__NS'], $_SESSION['__NM']);
     // old unused structures
     // initialize structures
     $nf =& $_SESSION['__NF'];
     if (empty($nf)) {
         // new session
         $nf = array('C' => 0);
     } else {
         $nf['C']++;
     }
     // browser closing detection
     $browserKey = $this->getHttpRequest()->getCookie('nette-browser');
     if (!$browserKey) {
         $browserKey = (string) lcg_value();
     }
     $browserClosed = !isset($nf['B']) || $nf['B'] !== $browserKey;
     $nf['B'] = $browserKey;
     // resend cookie
     $this->sendCookie();
     // process meta metadata
     if (isset($nf['META'])) {
         $now = time();
         // expire namespace variables
         foreach ($nf['META'] as $namespace => $metadata) {
             if (is_array($metadata)) {
                 foreach ($metadata as $variable => $value) {
                     if (!empty($value['B']) && $browserClosed || !empty($value['T']) && $now > $value['T'] || $variable !== '' && is_object($nf['DATA'][$namespace][$variable]) && (isset($value['V']) ? $value['V'] : NULL) !== Nette\Reflection\ClassReflection::from($nf['DATA'][$namespace][$variable])->getAnnotation('serializationVersion')) {
                         if ($variable === '') {
                             // expire whole namespace
                             unset($nf['META'][$namespace], $nf['DATA'][$namespace]);
                             continue 2;
                         }
                         unset($nf['META'][$namespace][$variable], $nf['DATA'][$namespace][$variable]);
                     }
                 }
             }
         }
     }
     register_shutdown_function(array($this, 'clean'));
 }
Пример #19
0
 /**
  * Register Doctrine 2 Panel
  */
 public static function getAndRegister()
 {
     $panel = new static();
     \Nette\Debug::addPanel($panel);
     return $panel;
 }
Пример #20
0
 private function processDelete()
 {
     $ids = $this->getRandomsNumbers(50, 50000, 1);
     $queryesExecution = array();
     $peoples = array();
     foreach ($ids as $id) {
         Debug::timer();
         // SELECT + DELETE DATA
         $people = Models\People::find($id);
         $peoples[] = $people;
         $people->delete();
         $queryesExecution[] = number_format(Debug::timer() * 1000, 2);
     }
     return array($queryesExecution, $peoples);
 }
Пример #21
0
$form->addGroup('Your account');
$form->addPassword('password', 'Choose password')->addRule(Form::FILLED, 'Choose your password')->addRule(Form::MIN_LENGTH, 'The password is too short: it must be at least %d characters', 3)->setOption('description', '(at least 3 characters)');
$form->addPassword('password2', 'Reenter password')->addConditionOn($form['password'], Form::VALID)->addRule(Form::FILLED, 'Reenter your password')->addRule(Form::EQUAL, 'Passwords do not match', $form['password']);
$form->addFile('avatar', 'Picture');
$form->addHidden('userid');
$form->addTextArea('note', 'Comment');
// group for buttons
$form->addGroup();
$form->addSubmit('submit', 'Send');
// Step 2: Check if form was submitted?
if ($form->isSubmitted()) {
    // Step 2c: Check if form is valid
    if ($form->isValid()) {
        echo '<h2>Form was submitted and successfully validated</h2>';
        $values = $form->getValues();
        Debug::dump($values);
        // this is the end, my friend :-)
        if (empty($disableExit)) {
            exit;
        }
    }
} else {
    // not submitted, define default values
    $defaults = array('name' => 'John Doe', 'userid' => 231, 'country' => 'CZ');
    $form->setDefaults($defaults);
}
// Step 3: Render form
?>
<!DOCTYPE html>
<html lang="en">
<head>
Пример #22
0
use Nette\Debug;
use Nette\Environment as Env;
use Nette\Web\Html;



// Load libraries
require LIBS_DIR . '/Nette/loader.php';
require APP_DIR . '/routers/StaticRouter.php';
require APP_DIR . '/managers/PageManager.php';
require APP_DIR . '/classes/TemplateLocator.php';
require APP_DIR . '/classes/PresenterFactory.php';

// Enable and setup Nette\Debug
Debug::enable();
Debug::$strictMode = !Debug::$productionMode;

// Configure environment
date_default_timezone_set('Europe/Prague');
Html::$xhtml = FALSE;

// Configure application
$application = Env::getApplication();
$application->errorPresenter = 'Error';
$application->catchExceptions = Debug::$productionMode;

// Configure application context
$context = $application->getContext();
$context->addService('StaticWeb\\TemplateLocator', 'StaticWeb\\TemplateLocator');
$context->addService('StaticWeb\\PageManager', function() use ($context) {
	$manager = new PageManager();
Пример #23
0
	/**
	 * Dispatch a HTTP request to a front controller.
	 * @return void
	 */
	public function run()
	{
		$httpRequest = $this->getHttpRequest();
		$httpResponse = $this->getHttpResponse();

		// check HTTP method
		if ($this->allowedMethods) {
			$method = $httpRequest->getMethod();
			if (!in_array($method, $this->allowedMethods, TRUE)) {
				$httpResponse->setCode(Nette\Web\IHttpResponse::S501_NOT_IMPLEMENTED);
				$httpResponse->setHeader('Allow', implode(',', $this->allowedMethods));
				echo '<h1>Method ' . htmlSpecialChars($method) . ' is not implemented</h1>';
				return;
			}
		}

		// dispatching
		$request = NULL;
		$repeatedError = FALSE;
		do {
			try {
				if (count($this->requests) > self::$maxLoop) {
					throw new ApplicationException('Too many loops detected in application life cycle.');
				}

				if (!$request) {
					$this->onStartup($this);

					// autostarts session
					$session = $this->getSession();
					if (!$session->isStarted() && $session->exists()) {
						$session->start();
					}

					// routing
					$router = $this->getRouter();

					// enable routing debuggger
					Nette\Debug::addPanel(new RoutingDebugger($router, $httpRequest));

					$request = $router->match($httpRequest);
					if (!$request instanceof PresenterRequest) {
						$request = NULL;
						throw new BadRequestException('No route for HTTP request.');
					}

					if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
						throw new BadRequestException('Invalid request. Presenter is not achievable.');
					}
				}

				$this->requests[] = $request;
				$this->onRequest($this, $request);

				// Instantiate presenter
				$presenterName = $request->getPresenterName();
				try {
					$this->presenter = $this->getPresenterFactory()->createPresenter($presenterName);
				} catch (InvalidPresenterException $e) {
					throw new BadRequestException($e->getMessage(), 404, $e);
				}

				$this->getPresenterFactory()->getPresenterClass($presenterName);
				$request->setPresenterName($presenterName);
				$request->freeze();

				// Execute presenter
				$response = $this->presenter->run($request);
				$this->onResponse($this, $response);

				// Send response
				if ($response instanceof ForwardingResponse) {
					$request = $response->getRequest();
					continue;

				} elseif ($response instanceof IPresenterResponse) {
					$response->send($httpRequest, $httpResponse);
				}
				break;

			} catch (\Exception $e) {
				// fault barrier
				$this->onError($this, $e);

				if (!$this->catchExceptions) {
					$this->onShutdown($this, $e);
					throw $e;
				}

				if ($repeatedError) {
					$e = new ApplicationException('An error occured while executing error-presenter', 0, $e);
				}

				if (!$httpResponse->isSent()) {
					$httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
				}

				if (!$repeatedError && $this->errorPresenter) {
					$repeatedError = TRUE;
					if ($this->presenter instanceof Presenter) {
						try {
							$this->presenter->forward(":$this->errorPresenter:", array('exception' => $e));
						} catch (AbortException $foo) {
							$request = $this->presenter->getLastCreatedRequest();
						}
					} else {
						$request = new PresenterRequest(
							$this->errorPresenter,
							PresenterRequest::FORWARD,
							array('exception' => $e)
						);
					}
					// continue

				} else { // default error handler
					if ($e instanceof BadRequestException) {
						$code = $e->getCode();
					} else {
						$code = 500;
						Nette\Debug::log($e, Nette\Debug::ERROR);
					}
					require __DIR__ . '/templates/error.phtml';
					break;
				}
			}
		} while (1);

		$this->onShutdown($this, isset($e) ? $e : NULL);
	}
Пример #24
0
                $item['exc_frames'][] = $frame['args'];
            }
            $file = str_replace(dirname(dirname(dirname($e->getFile()))), "…", $e->getFile());
            $item['template'] = ($e instanceof \ErrorException ? '' : get_class($e) . ': ') . $e->getMessage() . ($e->getCode() ? ' #' . $e->getCode() : '') . ' in ' . $file . ':' . $e->getLine();
            array_unshift($trace, array('file' => $e->getFile(), 'line' => $e->getLine()));
        } else {
            $trace = debug_backtrace();
            if (isset($trace[0]['class']) && $trace[0]['class'] === __CLASS__ && ($trace[0]['function'] === '_shutdownHandler' || $trace[0]['function'] === '_errorHandler')) {
                unset($trace[0]);
            }
        }
        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;
        foreach ($trace as $frame) {
            if (isset($frame['file']) && is_file($frame['file'])) {
                $item['pathname'] = $frame['file'];
                $item['lineno'] = $frame['line'];
                break;
            }
        }
        $payload['logs'][] = DebugHelpers::jsonDump($item, -1);
        foreach (str_split(base64_encode(@json_encode($payload)), 4990) as $k => $v) {
            header("FireLogger-de11e-{$k}:{$v}");
        }
        return TRUE;
    }
}
Debug::_init();
Пример #25
0
/**
 * cURL Test bootstrap file.
 *
 * @copyright  Copyright (c) 2009 Filip Procházka
 * @package    Vdsc
 */
require_once dirname(__FILE__) . '/Nette/loader.php';
require_once dirname(__FILE__) . '/Curl/Request.php';
use Curl\Request;
use Curl\CurlException;
use Nette\Environment;
use Nette\Debug;
// register wrapper safe for file manipulation
Nette\SafeStream::register();
Debug::enable();
Debug::$strictMode = True;
Environment::loadConfig(realpath('./config.ini'));
$config = Environment::getConfig('curl');
$config['downloadFolder'] = realpath("download");
$config['cookieFile'] = $config['downloadFolder'] . '/cookies.tmp';
function proxy(&$test)
{
    // 	$test->addProxy('192.168.1.160', 3128);
}
if (TRUE) {
    // test 1: get
    $test = new Request("http://curl.kdyby.org/prevodnik.asm.zdrojak", $config);
    // 	$test = new Curl("http://iskladka.cz/iCopy/downloadBalancer.php?file=1222561395_obava_bojov+cz.avi&ticket=pc1660-1265493063.25");
    echo "<hr>test 1: get ... init ok<hr>", "<h2>Setup:</h2>";
    proxy($test);
    // for debbuging at school
Пример #26
0
 /**
  * Renders form to string.
  * @return bool  can throw exceptions? (hidden parameter)
  * @return string
  */
 public function __toString()
 {
     try {
         return $this->getRenderer()->render($this);
     } catch (\Exception $e) {
         if (func_get_args() && func_get_arg(0)) {
             throw $e;
         } else {
             Nette\Debug::toStringException($e);
         }
     }
 }
Пример #27
0
	/**
	 * Dispatch a HTTP request to a front controller.
	 * @return void
	 */
	public function run()
	{
		$httpRequest = $this->getHttpRequest();
		$httpResponse = $this->getHttpResponse();

		// check HTTP method
		if ($this->allowedMethods) {
			$method = $httpRequest->getMethod();
			if (!in_array($method, $this->allowedMethods, TRUE)) {
				$httpResponse->setCode(Nette\Web\IHttpResponse::S501_NOT_IMPLEMENTED);
				$httpResponse->setHeader('Allow', implode(',', $this->allowedMethods));
				echo '<h1>Method ' . htmlSpecialChars($method) . ' is not implemented</h1>';
				return;
			}
		}

		// dispatching
		$request = NULL;
		$repeatedError = FALSE;
		do {
			try {
				if (count($this->requests) > self::$maxLoop) {
					throw new ApplicationException('Too many loops detected in application life cycle.');
				}

				if (!$request) {
					$this->onStartup($this);

					// autostarts session
					$session = $this->getSession();
					if (!$session->isStarted() && $session->exists()) {
						$session->start();
					}

					// routing
					$router = $this->getRouter();

					// enable routing debuggger
					Nette\Debug::addPanel(new RoutingDebugger($router, $httpRequest));

					$request = $router->match($httpRequest);
					if (!$request instanceof PresenterRequest) {
						$request = NULL;
						throw new BadRequestException('No route for HTTP request.');
					}

					if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
						throw new BadRequestException('Invalid request. Presenter is not achievable.');
					}
				}

				$this->requests[] = $request;
				$this->onRequest($this, $request);

				// Instantiate presenter
				$presenter = $request->getPresenterName();
				try {
					$class = $this->getPresenterLoader()->getPresenterClass($presenter);
					$request->setPresenterName($presenter);
				} catch (InvalidPresenterException $e) {
					throw new BadRequestException($e->getMessage(), 404, $e);
				}
				$request->freeze();

				// Execute presenter
				$this->presenter = new $class;
				$response = $this->presenter->run($request);
				$this->onResponse($this, $response);

				// Send response
				if ($response instanceof ForwardingResponse) {
					$request = $response->getRequest();
					continue;

				} elseif ($response instanceof IPresenterResponse) {
					$response->send();
				}
				break;

			} catch (\Exception $e) {
				// fault barrier
				$this->onError($this, $e);

				if (!$this->catchExceptions) {
					$this->onShutdown($this, $e);
					throw $e;
				}

				if ($repeatedError) {
					$e = new ApplicationException('An error occured while executing error-presenter', 0, $e);
				}

				if (!$httpResponse->isSent()) {
					$httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
				}

				if (!$repeatedError && $this->errorPresenter) {
					$repeatedError = TRUE;
					if ($this->presenter instanceof Presenter) {
						try {
							$this->presenter->forward(":$this->errorPresenter:", array('exception' => $e));
						} catch (AbortException $foo) {
							$request = $this->presenter->getLastCreatedRequest();
						}
					} else {
						$request = new PresenterRequest(
							$this->errorPresenter,
							PresenterRequest::FORWARD,
							array('exception' => $e)
						);
					}
					// continue

				} else { // default error handler
					if ($e instanceof BadRequestException) {
						$code = $e->getCode();
					} else {
						$code = 500;
						Nette\Debug::log($e, Nette\Debug::ERROR);
					}
					echo "<!DOCTYPE html><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><meta name=robots content=noindex><meta name=generator content='Nette Framework'>\n\n";
					echo "<style>body{color:#333;background:white;width:500px;margin:100px auto}h1{font:bold 47px/1.5 sans-serif;margin:.6em 0}p{font:21px/1.5 Georgia,serif;margin:1.5em 0}small{font-size:70%;color:gray}</style>\n\n";
					static $messages = array(
						0 => array('Oops...', 'Your browser sent a request that this server could not understand or process.'),
						403 => array('Access Denied', 'You do not have permission to view this page. Please try contact the web site administrator if you believe you should be able to view this page.'),
						404 => array('Page Not Found', 'The page you requested could not be found. It is possible that the address is incorrect, or that the page no longer exists. Please use a search engine to find what you are looking for.'),
						405 => array('Method Not Allowed', 'The requested method is not allowed for the URL.'),
						410 => array('Page Not Found', 'The page you requested has been taken off the site. We apologize for the inconvenience.'),
						500 => array('Server Error', 'We\'re sorry! The server encountered an internal error and was unable to complete your request. Please try again later.'),
					);
					$message = isset($messages[$code]) ? $messages[$code] : $messages[0];
					echo "<title>$message[0]</title>\n\n<h1>$message[0]</h1>\n\n<p>$message[1]</p>\n\n";
					if ($code) echo "<p><small>error $code</small></p>";
					break;
				}
			}
		} while (1);

		$this->onShutdown($this, isset($e) ? $e : NULL);
	}
Пример #28
0
 * @copyright  Copyright (c) 2010 John Doe
 * @package    MyApplication
 */
use Nette\Debug;
use Nette\Environment;
use Nette\Application\Route;
use Nette\Application\SimpleRouter;
// REMOVE THIS LINE
if (!is_file(LIBS_DIR . '/Nette/loader.php')) {
    die('Copy Nette Framework to /libs/ directory.');
}
// Step 1: Load Nette Framework
// this allows load Nette Framework classes automatically so that
// you don't have to litter your code with 'require' statements
require LIBS_DIR . '/Nette/loader.php';
// Step 2: Configure environment
// 2a) enable Nette\Debug for better exception and error visualisation
Debug::enable();
// 2b) load configuration from config.ini file
Environment::loadConfig();
// Step 3: Configure application
// 3a) get and setup a front controller
$application = Environment::getApplication();
$application->errorPresenter = 'Error';
//$application->catchExceptions = TRUE;
// Step 4: Setup application router
$router = $application->getRouter();
$router[] = new Route('index.php', array('presenter' => 'Homepage', 'action' => 'default'), Route::ONE_WAY);
$router[] = new Route('<presenter>/<action>/<id>', array('presenter' => 'Homepage', 'action' => 'default', 'id' => NULL));
// Step 5: Run the application!
$application->run();
Пример #29
0
 /**
  * Registeres panel to Debug bar
  */
 public static function register()
 {
     Debug::addPanel(new self());
 }