public function __construct($message, Exception $reason = null) { if ($reason) { $message .= ' --> ' . $reason->getMessage(); } parent::__construct($message); $this->reason = $reason; }
/** * New exception. * * @param Exception $exception * @param boolean $printError show error or not * @param boolean $clear clear the errorlog * @param string $errorFile file to save to */ public static function newMessage(\Exception $exception) { $message = $exception->getMessage(); $code = $exception->getCode(); $file = $exception->getFile(); $line = $exception->getLine(); $trace = $exception->getTraceAsString(); $trace = str_replace(DB_PASS, '********', $trace); $date = date('M d, Y G:iA'); $logMessage = "<h3>Exception information:</h3>\n\n <p><strong>Date:</strong> {$date}</p>\n\n <p><strong>Message:</strong> {$message}</p>\n\n <p><strong>Code:</strong> {$code}</p>\n\n <p><strong>File:</strong> {$file}</p>\n\n <p><strong>Line:</strong> {$line}</p>\n\n <h3>Stack trace:</h3>\n\n <pre>{$trace}</pre>\n\n <hr />\n"; if (is_file(self::$errorFile) === false) { file_put_contents(self::$errorFile, ''); } if (self::$clear) { $f = fopen(self::$errorFile, "r+"); if ($f !== false) { ftruncate($f, 0); fclose($f); } $content = null; } else { $content = file_get_contents(self::$errorFile); } file_put_contents(self::$errorFile, $logMessage . $content); //send email self::sendEmail($logMessage); if (self::$printError == true) { echo $logMessage; exit; } }
/** * Start handling errors * @param callable $callback */ public static function initialize($callback = FALSE) { // save the callback function static::$callback = $callback; if (static::$initialized === FALSE) { // only initialze once self::$initialized = TRUE; // register exception handler set_exception_handler('\\Core\\Exception::handle'); // register error handler set_error_handler(function ($code, $error, $file = NULL, $line = NULL) { // rerout as errorexception \Core\Exception::handle(new \ErrorException($error, $code, 0, $file, $line)); }); // register fatal error handler register_shutdown_function(function () { if ($error = error_get_last()) { if (in_array($error['type'], array(E_PARSE, E_ERROR, E_USER_ERROR))) { // clean output ob_clean(); // rerout as errorexception \Core\Exception::handle(new \ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line'])); // Actually shut down exit(1); } } }); } }
/** * Logs errors in file while directs the user to a generic error page. * * @param \Exception $ex */ public static function logProduction(\Exception $ex) { $message = $ex->getMessage(); $code = $ex->getCode(); $file = $ex->getFile(); $line = $ex->getLine(); $trace = $ex->getTraceAsString(); $log_folder = ROOT . DS . 'errors' . DS; $log = fopen($log_folder . 'ERROS ' . date('d-m-Y') . '.log', 'a+'); fwrite($log, 'message: ' . $message . PHP_EOL); fwrite($log, 'code: ' . $code . PHP_EOL); fwrite($log, 'file: ' . $file . PHP_EOL); fwrite($log, 'line: ' . $line . PHP_EOL); fwrite($log, 'trace: ' . $trace . PHP_EOL); fwrite($log, '================================================================================' . PHP_EOL); fclose($log); }
/** * Implements failing tables; if an account type fails multiple times, * then send the user an email and disable the account. * @see OpenclerkJobQueuer#getStandardJobs() */ function failed(\Exception $runtime_exception, Connection $db, Logger $logger) { // is this a standard job? $standard = $this->findStandardJob(); if ($standard) { $logger->info("Using standard job " . print_r($standard, true)); if (!$standard['failure']) { $logger->info("Not a failure standard job"); return; } } else { return; } $failing_table = $standard['table']; $job = $this->job; // find the relevant account_data for this standard job $account_data = false; foreach (account_data_grouped() as $label => $group) { foreach ($group as $exchange => $data) { if (isset($data['job_type']) && $job['job_type'] == $data['job_type']) { $account_data = $data; $account_data['exchange'] = $exchange; break; } } } if (!$account_data) { $logger->warn("Could not find any account data for job type '" . $job['job_type'] . "'"); } $logger->info("Using account data " . print_r($account_data, true)); // don't count CloudFlare as a failure if ($runtime_exception instanceof CloudFlareException || $runtime_exception instanceof \Openclerk\Apis\CloudFlareException) { $logger->info("Not increasing failure count: was a CloudFlareException"); } else { if ($runtime_exception instanceof IncapsulaException || $runtime_exception instanceof \Openclerk\Apis\IncapsulaException) { $logger->info("Not increasing failure count: was a IncapsulaException"); } else { if ($runtime_exception instanceof BlockchainException || $runtime_exception instanceof \Core\BlockchainException) { $logger->info("Not increasing failure count: was a BlockchainException"); } else { $q = $db->prepare("UPDATE {$failing_table} SET failures=failures+1,first_failure=IF(ISNULL(first_failure), NOW(), first_failure) WHERE id=?"); $q->execute(array($job['arg_id'])); $logger->info("Increasing account failure count"); } } } $user = get_user($job['user_id']); if (!$user) { $logger->info("Warning: No user " . $job['user_id'] . " found"); } else { // failed too many times? $q = $db->prepare("SELECT * FROM {$failing_table} WHERE id=? LIMIT 1"); $q->execute(array($job['arg_id'])); $account = $q->fetch(); $logger->info("Current account failure count: " . number_format($account['failures'])); if ($account['failures'] >= get_premium_value($user, 'max_failures')) { // disable it and send an email $q = $db->prepare("UPDATE {$failing_table} SET is_disabled=1 WHERE id=?"); $q->execute(array($job['arg_id'])); crypto_log(print_r($account_data, true)); if ($user['email'] && !$account['is_disabled']) { $email_type = $job['job_type'] == "notification" ? "failure_notification" : "failure"; send_user_email($user, $email_type, array("name" => $user['name'] ? $user['name'] : $user['email'], "exchange" => get_exchange_name($account_data['exchange']), "label" => $account_data['label'], "labels" => $account_data['labels'], "failures" => number_format($account['failures']), "message" => $runtime_exception->getMessage(), "length" => recent_format(strtotime($account['first_failure']), "", ""), "title" => isset($account['title']) && $account['title'] ? "\"" . $account['title'] . "\"" : "untitled", "url" => absolute_url(url_for("wizard_accounts")))); $logger->info("Sent failure e-mail to " . htmlspecialchars($user['email']) . "."); } } } }
public function ichatException(\Exception $e) { echo "Exception ('{$e->getMessage()}')\n{$e}\n"; }
public function get() { if ($this->_request->segment(1) == 'api') { self::$isApi = true; } $content = false; $routes = \Core\Route::$routes; $uri = trim($this->_request->uri(), '/'); $uriParts = explode('/', $uri); // d($routes); // d($uriParts); exit; foreach ($routes as $key => $route) { $key = trim($key, '/'); if (is_string($key) && $key == '*') { $routes[$uri] = $route; } if (strpos($key, ':')) { $parts = explode('/', $key); if (count($uriParts) === count($parts)) { foreach ($parts as $partKey => $arg) { if (substr($arg, 0, 1) == ':') { $args = []; $iteration = 0; foreach ($parts as $_arg) { if (empty($_arg)) { continue; } $iteration++; if (substr($_arg, 0, 1) == ':') { $segment = $this->_request->segment($iteration); if (isset($route['where']) && isset($route['where'][$_arg])) { if (!preg_match('/' . $route['where'][$_arg] . '/i', $segment)) { // return false; // continue; break 2; } } // $args[$_arg] = $segment; $args[$_arg] = $segment; } } $route['args'] = $args; $routes[$uri] = $route; break 2; } if ($arg != $uriParts[$partKey]) { break; } } } } } if (isset($routes[$uri]) || isset($routes['/' . $uri])) { $routes[$uri] = (array) (!isset($routes['/' . $uri]) ? $routes[$uri] : $routes['/' . $uri]); $r = $routes[$uri]; $r['route'] = $uri; self::$name = $r; try { if (isset($r['auth']) && $r['auth'] === true) { \Phpfox::isUser(true); } if (isset($r['accept'])) { if (!is_array($r['accept'])) { $r['accept'] = [$r['accept']]; } if (!in_array($this->_request->method(), $r['accept'])) { throw error('Method not support.'); } } if (isset($routes[$uri]['run'])) { $Controller = new \Core\Controller($routes[$uri]['path'] . 'views'); $pass = [$Controller]; if (isset($r['args'])) { $pass = array_merge($pass, $r['args']); } $content = call_user_func_array($routes[$uri]['run'], $pass); } else { if (isset($r['url'])) { $App = (new \Core\App())->get($r['id']); $innerHTML = function ($xml) { $innerXML = ''; foreach (dom_import_simplexml($xml)->childNodes as $child) { if ($child->nodeName == 'api') { continue; } $innerXML .= $child->ownerDocument->saveXML($child); } return $innerXML; }; $Template = \Phpfox_Template::instance(); $http = new \Core\HTTP($r['url']); \Core\Event::trigger('external_controller', $http); $response = $http->auth($App->auth->id, $App->auth->key)->using($this->_request->all())->header('API_ENDPOINT', \Phpfox_Url::instance()->makeUrl('api'))->call($_SERVER['REQUEST_METHOD']); if (is_object($response)) { header('Content-type: application/json'); echo json_encode($response, JSON_PRETTY_PRINT); exit; } if (empty($response)) { return false; } $doc = new \DOMDocument(); libxml_use_internal_errors(true); $doc->loadHTML($response); $xml = $doc->saveXML($doc); $xml = @simplexml_load_string($xml); if ($xml === false) { $xml = new \stdClass(); $xml->body = $response; } else { if (!isset($xml->body)) { $xml = new \stdClass(); $xml->body = $response; } } if (isset($xml->body->api)) { if (isset($xml->body->api->section)) { $Template->setBreadCrumb($xml->body->api->section->name, \Phpfox_Url::instance()->makeUrl($xml->body->api->section->url)); } if (isset($xml->body->api->h1)) { $Template->setBreadCrumb($xml->body->api->h1->name, \Phpfox_Url::instance()->makeUrl($xml->body->api->h1->url), true); } if (isset($xml->body->api->menu)) { $Template->setSubMenu($innerHTML($xml->body->api->menu)); } // unset($xml->body->api); } $Controller = new \Core\Controller(); if (isset($xml->head)) { $Controller->title('' . $xml->head->title); foreach ((array) $xml->head as $type => $data) { switch ($type) { case 'style': $Template->setHeader('<' . $type . '>' . (string) $data . '</' . $type . '>'); break; } } } $thisContent = is_string($xml->body) ? $xml->body : $innerHTML($xml->body); if ($this->_request->isPost()) { echo $thisContent; exit; } else { $content = $Controller->render('@Base/blank.html', ['content' => $thisContent]); } } else { if (isset($r['call'])) { $parts = explode('@', $r['call']); if (!isset($parts[1])) { $parts[1] = $this->_request->method(); } $Reflection = new \ReflectionClass($parts[0]); $Controller = $Reflection->newInstance(isset($routes[$uri]['path']) ? $routes[$uri]['path'] . 'views' : null); $args = isset($r['args']) ? $r['args'] : []; try { $content = call_user_func_array([$Controller, $parts[1]], $args); } catch (\Exception $e) { if (self::$isApi) { http_response_code(400); $content = ['error' => ['message' => $e->getMessage()]]; } else { throw new \Exception($e->getMessage(), $e->getCode(), $e); } } } } } } catch (\Exception $e) { if ($this->_request->isPost()) { $errors = \Core\Exception::getErrors(true); if (!$errors) { $errors = '<div class="error_message">' . $e->getMessage() . '</div>'; } $content = ['error' => $errors]; } else { throw new \Exception($e->getMessage(), $e->getCode(), $e); } } if (is_array($content) || self::$isApi) { header('Content-type: application/json'); echo json_encode($content, JSON_PRETTY_PRINT); exit; } if (empty($content) || $this->_request->isPost()) { if (is_object($content) && $content instanceof \Core\jQuery) { header('Content-type: application/json'); echo json_encode(['run' => (string) $content]); } exit; } } return $content; }
public function get() { if ($this->_request->segment(1) == 'api') { self::$isApi = true; new \Core\Route('/api', function () { }); } $content = false; $routes = \Core\Route::$routes; $uri = trim($this->_request->uri(), '/'); $uriParts = explode('/', $uri); // d($routes); foreach ($routes as $key => $route) { $key = trim($key, '/'); if (is_string($key) && $key == '*') { $routes[$uri] = $route; } else { if (strpos($key, '*')) { $parts = explode('/', trim($uri, '/')); $sub = explode('/', $key); if ($parts[0] == $sub[0]) { $routes[$uri] = $route; break; } } } if (strpos($key, ':')) { $parts = explode('/', $key); if (count($uriParts) === count($parts)) { foreach ($parts as $partKey => $arg) { if (substr($arg, 0, 1) == ':') { $args = []; $iteration = 0; foreach ($parts as $_arg) { if (empty($_arg)) { continue; } $iteration++; if (substr($_arg, 0, 1) == ':') { $segment = $this->_request->segment($iteration); if (isset($route['where']) && isset($route['where'][$_arg])) { if (!preg_match('/' . $route['where'][$_arg] . '/i', $segment)) { // p($iteration . ' -> ' . $segment . ' -> ' . $route['where'][$_arg]); // return false; // continue; break 2; } } // $args[$_arg] = $segment; $args[$_arg] = $segment; } } $route['args'] = $args; $routes[$uri] = $route; break 2; } if ($arg != $uriParts[$partKey]) { break; } } } } } if (isset($routes[$uri]) || isset($routes['/' . $uri])) { $routes[$uri] = (array) (!isset($routes['/' . $uri]) ? $routes[$uri] : $routes['/' . $uri]); $r = $routes[$uri]; $r['route'] = $uri; self::$name = $r; try { if (isset($r['auth']) && $r['auth'] === true) { \Phpfox::isUser(true); } if (isset($r['accept'])) { if (!is_array($r['accept'])) { $r['accept'] = [$r['accept']]; } if (!in_array($this->_request->method(), $r['accept'])) { throw error('Method not support.'); } } if (isset($routes[$uri]['run'])) { $Controller = new \Core\Controller($routes[$uri]['path'] . 'views', $uri); $pass = [$Controller]; if (isset($r['args'])) { $pass = array_merge($pass, $r['args']); } $content = call_user_func_array($routes[$uri]['run'], $pass); } else { if (isset($r['url'])) { $App = (new \Core\App())->get($r['id']); $innerHTML = function ($xml) { $innerXML = ''; foreach (dom_import_simplexml($xml)->childNodes as $child) { if ($child->nodeName == 'api') { continue; } $innerXML .= $child->ownerDocument->saveHTML($child); } return $innerXML; }; $Template = \Phpfox_Template::instance(); $http = new \Core\HTTP($r['url']); \Core\Event::trigger('external_controller', $http); $response = $http->auth($App->auth->id, $App->auth->key)->using($this->_request->all())->header('API_CLIENT_ID', PHPFOX_LICENSE_ID)->header('API_HOME', \Phpfox_Url::instance()->makeUrl(''))->header('API_ENDPOINT', \Phpfox_Url::instance()->makeUrl('api'))->header('API_URI', \Phpfox_Url::instance()->getUri())->header('API_USER', json_encode(\Phpfox::isUser() ? user() : []))->call($_SERVER['REQUEST_METHOD']); $parse = function ($thisContent, $isJson = false) { $thisContent = preg_replace_callback('/<user-([a-z\\-]+) ([a-zA-Z\\-0-9="\' ]+)><\\/user-\\1>/is', function ($matches) use($isJson) { $type = str_replace('-', '_', trim($matches[1])); $parts = explode(' ', trim($matches[2])); $keys = []; foreach ($parts as $part) { $part = trim($part); if (substr($part, 0, 5) != 'data-') { continue; } $sub = explode('=', str_replace('data-', '', $part)); $keys[$sub[0]] = isset($sub[1]) ? trim(trim($sub[1], '"'), "'") : ''; } if (!isset($keys['id'])) { return ''; } $userId = $keys['id']; try { $user = (new \Api\User())->get($userId); } catch (\Exception $e) { return ''; } if (property_exists($user, $type)) { $return = $user->{$type}; if ($isJson) { $return = str_replace('"', "'", $return); } return $return; } return ''; }, $thisContent); return $thisContent; }; if (is_object($response)) { header('Content-type: application/json'); if (isset($response->run)) { $response->run = str_replace('[PF_DOUBLE_QUOTE]', '\'', $response->run); $response->run = $parse($response->run, true); } echo json_encode($response, JSON_PRETTY_PRINT); exit; } if (empty($response)) { return false; } $doc = new \DOMDocument(); libxml_use_internal_errors(true); $doc->loadHTML(mb_convert_encoding($response, 'HTML-ENTITIES', 'UTF-8')); $xml = $doc->saveXML($doc); $xml = @simplexml_load_string($xml); if ($xml === false) { $xml = new \stdClass(); $xml->body = $response; } else { if (!isset($xml->body)) { $xml = new \stdClass(); $xml->body = $response; } } if (isset($xml->body->api)) { if (isset($xml->body->api->section)) { $Template->setBreadCrumb($xml->body->api->section->name, \Phpfox_Url::instance()->makeUrl($xml->body->api->section->url)); } if (isset($xml->body->api->h1)) { $Template->setBreadCrumb($xml->body->api->h1->name, \Phpfox_Url::instance()->makeUrl($xml->body->api->h1->url), true); } if (isset($xml->body->api->menu)) { $Template->setSubMenu($innerHTML($xml->body->api->menu)); } // unset($xml->body->api); } $Controller = new \Core\Controller(); if (isset($xml->head)) { $Controller->title('' . $xml->head->title); $attributes = function ($keys) { $attributes = ''; foreach ($keys as $key => $value) { $attributes .= ' ' . $key . '="' . $value . '" '; } return $attributes; }; foreach ((array) $xml->head as $type => $data) { switch ((string) $type) { case 'style': $Template->setHeader('<' . $type . '>' . (string) $data . '</' . $type . '>'); break; case 'link': $Template->delayedHeaders[] = '<' . $type . ' ' . $attributes($data->attributes()) . '>'; break; } } } $thisContent = is_string($xml->body) ? $xml->body : $innerHTML($xml->body); $thisContent = $parse($thisContent); // d(htmlspecialchars($thisContent)); exit; // echo htmlspecialchars($thisContent); exit; if ($this->_request->isPost()) { echo $thisContent; exit; } else { $content = $Controller->render('@Base/blank.html', ['content' => $thisContent]); } } else { if (isset($r['call'])) { $parts = explode('@', $r['call']); if (!isset($parts[1])) { $parts[1] = $this->_request->method(); } $Reflection = new \ReflectionClass($parts[0]); $Controller = $Reflection->newInstance(isset($routes[$uri]['path']) ? $routes[$uri]['path'] . 'views' : null); $args = isset($r['args']) ? $r['args'] : []; try { $content = call_user_func_array([$Controller, $parts[1]], $args); } catch (\Exception $e) { if (self::$isApi) { http_response_code(400); $content = ['error' => ['message' => $e->getMessage()]]; } else { throw new \Exception($e->getMessage(), $e->getCode(), $e); } } } } } } catch (\Exception $e) { if ($this->_request->isPost()) { $errors = \Core\Exception::getErrors(true); if (!$errors) { $errors = '<div class="error_message">' . $e->getMessage() . '</div>'; } $content = ['error' => $errors]; } else { if (!$e->getCode()) { $Controller = new \Core\Controller(); $content = $Controller->render('@Base/blank.html', ['content' => '<div class="error_message">' . $e->getMessage() . '</div>']); } else { throw new \Exception($e->getMessage(), $e->getCode(), $e); } } } if (is_array($content) || self::$isApi) { header('Content-type: application/json'); echo json_encode($content, JSON_PRETTY_PRINT); exit; } if (empty($content) || $this->_request->isPost()) { if (is_object($content) && $content instanceof \Core\jQuery) { header('Content-type: application/json'); echo json_encode(['run' => (string) $content]); } exit; } } return $content; }
public function __construct() { parent::__construct(); $this->message = 'Too many recursive calls in the app' . $this->getFile(); }
/** * New exception. * * @param Exception $exception * @param boolean $printError show error or not * @param boolean $clear clear the errorlog * @param string $errorFile file to save to */ public static function newMessage($exception) { $message = $exception->getMessage(); $code = $exception->getCode(); $file = $exception->getFile(); $line = $exception->getLine(); $trace = $exception->getTraceAsString(); $trace = str_replace(DB_PASS, '********', $trace); $date = date('M d, Y G:iA'); $logMessage = "Exception information:\n\n Date: {$date}\n\n Message: {$message}\n\n Code: {$code}\n\n File: {$file}\n\n Line: {$line}\n\n Stack trace:\n\n {$trace}\n\n ---------\n\n"; if (is_file(APPDIR . self::$errorFile) === false) { file_put_contents(APPDIR . self::$errorFile, ''); } if (self::$clear) { $f = fopen(APPDIR . self::$errorFile, "r+"); if ($f !== false) { ftruncate($f, 0); fclose($f); } } // Append file_put_contents(APPDIR . self::$errorFile, $logMessage, FILE_APPEND); self::$error = $logMessage; self::customErrorMsg(); //send email self::sendEmail($logMessage); }