/**
	 * Sends email.
	 * @param  NMail
	 * @return void
	 */
	public function send(NMail $mail)
	{
		$tmp = clone $mail;
		$tmp->setHeader('Subject', NULL);
		$tmp->setHeader('To', NULL);

		$parts = explode(NMail::EOL . NMail::EOL, $tmp->generateMessage(), 2);

		NDebugger::tryError();
		$args = array(
			str_replace(NMail::EOL, PHP_EOL, $mail->getEncodedHeader('To')),
			str_replace(NMail::EOL, PHP_EOL, $mail->getEncodedHeader('Subject')),
			str_replace(NMail::EOL, PHP_EOL, $parts[1]),
			str_replace(NMail::EOL, PHP_EOL, $parts[0]),
		);
		if ($this->commandArgs) {
			$args[] = (string) $this->commandArgs;
		}
		$res = call_user_func_array('mail', $args);

		if (NDebugger::catchError($e)) {
			throw new InvalidStateException('mail(): ' . $e->getMessage(), 0, $e);

		} elseif (!$res) {
			throw new InvalidStateException('Unable to send email.');
		}
	}
Example #2
0
function dde()
{
    foreach (func_get_args() as $arg) {
        NDebugger::dump($arg);
    }
    exit;
}
Example #3
0
/**
 * NDebugger::dump shortcut.
 */
function dump($var)
{
	foreach (func_get_args() as $arg) {
		NDebugger::dump($arg);
	}
	return $var;
}
Example #4
0
	public function __toString()
	{
		try {
			return (string) $this->getPrimary();
		} catch (Exception $e) {
			NDebugger::toStringException($e);
		}
	}
Example #5
0
	/**
	 * Reads configuration from INI file.
	 * @param  string  file name
	 * @return array
	 * @throws InvalidStateException
	 */
	public function load($file)
	{
		NDebugger::tryError();
		$ini = parse_ini_file($file, TRUE);
		if (NDebugger::catchError($e)) {
			throw new InvalidStateException('parse_ini_file(): ' . $e->getMessage(), 0, $e);
		}

		$data = array();
		foreach ($ini as $secName => $secData) {
			if (is_array($secData)) { // is section?
				if (substr($secName, -1) === self::RAW_SECTION) {
					$secName = substr($secName, 0, -1);
				} else { // process key nesting separator (key1.key2.key3)
					$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 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[NConfigHelpers::EXTENDS_KEY] = trim($parts[1]);
				}
			}

			$cursor = & $data; // nesting separator in section name
			foreach (explode(self::KEY_SEPARATOR, $secName) as $part) {
				if (!isset($cursor[$part]) || is_array($cursor[$part])) {
					$cursor = & $cursor[$part];
				} else {
					throw new InvalidStateException("Invalid section [$secName] in file '$file'.");
				}
			}

			if (is_array($secData) && is_array($cursor)) {
				$secData = NConfigHelpers::merge($secData, $cursor);
			}

			$cursor = $secData;
		}

		return $data;
	}
Example #6
0
	/**
	 * Returns the JSON representation of a value.
	 * @param  mixed
	 * @return string
	 */
	public static function encode($value)
	{
		NDebugger::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 (NDebugger::catchError($e)) { // needed to receive 'recursion detected' error
			throw new NJsonException($e->getMessage());
		}
		return $json;
	}
	public function __construct($host = 'localhost', $port = 11211, $prefix = '', ICacheJournal $journal = NULL, $timeout = 1)
	{
		if (!self::isAvailable()) {
			throw new NotSupportedException("PHP extension 'memcache' is not loaded.");
		}

		$this->prefix = $prefix;
		$this->journal = $journal;
		$this->memcache = new Memcache;
		NDebugger::tryError();
		$this->memcache->connect($host, $port, $timeout);
		if (NDebugger::catchError($e)) {
			throw new InvalidStateException('Memcache::connect(): ' . $e->getMessage(), 0, $e);
		}
	}
Example #8
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 NBadRequestException) {
         $code = $exception->getCode();
         // load template 403.latte or 404.latte or ... 4xx.latte
         $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         // log to access.log
         NDebugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
     } else {
         $this->setView('500');
         // load template 500.latte
         NDebugger::log($exception, NDebugger::ERROR);
         // and log exception
     }
 }
