/** * @expectedException \Edge\Core\Exceptions\Unauthorized */ public function testAuthenticationForGuestUserWithPosttAjax() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest'; $this->auth->preProcess(Edge::app()->response, Edge::app()->request); $this->assertEquals($_SERVER['REQUEST_URI'], Edge::app()->session->redirectUrl); }
/** * @expectedException \Edge\Core\Exceptions\Forbidden */ public function testUserWithNoPermissions() { $user = parent::getUser(["username" => "edge"], ["hasPrivilege"]); $user->method('hasPrivilege')->willReturn(false); $filter = $this->getFilter(["permissions" => ["Delete User"], "user" => $user]); $filter->preProcess(Edge::app()->response, Edge::app()->request); }
protected function getRecord($offset) { $db = Edge::app()->db; $db->dbSeek($this->result, $offset); $row = $db->dbFetchArray($this->result); return new $this->className($row); }
/** * After the request has been processed, get the response * body and cache it * @param Http\Response $response * @param Http\Request $request */ public function postProcess(Http\Response $response, Http\Request $request) { if (!$this->isCached) { Edge::app()->logger->debug("Creating page cache for " . $request->getRequestUrl()); $this->set($response->body); } return true; }
public function __construct($tpl) { $this->tpl = $tpl; $this->attrs['this'] = $this; if (isset(Edge::app()['i18n'])) { $this->attrs['i18n'] = Edge::app()->i18n; } }
public function rollback() { if ($this->isTransactional) { $this->link->rollback(); Edge::app()->logger->info("ROLLBACK"); $this->isTransactional = false; } }
/** * @expectedException1 \Edge\Core\Exceptions\BadRequest * @expectedExceptionMessage1 The body does not contain a CSRF token */ public function testFilterFail() { $data = json_encode(["username" => "test"]); $this->post("/test/csrf", "application/json", $data); $response = Edge::app()->response; $this->assertEquals(400, $response->httpCode); $this->assertEquals("The body does not contain a CSRF token", $response->body); }
/** * Mock user object * @param array $attrs * @param null $methods * * @return \PHPUnit_Framework_MockObject_MockObject */ protected function getUser($attrs = [], $methods = null) { if (!$attrs) { $attrs = ['id' => 1, 'username' => 'guest']; } $class = Edge::app()->getConfig('userClass'); return $this->getMockBuilder($class)->setMethods($methods)->setConstructorArgs([$attrs])->getMock(); }
public function __construct($tpl) { $this->tpl = stream_resolve_include_path($tpl); $this->originalTpl = $tpl; $this->attrs['this'] = $this; if (isset(Edge::app()['i18n'])) { $this->attrs['i18n'] = Edge::app()->i18n; } }
/** * Check cookie signature * @param $signature * @param $name * @param $value * @return bool */ protected function decodeCookie($signature, $name, $value) { $hash = hash_hmac('sha1', $value, $this->secret); if ($signature != $hash) { Edge::app()->logger->err("Cookie signature mismatch. Possible tampering. Deleting it"); $this->delete($name); return false; } return $value; }
public function write() { header('HTTP/1.0 ' . Response::$httpCodes[$this->httpCode]); $contentType = $this->contentType ? $this->contentType : Edge::app()->request->getContentType(); $contentType = sprintf("%s; charset=%s", $contentType, $this->charset); header('Content-Type: ' . $contentType, true); foreach ($this->headers as $key => $val) { header("{$key}: {$val}", true); } echo $this->body; exit; }
public function preProcess(Http\Response $response, Http\Request $request) { if (Edge::app()->user()->isGuest()) { if ($request->is("GET")) { Edge::app()->session->redirectUrl = $request->getRequestUrl(); } if ($request->isAjax()) { throw new Unauthorized("Unauthorized access"); } $response->redirect($this->url); } }
public function __construct($message, $logError = true, $logBackTrace = true) { parent::__construct($message); if ($logBackTrace) { ob_start(); debug_print_backtrace(); $parsed = ob_get_contents(); ob_end_clean(); Edge::app()->logger->err($parsed); } elseif ($logError) { Edge::app()->logger->err($this->message); } }
public function __construct($message, $logError = true, $logBackTrace = true) { parent::__construct($message); //if there is an active transaction, roll it back if (Edge::app()->db instanceof MysqlMaster) { Edge::app()->db->rollback(); } if ($logBackTrace) { Edge::app()->logger->err($message . "\\n" . $this->getTraceAsString()); } elseif ($logError) { Edge::app()->logger->err($this->message); } }
/** * Serve the file to the browser with aggressive caching * directives. * @param $key * @param $contentType * @return mixed */ protected static function load($key, $contentType) { $etag = md5($key); $mod = explode("_", $key); $mod = $mod[0]; $response = Edge::app()->response; $response->contentType = $contentType; $response->expires($mod + 365 * 24 * 3600); $response->setEtag($etag); $response->lastModified($mod); if ($response->isEtagValid($etag, $mod)) { $response->httpCode = 304; $response->write(); } return Edge::app()->cache->get($key); }
public function preProcess(Http\Response $response, Http\Request $request) { if ($this->user->isAdmin()) { if (!$this->permissions) { Edge::app()->logger->warn("No permissions defined for URL " . Edge::app()->request->getRequestUrl()); } return true; } if (!$this->permissions) { throw new EdgeException("No permissions defined for URL " . Edge::app()->request->getRequestUrl()); } foreach ($this->permissions as $perm) { if ($this->user->hasPrivilege($perm)) { return true; } } throw new Forbidden("User has not the privilege to invoke " . $request->getRequestUrl()); }
/** * Return a Crawler instance with the content to be served to the client * @see https://symfony.com/doc/current/components/dom_crawler.html * @return \Symfony\Component\DomCrawler\Crawler */ protected function getCrawler() { return new Crawler(Edge::app()->response->body); }
protected function cacheData($key, $data, $ttl, $cacheValidator = null) { $_data = null; switch ($this->fetchMode) { case Record::FETCH_ASSOC_ARRAY: $_data = $this->fetchArray($data); break; case Record::FETCH_INSTANCE: $class = $this->model; $attrs = $this->fetchArray($data); $_data = new $class($attrs); $_data->addKeyToIndex($key); break; case Record::FETCH_RESULTSET: $rs = $this->fetchAll($data); $_data = new CachedObjectSet($rs, $this->model); break; case Record::FETCH_NATIVE_RESULTSET: $_data = $this->fetchAll($data); break; } $res = Edge::app()->cache->add($key, $_data, $ttl, $cacheValidator); if (!$res) { throw new \Exception("Could not write data to cache"); } return $_data; }
public function endInLineCss() { if (!Edge::app()->request->isAjax()) { $content = ob_get_clean(); Layout::addInlineCss($content); } }
protected function getInlineFragment($content, $type) { if ($this->minify) { $cls = Edge::app()->getConfig("staticBundler"); $content = $cls::minify($type, $content); } return $content; }
public function filters() { return array_merge(parent::filters(), array(array('Edge\\Core\\Filters\\AccessControl', "permissions" => $this->getAclMap()[Edge::app()->router->getAction()]))); }
/** * Cache the files in the cache storage * @param $key * @param $type */ private function cache($key, $type) { if (!Edge::app()->cache->get($key)) { $content = ''; $valName = sprintf("%sFiles", $type); $arr = array_unique(array_keys($this->{$valName})); foreach ($arr as $file) { $content .= file_get_contents($file) . "\n"; } if ($this->minify) { if ($type == 'js') { $content = JSMin::minify($content); } else { $content = Css::minify($content); } } Edge::app()->cache->add($key, $content); } }
/** * Remove all caches for the object */ protected function clearInstanceCache() { $mem = Edge::app()->cache; $logger = Edge::app()->logger; $index = $this->getInstanceIndexKey(); $list = $mem->get($index); if ($list && count($list) > 0) { foreach ($list as $item) { $mem->delete($item); $logger->info('deleting from cache item ' . $item); } $mem->delete($index); $logger->info('deleting from cache index ' . $index); } }
/** * Execute the query and handle caching * @return array|CachedObjectSet|mixed|null */ protected function execute() { $model = $this->model; $cacheAttrs = $this->cacheAttrs; $cacheRecord = $model::cacheRecord() && $this->fetchMode == Record::FETCH_INSTANCE || $cacheAttrs; if ($cacheRecord) { $value = $this->getCachedRecord(); if ($value) { $skip = false; //for some strange reason some keys are not always deleted //from memcached causing issues. If there is no index key in the cache //or the cache key is not present in the list, we delete the cached data if ($value instanceof Record) { $key = $value->getInstanceIndexKey(); $cacheKey = $this->getCacheKey(); $indexList = Edge::app()->cache->get($key); if (!$indexList || !in_array($cacheKey, $indexList)) { Edge::app()->cache->delete($cacheKey); $skip = true; } } if (!$skip) { return $value; } } } $result = $this->executeQuery($this->query); $records = $this->countResults($result); if ($cacheRecord && $records) { $ttl = 0; $validator = null; if ($cacheAttrs && array_key_exists('ttl', $cacheAttrs)) { $ttl = $cacheAttrs['ttl']; } if ($cacheAttrs && array_key_exists('cacheValidator', $cacheAttrs)) { $validator = $cacheAttrs['cacheValidator']; } $cacheKey = $this->getCacheKey(); return $this->cacheData($cacheKey, $result, $ttl, $validator); } //no caching specified if ($records == 0) { if (in_array($this->fetchMode, array(Record::FETCH_RESULTSET, Record::FETCH_NATIVE_RESULTSET))) { return array(); } return null; } switch ($this->fetchMode) { case Record::FETCH_ASSOC_ARRAY: return $this->fetchArray($result); case Record::FETCH_NATIVE_RESULTSET: return $result; case Record::FETCH_INSTANCE: $class = $this->model; $attrs = $this->fetchArray($result); return new $class($attrs); case Record::FETCH_RESULTSET: return $this->getResultSet($result, $this->model); } }
/** * Return the Mongo db connection * @return mixed */ public function getDbConnection() { return Edge::app()->mongo; }
public function testGetMethod() { $_SERVER['REQUEST_METHOD'] = 'GET'; $request = $this->mockRequest(["username" => "test", "token" => "someTokenValue"]); $this->assertNull($this->filter->preProcess(Edge::app()->response, $request)); }
/** * * Logout the user and destroy * the session */ public function logout() { $app = Core\Edge::app(); $app->session->destroy(); $app->user(\Edge\Models\User::getUserByUsername("guest")); return true; }
public function invoke() { if (strstr($this->controller, "\\")) { $class = $this->controller; } else { $class = sprintf('Application\\Controllers\\%s', $this->controller); } $this->controller = new $class(); if (method_exists($this->controller, $this->method)) { try { $filters = static::getFilters($this->controller); $invokeRequest = $this->runFilters($filters, 'preProcess'); if ($invokeRequest) { $processed = false; $retries = 0; $max_retries = 20; while (!$processed && $retries < $max_retries) { try { $retries++; $this->response->body = $this->request->getTransformer()->encode(call_user_func_array(array($this->controller, $this->method), $this->args)); $processed = true; } catch (Exceptions\DeadLockException $e) { Edge::app()->logger->info('RETRYING TRANSACTION'); usleep(100); } } if (!$processed) { Edge::app()->logger->err('DEADLOCK ERROR'); throw new \Exception('Deadlock detected'); } } $this->runFilters($filters, 'postProcess'); } catch (\Exception $e) { $db = Edge::app()->db; if ($db instanceof MysqlMaster) { $db->rollback(); } Edge::app()->logger->err($e->getMessage()); if ($e instanceof NotFound) { $this->handle404Error($e->getMessage()); } else { $this->handleServerError($e->getMessage()); } } } else { $this->handle404Error(); } $this->response->write(); }
public function __construct($msg) { parent::__construct($msg); Edge::app()->response->httpCode = 404; }
/** * Construct the UPDATE sql query and update the object * @param \Edge\Models\Record $entry */ public function update(Record $entry) { $pks = $this->getPkValues($entry); $data = array_diff_assoc($entry->getAttributes(), $pks); $db = Edge::app()->writedb; $k = array_keys($data); $v = array_values($data); $c = join(", ", array_map(function ($k, $v) use($db) { return sprintf('%s="%s"', $k, $db->dbEscapeString($v)); }, $k, $v)); $q = sprintf("UPDATE %s SET %s WHERE %s", $entry::getTable(), $c, $this->joinConditions($pks, $db)); Edge::app()->logger->debug($q); $db->dbQuery($q); }