public function run() { $request = Service::get('request'); $router = Service::get('router')->getRoute(); $controller = $router['controller']; $action = $router['action']; }
public function attemptToFindRoute() { $request = Service::get('request'); $uri = $request->getURI(); if ($uri != '/') { rtrim($uri, '/'); } $result = NULL; foreach ($this->routes as $route => $rContent) { $requirements = isset($rContent["_requirements"]) ? $rContent["_requirements"] : NULL; $pattern = preg_replace('~\\{\\w+\\}~', isset($requirements["id"]) ? '(' . $requirements["id"] . ')' : '([\\w\\d]+)', $rContent['pattern']); //����� �������� ���� ������� ��������� � requirements � ����������� ������������� (c)���� if (preg_match(self::DLMTR . "^" . $pattern . "\$" . self::DLMTR, $uri, $match) && isset($requirements["_method"])) { if ($requirements["_method"] !== $request->getMethod()) { continue; } $result = $this->routes[$route]; $result['name'] = $route; if (!empty($match[1])) { $result['variables'] = [$match[1]]; } self::$currentRoute = $result; return $result; } if (preg_match(self::DLMTR . "^" . $pattern . "\$" . self::DLMTR, $uri, $match)) { $result = $this->routes[$route]; $result['name'] = $route; if (!empty($match[1])) { $result['variables'] = [$match[1]]; } self::$currentRoute = $result; return $result; } } }
/** * Render specified template file with data provided * @param $template_path Template file path (full) * @param array $data Data array * @param bool|true $wrap To be wrapped with main template if true * @return bool|html * @throws FileException if template file does not exist */ public function render($template_path, $data = array(), $wrap = true) { //Launches the appropriate event Service::get('eventManager')->trigger('renderAction', "Render specified template file \"" . $template_path . "\" with data provided"); $data['include'] = function ($controllerName, $actionName, $params) { Helper::dispatch($controllerName, $actionName, $params); }; $data['getRoute'] = function ($route_name, $params = array()) { return Service::get('router')->buildRoute($route_name, $params); }; $data['generateToken'] = function () { echo '<input type="hidden" name="token" value="' . Service::get('session')->get('token') . '"/>'; }; $data['route'] = Registry::getConfig('route'); $data['user'] = Service::get('session')->get('user'); if (!$wrap) { //Gets messages from session message container to display them in view $flush = Service::get('session')->get('messages') ? Service::get('session')->get('messages') : array(); Service::get('session')->del('messages'); } extract($data); //Checks if template file exists if (file_exists($template_path)) { ob_start(); include $template_path; $content = ob_get_contents(); ob_end_clean(); } else { throw new FileException("File " . $template_path . " does not found"); } if ($wrap) { $content = $this->renderMain($content); } return $content; }
public function uploadImage($image, $alt) { try { $file = new File($image, 10000); $uploadDir = ASSETS . 'uploads/portfolio/gallery/'; $tmp = ASSETS . 'uploads/portfolio/tmp/'; $file->setUploadDir($tmp); $fileSaver = new FileSaver($file); if (!$file->isNormalSize()) { throw new \Exception('Very big file size'); } if (!$fileSaver->save()) { throw new \Exception('File not selected'); } if (!ImageHelper::isImage($fileSaver->uploadedFile, ['gif', 'png', 'jpg', 'jpeg'])) { throw new \Exception('File is not image'); } if (file_exists($uploadDir . $file->getName())) { $uniqName = FileHelper::getUniqFileName($uploadDir, FileHelper::getFileExtension($file->getName())); $file->setName($uniqName); } FileHelper::move($fileSaver->uploadedFile, $uploadDir . $file->getName()); $db = Service::get('db'); $query = 'INSERT INTO ' . self::getTable() . '(name, alt) VALUES (:name, :alt)'; $stmt = $db->prepare($query); if (!$stmt->execute([':name' => $file->getName(), ':alt' => $alt])) { throw new \Exception('File not saved into DB'); } Service::get('session')->setFlushMsg('success', 'File successfully downloaded'); } catch (\Exception $e) { Service::get('session')->setFlushMsg('error', $e->getMessage()); $response = new ResponseRedirect(Request::getHost() . '/admin'); $response->send(); } }
/** * */ public function sendHeaders() { header(Service::get('request')->get('protocol') . ' ' . $this->code . ' ' . self::$msgs[$this->code]); foreach ($this->headers as $key => $value) { header(sprintf("%s: %s", $key, $value)); } }
public function run() { $route = $this->router->parseRoute(); try { if (!empty($route)) { if (empty($route['security']) || in_array(Service::get('security')->getUserRole(), @$route['security'])) { $controllerReflection = new \ReflectionClass($route['controller']); $action = $route['action'] . 'Action'; if ($controllerReflection->hasMethod($action)) { $controller = $controllerReflection->newInstance(); $actionReflection = $controllerReflection->getMethod($action); $response = $actionReflection->invokeArgs($controller, $route['params']); // sending $response->send(); } } else { throw new AuthRequredException('Login required'); } } else { throw new HttpNotFoundException('Route not found!'); } } catch (HttpNotFoundException $e) { // Render 404 or just show msg echo $e->getMessage(); } catch (AuthRequredException $e) { echo $e->getMessage(); } catch (\Exception $e) { // Do 500 layout... echo $e->getMessage(); } }
/** * Rendering method * * @param string Layout file name * @param mixed Data * * @return Response */ public function render($layout, $data = array()) { $fullpath = realpath($this->getViewPath() . $layout . '.php'); $renderer = new Renderer(Service::get('config')['main_layout']); $content = $renderer->render($fullpath, $data); return new Response($content); }
/** * Include HTML layout file and extract data. * * @return string */ public function render() { $user = Service::get('session')->get('authenticated'); $route = Service::get('router')->find(); $getRoute = function ($route_name, $params = null) { $router = Service::get('router'); return $router->generateRoute($route_name, $params); }; $include = function ($class_name, $action, $params) { $response = Service::get('app')->runControllerAction($class_name, $action, $params); if (is_object($response)) { $response->send(); } }; $generateToken = function () { $token = Service::get('security')->generateToken(); echo '<input type="hidden" name="token" value="' . $token . '">'; }; $data['getRoute'] = $getRoute; $data['generateToken'] = $generateToken; $data['include'] = $include; $data['user'] = $user; $data['route'] = $route; ob_start(); extract($this->_data); extract($data); include $this->_layout; $result = ob_get_clean(); return $result; }
public function run() { $router = Service::get('router'); $route = $router->parseRoute($_SERVER['REQUEST_URI']); try { //Checks if route is empty if (!empty($route)) { //Verifies user role if it needs if (array_key_exists('security', $route)) { if (is_null($user = Service::get('session')->get('user')) || !in_array($user->role, $route['security'])) { throw new SecurityException("Access is denied"); } } //Returns Response object $response = Helper::dispatch($route['controller'], $route['action'], $route['params']); } else { throw new HttpNotFoundException("Route does not found", 404); } } catch (SecurityException $e) { Service::get('session')->set('returnUrl', Registry::getConfig('route')['pattern']); $response = new ResponseRedirect(Service::get('router')->buildRoute('login')); } catch (HttpNotFoundException $e) { $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_400'), array('code' => $e->getCode(), 'message' => $e->getMessage()))); } catch (\Exception $e) { $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_500'), array('code' => $e->getCode(), 'message' => $e->getMessage()))); } $response->send(); }
/** * Response constructor. * @param string $content контент, который вернется в ответе на запрос * @param string $response_code HTTP код ответа, 200 по умолчанию * @param string $content_type HTTP тип коннтенат ответа, по умолчанию - text/html */ public function __construct($content, $response_code = ResponseType::OK, $content_type = "text/html") { $this->content = $content; $this->response_code = $response_code; $this->content_type = $content_type; self::$logger = Service::get("logger"); }
/** * Class instance constructor * * @param $main_layout */ public function __construct($main_layout) { $this->main_layout = $main_layout; $this->helpers = array('include' => function ($controller, $action, $params) { $controllerReflection = new \ReflectionClass($controller); $action = $action . 'Action'; if ($controllerReflection->hasMethod($action)) { $controller = $controllerReflection->newInstance(); $actionReflection = $controllerReflection->getMethod($action); $response = $actionReflection->invokeArgs($controller, $params); $response->sendBody(); } }, 'generateToken' => function () { $token = Service::get('security')->getToken(); echo '<input type="hidden" name="token" value="' . $token . '" />'; }, 'getRoute' => function ($route, $params = array()) { return Service::get('router')->getRoute($route, $params); }); if (Service::get('security')->isAuthenticated()) { $this->data['user'] = Service::get('session')->user; } else { $this->data['user'] = null; } $this->data['flush'] = Service::get('session')->getFlush(); }
/** * @throws ServiceException * * solve exception depending from enter message (number or string) * if message is numeric get code from Response class and redirect to 500 html page * if string redirect to $redirectAddress */ public function solveException() { $data = array(); if ($this->getMessage() && is_numeric($this->getMessage())) { $data['code'] = $this->getMessage(); $data['message'] = Response::getMessageByCode($this->getMessage()); if ($this->beforeSolve) { $this->beforeSolveException(); } $renderer = new Renderer(); $responce = new Response($renderer::render(Service::get('config')->get500Layout(), $data), 'text/html', 202); $responce->send(); } else { if ($this->getMessage()) { Service::get('session')->addFlush($this->type, $this->getMessage()); if ($this->beforeSolve) { $this->beforeSolveException(); } echo $this->redirectAddress; $redirect = new ResponseRedirect($this->redirectAddress); $redirect->sendHeaders(); } else { throw new ServiceException(500); } } }
/** * Divide uri and call the appropriate controllers, methods and params. * * @param string $uri Uri. * * @return array An array which contains the required controllers, methods and params. * @throws \Framework\Exception\DIException */ public function execute($uri = null) { if ($uri === null) { $uri = Service::get('request')->getUri(); } $uri = '/' . trim(trim($uri), '/'); foreach ($this->routes as $name => $route) { $pattern = str_replace(array('{', '}'), array('(?P<', '>)'), $route['pattern']); if (array_key_exists('_requirements', $route)) { if (array_key_exists('_method', $route['_requirements']) && $route['_requirements']['_method'] != Service::get('request')->getMethod()) { continue; } if (0 !== count($route['_requirements'])) { $search = $replace = array(); foreach ($route['_requirements'] as $key => $value) { $search[] = '<' . $key . '>'; $replace[] = '<' . $key . '>' . $value; } $pattern = str_replace($search, $replace, $pattern); } } if (!preg_match('&^' . $pattern . '$&', $uri, $params)) { continue; } $params = array_merge(array('controller' => $route['controller'], 'action' => $route['action']), $params); foreach ($params as $key => $value) { if (is_int($key)) { unset($params[$key]); } } $this->currentRoute = array_merge($route, array('_name' => $name)); return $params; } }
public function updateAction() { $errors = array(); $msgs = array(); $user_id = Service::get('Session')->user->id; if (isset(Service::get('Session')->profile)) { $profile = Service::get('Session')->profile; } else { $profile = Profile::getProfile($user_id); } if (!$profile) { $profile = new Profile(); $profile->user_id = $user_id; } if ($this->getRequest()->isPost()) { try { $profile->name = $this->getRequest()->post('name'); $profile->second_name = $this->getRequest()->post('second_name'); $profile->info = $this->getRequest()->post('info'); $validator = new Validator($profile); if ($validator->isValid()) { $profile->save(); return $this->redirect($this->generateRoute('home'), 'The data has been saved successfully'); } else { $errors = $validator->getErrors(); } } catch (DatabaseException $e) { $msgs = $e->getMessage(); } } return $this->render('profile.html', array('errors' => $errors, 'msgs' => $msgs, 'profile' => $profile)); }
/** * Create page * * @param $path_to_layout * @param $content * @return string */ public function render($path_to_layout, $content) { $include = function ($controller, $action, $params = array()) { $app = Service::get('app'); $app->generateResponseCtrl($controller, $action, $params); }; $user = Service::get('session')->get('user'); //массив $router = Service::get('route'); $getRoute = function ($rout) use(&$router) { return $router->buildRoute($rout); }; $generateToken = function () { $csrf = Service::get('csrf'); $token = $csrf->generateToken(); echo '<input type="hidden" name="token" value="' . $token . '" />'; }; ob_start(); if (is_array($content)) { extract($content); } include $path_to_layout; //костыль на отобжажение ссылки на редактирование поста, чтобы не менять стандартную вьюху show.html if (!empty($content['post']->id) && Service::get('security')->isAuthenticated() && empty($content['show'])) { echo '<br/><a href="/posts/' . $content['post']->id . '/edit"> Edit post</a>'; echo '<br/><a href="/posts/' . $content['post']->id . '/delete"> Delete post</a>'; } return ob_get_clean(); }
public function signinAction() { if (Service::get('security')->isAuthenticated()) { return new ResponseRedirect($this->generateRoute('home')); } $errors = array(); if ($this->getRequest()->isPost()) { try { if ($user_mas = User::findByEmail($this->getRequest()->post('email'))) { array_push($errors, 'This email is already register!'); return $this->render('signin.html', array('errors' => $errors)); } else { $user = new User(); $user->email = $this->getRequest()->post('email'); $user->password = $this->getRequest()->post('password'); $user->role = 'ROLE_USER'; $user->save(); $user_mas = User::findByEmail($this->getRequest()->post('email')); Service::get('security')->setUser($user_mas); return $this->redirect($this->generateRoute('home')); } } catch (DatabaseException $e) { $errors = array($e->getMessage()); } } return $this->render('signin.html', array('errors' => $errors)); }
/** * * @throws HttpNotFoundException * @throws BadResponseTypeException */ public function run() { $route = Service::get('router')->parseRoute(Service::get('request')->get('uri')); try { if (empty($route)) { throw new HttpNotFoundException('Route not found', 404); } $controllerReflection = new \ReflectionClass($route['controller']); $action = $route['action'] . 'Action'; if ($controllerReflection->hasMethod($action)) { $controller = $controllerReflection->newInstance(); $actionReflection = $controllerReflection->getMethod($action); $this->response = $actionReflection->invokeArgs($controller, $route['params']); if ($this->response instanceof Response) { $this->response->send(); } else { throw new BadResponseTypeException('Result is not instance of Response'); } } else { throw new HttpNotFoundException('The method or controller not found', 404); } } catch (BadResponseTypeException $e) { $e->getResponse()->send(); } catch (HttpNotFoundException $e) { $e->getResponse()->send(); } catch (DatabaseException $e) { echo $e->getMessage(); } catch (AuthRequredException $e) { $e->getResponse()->send(); } catch (\Exception $e) { echo $e->getMessage(); } }
/** * Render specified template file with data provided * * @param string Template file path (full) * @param mixed Data array * @param bool To be wrapped with main template if true * * @return text/html */ public function render($template_path, $data = array(), $wrap = true) { extract($data); ob_start(); $include = function ($controller, $action, $data = array()) { $controller = new $controller(); $method = $action . 'Action'; extract($data); return $result = $controller->{$method}($id); }; $generateToken = function () { }; $getRoute = function ($key) { $controller = Service::get('route_controller')['controller']; $controller = new $controller(); return $controller->generateRoute($key); }; include $template_path; $content = ob_get_contents(); ob_end_clean(); if ($wrap) { $content = $this->renderMain($content); } return $content; }
/** * Renders * * @param $templatePath * @param $data * @param bool|true $wrap * @return string */ public function render($templatePath, $data, $wrap = true) { $templatePath = realpath($templatePath); $include = function ($controller, $action, $args = array()) { $controllerInstance = new $controller(); if ($args === null) { $args = array(); } return call_user_func_array(array($controllerInstance, $action . 'Action'), $args); }; $generateToken = function () { $token = md5('solt_string' . uniqid()); setcookie('token', $token); echo '<input type="hidden" value="' . $token . '" name="token">'; }; $getRoute = function ($name) { if (array_key_exists($name, Service::get('routes'))) { $uri = Service::get('routes')[$name]['pattern']; return $uri; } }; extract($data); ob_start(); if (file_exists($templatePath)) { include $templatePath; } $content = ob_get_contents(); ob_end_clean(); if ($wrap) { $content = $this->renderMain($content); } return $content; }
/** * Registers custom error handler * * @access public * @static * * @return void */ public static function loadErrorHandler() { set_error_handler(function ($errno, $errmsg, $filename, $linenum) { $date = date('Y-m-d H:i:s (T)'); if (!file_exists(__DIR__ . '/../../app/logs/')) { mkdir(__DIR__ . '/../../app/logs/'); } $f = fopen(__DIR__ . '/../../app/logs/errorlog.txt', 'a'); if (!empty($f)) { $error = "____________________________________________________________\n"; $error .= $date . "\n"; $error .= $errno . "\n"; $error .= $errmsg . "\n"; $error .= $filename . "\n"; $error .= $linenum . "\n"; $error .= "____________________________________________________________\n"; fwrite($f, $error); fclose($f); } if (Service::get('config')['mode'] == 'user') { $renderer = new Renderer(Service::get('config')['layouts']); $renderer->set('code', 500); $renderer->set('message', 'Oooops'); $content = $renderer->generatePage('500.html'); $response = new Response($content, array(), 500); $response->send(); } }); }
/** * Creates an instance of controller and calls an action of that controller * @param $controllerName * @param $actionName * @param $params * @return mixed * @throws ClassException * @throws WrongResponseTypeException */ public static function dispatch($controllerName, $actionName, $params) { //Checks if controller class exists if (class_exists($controllerName)) { $controllerReflection = new \ReflectionClass($controllerName); $action = $actionName . 'Action'; //Check if controller has action if ($controllerReflection->hasMethod($action)) { $controller = $controllerReflection->newInstance(); $actionReflection = $controllerReflection->getMethod($action); //Checks if action has the appropriate number of parameters if ($actionReflection->getNumberOfParameters() <= count($params)) { //Launches the appropriate event Service::get('eventManager')->trigger('dispatchAction', "Created an instance of controller \"" . $controllerName . "\" and called an action \"" . $actionName . "\" of that controller"); $response = $actionReflection->invokeArgs($controller, $params); } else { throw new ClassException("Does not match the number of parameters"); } //Checks if the object $response is of the same class or a descendant of the class Response if ($response instanceof Response) { return $response; } else { throw new WrongResponseTypeException("Controller returns wrong type of Response"); } } else { throw new ClassException("Controller does not have this action"); } } else { throw new ClassException("Class of controller does not found"); } }
public static function getDBCon() { if (empty(self::$db)) { self::$db = Service::get('db')->getConnection(); } return self::$db; }
/** * Redirects user to specified url. */ public function send() { $request = Service::get('request'); header('Referer: ' . $request->getUri()); header('Location: ' . $this->url, $this->replace, $this->code); exit; }
public function editAction($postId) { if (!Service::get('security')->isAuthenticated()) { throw new AuthRequredException('You need authorizate for this action'); } try { $post = new Post(); $date = new \DateTime(); $post->id = $postId; $post->title = $this->getRequest()->post('title'); $post->content = trim($this->getRequest()->post('content')); $post->date = $date->format('Y-m-d H:i:s'); $post->user_id = Service::get('security')->getUser()->id; $validator = new Validator($post); if ($validator->isValid()) { $post->save(); return $this->redirect($this->generateRoute('home'), 'The data has been saved successfully'); } else { $error = $validator->getErrors(); } } catch (DatabaseException $e) { $error = $e->getMessage(); } if (!($post = Post::find((int) $postId))) { throw new HttpNotFoundException(404); } return $this->render('add.html', array('post' => $post, 'errors' => isset($error) ? $error : null, 'action' => $this->generateRoute('edit_post', array('id' => $postId)), 'src' => array('src' => 'Blog', 'controller' => 'Post'))); }
public function addAction() { if ($this->getRequest()->isPost()) { try { $post = new Post(); $date = new \DateTime(); $post->title = $this->getRequest()->post('title'); $post->content = trim($this->getRequest()->post('content')); $post->date = $date->format('Y-m-d H:i:s'); $validator = new Validator($post); if ($validator->isValid()) { $lastId = $post->save(); $userPosts = new UserPosts(); $userPosts->post_id = (int) $lastId; $userPosts->user_id = (int) Service::get('security')->getUser()->id; $userPosts->save(); return $this->redirect($this->generateRoute('home'), 'The data has been saved successfully'); } else { $error = $validator->getErrors(); } } catch (DatabaseException $e) { $error = $e->getMessage(); } } return $this->render('add.html', array('action' => $this->generateRoute('add_post'), 'errors' => isset($error) ? $error : null)); }
/** * Method includes layout and substitutes data. Result is written into buffer and is returned * Method has realization of some callbacks * * @return string */ public function render(){ $getRoute = function ($name){ return Service::get('router')->buildRoute($name); }; $user = Service::get('session')->get('user'); $include = function($controller, $action, $params = array()){ $response = Service::get('app')->startController($controller, $action, $params); if ($response) $response->send(); }; $route = Service::get('router')->start(); $generateToken = function(){ $token = Service::get('security')->generateToken(); echo '<input type = "hidden" name = "token" value = "'.$token.'">'; }; ob_start(); if (is_array($this->content)){ extract($this->content); }else{ $content = $this->content; } include $this->layout; return ob_get_clean(); }
/** * @return \Framework\Response\Response * @throws \Framework\Exception\ServiceException */ public function getAction() { $user = Service::get('security')->getUser(); unset($user->password); unset($user->solt); return $this->render('update.html', array('user' => $user, 'errors' => isset($error) ? $error : null, 'action' => $this->generateRoute('update_profile'), 'src' => array('src' => 'Blog', 'controller' => 'Security'))); }
/** * Execute MVC application. * * @return \Framework\Http\Response object. * @throws HttpException * @throws \Framework\Exception\DIException */ public function run() { try { $tmp = Service::get('router')->execute(); //var_dump($tmp); Service::set('sub_view', new \Framework\View()); Service::set('view', new \Framework\View()); if (class_exists($tmp['controller'])) { $controller = new $tmp['controller'](); $tmp['action'] .= 'Action'; if (method_exists($controller, $tmp['action'])) { $action = $tmp['action']; unset($tmp['controller'], $tmp['action']); $response = $controller->{$action}($tmp); if (is_string($response)) { return Service::get('response')->setContent($response); } elseif (null === $response) { return Service::get('response'); } else { throw new \Exception('All is bad', 404); } } else { throw new HttpException('Action isn\'t found!', 404); } } else { throw new HttpException('Controller isn\'t found!', 404); } } catch (\Exception $e) { return Service::get('response')->setContent(Service::get('view')->set('content', Service::get('sub_view')->render($this->config['error_500'], array('code' => $e->getCode(), 'message' => $e->getMessage())))->set('flush', array())->render(Service::get('application')->config['main_layout'])); } }
public function __construct($path, $message = '') { if (!empty($message)) { Service::get('session')->addFlush('info', $message); } parent::setHeader('Location', $path); }
/** * Edit post. * * @param $id * @return \Framework\Response\ResponseRedirect * @throws HttpNotFoundException * @throws \Framework\Exception\DatabaseException */ public function editAction($id) { $dirty_request = new Request(null, false); if ($this->getRequest()->isPost()) { try { $post = new Post(); $date = new \DateTime(); $post->id = $id; $post->title = $dirty_request->post('title'); $post->content = $dirty_request->post('content'); $post->date = $date->format('Y-m-d H:i:s'); $post->users_id = Service::get('session')->get('authenticated')->id; $validator = new Validator($post); if ($validator->isValid()) { $post->save($id); return $this->redirect($this->generateRoute('home'), 'success', 'The post has been edit successfully'); } else { $error = $validator->getErrors(); } } catch (DatabaseException $e) { $error = $e->getMessage(); } } $post = Post::find((int) $id); return $this->render('add.html', array('post' => $post, 'action' => '/posts/' . $id . '/edit', 'errors' => isset($error) ? $error : null)); }