Example #9
0
 public function register(DibiConnection $connection)
 {
     if (is_callable('Nette\\Diagnostics\\Debugger::enable') && !class_exists('NDebugger')) {
         class_alias('Nette\\Diagnostics\\Debugger', 'NDebugger');
         // PHP 5.2 code compatibility
     }
     if (is_callable('NDebugger::enable') && is_callable('NDebugger::getBlueScreen')) {
         // Nette Framework 2.1
         NDebugger::getBar()->addPanel($this);
         NDebugger::getBlueScreen()->addPanel(array(__CLASS__, 'renderException'));
         $connection->onEvent[] = array($this, 'logEvent');
     } elseif (is_callable('NDebugger::enable')) {
         // Nette Framework 2.0 (for PHP 5.3 or PHP 5.2 prefixed)
         NDebugger::$bar && NDebugger::$bar->addPanel($this);
         NDebugger::$blueScreen && NDebugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
         $connection->onEvent[] = array($this, 'logEvent');
     } elseif (is_callable('Debugger::enable') && !is_callable('Debugger::getBlueScreen')) {
         // Nette Framework 2.0 for PHP 5.2 non-prefixed
         Debugger::$bar && Debugger::$bar->addPanel($this);
         Debugger::$blueScreen && Debugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
         $connection->onEvent[] = array($this, 'logEvent');
     }
 }
Example #10
0
	/**
	 * Dispatch a HTTP request to a front controller.
	 * @return void
	 */
	public function run()
	{
		$request = NULL;
		$repeatedError = FALSE;
		do {
			try {
				if (count($this->requests) > self::$maxLoop) {
					throw new NApplicationException('Too many loops detected in application life cycle.');
				}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				} else { // default error handler
					if ($e instanceof NBadRequestException) {
						$code = $e->getCode();
					} else {
						$code = 500;
						NDebugger::log($e, NDebugger::ERROR);
					}
					require dirname(__FILE__) . '/templates/error.phtml';
					break;
				}
			}
		} while (1);

		$this->onShutdown($this, isset($e) ? $e : NULL);
	}
