/** * * @param type $page */ public function index($page = 1) { $view = $this->getActionView(); $layoutView = $this->getLayoutView(); $config = Registry::get('configuration'); $articlesPerPage = $config->news_per_page; if ($page == 1) { $canonical = 'http://' . $this->getServerHost() . '/aktuality'; } else { $canonical = 'http://' . $this->getServerHost() . '/aktuality/p/' . $page; } $content = $this->getCache()->get('news-' . $page); if ($content !== null) { $news = $content; } else { $news = App_Model_News::all(array('active = ?' => true, 'expirationDate >= ?' => date('Y-m-d H:i:s')), array('id', 'urlKey', 'author', 'title', 'shortBody', 'created', 'rank'), array('rank' => 'asc', 'created' => 'DESC'), (int) $articlesPerPage, (int) $page); $this->getCache()->set('news-' . $page, $news); } $newsCount = App_Model_News::count(array('active = ?' => true, 'expirationDate >= ?' => date('Y-m-d H:i:s'))); $newsPageCount = ceil($newsCount / $articlesPerPage); $view->set('newsbatch', $news)->set('newspagecount', $newsPageCount); if ($newsPageCount > 1) { $prevPage = $page - 1; $nextPage = $page + 1; if ($nextPage > $newsPageCount) { $nextPage = 0; } $layoutView->set('pagedprev', $prevPage)->set('pagedprevlink', '/aktuality/p/' . $prevPage)->set('pagednext', $nextPage)->set('pagednextlink', '/aktuality/p/' . $nextPage); } $layoutView->set('metatitle', 'ZKO - Aktuality')->set('canonical', $canonical); }
/** * * @param type $options */ public function __construct($options = array()) { parent::__construct($options); // schedule disconnect from database Events::add('framework.controller.destruct.after', function ($name) { $database = Registry::get('database'); $database->disconnect(); }); $this->_security = Registry::get('security'); $this->_serverHost = RequestMethods::server('HTTP_HOST'); $this->_cache = Registry::get('cache'); $cfg = Registry::get('configuration'); $links = $this->getCache()->get('links'); if ($links !== null) { $links = $links; } else { $links = \App_Model_Link::all(array('active = ?' => true)); $this->getCache()->set('links', $links); } $metaData = $this->getCache()->get('global_meta_data'); if ($metaData !== null) { $metaData = $metaData; } else { $metaData = array('metadescription' => $cfg->meta_description, 'metarobots' => $cfg->meta_robots, 'metatitle' => $cfg->meta_title, 'metaogurl' => $cfg->meta_og_url, 'metaogtype' => $cfg->meta_og_type, 'metaogimage' => $cfg->meta_og_image, 'metaogsitename' => $cfg->meta_og_site_name); $this->getCache()->set('global_meta_data', $metaData); } $this->getLayoutView()->set('links', $links)->set('metatitle', $metaData['metatitle'])->set('metarobots', $metaData['metarobots'])->set('metadescription', $metaData['metadescription'])->set('metaogurl', $metaData['metaogurl'])->set('metaogtype', $metaData['metaogtype'])->set('metaogimage', $metaData['metaogimage'])->set('metaogsitename', $metaData['metaogsitename']); }
/** * * @param array $params */ public function adminLog() { $params = func_get_args(); $router = Registry::get('router'); $route = $router->getLastRoute(); $security = Registry::get('security'); $userId = $security->getUser()->getWholeName(); $module = $route->getModule(); $controller = $route->getController(); $action = $route->getAction(); if (!empty($params)) { $result = array_shift($params); $paramStr = ''; if (!empty($params)) { $paramStr = join(', ', $params); } } else { $result = 'fail'; $paramStr = ''; } $log = new Admin_Model_AdminLog(array('userId' => $userId, 'module' => $module, 'controller' => $controller, 'action' => $action, 'result' => $result, 'params' => $paramStr)); if ($log->validate()) { $log->save(); } }
/** * * @param type $options */ public function __construct($options = array()) { parent::__construct($options); Event::fire('framework.view.construct.before', array($this->file)); $this->_session = Registry::get('session'); $this->_template = new Template\Template(array('implementation' => new Template\Implementation\Extended())); $this->_checkMessage(); Event::fire('framework.view.construct.after', array($this->file, $this->template)); }
/** * * @param type $options */ public function __construct($options = array()) { parent::__construct($options); $this->connect(); Event::add('framework.controller.destruct.after', function ($name) { $cache = Registry::get('cache'); $cache->disconnect(); }); }
/** * Object constructor * * @param IDatabase $database * @param mixed $settings */ public function __construct($settings = null) { // ini_set('default_charset', 'UTF-8'); $this->_database = Registry::get('database'); $this->_database->connect(); $this->_settings = $this->_extend($this->_defaultSettings, $settings); $this->_filename = APP_PATH . '/temp/db/' . $this->_database->getSchema() . '_' . date('Y-m-d') . '.sql'; $this->_backupname = $this->_database->getSchema() . '_' . date('Y-m-d') . '.sql'; }
/** * * @param type $message */ public function log($message) { require_once APP_PATH . '/vendors/swiftmailer/swift_required.php'; $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $config = Registry::get('configuration'); $sendTo = $config->system->adminemail; $appName = $config->system->appname; $email = Swift_Message::newInstance()->setSubject($appName . ' error')->setFrom('*****@*****.**')->setTo($sendTo)->setBody($message); $result = $mailer->send($email); }
/** * @before _secured, _admin */ public function clearCache() { $view = $this->getActionView(); if (RequestMethods::post('clearCache')) { Event::fire('admin.log', array('success')); $cache = Registry::get('cache'); $cache->clearCache(); $view->successMessage('Cache byly úspěšně smazány'); self::redirect('/admin/system/'); } }
/** * Class constructor * * @param array $options * @throws \Exception */ public function __construct($options = array()) { parent::__construct($options); $configuration = Registry::get('configuration'); if (!empty($configuration->files)) { $this->_pathToDocs = trim($configuration->files->pathToDocuments, '/'); $this->_pathToImages = trim($configuration->files->pathToImages, '/'); $this->_pathToThumbs = trim($configuration->files->pathToThumbs, '/'); $this->checkDirectories(); } else { throw new \Exception('Error in configuration file'); } }
/** * * @param type $page */ public function index() { $view = $this->getActionView(); $layoutView = $this->getLayoutView(); $config = Registry::get('configuration'); $content = $this->getCache()->get('news-1'); $npp = $config->news_per_page; if (NULL !== $content) { $news = $content; } else { $news = App_Model_News::all(array('active = ?' => true, 'expirationDate >= ?' => date('Y-m-d H:i:s')), array('id', 'urlKey', 'author', 'title', 'shortBody', 'created', 'rank'), array('rank' => 'desc', 'created' => 'DESC'), (int) $npp, 1); $this->getCache()->set('news-1', $news); } $newsCount = App_Model_News::count(array('active = ?' => true, 'expirationDate >= ?' => date('Y-m-d H:i:s'))); $newsPageCount = ceil($newsCount / $npp); $view->set('newsbatch', $news)->set('newspagecount', $newsPageCount); $canonical = 'http://' . $this->getServerHost() . '/'; $layoutView->set('canonical', $canonical); }
/** * @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); } } }
/** * Method erases all authentication tokens for logged user and regenerates * session */ public function logout() { $session = Registry::get('session'); $session->erase('authUser')->erase('lastActive')->erase('csrf'); BasicUser::deleteAuthenticationToken(); $this->_user = NULL; @session_regenerate_id(); }
/** * Static wrapper for validatePassword function * * @param string $newPassword The given password in plain-text * @param string $oldHash The old hash * @param string $oldSalt The old dynamic salt used to create the old hash * @return boolean True if new hash and old hash match. False otherwise */ public static function validatePassword($newPassword, $oldHash, $oldSalt) { $configuration = Registry::get('configuration'); $pm = new static($configuration->security); return $pm->isPasswordValid($newPassword, $oldHash, $oldSalt); }
/** * @before _secured, _admin * @param type $id */ public function edit($id) { $view = $this->getActionView(); $user = App_Model_User::first(array('id = ?' => (int) $id)); if (NULL === $user) { $view->warningMessage(self::ERROR_MESSAGE_2); $this->_willRenderActionView = false; self::redirect('/admin/user/'); } elseif ($user->role == 'role_superadmin' && $this->getUser()->getRole() != 'role_superadmin') { $view->warningMessage(self::ERROR_MESSAGE_4); $this->_willRenderActionView = false; self::redirect('/admin/user/'); } $dogs = App_Model_Dog::fetchAllDogsByUserId($user->getId()); $view->set('user', $user)->set('dogs', $dogs); if (RequestMethods::post('submitEditUser')) { if ($this->checkCSRFToken() !== true) { self::redirect('/admin/user/'); } $errors = array(); if (RequestMethods::post('password') !== RequestMethods::post('password2')) { $errors['password2'] = array('Hesla se neshodují'); } if (RequestMethods::post('email') != $user->email) { $email = App_Model_User::first(array('email = ?' => RequestMethods::post('email', $user->email)), array('email')); if ($email) { $errors['email'] = array('Tento email je již použit'); } } $pass = RequestMethods::post('password'); if ($pass === null || $pass == '') { $salt = $user->getSalt(); $hash = $user->getPassword(); } else { $salt = PasswordManager::createSalt(); $hash = PasswordManager::hashPassword($pass, $salt); } if ($user->imgMain == '') { $cfg = Registry::get('configuration'); $fileManager = new FileManager(array('thumbWidth' => $cfg->thumb_width, 'thumbHeight' => $cfg->thumb_height, 'thumbResizeBy' => $cfg->thumb_resizeby, 'maxImageWidth' => $cfg->photo_maxwidth, 'maxImageHeight' => $cfg->photo_maxheight)); $photoNameRaw = RequestMethods::post('firstname') . '-' . RequestMethods::post('lastname'); $photoName = $this->_createUrlKey($photoNameRaw); $fileErrors = $fileManager->uploadBase64Image(RequestMethods::post('croppedimage'), $photoName, 'members', time() . '_')->getUploadErrors(); $files = $fileManager->getUploadedFiles(); if (!empty($files)) { foreach ($files as $i => $file) { if ($file instanceof \THCFrame\Filesystem\Image) { $imgMain = trim($file->getFilename(), '.'); $imgThumb = trim($file->getThumbname(), '.'); break; } } } else { $errors['croppedimage'] = $fileErrors; } } else { $imgMain = $user->imgMain; $imgThumb = $user->imgThumb; } $user->firstname = RequestMethods::post('firstname'); $user->lastname = RequestMethods::post('lastname'); $user->email = RequestMethods::post('email'); $user->password = $hash; $user->salt = $salt; $user->imgMain = $imgMain; $user->imgThumb = $imgThumb; $user->role = RequestMethods::post('role', $user->getRole()); $user->active = RequestMethods::post('active'); if (empty($errors) && $user->validate()) { $user->save(); Event::fire('admin.log', array('success', 'User id: ' . $id)); $view->successMessage(self::SUCCESS_MESSAGE_2); self::redirect('/admin/user/'); } else { Event::fire('admin.log', array('fail', 'User id: ' . $id)); $view->set('errors', $errors + $user->getErrors()); } } }
/** * Check if profiler should be active or not * * @return boolean */ private function isActive() { if ($this->_active === null) { $configuration = Registry::get('configuration'); $active = (bool) $configuration->profiler->active; } else { $active = $this->_active; } if ($active === true) { return true; } else { return false; } }
/** * @before _secured, _admin */ public function edit($id) { $view = $this->getActionView(); $dog = App_Model_Dog::fetchDogById((int) $id); if ($dog === null) { $view->warningMessage(self::ERROR_MESSAGE_2); $this->_willRenderActionView = false; self::redirect('/admin/dog/'); } $dogExams = $dog->exams; $dogExamIds = array(); if (!empty($dogExams)) { foreach ($dogExams as $dogExam) { $dogExamIds[] = $dogExam->examId; } } $exams = App_Model_Exam::all(array('active = ?' => true)); $users = App_Model_User::all(array('role = ?' => 'role_member'), array('id', 'firstname', 'lastname')); $view->set('dog', $dog)->set('exams', $exams)->set('dogexamids', $dogExamIds)->set('users', $users); if (RequestMethods::post('submitEditDog')) { if ($this->checkCSRFToken() !== true) { self::redirect('/admin/dog/'); } $errors = array(); $cfg = Registry::get('configuration'); $fileManager = new FileManager(array('thumbWidth' => $cfg->thumb_width, 'thumbHeight' => $cfg->thumb_height, 'thumbResizeBy' => $cfg->thumb_resizeby, 'maxImageWidth' => $cfg->photo_maxwidth, 'maxImageHeight' => $cfg->photo_maxheight)); $imgMain = $imgThumb = ''; if ($dog->imgMain == '') { $photoNameRaw = RequestMethods::post('user') . '-' . RequestMethods::post('dogname'); $photoName = $this->_createUrlKey($photoNameRaw); $fileErrors = $fileManager->uploadBase64Image(RequestMethods::post('croppedimage'), $photoName, 'dog', time() . '_')->getUploadErrors(); $files = $fileManager->getUploadedFiles(); if (!empty($fileErrors)) { $errors['croppedimage'] = $fileErrors; } if (!empty($files)) { foreach ($files as $i => $file) { if ($file instanceof \THCFrame\Filesystem\Image) { $imgMain = trim($file->getFilename(), '.'); $imgThumb = trim($file->getThumbname(), '.'); break; } } } } else { $imgMain = $dog->imgMain; $imgThumb = $dog->imgThumb; } if ((int) RequestMethods::post('isactive') == 1) { App_Model_Dog::updateAll(array('isActive = ?' => true, 'userId = ?' => (int) RequestMethods::post('user')), array('isActive' => 0)); } $dog->userId = RequestMethods::post('user'); $dog->isActive = RequestMethods::post('isactive', 0); $dog->dogName = RequestMethods::post('dogname'); $dog->race = RequestMethods::post('dograce'); $dog->dob = RequestMethods::post('dogdob'); $dog->information = RequestMethods::post('doginfo'); $dog->active = RequestMethods::post('active'); $dog->imgMain = $imgMain; $dog->imgThumb = $imgThumb; if (empty($errors) && $dog->validate()) { $dog->save(); $examsArr = (array) RequestMethods::post('chexam'); if ($examsArr[0] != '') { $deleteStatus = App_Model_DogExam::deleteAll(array('dogId = ?' => (int) $dog->getId())); if ($deleteStatus != -1) { foreach ($examsArr as $exam) { $de = new App_Model_DogExam(array('dogId' => (int) $dog->getId(), 'examId' => (int) $exam)); $de->save(); Event::fire('admin.log', array('success', 'Dog id: ' . $dog->getId() . ' has exam ' . $exam)); } } else { $errors['exams'] = array('Nastala chyba při ukládání zkoušek'); } } if (RequestMethods::post('uploadmorephotos') == '1') { $fileErrors = $fileManager->newUpload()->uploadImage('secondfile', 'dog', time() . '_')->getUploadErrors(); $files = $fileManager->getUploadedFiles(); if (!empty($fileErrors)) { $errors['secondfile'] = $fileErrors; } if (!empty($files)) { foreach ($files as $i => $file) { if ($file instanceof \THCFrame\Filesystem\Image) { $info = $file->getOriginalInfo(); $photo = new App_Model_Photo(array('galleryId' => 2, 'imgMain' => trim($file->getFilename(), '.'), 'imgThumb' => trim($file->getThumbname(), '.'), 'description' => RequestMethods::post('description'), 'photoName' => pathinfo($file->getFilename(), PATHINFO_FILENAME), 'mime' => $info['mime'], 'format' => $info['format'], 'width' => $file->getWidth(), 'height' => $file->getHeight(), 'size' => $file->getSize())); if ($photo->validate()) { $photoId = $photo->save(); $dp = new App_Model_DogPhoto(array('dogId' => $dog->getId(), 'photoId' => $photoId)); $dp->save(); Event::fire('admin.log', array('success', 'Photo id: ' . $photoId)); } else { Event::fire('admin.log', array('fail')); $errors['secondfile'][] = $photo->getErrors(); } } } } if (empty($errors)) { Event::fire('admin.log', array('success', 'Dog Id: ' . $id)); $view->successMessage(self::SUCCESS_MESSAGE_2); self::redirect('/admin/dog/'); } else { Event::fire('admin.log', array('fail')); $view->set('errors', $errors)->set('dog', $dog); } } else { Event::fire('admin.log', array('success', 'Dog Id: ' . $id)); $view->successMessage(self::SUCCESS_MESSAGE_2); self::redirect('/admin/dog/'); } } else { Event::fire('admin.log', array('fail', 'Dog Id: ' . $dog->getId())); $view->set('errors', $errors + $dog->getErrors())->set('dog', $dog); } } }
/** * Get module-specific redirects * * @return array */ public function getRedirects() { if ($this->checkForRedirects) { $cache = Registry::get('cache'); $cachedRedirects = $cache->get('core_redirects_' . $this->getModuleName()); if (null !== $cachedRedirects) { $redirects = $cachedRedirects; } else { $redirects = Redirect::all(array('module = ?' => strtolower($this->getModuleName()))); if (null === $redirects) { $redirects = array(); } $cache->set('core_redirects_' . $this->getModuleName(), $redirects); } return $redirects; } else { return array(); } }
/** * * @param type $key * @return string */ protected function _getValue($key) { $data = Registry::get($this->defaultKey); if (isset($data[$key])) { return $data[$key]; } return ""; }
/** * Extends configuration loaded from config file for configuration loaded * form database */ public function extendForDbConfig() { $ca = Config::all(); if ($ca !== null) { foreach ($ca as $key => $value) { $this->_configArrMerged[$value->xkey] = $value->value; } $this->_parsed = ArrayMethods::toObject($this->_configArrMerged); Registry::set('configuration', $this->_parsed); } }
/** * * @param string $tokenname */ public function __construct($tokenname = 'csrf') { self::$_tokenname = $tokenname; $this->_session = Registry::get('session'); $this->setToken(); }
/** * Method begins by getting a list of columns and iterating over that list. * For each column, we determine whether validation should occur. * We then split the @validate metadata into a list of validation conditions. * If a condition has arguments (e.g., max(100)), we extract the arguments. * We then run each validation method on the column data and generate error * messages for those validation conditions that failed. * We return a final true/false to indicate whether the complete validation passed or failed. * * @return type * @throws Exception\Validation */ public function validate() { $this->_errors = array(); $config = Registry::get('configuration'); $errLang = $config->system->lang; foreach ($this->columns as $column) { if ($column['validate']) { $pattern = '#[a-z]+\\(([a-zá-žA-ZÁ-Ž0-9, ]+)\\)#'; $raw = $column['raw']; $name = $column['name']; $validators = $column['validate']; $label = $column['label']; $defined = $this->getValidators(); foreach ($validators as $validator) { $function = $validator; $arguments = array($this->{$raw}); $match = StringMethods::match($validator, $pattern); if (count($match) > 0) { $matches = StringMethods::split($match[0], ',\\s*'); $arguments = array_merge($arguments, $matches); $offset = StringMethods::indexOf($validator, '('); $function = substr($validator, 0, $offset); } if (!isset($defined[$function])) { throw new Exception\Validation(sprintf('The %s validator is not defined', $function)); } $template = $defined[$function]; if (!call_user_func_array(array($this, $template['handler']), $arguments)) { $replacements = array_merge(array($label ? $label : $raw), $arguments); $message = $template['message_' . $errLang]; foreach ($replacements as $i => $replacement) { $message = str_replace("{{$i}}", $replacement, $message); } if (!isset($this->_errors[$name])) { $this->_errors[$name] = array(); } $this->_errors[$name][] = $message; } } } } return !count($this->errors); }
/** * 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 constructor * * @param array $options */ public function __construct($options = array()) { parent::__construct($options); Event::fire('framework.controller.construct.before', array($this->name)); //get resources $configuration = Registry::get('configuration'); $session = Registry::get('session'); $router = Registry::get('router'); if (!empty($configuration->view)) { $this->defaultExtension = $configuration->view->extension; $this->defaultLayout = $configuration->view->layout; $this->mobileLayout = $configuration->view->mobilelayout; $this->tabletLayout = $configuration->view->tabletlayout; $this->defaultPath = $configuration->view->path; } else { throw new \Exception('Error in configuration file'); } //collect main variables $module = $router->getLastRoute()->getModule(); $controller = $router->getLastRoute()->getController(); $action = $router->getLastRoute()->getAction(); $deviceType = $session->get('devicetype'); if ($deviceType == 'phone' && $this->mobileLayout != '') { $defaultLayout = $this->mobileLayout; } elseif ($deviceType == 'tablet' && $this->tabletLayout != '') { $defaultLayout = $this->tabletLayout; } else { $defaultLayout = $this->defaultLayout; } $defaultPath = sprintf($this->defaultPath, $module); $defaultExtension = $this->defaultExtension; //create view instances if ($this->willRenderLayoutView) { $view = new View(array('file' => APP_PATH . "/{$defaultPath}/{$defaultLayout}.{$defaultExtension}")); $this->layoutView = $view; } if ($this->willRenderActionView) { $view = new View(array('file' => APP_PATH . "/{$defaultPath}/{$controller}/{$action}.{$defaultExtension}")); $this->actionView = $view; } Event::fire('framework.controller.construct.after', array($this->name)); }
/** * Initialize router and dispatcher and dispatch request. * If there is some error method tries to find and render error template */ public static function run() { try { //router $router = new \THCFrame\Router\Router(array('url' => urldecode($_SERVER['REQUEST_URI']))); Registry::set('router', $router); //dispatcher $dispatcher = new \THCFrame\Router\Dispatcher(); Registry::set('dispatcher', $dispatcher->initialize()); $dispatcher->dispatch($router->getLastRoute()); unset($router); unset($dispatcher); } catch (\Exception $e) { $exception = get_class($e); // attempt to find the approapriate error template, and render foreach (self::$_exceptions as $template => $classes) { foreach ($classes as $class) { if ($class == $exception) { $defaultErrorFile = MODULES_PATH . "/app/view/errors/{$template}.phtml"; http_response_code($template); header('Content-type: text/html'); include $defaultErrorFile; exit; } } } // render fallback template http_response_code(500); header('Content-type: text/html'); echo 'An error occurred.'; if (ENV == 'dev') { print_r($e); } exit; } }
/** * * @return type */ public function revalidateMutliSubmissionProtectionToken() { $session = Registry::get('session'); $session->erase('submissionprotection'); $token = md5(microtime()); $session->set('submissionprotection', $token); return $token; }
/** * Method save additional configuration into database * Config table is required * * @param string $key * @param mixed $value * @return boolean */ public function saveConfigToDb($key, $value) { if (Registry::get('database') instanceof \THCFrame\Database\Connector) { $conf = Config::first(array('xkey = ?' => $key)); $conf->value = $value; if ($conf->validate()) { $conf->save(); return true; } else { return false; } } else { throw new Exception\Argument('Connection to the database has not been initialized'); } }
/** * Action method shows and processes form used for uploading photos into * collection specified by param id * * @before _secured, _admin * @param int $id collection id */ public function addPhoto($id) { $view = $this->getActionView(); $gallery = App_Model_Gallery::first(array('id = ?' => (int) $id, 'active = ?' => true), array('id', 'title')); if ($gallery === null) { $view->warningMessage(self::ERROR_MESSAGE_2); self::redirect('/admin/gallery/'); } $view->set('gallery', $gallery)->set('submstoken', $this->mutliSubmissionProtectionToken()); if (RequestMethods::post('submitAddPhoto')) { if ($this->checkCSRFToken() !== true && $this->checkMutliSubmissionProtectionToken(RequestMethods::post('submstoken')) !== true) { self::redirect('/admin/gallery/'); } $errors = array(); $cfg = Registry::get('configuration'); $fileManager = new FileManager(array('thumbWidth' => $cfg->thumb_width, 'thumbHeight' => $cfg->thumb_height, 'thumbResizeBy' => $cfg->thumb_resizeby, 'maxImageWidth' => $cfg->photo_maxwidth, 'maxImageHeight' => $cfg->photo_maxheight)); $fileErrors = $fileManager->uploadImage('secondfile', 'gallery/' . $gallery->getId(), time() . '_')->getUploadErrors(); $files = $fileManager->getUploadedFiles(); if (!empty($files)) { foreach ($files as $i => $file) { if ($file instanceof \THCFrame\Filesystem\Image) { $info = $file->getOriginalInfo(); $photo = new App_Model_Photo(array('galleryId' => $gallery->getId(), 'imgMain' => trim($file->getFilename(), '.'), 'imgThumb' => trim($file->getThumbname(), '.'), 'description' => RequestMethods::post('description'), 'photoName' => pathinfo($file->getFilename(), PATHINFO_FILENAME), 'mime' => $info['mime'], 'format' => $info['format'], 'width' => $file->getWidth(), 'height' => $file->getHeight(), 'size' => $file->getSize())); if ($photo->validate()) { $aid = $photo->save(); Event::fire('admin.log', array('success', 'Photo id: ' . $aid . ' in gallery ' . $gallery->getId())); } else { Event::fire('admin.log', array('fail', 'Photo in gallery ' . $gallery->getId())); $errors['secondfile'][] = $photo->getErrors(); } } } } $errors['secondfile'] = $fileErrors; if (empty($errors['secondfile'])) { $view->successMessage(self::SUCCESS_MESSAGE_7); self::redirect('/admin/gallery/detail/' . $gallery->getId()); } else { $view->set('errors', $errors); } } }