/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property */ public function initialize($configuration) { Event::fire('framework.authentication.initialize.before', array($this->type)); if (!$this->type) { if (!empty($configuration->security->authentication)) { $this->type = $configuration->security->authentication->type; $this->options = (array) $configuration->security->authentication; } else { throw new \Exception('Error in configuration file'); } } if (!$this->type) { throw new Exception\Argument('Invalid authentication type'); } Event::fire('framework.authentication.initialize.after', array($this->type)); switch ($this->type) { case 'database': return new DatabaseAuthentication($this->options); break; case 'config': $users = (array) $configuration->security->authentication->users; return new ConfigAuthentication($users); break; default: throw new Exception\Argument('Invalid authentication type'); break; } }
/** * @before _secured, _admin */ public function settings() { $view = $this->getActionView(); $config = Config::all(); $view->set('config', $config); if (RequestMethods::post('submitEditSet')) { if ($this->checkCSRFToken() !== true) { self::redirect('/admin/'); } $errors = array(); foreach ($config as $conf) { $oldVal = $conf->getValue(); $conf->value = RequestMethods::post($conf->getXkey(), ''); if ($conf->validate()) { Event::fire('admin.log', array('success', $conf->getXkey() . ': ' . $oldVal . ' - ' . $conf->getValue())); $conf->save(); } else { Event::fire('admin.log', array('fail', $conf->getXkey() . ': ' . $conf->getValue())); $errors[$conf->xkey] = array_shift($conf->getErrors()); } } if (empty($errors)) { $view->successMessage(self::SUCCESS_MESSAGE_2); self::redirect('/admin/system/'); } else { $view->set('errors', $errors); } } }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property. * * @return \THCFrame\Cache\Cache\Driver\Memcached * @throws Exception\Argument */ public function initialize($configuration) { Event::fire('framework.cache.initialize.before', array($this->type, $this->options)); if (!$this->type) { if (!empty($configuration->cache) && !empty($configuration->cache->type)) { $this->type = $configuration->cache->type; $this->options = (array) $configuration->cache; } else { $this->type = 'filecache'; $this->options = array('mode' => 'active', 'duration' => 1800, 'suffix' => 'tmp', 'path' => 'temp/cache'); } } Event::fire('framework.cache.initialize.after', array($this->type, $this->options)); switch ($this->type) { case 'memcached': return new Driver\Memcached($this->options); break; case 'filecache': return new Driver\Filecache($this->options); break; default: throw new Exception\Argument('Invalid type'); break; } }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property. * * @return \THCFrame\Session\Session\Driver\Server * @throws Exception\Argument */ public function initialize($configuration) { Event::fire('framework.session.initialize.before', array($this->type, $this->options)); if (!$this->type) { if (!empty($configuration->session) && !empty($configuration->session->type)) { $this->type = $configuration->session->type; $this->options = (array) $configuration->session; } else { throw new \Exception('Error in configuration file'); } } if (!$this->type) { throw new Exception\Argument('Invalid session type'); } Event::fire('framework.session.initialize.after', array($this->type, $this->options)); switch ($this->type) { case 'server': return new Driver\Server($this->options); break; case 'database': return new Driver\Database($this->options); break; default: throw new Exception\Argument('Invalid session type'); break; } }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property */ public function initialize($configuration) { Event::fire('framework.authorization.initialize.before', array($this->type)); if (!$this->type) { if (!empty($configuration->security->authorization)) { $this->type = $configuration->security->authorization->type; $this->options = (array) $configuration->security->authorization; $roles = (array) $configuration->security->authorization->roles; $roleManager = new RoleManager($roles); } else { throw new \Exception('Error in configuration file'); } } if (!$this->type) { throw new Exception\Argument('Invalid authorization type'); } Event::fire('framework.authorization.initialize.after', array($this->type)); switch ($this->type) { case 'annotationbase': return new AnnotationBaseAuthorization($roleManager); break; case 'resourcebase': $resources = (array) $configuration->security->authorization->resources; return new ResourceBaseAuthorization($roleManager, $resources); break; default: throw new Exception\Argument('Invalid authorization type'); break; } }
/** * Object constructor * * @param array $options */ public function __construct($options = array()) { parent::__construct($options); Event::fire('framework.module.initialize.before', array($this->moduleName)); $this->addModuleEvents(); Event::add('framework.router.construct.after', function ($router) { $router->addRedirects($this->getRedirects()); $router->addRoutes($this->getRoutes()); }); Event::fire('framework.module.initialize.after', array($this->moduleName)); }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property. * * @return \THCFrame\Configuration\Configuration\Driver\Ini * @throws Exception\Argument */ public function initialize() { Event::fire('framework.configuration.initialize.before', array($this->type, $this->options)); if (!$this->type) { throw new Exception\Argument('Invalid type'); } Event::fire('framework.configuration.initialize.after', array($this->type, $this->options)); switch ($this->type) { case 'ini': return new Driver\Ini($this->options); break; default: throw new Exception\Argument('Invalid type'); break; } }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property. * * @return \THCFrame\Configuration\Configuration\Driver\Ini * @throws Exception\Argument */ public function initialize() { Event::fire('framework.logger.initialize.before', array($this->type, $this->options)); $this->type = 'file'; if (!$this->type) { throw new Exception\Argument('Error in configuration file'); } Event::fire('framework.logger.initialize.after', array($this->type, $this->options)); switch ($this->type) { case 'file': return new Driver\File(); break; default: throw new Exception\Argument('Invalid logger type'); break; } }
/** * Factory method * It accepts initialization options and selects the type of returned object, * based on the internal $_type property. * * @return \THCFrame\Database\Database\Connector * @throws Exception\Argument */ public function initialize($configuration) { Event::fire('framework.database.initialize.before', array($this->type, $this->options)); if (!$this->type) { if (!empty($configuration->database) && !empty($configuration->database->type)) { $this->type = $configuration->database->type; $this->options = (array) $configuration->database; } else { throw new Exception\Argument('Error in configuration file'); } } Event::fire('framework.database.initialize.after', array($this->type, $this->options)); switch ($this->type) { case 'mysql': return new Connector\Mysql($this->options); break; default: throw new Exception\Argument('Invalid database type'); break; } }
/** * @before _secured, _admin */ public function deleteUserMainPhoto($id) { $this->willRenderActionView = false; $this->willRenderLayoutView = false; if ($this->checkCSRFToken()) { $user = App_Model_User::first(array('id = ?' => (int) $id)); if ($user === null) { echo self::ERROR_MESSAGE_2; } else { $unlinkMainImg = $user->getUnlinkPath(); $unlinkThumbImg = $user->getUnlinkThumbPath(); $user->imgMain = ''; $user->imgThumb = ''; if ($user->validate()) { $user->save(); @unlink($unlinkMainImg); @unlink($unlinkThumbImg); Event::fire('admin.log', array('success', 'User id: ' . $user->getId())); echo 'success'; } else { Event::fire('admin.log', array('fail', 'User id: ' . $user->getId())); echo self::ERROR_MESSAGE_1; } } } else { echo self::ERROR_MESSAGE_1; } }
/** * The request() method use Curl to make the HTTP requests. * The method begins by creating a new curl resource instance and continues by setting some parameters of the * instance. It then makes the request, and if the request is successful, it will be returned in the form of a * Request\Response class instance. If the request fails, an exception will be raised. * Finally, the curl resource is destroyed and the response is returned. * * @param type $method * @param type $url * @param type $parameters * @return \THCFrame\Request\Request\Response * @throws Exception\Response */ public function request($method, $url, $parameters = array()) { session_write_close(); Event::fire('framework.request.request.before', array($method, $url, $parameters)); $request = $this->_request = curl_init(); if (is_array($parameters)) { $parameters = http_build_query($parameters, '', '&'); } $this->_setRequestMethod($method)->_setRequestOptions($url, $parameters)->_setRequestHeaders(); $response = curl_exec($request); if (!headers_sent()) { session_start(); } if ($response) { $response = new Response(array('response' => $response)); } else { throw new Exception\Response(ucfirst(curl_error($request))); } Event::fire('framework.request.request.after', array($method, $url, $parameters, $response)); curl_close($request); return $response; }
/** * End of application profiling * * @param string $identifier */ public function stop($identifier = 'CORE') { if ($this->isActive()) { Event::fire('framework.profiler.stop.before', array($identifier)); $this->_profiles[$identifier]['requestUri'] = RequestMethods::server('REQUEST_URI'); $this->_profiles[$identifier]['totalTime'] = round(microtime(true) - $this->_profiles[$identifier]['startTime'], 8); $this->_profiles[$identifier]['endMemoryPeakUsage'] = $this->convert(memory_get_peak_usage()); $this->_profiles[$identifier]['endMomoryUsage'] = $this->convert(memory_get_usage()); $this->_profiles[$identifier]['dbProfiles'] = $this->_dbProfiles[$identifier]; $this->_profiles[$identifier]['sessionArr'] = $_SESSION; $this->_profiles[$identifier]['postArr'] = $_POST; $this->_profiles[$identifier]['getArr'] = $_GET; $this->dbStop($identifier); $this->process(); Event::fire('framework.profiler.stop.after', array($identifier)); } }
/** * @before _secured, _admin * @param type $id */ public function deleteMainPhoto($id) { $this->willRenderActionView = false; $this->willRenderLayoutView = false; if ($this->checkCSRFToken()) { $dog = App_Model_Dog::first(array('id = ?' => (int) $id)); if (NULL === $dog) { echo self::ERROR_MESSAGE_2; } else { @unlink($dog->getUnlinkPath()); @unlink($dog->getUnlinkThumbPath()); $dog->imgMain = ''; $dog->imgThumb = ''; if ($dog->validate()) { $dog->save(); Event::fire('admin.log', array('success', 'Dog Id: ' . $id)); echo 'success'; } else { Event::fire('admin.log', array('fail', 'Dog Id: ' . $id)); echo self::ERROR_MESSAGE_1; } } } else { echo self::ERROR_MESSAGE_1; } }
/** * Finds a maching route in the routes array using specified $path * * @param string $path */ private function _findRoute($path) { Event::fire('framework.router.findroute.checkredirect.before', array($path)); if (!empty($this->_redirects)) { if (array_key_exists($path, $this->_redirects)) { $path = $this->_redirects[$path]; } } Event::fire('framework.router.findroute.checkredirect.after', array($path)); Event::fire('framework.router.findroute.before', array($path)); foreach ($this->_routes as $route) { if (TRUE === $route->matchMap($path)) { $this->_lastRoute = $route; break; } } if ($this->_lastRoute === null) { throw new Exception\Module('Not found'); } Event::fire('framework.router.findroute.after', array($path, $this->_lastRoute->getModule(), $this->_lastRoute->getController(), $this->_lastRoute->getAction())); }
/** * Attempts to dispatch the supplied Route object * * @param \THCFrame\Router\Route $route * @throws Exception\Module * @throws Exception\Controller * @throws Exception\Action */ public function dispatch(\THCFrame\Router\Route $route) { $module = trim($route->getModule()); $class = trim($route->getController()); $action = trim($route->getAction()); $parameters = $route->getMapArguments(); if ('' === $module) { throw new Exception\Module('Module Name not specified'); } elseif ('' === $class) { throw new Exception\Controller('Class Name not specified'); } elseif ('' === $action) { throw new Exception\Action('Method Name not specified'); } $status = $this->loadConfigFromDb($module . 'status'); if ($status !== null && $status != 1) { throw new Exception\Offline('Application is offline'); } $module = str_replace('\\', '', $module); preg_match('/^[a-zA-Z0-9_]+$/', $module, $matches); if (count($matches) !== 1) { throw new Exception\Module(sprintf('Disallowed characters in module name %s', $module)); } $class = str_replace('\\', '', $class); preg_match('/^[a-zA-Z0-9_]+$/', $class, $matches); if (count($matches) !== 1) { throw new Exception\Controller(sprintf('Disallowed characters in class name %s', $class)); } $file_name = strtolower("./modules/{$module}/controller/{$class}.php"); $class = ucfirst($module) . '_Controller_' . ucfirst($class); if (FALSE === file_exists($file_name)) { throw new Exception\Controller(sprintf('Class file %s not found', $file_name)); } else { require_once $file_name; } $this->_activeModule = $module; Event::fire('framework.dispatcher.controller.before', array($class, $parameters)); try { $instance = new $class(array('parameters' => $parameters)); Registry::set('controller', $instance); } catch (\Exception $e) { throw new Exception\Controller(sprintf('Controller %s error: %s', $class, $e->getMessage())); } Event::fire('framework.dispatcher.controller.after', array($class, $parameters)); if (!method_exists($instance, $action)) { $instance->willRenderLayoutView = false; $instance->willRenderActionView = false; throw new Exception\Action(sprintf('Action %s not found', $action)); } $inspector = new Inspector($instance); $methodMeta = $inspector->getMethodMeta($action); if (!empty($methodMeta['@protected']) || !empty($methodMeta['@private'])) { throw new Exception\Action(sprintf('Action %s not found', $action)); } $hooks = function ($meta, $type) use($inspector, $instance) { if (isset($meta[$type])) { $run = array(); foreach ($meta[$type] as $method) { $hookMeta = $inspector->getMethodMeta($method); if (in_array($method, $run) && !empty($hookMeta['@once'])) { continue; } $instance->{$method}(); $run[] = $method; } } }; Event::fire('framework.dispatcher.beforehooks.before', array($action, $parameters)); $hooks($methodMeta, '@before'); Event::fire('framework.dispatcher.beforehooks.after', array($action, $parameters)); Event::fire('framework.dispatcher.action.before', array($action, $parameters)); call_user_func_array(array($instance, $action), is_array($parameters) ? $parameters : array()); Event::fire('framework.dispatcher.action.after', array($action, $parameters)); Event::fire('framework.dispatcher.afterhooks.before', array($action, $parameters)); $hooks($methodMeta, '@after'); Event::fire('framework.dispatcher.afterhooks.after', array($action, $parameters)); // unset controller Registry::erase('controller'); }
/** * Object destruct */ public function __destruct() { Event::fire('framework.controller.destruct.before', array($this->name)); $this->render(); Event::fire('framework.controller.destruct.after', array($this->name)); }
/** * Method is called via ajax and activate or deactivate photo specified by * param id * * @before _secured, _admin * @param int $id photo id */ public function changePhotoStatus($id) { $this->willRenderLayoutView = false; $this->willRenderActionView = false; $photo = App_Model_Photo::first(array('id = ?' => $id)); if (null === $photo) { echo self::ERROR_MESSAGE_2; } else { if (!$photo->active) { $photo->active = true; if ($photo->validate()) { $photo->save(); Event::fire('admin.log', array('success', 'Photo id: ' . $id)); echo 'active'; } else { echo join('<br/>', $photo->getErrors()); } } elseif ($photo->active) { $photo->active = false; if ($photo->validate()) { $photo->save(); Event::fire('admin.log', array('success', 'Photo id: ' . $id)); echo 'inactive'; } else { echo join('<br/>', $photo->getErrors()); } } } }
/** * Method initialize security context. Check session for user token and * initialize authentication and authorization classes */ public function initialize($configuration) { Event::fire('framework.security.initialize.before', array()); if (!empty($configuration->security)) { $this->_csrf = new CSRF(); $this->_passwordManager = new PasswordManager($configuration->security); } else { throw new \Exception('Error in configuration file'); } $session = Registry::get('session'); $user = $session->get('authUser'); $authentication = new Authentication\Authentication(); $this->_authentication = $authentication->initialize($configuration); $authorization = new Authorization\Authorization(); $this->_authorization = $authorization->initialize($configuration); if ($user instanceof BasicUser) { $this->_user = $user; Event::fire('framework.security.initialize.user', array($user)); } if ($this->_authorization->type == 'resourcebase') { Event::add('framework.router.findroute.after', function ($path) { $role = $this->getAuthorization()->checkForResource($path); if ($role !== null) { if ($this->isGranted($role) !== true) { throw new \THCFrame\Security\Exception\Unauthorized(); } } }); } Event::fire('framework.security.initialize.after', array()); return $this; }
/** * @before _secured, _admin */ public function massAction() { $this->willRenderActionView = false; $this->willRenderLayoutView = false; $errors = array(); $ids = RequestMethods::post('ids'); $action = RequestMethods::post('action'); if (empty($ids)) { echo 'Nějaký řádek musí být označen'; return; } switch ($action) { case 'delete': $news = App_Model_News::all(array('id IN ?' => $ids)); if (NULL !== $news) { foreach ($news as $_news) { if (!$_news->delete()) { $errors[] = self::ERROR_MESSAGE_3 . ' ' . $_news->getTitle(); } } } if (empty($errors)) { Event::fire('admin.log', array('delete success', 'News ids: ' . join(',', $ids))); echo self::SUCCESS_MESSAGE_6; } else { Event::fire('admin.log', array('delete fail', 'Error count:' . count($errors))); $message = join(PHP_EOL, $errors); echo $message; } break; case 'activate': $news = App_Model_News::all(array('id IN ?' => $ids, 'active = ?' => false)); if (NULL !== $news) { foreach ($news as $_news) { $_news->active = true; if ($_news->validate()) { $_news->save(); } else { $errors[] = "News id {$_news->getId()} - {$_news->getTitle()} errors: " . join(', ', $_news->getErrors()); } } } if (empty($errors)) { Event::fire('admin.log', array('activate success', 'News ids: ' . join(',', $ids))); echo self::SUCCESS_MESSAGE_4; } else { Event::fire('admin.log', array('activate fail', 'Error count:' . count($errors))); $message = join(PHP_EOL, $errors); echo $message; } break; case 'deactivate': $news = App_Model_News::all(array('id IN ?' => $ids, 'active = ?' => true)); if (NULL !== $news) { foreach ($news as $_news) { $_news->active = false; if ($_news->validate()) { $_news->save(); } else { $errors[] = "News id {$_news->getId()} - {$_news->getTitle()} errors: " . join(', ', $_news->getErrors()); } } } if (empty($errors)) { Event::fire('admin.log', array('deactivate success', 'News ids: ' . join(',', $ids))); echo self::SUCCESS_MESSAGE_5; } else { Event::fire('admin.log', array('deactivate fail', 'Error count:' . count($errors))); $message = join(PHP_EOL, $errors); echo $message; } break; default: echo self::ERROR_MESSAGE_2; break; } }
/** * @before _secured, _admin */ public function delete($id) { $this->willRenderActionView = false; $this->willRenderLayoutView = false; $exam = App_Model_Exam::first(array('id = ?' => (int) $id), array('id')); if (NULL === $exam) { echo self::ERROR_MESSAGE_2; } else { if ($exam->delete()) { Event::fire('admin.log', array('success', 'Exam Id: ' . $id)); echo 'success'; } else { Event::fire('admin.log', array('fail', 'Exam Id: ' . $id)); echo self::ERROR_MESSAGE_1; } } }
/** * Main call * * @param string $filename * @throws \Exception */ public function create($filename = '') { if (!empty($filename)) { $this->_filename = $filename; } if (empty($this->_filename)) { throw new Exception\Backup('Output file name is not set', 1); } if (!$this->_open($this->_filename)) { throw new Exception\Backup(sprintf('Output file %s is not writable', $this->_filename), 2); } Event::fire('framework.mysqldump.create.before', array($this->_filename)); $this->_write($this->_getHeader()); $this->_tables = array(); $sqlResult = $this->_database->execute('SHOW TABLES'); while ($row = $sqlResult->fetch_array(MYSQLI_ASSOC)) { if (empty($this->_settings['include-tables']) || !empty($this->_settings['include-tables']) && in_array($row['Tables_in_' . $this->_database->getSchema()], $this->_settings['include-tables'], true)) { array_push($this->_tables, $row['Tables_in_' . $this->_database->getSchema()]); } } // Exporting tables one by one foreach ($this->_tables as $table) { if (in_array($table, $this->_settings['exclude-tables'], true)) { continue; } foreach ($this->_settings['exclude-tables-reqex'] as $regex) { if (mb_ereg_match($regex, $table)) { continue 2; } } $is_table = $this->_getTableStructure($table); if (true === $is_table && false === $this->_settings['no-data']) { $this->_listValues($table); } } Event::fire('framework.mysqldump.create.after', array($this->_filename)); $this->_close(); return $this; }
/** * @before _secured, _admin */ public function edit($id) { $view = $this->getActionView(); $content = App_Model_PageContent::first(array('id = ?' => (int) $id)); if (NULL === $content) { $view->warningMessage('Obsah nenalezen'); $this->_willRenderActionView = false; self::redirect('/admin/content/'); } $view->set('content', $content); if (RequestMethods::post('submitEditContent')) { if ($this->checkCSRFToken() !== true) { self::redirect('/admin/content/'); } $cache = Registry::get('cache'); $errors = array(); $urlKey = $this->_createUrlKey(RequestMethods::post('page')); if ($content->getUrlKey() !== $urlKey && !$this->_checkUrlKey($urlKey)) { $errors['title'] = array('Stránka s tímto názvem již existuje'); } $content->pageName = RequestMethods::post('page'); $content->urlKey = $urlKey; $content->body = RequestMethods::post('text'); $content->bodyEn = RequestMethods::post('texten'); $content->metaTitle = RequestMethods::post('metatitle'); $content->metaDescription = RequestMethods::post('metadescription'); $content->active = RequestMethods::post('active'); if (empty($errors) && $content->validate()) { $content->save(); Event::fire('admin.log', array('success', 'Content id: ' . $id)); $view->successMessage(self::SUCCESS_MESSAGE_2); $cache->erase($content->getUrlKey()); self::redirect('/admin/content/'); } else { Event::fire('admin.log', array('fail', 'Content id: ' . $id)); $view->set('errors', $content->getErrors())->set('content', $content); } } }
/** * * @return string */ public function render() { Event::fire('framework.view.render.before', array($this->file)); if (!file_exists($this->file)) { return ''; } return $this->template->parse(file_get_contents($this->file))->process($this->data); }