Example #11
0
	/**
	 * Outputs image to string.
	 * @return string
	 */
	public function __toString()
	{
		try {
			return $this->toString();

		} catch (Exception $e) {
			NDebugger::toStringException($e);
		}
	}
 /**
  * @param Job $job
  * @return array|void
  */
 public function execute(Job $job)
 {
     \Keboola\StorageApi\Config\Reader::$client = $this->storageApi;
     $configBucket = \Keboola\StorageApi\Config\Reader::read("sys.c-{$this->appName}", $this->storageApi->token);
     $passed = false;
     $accountsIds = array();
     $accountsOffset = 0;
     $accountsLimit = 0;
     $jsonParams = $job->getAttribute("params");
     if (isset($jsonParams["accountsIds"])) {
         $accountsIds = explode(',', $jsonParams["accountsIds"]);
     } else {
         if (isset($jsonParams["accountsOffset"]) && is_integer($jsonParams["accountsOffset"]) && $jsonParams["accountsOffset"] > 0) {
             $accountsOffset = $jsonParams["accountsOffset"];
         }
         if (isset($jsonParams["accountsLimit"]) && is_integer($jsonParams["accountsLimit"]) && $jsonParams["accountsLimit"] > 0) {
             $accountsLimit = $jsonParams["accountsLimit"];
         }
     }
     if (isset($jsonParams["since"])) {
         $since = $jsonParams["since"];
     } else {
         $days = isset($jsonParams["days"]) ? $jsonParams["days"] : 14;
         $since = '-' . $days . ' days';
     }
     $until = isset($jsonParams["until"]) ? $jsonParams["until"] : 'today';
     if (strtotime($since) > strtotime($until)) {
         return false;
     }
     if (isset($jsonParams["config"])) {
         $jsonParams["configurationId"] = $jsonParams["config"];
     }
     $reservedTables = array('accounts');
     foreach ($configBucket["items"] as $configurationId => $configInstance) {
         if (!in_array($configurationId, $reservedTables)) {
             if (count($jsonParams) && isset($jsonParams["configurationId"]) && $jsonParams["configurationId"] != $configurationId) {
                 continue;
             }
             $passed = true;
             $connectionConfig = $configInstance;
             unset($connectionConfig["items"]);
             $connectionConfig = new \Zend_Config($connectionConfig, true);
             $runConfig = $configInstance["items"];
             $runConfig = new \Zend_Config($runConfig, true);
             try {
                 $fbImport = new Import($this->appName);
                 $fbImport->storageApi = $this->storageApi;
                 $fbImport->runId = $this->storageApi->getRunId();
                 $fbImport->log("Extraction of row {$configurationId} started");
                 if (isset($configInstance["paging"])) {
                     $fbImport->paging = $configInstance["paging"];
                 }
                 $fbImport->configurationId = $configurationId;
                 $fbImport->importConfig = $connectionConfig;
                 $fbImport->runConfig = $runConfig;
                 $fbImport->storageApiBucket = "in.c-{$this->appName}-" . $configurationId;
                 \NDebugger::timer('configuration');
                 $fbImport->log("Extraction of configuration {$configurationId} started", array('since' => $since, 'until' => $until, 'accountsOffset' => $accountsOffset, 'accountsLimit' => $accountsLimit, 'accountsIds' => $accountsIds));
                 if (!$this->storageApi->bucketExists($fbImport->storageApiBucket)) {
                     $this->storageApi->createBucket($this->appName . '-' . $configurationId, \Keboola\StorageApi\Client::STAGE_IN, "Facebook Extractor Data");
                 }
                 $tokenInfo = $this->storageApi->getLogData();
                 $tmpDir = "/tmp/" . $tokenInfo["token"] . "-" . uniqid($configurationId . "-") . "/";
                 if (!file_exists($tmpDir)) {
                     mkdir($tmpDir);
                 }
                 if (!is_dir($tmpDir)) {
                     throw new ApplicationException("Temporary directory path ({$tmpDir}) is not a directory", null, null, "TMP_DIR");
                 }
                 $fbImport->tmpDir = $tmpDir;
                 $fbImport->import($since, $until, $accountsOffset, $accountsLimit, $accountsIds);
                 $duration = \NDebugger::timer('configuration');
                 $fbImport->log("Extraction of configuration {$configurationId} ended", array(), $duration);
                 // Cleanup
                 exec("rm -rf {$tmpDir}");
                 $fbImport->log("Extraction of row {$configurationId} finished", array(), $duration);
             } catch (InvalidTokenException $e) {
                 throw new UserException("Invalid account {$e->getAccount()} or token for this account: " . $e->getMessage(), $e);
             } catch (UserException $e) {
                 throw $e;
             } catch (\Exception $e) {
                 throw new ApplicationException($e->getMessage(), $e);
             }
         }
     }
     if (!$passed) {
         throw new UserException("ConfigurationId {$jsonParams["configurationId"]} not found");
     }
     $response = array("status" => "ok");
     return $response;
 }
Example #13
0
 /**
  * Register this panel
  *
  * @param array	items for add to pannel
  */
 public static function register(array $items = NULL)
 {
     if (self::$registered) {
         throw new \InvalidStateException("Callback panel is already registered");
     }
     NDebugger::addPanel(new static($items));
     self::$registered = TRUE;
 }
if (!empty($_control->snippetMode)) {
	return NUIMacros::renderSnippets($_control, $_l, get_defined_vars());
}

//
// main template
//
?>
<script>
       $(function() {
                $("table.tablesorter")
                        .tablesorter( { widthFixed: true, widgets: ['zebra'] } );
        });
</script>
<div class="vysledky">
<?php if ($vysledky): NDebugger::barDump(array('$vysledky' => $vysledky), "Template " . str_replace(dirname(dirname($template->getFile())), "\xE2\x80\xA6", $template->getFile())) ?>
        <table cellspacing="1" class="tablesorter clickselect" >
            <thead>
                <tr>
                    <th>&nbsp;</th>
                    <th>Jméno</th>
                    <th>Ročník</th>
                    <th>Oddíl</th>
                    <th>Trenér</th>
<?php $iterations = 0; foreach ($naradi as $nar=>$preklad_naradi): ?>
                    <th>D</th>
                    <th>E</th>
                    <th>pen</th>
                    <th><?php echo NTemplateHelpers::escapeHtml($preklad_naradi, ENT_NOQUOTES) ?></th>
