public function query($query) { //$cache = Ajde_Db_Cache::getInstance(); $log = ['query' => $query]; $start = microtime(true); //if (!$cache->has($query)) { try { $result = parent::query($query); } catch (Exception $e) { if (config('app.debug') === true) { if (isset($this->queryString)) { dump($this->queryString); } dump('Go to ' . config('app.rootUrl') . '?install=1 to install DB'); throw new Ajde_Db_Exception($e->getMessage()); } else { Ajde_Exception_Log::logException($e); die('DB connection problem. <a href="?install=1">Install database?</a>'); } } //$cache->set($query, serialize($result)); // $log['cache'] = false; //} else { // $result = $cache->get($query); // $log['cache'] = true; //} $time = microtime(true) - $start; $log['time'] = round($time * 1000, 0); self::$log[] = $log; return $result; }
/** * When execute is called record the time it takes and * then log the query * @return PDO result set */ public function execute($input_parameters = null) { //$cache = Ajde_Db_Cache::getInstance(); $log = array('query' => '[PS] ' . $this->queryString); $start = microtime(true); try { //if (!$cache->has($this->queryString . serialize($input_parameters))) { $result = parent::execute($input_parameters); //$cache->set($this->queryString . serialize($input_parameters), $result); // $log['cache'] = false; //} else { // $result = $cache->get($this->queryString . serialize($input_parameters)); // $log['cache'] = true; //} } catch (Exception $e) { if (Config::get('debug') === true) { dump($this->queryString); throw $e; } else { Ajde_Exception_Log::logException($e); return false; } } $time = microtime(true) - $start; $log['time'] = round($time * 1000, 0); Ajde_Db_PDO::$log[] = $log; return $result; }
/** * When execute is called record the time it takes and * then log the query. * * @param array $input_parameters * * @throws Ajde_Db_Exception * @throws Ajde_Exception * * @return PDO result set */ public function execute($input_parameters = null) { $log = ['query' => '']; if (config('app.debug') === true) { //$cache = Ajde_Db_Cache::getInstance(); if (count($input_parameters)) { $log = ['query' => vsprintf(str_replace('?', '%s', $this->queryString), $input_parameters)]; } else { $log = ['query' => '[PS] ' . $this->queryString]; } // add backtrace $i = 0; $source = []; foreach (array_reverse(debug_backtrace()) as $item) { try { $line = issetor($item['line']); $file = issetor($item['file']); $source[] = sprintf('%s. <em>%s</em>%s<strong>%s</strong> (%s on line %s)', $i, !empty($item['class']) ? $item['class'] : '<unknown class>', !empty($item['type']) ? $item['type'] : '::', !empty($item['function']) ? $item['function'] : '<unknown function>', $file, $line); } catch (Exception $e) { } $i++; } $hash = md5(implode('', $source) . microtime()); $log['query'] = '<a href="javascript:void(0)" onclick="$(\'#' . $hash . '\').slideToggle(\'fast\');" style="color: black;">' . $log['query'] . '</a>'; $log['query'] .= '<div id="' . $hash . '" style="display: none;">' . implode('<br/>', $source) . '</div>'; } // start timer $start = microtime(true); try { //if (!$cache->has($this->queryString . serialize($input_parameters))) { $result = parent::execute($input_parameters); //$cache->set($this->queryString . serialize($input_parameters), $result); // $log['cache'] = false; //} else { // $result = $cache->get($this->queryString . serialize($input_parameters)); // $log['cache'] = true; //} } catch (Exception $e) { if (substr_count(strtolower($e->getMessage()), 'integrity constraint violation')) { throw new Ajde_Db_IntegrityException($e->getMessage()); } else { if (config('app.debug') === true) { if (isset($this->queryString)) { dump($this->queryString); } dump('Go to ' . config('app.rootUrl') . '?install=1 to install DB'); throw new Ajde_Db_Exception($e->getMessage()); } else { Ajde_Exception_Log::logException($e); die('DB connection problem. <a href="?install=1">Install database?</a>'); } } } $time = microtime(true) - $start; $log['time'] = round($time * 1000, 0); Ajde_Db_PDO::$log[] = $log; return $result; }
public function getLastTweet($username) { $ret = false; try { $ret = $this->_twitter->get('statuses/update', array('status' => $status)); } catch (Exception $e) { Ajde_Exception_Log::logException($e); } return $ret; }
/** * @throws Ajde_Core_Exception_Security * * @return Ajde_Http_Request */ public static function fromGlobal() { $instance = new self(); $post = self::globalPost(); if (!empty($post) && self::requirePostToken() && !self::_isWhitelisted()) { // Measures against CSRF attacks $session = new Ajde_Session('AC.Form'); if (!isset($post['_token']) || !$session->has('formTime')) { $exception = new Ajde_Core_Exception_Security('No form token received or no form time set, bailing out to prevent CSRF attack'); if (config('app.debug') === true) { Ajde_Http_Response::setResponseType(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); throw $exception; } else { // Prevent inf. loops unset($_POST); unset($_REQUEST); // Rewrite Ajde_Exception_Log::logException($exception); Ajde_Http_Response::dieOnCode(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); } } $formToken = $post['_token']; if (!self::verifyFormToken($formToken) || !self::verifyFormTime()) { // TODO: if (!self::verifyFormToken($formToken)) { $exception = new Ajde_Core_Exception_Security('No matching form token (got ' . self::_getHashFromSession($formToken) . ', expected ' . self::_tokenHash($formToken) . '), bailing out to prevent CSRF attack'); } else { $exception = new Ajde_Core_Exception_Security('Form token timed out, bailing out to prevent CSRF attack'); } if (config('app.debug') === true) { Ajde_Http_Response::setResponseType(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); throw $exception; } else { // Prevent inf. loops unset($_POST); unset($_REQUEST); // Rewrite Ajde_Exception_Log::logException($exception); Ajde_Http_Response::dieOnCode(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); } } } // Security measure, protect $_POST $global = self::globalGet(); foreach ($global as $key => $value) { $instance->set($key, $value); } $instance->_postData = self::globalPost(); if (!empty($instance->_postData)) { Ajde_Cache::getInstance()->disable(); } return $instance; }
public function __construct($dsn, $user, $password, $options) { $options = $options + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; try { $connection = new Ajde_Db_PDO($dsn, $user, $password, $options); } catch (Exception $e) { // Disable trace on this exception to prevent exposure of sensitive data // TODO: exception Ajde_Exception_Log::logException($e); throw new Ajde_Exception('Could not connect to database', 0, false); } $this->_connection = $connection; }
public static function lessifyCss($css) { if (substr_count($css, '/*#!less*/') === 0) { return $css; } $less = new lessc(); try { $lesser = $less->parse($css); } catch (Exception $e) { Ajde_Exception_Log::logException($e); return $css; } return $lesser; }
public function getThumbnail() { $vmid = $this->_getVimeoId(); if ($vmid) { $response = Ajde_Http_Curl::get("http://vimeo.com/api/v2/video/{$vmid}.php"); try { $hash = unserialize($response); } catch (Exception $e) { Ajde_Exception_Log::logException(new Ajde_Exception('Could not parse result from Vimeo')); return; } return $hash[0]['thumbnail_large']; } }
public function updateJson() { $step = Ajde::app()->getRequest()->getPostParam('step', 'start'); $status = true; if ($step !== 'start') { $status = false; $updater = Ajde_Core_Updater::getInstance(); try { $status = $updater->update($step); } catch (Exception $e) { Ajde_Exception_Log::logException($e); $status = $e->getMessage(); } } return ['status' => $status]; }
public function __bootstrap() { // Session name session_name(Config::get('ident') . '_session'); // Security ini_set('session.gc_maxlifetime', Config::get("gcLifetime") * 60); // PHP session garbage collection timeout in minutes ini_set('session.use_cookies', 1); ini_set('session.use_only_cookies', 1); // @see http://www.php.net/manual/en/session.configuration.php#ini.session.use-only-cookies // Cookie parameter $lifetime = Config::get("cookieLifetime"); $path = Config::get('site_path'); $domain = Config::get('cookieDomain'); $secure = Config::get('cookieSecure'); $httponly = Config::get('cookieHttponly'); session_set_cookie_params($lifetime * 60, $path, $domain, $secure, $httponly); session_cache_limiter('private_no_expire'); // Start the session! session_start(); // Force send new cookie with updated lifetime (forcing keep-alive) // @see http://www.php.net/manual/en/function.session-set-cookie-params.php#100672 session_regenerate_id(); // Strengthen session security with REMOTE_ADDR and HTTP_USER_AGENT // @see http://shiflett.org/articles/session-hijacking if (isset($_SESSION['client']) && $_SESSION['client'] !== md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . Config::get('secret'))) { session_regenerate_id(); session_destroy(); // TODO: $exception = new Ajde_Exception('Possible session hijacking detected. Bailing out.'); if (Config::getInstance()->debug === true) { throw $exception; } else { Ajde_Exception_Log::logException($exception); Ajde_Http_Response::dieOnCode(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); } } else { $_SESSION['client'] = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . Config::get('secret')); } // remove cache headers invoked by session_start(); if (version_compare(PHP_VERSION, '5.3.0') >= 0) { header_remove('X-Powered-By'); } return true; }
public static function dieOnCode($code) { self::setResponseType($code); header('Content-type: text/html; charset=UTF-8'); $_SERVER['REDIRECT_STATUS'] = $code; $errorRoutes = config('routes.errors'); if (isset($errorRoutes[$code])) { try { self::dieOnRoute($errorRoutes[$code]); } catch (Exception $e) { Ajde_Exception_Log::logException($e); } } // fallback ob_get_clean(); include LOCAL_ROOT . PUBLIC_DIR . 'error.php'; die; }
public static function handler(Exception $exception) { try { if (Config::getInstance()->debug === true) { if (!((get_class($exception) == 'Ajde_Exception' || is_subclass_of($exception, 'Ajde_Exception')) && !$exception->traceOnOutput())) { Ajde_Exception_Log::logException($exception); echo self::trace($exception); } else { Ajde_Exception_Log::logException($exception); Ajde_Http_Response::redirectServerError(); } } else { Ajde_Exception_Log::logException($exception); Ajde_Http_Response::redirectServerError(); } } catch (Exception $exception) { error_log(self::trace($exception, self::EXCEPTION_TRACE_LOG)); die("An uncatched exception occured within the error handler, see the server error_log for details"); } }
public function publish() { $tweet = $this->getTitle(); if ($url = $this->getUrl()) { $tweet = substr($tweet, 0, 140 - strlen($url) - 5) . '... ' . $url; } while ($curlength = iconv_strlen(htmlspecialchars($tweet, ENT_QUOTES, 'UTF-8'), 'UTF-8') >= 140) { $tweet = substr($tweet, 0, -1); } try { $response = $this->_twitter->post('statuses/update', ['status' => $tweet]); } catch (Exception $e) { Ajde_Log::log($response); Ajde_Exception_Log::logException($e); return false; } if ($response->user && $response->user->id && $response->id_str) { return sprintf('http://twitter.com/%s/status/%s', $response->user->id, $response->id_str); } else { return false; } }
public function updatePayment() { $payment = false; $mollie = new Mollie_API_Client(); $mollie->setApiKey($this->getApiKey()); $transaction = new TransactionModel(); $changed = false; // see if we are here for the webhook or user return url $mollie_id = Ajde::app()->getRequest()->getPostParam('id', false); // from webhook $order_id = Ajde::app()->getRequest()->getParam('order_id', false); // from user request if (!$mollie_id && $order_id) { // load from order_id $transaction->loadByField('secret', $order_id); $mollie_id = $transaction->payment_providerid; try { $payment = $mollie->payments->get($mollie_id); } catch (Mollie_API_Exception $e) { Ajde_Exception_Log::logException($e); $payment = false; } } else { if ($mollie_id) { // laod from mollie transaction id try { $payment = $mollie->payments->get($mollie_id); $order_id = $payment->metadata->order_id; $transaction->loadByField('secret', $order_id); } catch (Mollie_API_Exception $e) { Ajde_Exception_Log::logException($e); $payment = false; } } } if (!$payment || !$mollie_id || !$order_id || !$transaction->hasLoaded()) { Ajde_Log::log('Could not find transaction for Mollie payment for mollie id ' . $mollie_id . ' and transaction secret ' . $order_id); return ['success' => false, 'changed' => $changed, 'transaction' => $transaction]; } // what to return? $paid = false; $payment_details = $payment->details; if (is_object($payment_details) || is_array($payment_details)) { $payment_details = json_encode($payment_details); } // save details $details = 'PAYMENT STATUS: ' . (string) $payment->status . PHP_EOL . 'PAYMENT AMOUNT: ' . (string) $payment->amount . PHP_EOL . 'PAYMENT AT: ' . (string) $payment->paidDatetime . PHP_EOL . 'CANCELLED AT: ' . (string) $payment->cancelledDatetime . PHP_EOL . 'EXPIRED AT: ' . (string) $payment->expiredDatetime . PHP_EOL . 'PAYER DETAILS: ' . (string) $payment_details; $transaction->payment_details = $details; switch ($payment->status) { case 'open': if ($transaction->payment_status != 'requested') { $transaction->payment_status = 'requested'; $transaction->save(); $changed = true; } break; case 'paidout': case 'paid': $paid = true; // update transaction only once if ($transaction->payment_status != 'completed') { $transaction->paid(); $changed = true; } break; case 'cancelled': // update transaction only once if ($transaction->payment_status != 'cancelled') { $transaction->payment_status = 'cancelled'; $transaction->save(); $changed = true; } break; case 'expired': // update transaction only once if ($transaction->payment_status != 'refused') { $transaction->payment_status = 'refused'; $transaction->save(); $changed = true; } break; } return ['success' => $paid, 'changed' => $changed, 'transaction' => $transaction]; }
public static function routingError(Ajde_Exception $exception) { if (Config::get("debug") === true) { throw $exception; } else { Ajde_Exception_Log::logException($exception); Ajde_Http_Response::redirectNotFound(); } }
public function __bootstrap() { // Session name $sessionName = config('app.id') . '_session'; session_name($sessionName); // Session lifetime $lifetime = config('session.lifetime'); // Security garbage collector ini_set('session.gc_maxlifetime', $lifetime == 0 ? 180 * 60 : $lifetime * 60); // PHP session garbage collection timeout in minutes ini_set('session.gc_divisor', 100); // Set divisor and probability for cronjob Ubuntu/Debian // ini_set('session.gc_probability', 1); // @see http://www.php.net/manual/en/function.session-save-path.php#98106 // Set session save path if (config('session.savepath')) { ini_set('session.save_path', str_replace('~', LOCAL_ROOT, config('session.savepath'))); } // Set sessions to use cookies ini_set('session.use_cookies', 1); ini_set('session.use_only_cookies', 1); // @see http://www.php.net/manual/en/session.configuration.php#ini.session.use-only-cookies // Session cookie parameter $path = config('app.path'); $domain = config('security.cookie.domain'); $secure = config('security.cookie.secure'); $httponly = config('security.cookie.httponly'); // Set cookie lifetime session_set_cookie_params($lifetime * 60, $path, $domain, $secure, $httponly); session_cache_limiter('private_no_expire'); // Start the session! session_start(); // Strengthen session security with REMOTE_ADDR and HTTP_USER_AGENT // @see http://shiflett.org/articles/session-hijacking // Removed REMOTE_ADDR, use HTTP_X_FORWARDED_FOR if available $remoteIp = Ajde_Http_Request::getClientIP(); // Ignore Google Chrome frame as it has a split personality // @todo TODO: security issue!! // @see http://www.chromium.org/developers/how-tos/chrome-frame-getting-started/understanding-chrome-frame-user-agent if (isset($_SERVER['HTTP_USER_AGENT']) && substr_count($_SERVER['HTTP_USER_AGENT'], 'chromeframe/') === 0 && isset($_SESSION['client']) && $_SESSION['client'] !== md5($remoteIp . $_SERVER['HTTP_USER_AGENT'] . config('security.secret'))) { // TODO: overhead to call session_regenerate_id? is it not required?? //session_regenerate_id(); // thoroughly destroy the current session session_destroy(); unset($_SESSION); setcookie(session_name(), session_id(), time() - 3600, $path, $domain, $secure, $httponly); // TODO: $exception = new Ajde_Core_Exception_Security('Possible session hijacking detected. Bailing out.'); if (config('app.debug') === true) { throw $exception; } else { // don't redirect/log for resource items, as they should have no side effect // this makes it possible for i.e. web crawlers/error pages to view resources $request = Ajde_Http_Request::fromGlobal(); $route = $request->initRoute(); Ajde::app()->setRequest($request); if (!in_array($route->getFormat(), ['css', 'js'])) { Ajde_Exception_Log::logException($exception); Ajde_Cache::getInstance()->disable(); // Just destroying the session should be enough // Ajde_Http_Response::dieOnCode(Ajde_Http_Response::RESPONSE_TYPE_FORBIDDEN); } } } else { $_SESSION['client'] = md5($remoteIp . issetor($_SERVER['HTTP_USER_AGENT']) . config('security.secret')); if ($lifetime > 0) { // Force send new cookie with updated lifetime (forcing keep-alive) // @see http://www.php.net/manual/en/function.session-set-cookie-params.php#100672 //session_regenerate_id(); // Set cookie manually if session_start didn't just sent a cookie // @see http://www.php.net/manual/en/function.session-set-cookie-params.php#100657 if (isset($_COOKIE[$sessionName])) { setcookie(session_name(), session_id(), time() + $lifetime * 60, $path, $domain, $secure, $httponly); } } } // remove cache headers invoked by session_start(); if (version_compare(PHP_VERSION, '5.3.0') >= 0) { header_remove('X-Powered-By'); } return true; }
public static function routingError(Exception $exception) { if (config('app.debug') === true) { throw $exception; } else { if (class_exists('Ajde_Exception_Log')) { Ajde_Exception_Log::logException($exception); } Ajde_Http_Response::redirectNotFound(); } }