/** * Connection factory. Connects to DB. * * @param Nette\DI\IContainer $container * @return NotORM */ public static function dbConnect(IContainer $container) { $db = $container->params['database']; $dsn = (isset($db->port)) ? "{$db->driver}:host={$db->host};dbname={$db->database};port={$db->port}" : "{$db->driver}:host={$db->host};dbname={$db->database}"; $pdo = new PDO($dsn, $db->username, $db->password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->query('SET NAMES utf8'); $conn = new NotORM($pdo, new NotORM_Structure_Convention('id', '%s_id', '%ss'), new NotORM_Cache_Session); if ($db->profiler) { $panel = Panel::getInstance(); $panel->setPlatform($db->driver); Debugger::addPanel($panel); $conn->debug = function($query, $parameters) { Panel::getInstance()->logQuery($query, $parameters); }; } return $conn; }
/** * @param ItemRepository $productRepository */ public function __construct(ItemRepository $productRepository) { parent::__construct(); $this->productRepository = $productRepository; $this->absoluteUrls = true; Debugger::$bar = false; }
/** * @param Exception * @return void */ public function renderDefault($exception) { // this block is there due to nette caching issue 11 // https://github.com/nette/caching/issues/11 if ($exception instanceof Nette\InvalidStateException) { $temp = $this->context->parameters['tempDir']; //unlink($temp . '/btfj.dat'); rename($temp . '/btfj.dat', $temp . '/btfj.dat' . microtime(TRUE)); } if ($exception instanceof Nette\Application\BadRequestException) { $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 Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access'); } else { $this->setView('500'); // load template 500.latte Debugger::log($exception, Debugger::ERROR); // and log exception } if ($this->isAjax()) { // AJAX request? Note this error in payload. $this->payload->error = TRUE; $this->terminate(); } }
public function stopQuery() { $keys = array_keys($this->queries); $key = end($keys); $this->queries[$key][2] = Debugger::timer('doctrine'); $this->totalTime += $this->queries[$key][2]; }
function d10() { $tmp = Debug::$maxDepth; Debug::$maxDepth = 10; call_user_func_array('d', func_get_args()); Debug::$maxDepth = $tmp; }
/** * Parses a signed_request and validates the signature. * * @param string $signedRequest A signed token * @param string $appSecret * * @return array The payload inside it or null if the sig is wrong */ public static function decode($signedRequest, $appSecret) { if (!$signedRequest || strpos($signedRequest, '.') === false) { Debugger::log('Signed request is invalid! ' . json_encode($signedRequest), 'facebook'); return NULL; } list($encoded_sig, $payload) = explode('.', $signedRequest, 2); // decode the data $sig = Helpers::base64UrlDecode($encoded_sig); $data = Json::decode(Helpers::base64UrlDecode($payload), Json::FORCE_ARRAY); if (!isset($data['algorithm']) || strtoupper($data['algorithm']) !== Configuration::SIGNED_REQUEST_ALGORITHM) { Debugger::log("Unknown algorithm '{$data['algorithm']}', expected " . Configuration::SIGNED_REQUEST_ALGORITHM, 'facebook'); return NULL; } // check sig $expected_sig = hash_hmac('sha256', $payload, $appSecret, $raw = TRUE); if (strlen($expected_sig) !== strlen($sig)) { Debugger::log('Bad Signed JSON signature! Expected ' . self::dump($expected_sig) . ', but given ' . self::dump($sig), 'facebook'); return NULL; } $result = 0; for ($i = 0; $i < strlen($expected_sig); $i++) { $result |= ord($expected_sig[$i]) ^ ord($sig[$i]); } if ($result !== 0) { Debugger::log('Bad Signed JSON signature! Expected ' . self::dump($expected_sig) . ', but given ' . self::dump($sig), 'facebook'); return NULL; } return $data; }
public function stopQuery() { if ($this->explainRunning) { return; } $keys = array_keys($this->queries); $key = end($keys); $this->queries[$key][self::TIME] = Debugger::timer('doctrine'); $this->totalTime += $this->queries[$key][self::TIME]; // get EXPLAIN for SELECT queries if ($this->doExplains) { if ($this->connection === NULL) { throw new \Nette\InvalidStateException('You must set a Doctrine\\DBAL\\Connection to get EXPLAIN.'); } $query = $this->queries[$key][self::SQL]; if (strtoupper(substr(ltrim($query), 0, 6)) !== 'SELECT') { // only SELECTs are supported return; } // prevent logging explains & infinite recursion $this->explainRunning = TRUE; $params = $this->queries[$key][self::PARAMS]; $types = $this->queries[$key][self::TYPES]; $stmt = $this->connection->executeQuery('EXPLAIN ' . $query, $params, $types); $this->queries[$key][self::EXPLAIN] = $stmt->fetchAll(); $this->explainRunning = FALSE; } }
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']) && !Nette\Diagnostics\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()); } }
protected function createComponentAddSetting() { $form = new Form(); $form->addText('key', 'Klíč')->setRequired('Zadejte klíč nastavení'); $form->addText('value', 'Hodnota')->setRequired('Zadejte hodnotu nastavení'); $form->addSubmit('send', 'Zapsat'); $form->onSuccess[] = function (Form $f) { try { $val = $f->values; $this->settings->set($val->key, $val->value); $this->settings->push(); //Write $this->logger->log('System', 'edit', "%user% změnila(a) nastavení"); $msg = $this->flashMessage("Nastavení bylo zapsáno", 'success'); $msg->title = 'Yehet!'; $msg->icon = 'check'; $this->redirect('this'); } catch (\PDOException $e) { \Nette\Diagnostics\Debugger::log($e); $msg = $this->flashMessage("Něco se podělalo. Zkuste to prosím později.", 'danger'); $msg->title = 'Oh shit!'; $msg->icon = 'warning'; } }; return $form; }
function log_write($data, FileDownload $file, IDownloader $downloader) { $cache = Environment::getCache("FileDownloader/log"); $log = array(); $tid = (string) $file->getTransferId(); if (!isset($cache["registry"])) { $cache["registry"] = array(); } $reg = $cache["registry"]; $reg[$tid] = true; $cache["registry"] = $reg; if (isset($cache[$tid])) { $log = $cache[$tid]; } Debugger::fireLog("Data: " . $data . "; " . $downloader->end); $data = $data . ": " . Helpers::bytes($file->transferredBytes) . " <->; "; if ($downloader instanceof AdvancedDownloader and $downloader->isInitialized()) { $data .= "position: " . Helpers::bytes($downloader->position) . "; "; //$data .= "length: ".Helpers::bytes($downloader->length)."; "; $data .= "http-range: " . Helpers::bytes($downloader->start) . "-" . Helpers::bytes($downloader->end) . "; "; $data .= "progress (con: " . round($file->transferredBytes / $downloader->end * 100) . "% X "; $data .= "file: " . round($downloader->position / $file->sourceFileSize * 100) . "%)"; } $log[] = $data; $cache[$tid] = $log; }
/** * @param $id * @param $status * @throws \Nette\Application\BadRequestException */ public function actionView($id, $status = null) { $interpret = $this->interpreti->find($id); if ($status) { $this->template->status = $status; } if (!$interpret) { throw new Nette\Application\BadRequestException("Interpret does not exists!", 404); } if ($interpret->interpret_id) { $msg = $this->flashMessage("Přesměrováno z '{$interpret->nazev}'"); $msg->title = "Alias"; $this->redirect("this", array("id" => $interpret->interpret_id)); //If is alias => redirect to real } $this->template->interpret = $interpret; //Register helper fot fetching song form last.fm $this->template->registerhelper('songImage', function ($song, $img = 0) { try { return $this->lastfm->call('Track.getInfo', ['track' => $song->name, 'artist' => $song->interpret_name])->track->album->image[$img]->{'#text'}; } catch (Model\Lastfm\LastfmException $e) { return null; } }); //Last.fm Interpret info (images) try { $this->template->lastfm = $this->lastfm->call('Artist.getInfo', ['artist' => $interpret->nazev])->artist; } catch (Model\Lastfm\LastfmException $e) { if ($this->settings->get('lastfm_enabled', false)) { Debugger::log($e); } } }
/** * Nette\Diagnostics\Debugger::dump() shortcut. * @tracySkipLocation */ function dump($var) { foreach (func_get_args() as $arg) { Debugger::dump($arg); } return $var; }
/** * @param Exception * @return void */ public function renderDefault($exception) { if ($exception) { $data = array('error_msg' => $exception->getMessage(), 'upd_process_id' => 'ErrorPresenter::renderDefault()'); if (isset($this->lastLogItem) && is_object($this->lastLogItem)) { $this->logger->updateLogVisit($this->lastLogItem->id, $data); } } if ($this->isAjax()) { // AJAX request? Just note this error in payload. $this->payload->error = TRUE; $this->terminate(); } elseif ($exception instanceof NA\BadRequestException || $exception instanceof HQ\UnauthorizedAccessException) { $code = $exception->getCode(); if ($exception instanceof HQ\UnauthorizedAccessException) { // Unathorized access in admin $this->setView("admin403"); } else { // 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 Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access'); } else { $this->setView('500'); // load template 500.latte $this->logger->logError($exception, 'exception', 'ErrorPresenter::LOG_EXCEPTION'); } }
/** * generateExceptionFile * @param Exception $exception * @return string */ private function generateExceptionFile($exception) { $hash = md5($exception); $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-{$hash}.html"; foreach (new \DirectoryIterator($this->loggerDirectory) as $entry) { if (strpos($entry, $hash)) { $exceptionFilename = $entry; $saved = TRUE; break; } } $exceptionFilename = $this->loggerDirectory . '/' . $exceptionFilename; if (empty($saved) && ($logHandle = @fopen($exceptionFilename, 'w'))) { ob_start(); // double buffer prevents sending HTTP headers in some PHP ob_start(function ($buffer) use($logHandle) { fwrite($logHandle, $buffer); }, 4096); Debugger::getBlueScreen()->render($exception); ob_end_flush(); ob_end_clean(); fclose($logHandle); } return $exceptionFilename; }
/** * @param Method $element * @throws \Flame\Rest\Security\ForbiddenRequestException */ public function authenticate(Method $element) { $referer = $this->getReferer(); if (!in_array($referer, $this->allowedReferers)) { Debugger::log('Invalid HTTP REFERER header "' . $referer . '"', Debugger::DETECT); throw new ForbiddenRequestException(); } }
public function __toString() { try { return (string) $this->getPrimary(); } catch (\Exception $e) { Nette\Diagnostics\Debugger::toStringException($e); } }
public function addServer($host = 'localhost', $port = 11211, $timeout = 1) { Nette\Diagnostics\Debugger::tryError(); $this->memcache->addServer($host, $port, TRUE, 1, $timeout); if (Nette\Diagnostics\Debugger::catchError($e)) { throw new Nette\InvalidStateException('Memcache::addServer(): ' . $e->getMessage(), 0, $e); } }
/** * Converts link to URL. * @return string */ public function __toString() { try { return $this->component->link($this->destination, $this->params); } catch (\Exception $e) { Nette\Diagnostics\Debugger::toStringException($e); } }
public static function register() { //register panel only once if (!self::$registered) { Debugger::addPanel(new self()); self::$registered = TRUE; } }
/** * @param Method $element * @throws \Flame\Rest\Security\ForbiddenRequestException */ public function authenticate(Method $element) { $ip = $this->getClientIp(); if (!in_array($ip, $this->allowedIps)) { Debugger::log('Banned ip "' . $ip . '"', Debugger::DETECT); throw new ForbiddenRequestException(); } }
/** * Nette\Diagnostics\Debugger::log() shortcut. */ function dlog($var = NULL) { if (func_num_args() === 0) { Debugger::log(new Exception(), 'dlog'); } foreach (func_get_args() as $arg) { Debugger::log($arg, 'dlog'); } return $var; }
public static function register($container) { $panel = new self(); Debugger::addPanel($panel); if (static::$appDir === null) { static::$appDir = \jasir\FileHelpers\File::simplifyPath(__DIR__ . '/../../../../app'); } $application = $container->getService('application'); $application->onResponse[] = callback(array($panel, 'getResponseCb')); }
protected function attached($parent) { parent::attached($parent); if (!$parent instanceof UI\Presenter || !Debugger::isEnabled()) { return; } Debugger::$bar->addPanel($this); $this->addText('destination', 'Destination')->addRule($this::FILLED, 'Je třeba zadat destinaci.')->getControlPrototype()->placeholder = 'Please enter destination'; $this->addSubmit('redirect', 'Redirect')->onClick[] = callback($this, 'processRedirect'); $this->addSubmit('showLink', 'Show link')->onClick[] = callback($this, 'processShowLink'); }
public function runBare() { try { return parent::runBare(); } catch (\Exception $e) { if (!$e instanceof \PHPUnit_Framework_AssertionFailedError) { \Nette\Diagnostics\Debugger::_exceptionHandler($e); } throw $e; } }
public function actionDoctrineExample() { $articles = $this->em->getDao(Article::getClassName()); $article = new Article(); $article->title = "The Fight Club"; $articles->save($article); $article = $articles->find(1); $this->template->article = $article->title; Debugger::dump($article); $this->redirect('Homepage:default'); }
/** Bar dump */ function dd($var) { if (func_num_args() > 1) { $var = func_get_args(); } else { if (is_array($var)) { $var = array(NULL => $var); } } Debugger::barDump($var); return func_get_arg(0); }
/** * Reads configuration from INI file. * * @param string file name * * @return array * @throws Nette\InvalidStateException */ public function load($file) { Nette\Diagnostics\Debugger::tryError(); $ini = parse_ini_file($file, true); if (Nette\Diagnostics\Debugger::catchError($e)) { throw new Nette\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, "ÿ", $key); foreach (explode(self::KEY_SEPARATOR, $key) as $part) { $part = str_replace("ÿ", 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; // 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 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 renderDefault($exception) { if ($this->isAjax()) { $this->payload->error = TRUE; $this->terminate(); } elseif ($exception instanceof Nette\Application\BadRequestException) { $this->setView('404'); } else { $this->setView('500'); Debugger::log($exception, Debugger::ERROR); } }
public function shutdown($response) { parent::shutdown($response); if ($this->getHttpRequest()->getUrl()->path != '/healthy-check') { $elapsed = \Nette\Diagnostics\Debugger::timer('global'); // Log Valid Response $data = array('elapsed' => $elapsed, 'upd_process_id' => 'BasePresenter::shutdown()'); if ($this->lastLogItem) { $this->logger->updateLogVisit($this->lastLogItem->id, $data); } } }
/** * Returns system DI container. * @return \SystemContainer */ public function createContainer() { $container = parent::createContainer(); // We setup email for bug reporting from config file // (if not set up in bootstrap) if (isset($container->parameters['errorRecipients'])) { if (Nette\Diagnostics\Debugger::$email === NULL) { Nette\Diagnostics\Debugger::$email = $container->parameters['errorRecipients']; } } return $container; }