<?php $iterations++; endforeach ?>
                    <th>Celkem</th>
Example #15
0
	/**
	 * Converts link to URL.
	 * @return string
	 */
	public function __toString()
	{
		try {
			return $this->component->link($this->destination, $this->params);

		} catch (Exception $e) {
			NDebugger::toStringException($e);
		}
	}
Example #16
0
	/**
	 * @param  string        error log directory
	 * @param  string        administrator email
	 * @return void
	 */
	public function enableDebugger($logDirectory = NULL, $email = NULL)
	{
		NDebugger::$strictMode = TRUE;
		NDebugger::enable($this->parameters['productionMode'], $logDirectory, $email);
	}
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">

<style> html { background: url(data/arrow.png) no-repeat bottom right; height: 100%; } </style>

<h1>Nette Debugger & Variables | dibi</h1>

<p>Dibi can dump variables via Nette Debugger, part of Nette Framework.</p>

<ul>
	<li>Nette Framework: http://nette.org
</ul>

<?php 
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
// enable Nette Debugger
NDebugger::enable();
dibi::connect(array('driver' => 'sqlite', 'database' => 'data/sample.sdb', 'profiler' => array('run' => TRUE)));
NDebugger::barDump(dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]');
Example #18
0
<?php

/**
 * My Application bootstrap file.
 */
// Load Nette Framework
require LIBS_DIR . '/Nette/loader.php';
// Enable Nette Debugger for error visualisation & logging
NDebugger::$logDirectory = dirname(__FILE__) . '/../log';
NDebugger::$strictMode = TRUE;
NDebugger::enable();
// Configure application
$configurator = new NConfigurator();
$configurator->setTempDirectory(dirname(__FILE__) . '/../temp');
// Enable RobotLoader - this will load all classes automatically
$configurator->createRobotLoader()->addDirectory(APP_DIR)->addDirectory(LIBS_DIR)->register();
// Create Dependency Injection container from config.neon file
$configurator->addConfig(dirname(__FILE__) . '/config/config.neon');
$container = $configurator->createContainer();
// Opens already started session
if ($container->session->exists()) {
    $container->session->start();
}
// Setup router
$router = $container->router;
$router[] = new NRoute('index.php', 'Dashboard:default', NRoute::ONE_WAY);
$router[] = new NRoute('<presenter>/<action>[/<id>]', 'Dashboard:default');
// Configure and run the application!
$application = $container->application;
//$application->catchExceptions = TRUE;
$application->errorPresenter = 'Error';
Example #19
0
 function register(DibiConnection $connection)
 {
     if (is_callable('Nette\\Diagnostics\\Debugger::enable') && !class_exists('NDebugger')) {
         class_alias('Nette\\Diagnostics\\Debugger', 'NDebugger');
     }
     if (is_callable('NDebugger::enable') && is_callable('NDebugger::getBlueScreen')) {
         NDebugger::getBar()->addPanel($this);
         NDebugger::getBlueScreen()->addPanel(array(__CLASS__, 'renderException'));
         $connection->onEvent[] = array($this, 'logEvent');
     } elseif (is_callable('NDebugger::enable')) {
         NDebugger::$bar && NDebugger::$bar->addPanel($this);
         NDebugger::$blueScreen && NDebugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
         $connection->onEvent[] = array($this, 'logEvent');
     } elseif (is_callable('Debugger::enable') && !is_callable('Debugger::getBlueScreen')) {
         Debugger::$bar && Debugger::$bar->addPanel($this);
         Debugger::$blueScreen && Debugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
         $connection->onEvent[] = array($this, 'logEvent');
     }
 }
Example #20
0
<?php

function set_magic_quotes_runtime()
{
    return false;
}
// Step 1: Load Nette Framework
require LIBS_DIR . '/nette.min.php';
define('_NETTE_MODE', false);
NDebugger::$strictMode = TRUE;
NDebugger::enable(false, APP_NETTE_DIR . '/log');
//NEnvironment::setVariable ( "tempDir", "%appNetteDir%/temp" );
// 2c) enable RobotLoader - this allows load all classes automatically
$loader = new NRobotLoader();
$loader->setCacheStorage(new NFileStorage(TEMP_DIR));
$loader->addDirectory(APP_NETTE_DIR);
$loader->addDirectory(LIBS_DIR);
$loader->addDirectory(WWW_DIR . '/require_modules');
$loader->addDirectory(WWW_DIR . '/classes');
//$loader->addDirectory ( WWW_DIR.'/app/models' );
//$loader->addDirectory ( WWW_DIR.'/app/components' );
$loader->register();
// 2b) load configuration from config.ini file
$config = NEnvironment::loadConfig(APP_NETTE_DIR . '/config/config.neon');
$neon = new NConfigNeonAdapter();
$n = $neon->load(APP_NETTE_DIR . '/config/config.db.neon');
$database = $n['common']['parameters'];
foreach ($database as $k => $p) {
    NEnvironment::setVariable($k, $p);
}
//var_dump($d);exit;
Example #21
0
	/**
	 * Returns array entries that match the pattern.
	 * @param  array
	 * @param  string
	 * @param  int
	 * @return array
	 */
	public static function grep(array $arr, $pattern, $flags = 0)
	{
		NDebugger::tryError();
		$res = preg_grep($pattern, $arr, $flags);
		NStrings::catchPregError($pattern);
		return $res;
	}
Example #22
0
	/**
	 * @return void
	 */
	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']) { // intentionally ==, file may not exists
					$this->updateFile($info['file']);
					$info = & $this->classes[strtolower($class)];
				}
				if (isset($info['file'])) {
					$e = new InvalidStateException("Ambiguous class $class resolution; defined in {$info['file']} and in $file.");
					if (PHP_VERSION_ID < 50300) {
						NDebugger::_exceptionHandler($e);
						exit;
					} else {
						throw $e;
					}
				}
				$info = array('file' => $file, 'time' => filemtime($file), 'orig' => $class);
			}
		}
	}
Example #23
0
	/**
	 * Starts and initializes session data.
	 * @throws InvalidStateException
	 * @return void
	 */
	public function start()
	{
		if (self::$started) {
			return;
		}

		$this->configure($this->options);

		NDebugger::tryError();
		session_start();
		if (NDebugger::catchError($e)) {
			@session_write_close(); // this is needed
			throw new InvalidStateException('session_start(): ' . $e->getMessage(), 0, $e);
		}

		self::$started = TRUE;

		/* structure:
			__NF: Counter, BrowserKey, Data, Meta, Time
				DATA: section->variable = data
				META: section->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']++;
		}

		// session regenerate every 30 minutes
		$nfTime = & $nf['Time'];
		$time = time();
		if ($time - $nfTime > self::REGENERATE_INTERVAL) {
			$nfTime = $time;
			$this->regenerationNeeded = TRUE;
		}

		// browser closing detection
		$browserKey = $this->request->getCookie('nette-browser');
		if (!$browserKey) {
			$browserKey = NStrings::random();
		}
		$browserClosed = !isset($nf['B']) || $nf['B'] !== $browserKey;
		$nf['B'] = $browserKey;

		// resend cookie
		$this->sendCookie();

		// process meta metadata
		if (isset($nf['META'])) {
			$now = time();
			// expire section variables
			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']) // whenBrowserIsClosed || Time
							|| ($variable !== '' && is_object($nf['DATA'][$section][$variable]) && (isset($value['V']) ? $value['V'] : NULL) // Version
								!== NClassReflection::from($nf['DATA'][$section][$variable])->getAnnotation('serializationVersion'))
						) {
							if ($variable === '') { // expire whole section
								unset($nf['META'][$section], $nf['DATA'][$section]);
								continue 2;
							}
							unset($nf['META'][$section][$variable], $nf['DATA'][$section][$variable]);
						}
					}
				}
			}
		}

		if ($this->regenerationNeeded) {
			session_regenerate_id(TRUE);
			$this->regenerationNeeded = FALSE;
		}

		register_shutdown_function(array($this, 'clean'));
	}
Example #24
0
	/**
	 * Add class and file name to the list.
	 * @param  string
	 * @param  string
	 * @param  int
	 * @return void
	 */
	private function addClass($class, $file, $time)
	{
		$lClass = strtolower($class);
		if (isset($this->list[$lClass][0]) && ($file2 = $this->list[$lClass][0]) !== $file && is_file($file2)) {
			if ($this->files[$file2] !== filemtime($file2)) {
				$this->scanScript($file2);
				return $this->addClass($class, $file, $time);
			}
			$e = new InvalidStateException("Ambiguous class '$class' resolution; defined in $file and in " . $this->list[$lClass][0] . ".");
			if (PHP_VERSION_ID < 50300) {
				NDebugger::_exceptionHandler($e);
				exit;
			} else {
				throw $e;
			}
		}
		$this->list[$lClass] = array($file, $time, $class);
		$this->files[$file] = $time;
	}
Example #25
0
function dd($var, $name = null)
{
    return NDebugger::barDump($var, $name);
}
Example #26
0
	public function getPanel()
	{
		$this->disabled = TRUE;
		$s = '';
		foreach ($this->queries as $i => $query) {
			list($sql, $params, $time, $rows, $connection, $source) = $query;

			$explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS()
			if ($this->explain && preg_match('#\s*\(?\s*SELECT\s#iA', $sql)) {
				try {
					$cmd = is_string($this->explain) ? $this->explain : 'EXPLAIN';
					$explain = $connection->queryArgs("$cmd $sql", $params)->fetchAll();
				} catch (PDOException $e) {}
			}

			$s .= '<tr><td>' . sprintf('%0.3f', $time * 1000);
			if ($explain) {
				static $counter;
				$counter++;
				$s .= "<br /><a href='#' class='nette-toggler' rel='#nette-DbConnectionPanel-row-$counter'>explain&nbsp;&#x25ba;</a>";
			}

			$s .= '</td><td class="nette-DbConnectionPanel-sql">' . NDatabaseHelpers::dumpSql(self::$maxLength ? NStrings::truncate($sql, self::$maxLength) : $sql);
			if ($explain) {
				$s .= "<table id='nette-DbConnectionPanel-row-$counter' class='nette-collapsed'><tr>";
				foreach ($explain[0] as $col => $foo) {
					$s .= '<th>' . htmlSpecialChars($col) . '</th>';
				}
				$s .= "</tr>";
				foreach ($explain as $row) {
					$s .= "<tr>";
					foreach ($row as $col) {
						$s .= '<td>' . htmlSpecialChars($col) . '</td>';
					}
					$s .= "</tr>";
				}
				$s .= "</table>";
			}
			if ($source) {
				$s .= NDebugHelpers::editorLink($source[0], $source[1])->class('nette-DbConnectionPanel-source');
			}

			$s .= '</td><td>';
			foreach ($params as $param) {
				$s .= NDebugger::dump($param, TRUE);
			}

			$s .= '</td><td>' . $rows . '</td></tr>';
		}

		return empty($this->queries) ? '' :
			'<style class="nette-debug"> #nette-debug td.nette-DbConnectionPanel-sql { background: white !important }
			#nette-debug .nette-DbConnectionPanel-source { color: #BBB !important } </style>
			<h1 title="' . htmlSpecialChars($connection->getDsn()) . '">Queries: ' . count($this->queries)
			. ($this->totalTime ? ', time: ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms' : '') . ', ' . htmlSpecialChars($this->name) . '</h1>
			<div class="nette-inner nette-DbConnectionPanel">
			<table>
				<tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Params</th><th>Rows</th></tr>' . $s . '
			</table>
			</div>';
	}
Example #27
0
	/** @internal */
	public static function catchPregError($pattern)
	{
		if (NDebugger::catchError($e)) { // compile error
			throw new NRegexpException($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 NRegexpException((isset($messages[$code]) ? $messages[$code] : 'Unknown error') . " (pattern: $pattern)", $code);
		}
	}
Example #28
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 {
				NDebugger::toStringException($e);
			}
		}
	}
Example #29
0
 public static function catchError(&$error)
 {
     if (!self::$enabled && self::$lastError !== FALSE) {
         restore_error_handler();
     }
     $error = self::$lastError;
     self::$lastError = FALSE;
     return (bool) $error;
 }
Example #30
0
	/**
	 * Renders template to string.
	 * @param  bool  can throw exceptions? (hidden parameter)
	 * @return string
	 */
	public function __toString()
	{
		$args = func_get_args();
		ob_start();
		try {
			$this->render();
			return ob_get_clean();

		} catch (Exception $e) {
			ob_end_clean();
			if ($args && $args[0]) {
				throw $e;
			} else {
				NDebugger::toStringException($e);
			}
		}
	}