function init($controller, $method) { // include controller file require_once 'controllers/' . $controller . '.php'; // create controller objects switch ($controller) { // special cases case 'pages': $controller = new PagesController(); $controller->showPage($method); break; case 'error': $controller = new ErrorController(); $controller->showError($method); break; // standard controllers // standard controllers case 'sorting': $controller = new SortingController(); } // 'pages' and 'error' controllers do not use this if (method_exists($controller, $method)) { // call requested method from controller $controller->{$method}(); } }
/** * Executes the system routing * @throws Exception */ public function execute($routes) { // tries to find the route and run the given action on the controller try { // the controller and action to execute $controller = null; $action = null; // tries to find a simple route $routeFound = $this->_getSimpleRoute($routes, $controller, $action); if (!$routeFound) { // tries to find the a matching "parameter route" $routeFound = $this->_getParameterRoute($routes, $controller, $action); } // no route found, throw an exception to run the error controller if (!$routeFound || $controller == null || $action == null) { throw new Exception('no route added for ' . $_SERVER['REQUEST_URI']); } else { // executes the action on the controller $controller->execute($action); } } catch (Exception $exception) { // runs the error controller $controller = new ErrorController(); $controller->setException($exception); $controller->execute('error'); } }
protected function create() { if ($_SESSION['CURRENT_USER']['role'] != 'USER') { $error = new ErrorController("accessDenied", $this->getvalues, $this->postvalues, $twig, $this->config, $this->logger); $error->ExecuteAction(); } else { $view = "events/create.html.twig"; $this->returnView($view, array('auth_header_name' => $this->config['auth_header_name'], 'auth_token' => $_SESSION['AUTH_TOKEN'], 'events_list' => $this->getEvents(true)['data'], 'current_user' => $this->getCurrentUser())); } }
private function _dispatch($controller, $actionName) { $className = $controller . 'Controller'; $instance = new $className($this->_params); $action = "{$actionName}Action"; if (strcmp(method_exists($instance, $action), '1') !== 0) { $errorController = new ErrorController(); $errorController->error404("アクションが存在しません:【クラス】{$className} 【アクション】{$action}"); } $instance->run($action, $actionName, $controller); }
/** * ファイルをロードする * * @param string $className クラス名 * @return ファイルをロードすればtrueを返す */ public function autoLoad($className) { foreach ($this->_dirs as $dir) { $file = "{$dir}/{$className}.php"; if (is_readable($file)) { require_once $file; return true; } } $errorController = new ErrorController(); $errorController->error404("ファイルが存在しません:{$file}"); }
function __construct() { $url = isset($_GET['url']) ? $_GET['url'] : null; $url = rtrim($url, '/'); $url = filter_var($url, FILTER_SANITIZE_URL); $url = explode('/', $_GET['url']); if (empty($url[0])) { require 'app/controllers/index_controller.php'; $controller = new IndexController(); $controller->index(); return false; } else { $controller = $url[0]; } $file = 'app/controllers/' . $url[0] . '_controller.php'; if (file_exists($file)) { require $file; $controller_class = ucfirst($controller) . 'Controller'; $controller = new $controller_class(); $controller->loadModel($url[0]); if (!$url[1]) { $controller->index(); return false; // Check back on this! } } else { require 'app/controllers/error_controller.php'; $controller = new ErrorController(); $controller->notfound(); exit; } if (isset($url[2])) { $arg = $url[2]; } else { $arg = ''; } if (isset($url[1])) { if (method_exists($controller, $url[1])) { $action = $url[1]; if (empty($arg)) { $controller->{$action}(); } else { $controller->{$action}($arg); } } else { require 'app/controllers/error_controller.php'; $controller = new ErrorController(); $controller->notfound(); exit; } } }
public function deleteAction() { try { $article = new ArticlesModel(); $article->id = intval($_POST['id']); $article->delete(); $view = new View(); $view->display('DeletedArticle.php'); } catch (Exception $e) { // echo $e->getMessage(); $view = new ErrorController(); $view->error(); } }
protected function oneAction($id) { try { $single_article = ArticlesModel::findOne($id); $twig = new TwigClass('SingleArticle.twig'); $twig->display($single_article); // var_dump($single_article); } catch (Twig_Error $e) { echo $e->getMessage(); } catch (Exception $e) { // echo $e->getMessage(); $view = new ErrorController(); $view->error(); } }
/** * Initialize the DisplayController class */ public function init() { try { parent::init(); } catch (Exception $e) { throw new Exception('Une erreur est survenue durant le chargement du module: ' . $e->getMessage()); } if (file_exists(_CONTROLLERS_DIR_ . '/Tools.php')) { $url = Tools::getInstance()->request_url; $url .= '&id=ukn'; $controller = Tools::getInstance()->getUrl_controller($url); if ($controller == 'Display404Controller') { if (file_exists(_ERRORS_VIEWS_ . '/' . $this->view_name . '.tpl')) { try { echo $this->twig->render($this->view_name . '.tpl', array('bootstrapPath' => _BOOTSTRAP_FILE_)); } catch (Exception $e) { throw new Exception('Une erreur est survenue durant la récupération des données: ' . $e->getMessage()); } } else { throw new Exception('Le template "' . $this->view_name . '" n\'existe pas dans "' . _ERRORS_VIEWS_ . '"!'); } } else { throw new Exception('Une erreur est survenue durant la phase de routage!'); } } else { throw new Exception('L\'URL n\'est pas évaluable!'); } }
public function run($action, $actionName, $route) { try { $this->_view->addTemplateDir("resources/templates/{$route}"); $template = "{$actionName}.tpl"; if (strcmp($this->_view->templateExists($template), '1') !== 0) { $errorController = new ErrorController(); $errorController->error404("テンプレートファイルが存在しません:{$template}"); } $this->{$action}(); $this->_view->display($template); } catch (Exception $e) { $errorController = new ErrorController(); $errorController->error500($e); } }
function __construct() { $url = isset($_GET["url"]) ? $_GET["url"] : NULL; $url = rtrim($url, '/'); $url = explode('/', $url); if (empty($url[0]) || $url[0] == 'index.php') { require 'controller/IndexController.php'; $controller = new IndexController(); $controller->index(); return FALSE; } $file = 'controller/' . $url[0] . 'Controller.php'; if (file_exists($file)) { require $file; } else { require 'controller/ErrorController.php'; $error = new ErrorController(); $error->index(); return FALSE; } $controllerFullName = $url[0] . "Controller"; $controller = new $controllerFullName(); if (isset($url[2])) { if (method_exists($controller, $url[1])) { $controller->{$url[1]}($url[2]); } else { require 'controller/ErrorController.php'; $error = new ErrorController(); $error->index(); return FALSE; } } else { if (isset($url[1])) { if (method_exists($controller, $url[1])) { $controller->{$url[1]}(); } else { require 'controller/ErrorController.php'; $error = new ErrorController(); $error->index(); return FALSE; } } else { $controller->index(); } } }
function regError($msg) { // Development echo '<pre>' . $msg . '</pre><hr>'; /* // Production $logger = null; $mailer = new Mailer; // Initialize logger try{ $logger = new FileLogger(LOG_FILE); }catch(Exception $e){ try{ $mailer->compose('*****@*****.**', ADMIN_EMAIL, PROJECT_NAME . ' - Logger error', $e->__toString()); $mailer->sendMail(); }catch(phpmailerException $pme){ $mailer = null; // Write errors to default PHP log error_log($e->__toString()); error_log($pme->__toString()); } } // Log error if($logger !== null) $logger->error($msg); if($mailer !== null){ try{ // Alert admin by mail $mailer->compose('*****@*****.**', ADMIN_EMAIL, PROJECT_NAME . ' - Unexpected error', $msg); $mailer->sendMail(); }catch(phpmailerException $pme){ ($logger !== null) ? $logger->error($pme->__toString()) : error_log($pme->__toString()); } } */ // Display error page to user $error = new ErrorController(); $error->show(); redirect(404); }
public function launch() { $controller = ucfirst($this->controller) . 'Controller'; if (class_exists($controller)) { $controller = new $controller(); } else { $controller = new ErrorController(); return $controller->index('404: ' . $this->controller . ' not found.'); } if (!$controller->restful) { $method = 'action_' . $this->method; } else { $method = strtolower($_SERVER['REQUEST_METHOD']) . "_" . $this->method; } if (method_exists($controller, $method)) { return call_user_func_array(array($controller, $method), $this->args); } else { return $controller->index("404: Method " . str_replace('get_', '', "'{$method}' not exists.")); } }
public function init() { define("NET_PATH_SITE", $this->_nps); define("NET_PATH", $this->_np); $this->view->host = $this->_host; self::$host = NetActionController::$host; self::$lang = $this->_sesija->lang; $request = $this->getRequest(); if ($request->isXmlHttpRequest()) { } $this->_helper->layout()->disableLayout(); }
public function __construct() { var_dump(rtrim($_SERVER["REQUEST_URI"])); $tokens = explode('/', rtrim($_SERVER["REQUEST_URI"], '/')); $controllerName = ucfirst($tokens[1]); echo $controllerName; if (file_exists('../controller/' . $controllerName . '.php')) { require_once '../controller/' . $controllerName . '.php'; $controller = new $controllerName(); $actionName = $tokens[2]; $param = $tokens[3]; var_dump($actionName, $param); $controller->{$actionName}($param); } else { if (!file_exists('../controller/' . $controllerName . '.php')) { require_once '../controller/ErrorController.php'; $controller = new ErrorController(); $controller->defaultError(); } } }
protected function LoadModel($model) { $this->Model = 'model/' . strtolower($model) . '.php'; // Verificamos que exista if (!file_exists($this->Model)) { ErrorController::Show(5, $this); } // Guardamos en nuestra variable Models todo los modelos que vamos cargando $this->Models[] = $model; // Cargamos el modelo require_once $this->Model; return new $model(); }
public static function start() { $url = !empty($_GET['url']) ? $_GET['url'] : 'Articles/all'; $url = rtrim($url, '/'); $url = explode('/', $url); $ctrlClass = $url[0] . 'Controller'; $action = !empty($url[1]) ? $url[1] : 'all'; $param = isset($url[2]) ? $url[2] : ''; if (!class_exists($ctrlClass) || !method_exists($ctrlClass, $action . 'Action')) { $ctrl = new ErrorController(); $ctrl->error(); } else { $controller = new $ctrlClass(); if (!empty($param)) { $controller->action($action, $param); } else { // if ($url[0] === 'Admin') { // header('Location: ../User/SignIn'); // } $controller->action($action); } } }
public function __CONSTRUCT($reload = false) { // 0 => 'Raíz del Proyecto' 1=> 'index.php' 1 => 'Controlador' 3 => 'Accion' 4 => 'Parametros Adicionales' $this->Uri = explode('/', substr($_SERVER['REQUEST_URI'], 1, strlen($_SERVER['REQUEST_URI']) - 1)); // Preguntamos si existe en la URL actual una llamada a algun controlador especifico if (count($this->Uri) == 2) { $this->Controller = _DEFAULT_CONTROLLER_; } elseif (count($this->Uri) > 2) { // Si en la URL por defecto no hay referencia de un controlador, cargamos el que esta por defecto if ($this->Uri[2] == '' || $this->Uri[2] == '/') { $this->Controller = _DEFAULT_CONTROLLER_; } else { // Verificamos si es un Area if (is_dir(_BASE_FOLDER_ . 'controller\\' . $this->Uri[2])) { $this->Area = $this->Uri[2]; $this->Controller = str_replace('/', '', $this->Uri[3]); } else { $this->Controller = str_replace('/', '', $this->Uri[2]); } } // Si se ha especificado la acción $i = $this->Area == null ? 3 : 4; if (isset($this->Uri[$i])) { if ($this->Uri[$i] != '' && $this->Uri[$i] != '/') { $this->Action = str_replace('/', '', $this->Uri[$i]); } } } if (!$reload) { // Guardamos la ruta del controlador $_Controller = 'controller/' . ($this->Area == null ? '' : $this->Area . '/') . $this->Controller . 'controller.php'; // Verificamos que la vista exista if (!file_exists($_Controller)) { ErrorController::Show(1, $this); } // Cargamos el fichero require_once $_Controller; $ControladorActual = $this->Controller . 'controller'; $AccionActual = $this->Action; // Creamos una instancia del controlador actual y ejecutamos su accion $c = new $ControladorActual(); // Verificamos si la acción existe if (!method_exists($c, $this->Action)) { ErrorController::Show(2, $this); } // Ejecutamos la acción actual $c->{$AccionActual}(); } }
/** * "Start" the application: * Analyze the URL elements and calls the according controller/method or the fallback */ public function __construct() { // create array with URL parts in $url $this->splitUrl(); // check for controller: no controller given ? then load start-page if (!$this->url_controller) { Home::index(); } elseif (file_exists(APP_PATH . 'controllers/' . $this->url_controller . '.php')) { // here we did check for controller: does such a controller exist ? // if so, then load this file and create this controller // example: if controller would be "car", then this line would translate into: $this->car = new car(); $this->url_controller = new $this->url_controller(); // check for method: does such a method exist in the controller ? if (method_exists($this->url_controller, $this->url_action)) { if (!empty($this->url_params)) { // Call the method and pass arguments to it call_user_func_array(array($this->url_controller, $this->url_action), $this->url_params); } else { // If no parameters are given, just call the method without parameters, like $this->home->method(); $this->url_controller->{$this->url_action}(); } } else { if (strlen($this->url_action) == 0) { // no action defined: call the default index() method of a selected controller $this->url_controller->index(); } else { // defined action not existent: show the error page $page = new ErrorController(); $page->index(); } } } else { $page = new ErrorController(); $page->index(); } }
public function __CONSTRUCT() { // Recuperamos nuestra cadena de conexión $ConnectionString = explode('|', _DB_CONNECTION_STRING_); try { // Instanciamos PDO $this->Link = new PDO($ConnectionString[0], $ConnectionString[1], $ConnectionString[2]); // Le indicamos que nos muestre los errores $this->Link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { // Si hay un error llamamos al ErrorController ErrorController::Show(4, $e); } return $this; }
private static function startDispatch() { $buffering = !IN_CLI && self::$outputBuffer; if ($buffering) { ob_start(); } try { self::dispatch(); $controllerPath = self::$request->getControllerPath(); $actionFile = self::$request->getActionFile(); } catch (Exception $e) { if (IN_CLI) { throw $e; return; } $controllerPath = 'error'; self::$request->setUserParam('exception', $e); $controller = new ErrorController(); if ($e instanceof PageNotFoundException) { $actionFile = 'page-not-found'; self::$response->setHttpResponseCode(404); $controller->pageNotFoundAction(); } else { $actionFile = 'internal-error'; self::$response->setHttpResponseCode(500); $controller->internalErrorAction(); } } if (self::$shouldRender && !self::$response->isRedirect()) { self::$view->render($controllerPath, $actionFile); } if ($buffering && !self::$response->isRedirect()) { self::$response->setBody(ob_get_clean()); } self::$response->sendResponse(); }
/** * Initialize the ErrorController class */ public function init() { if (self::$initialized) { return; } self::$initialized = true; if (file_exists(_TWIG_AUTOLOADER_)) { try { require_once _TWIG_AUTOLOADER_; Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem(array(_DEPENDENCIES_DIR_, _ERRORS_VIEWS_)); $this->twig = new Twig_Environment($loader, array('cache' => _TWIG_CACHE_)); } catch (Exception $e) { throw new Exception('Le fichier de démarrage Twig ne peut pas s\'executer!'); } } else { throw new Exception('Il n\'existe pas le fichier de démarrage Twig à cet emplacement "' . _TWIG_AUTOLOADER_ . '"!'); } }
/** * Configure everything, then call controller, then call view. * * @return void */ public function run() { session_start(); /* BASIC CONSTANTS */ // Root path on the server filesystem. $root_path = rtrim(pathinfo($_SERVER['SCRIPT_FILENAME'], PATHINFO_DIRNAME), '/'); // Root URI for the site. $proto = 'http://'; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { $proto = 'https://'; } $scr_dir = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')); $scr_uri = $proto . $_SERVER['HTTP_HOST'] . $scr_dir; $root_uri = rtrim($scr_uri, '/'); // Have those three available everywhere. define('ROOT_PATH', $root_path); define('DS', DIRECTORY_SEPARATOR); define('ROOT_URI', $root_uri); /* ROUTE IT */ $this->routes = new Routes(); // array url_elements is the main routing container. See bellow. $url_info = substr($_SERVER['REQUEST_URI'], strlen($scr_dir)); // check for defined static routes if (array_key_exists($url_info, $this->routes->static_routes)) { $url_info = $this->routes->static_routes[$url_info]; } $url_info = trim($url_info, '/'); $url_elements = explode('/', $url_info); if ('index' == $url_elements[0] || 'index.php' == $url_elements[0]) { array_shift($url_elements); } // Prefixed routes. Always lowercase. $prefx = ''; if (!empty($url_elements[0])) { if (in_array($url_elements[0], $this->routes->prefixes)) { $prefx = array_shift($url_elements); } } define('PREFIX', strtolower($prefx)); // Static pages // No url parameters $ctlr_name = !empty($url_elements[0]) ? $url_elements[0] : ''; // url parameter is among static pages if (PREFIX == '') { if (in_array($ctlr_name, $this->routes->static_pages)) { array_unshift($url_elements, 'pages'); $ctlr_name = 'pages'; } } else { // static page in prefixed routes if (array_key_exists(PREFIX, $this->routes->prefixes_with_stpages)) { if (in_array($ctlr_name, $this->routes->prefixes_with_stpages[PREFIX]) || $ctlr_name == '') { array_unshift($url_elements, 'pages'); $ctlr_name = 'pages'; } } } $compl_ctlr_name = ucfirst($ctlr_name . 'Controller'); // default action is index $action = isset($url_elements[1]) ? $url_elements[1] : 'index'; // ErrorController require_once ROOT_PATH . DS . 'controllers' . DS . 'ErrorController.php'; $controller_path = DS . 'controllers' . DS; if (PREFIX != '') { $controller_path = DS . 'controllers' . DS . PREFIX . DS; } if (is_file(ROOT_PATH . $controller_path . $compl_ctlr_name . '.php')) { require_once ROOT_PATH . $controller_path . $compl_ctlr_name . '.php'; } else { $controller_path = DS . 'controllers' . DS; $compl_ctlr_name = 'ErrorController'; $ctlr_name = 'error'; Out::flash('Controller not found'); } // Accept json and xml extensions. Call _json, _xml. if (strtolower(substr($action, -5)) == '.json') { $action = str_replace('.json', '_json', $action); } if (strtolower(substr($action, -4)) == '.xml') { $action = str_replace('.xml', '_xml', $action); } /* CONTROLLER */ // Start action $ctlr = $compl_ctlr_name; $this->controller = new $ctlr($this); if (method_exists($this->controller, $action)) { // Call method. Everything after method name, becomes a parameter. call_user_func_array(array($this->controller, $action), array_slice($url_elements, 2)); } else { $error_controller = new ErrorController($this); $error_controller->index(); Out::flash('Action not found'); } /* VIEW */ $this->view = new BaseView($this); // Set default pg_name to be rendered. if (empty($this->pg_name)) { $this->pg_name = strtolower($ctlr_name) . DS . strtolower($action); if (PREFIX != '') { $this->pg_name = PREFIX . DS . $this->pg_name; } } // If pg_name set to 'no_view' it gives output from the controller. // Use it to output json, xml, ... // // $this->app->pg_name = 'pages/override'; in the controller // overrides the default page if (!($this->pg_name == 'no_view')) { $this->view->render($this->pg_name); } }
/** * A utility method to load a controller. This method loads the controller * and fetches the contents of the controller into the Controller::$contents * variable if the get_contents parameter is set to true on call. If a controller * doesn't exist in the module path, a ModelController is loaded to help * manipulate the contents of the model. If no model exists in that location, * it is asumed to be a package and a package controller is loaded. * * @param $path The path for the model to be loaded. * @param $get_contents A flag which determines whether the contents of the * controller should be displayed. * @return Controller */ public static function load($path, $get_contents = true) { global $redirectedPackage; global $packageSchema; $controller_path = ""; $controller_name = ""; $redirected = false; $redirect_path = ""; $package_name = ""; $package_main = ""; //Go through the whole path and build the folder location of the system for ($i = 0; $i < count($path); $i++) { $p = $path[$i]; $baseClassName = $package_name . Application::camelize("{$controller_path}/{$p}", "/"); if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/{$baseClassName}Controller.php")) { $controller_class_name = $baseClassName . "Controller"; $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_MODULE; add_include_path("app/modules/{$controller_path}/"); break; } else { if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/{$p}.php")) { $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_MODULE; break; } else { if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/{$baseClassName}Model.php")) { $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_MODEL; break; } else { if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/model.xml")) { $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_MODEL; break; } else { if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/report.xml")) { $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_REPORT; break; } else { if (file_exists(SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/package_redirect.php")) { include SOFTWARE_HOME . "app/modules/{$controller_path}/{$p}/package_redirect.php"; $redirected = true; $previousControllerPath = $controller_path . "/{$p}"; $controller_path = ""; $redirectedPackage = $package_path; $packageSchema = $package_schema; } else { if ($redirected === true && file_exists(SOFTWARE_HOME . "{$redirect_path}/{$controller_path}/{$p}/report.xml")) { $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_REPORT; break; } else { if ($redirected === true && file_exists(SOFTWARE_HOME . "{$redirect_path}/{$controller_path}/{$p}/{$baseClassName}Controller.php")) { $controller_class_name = $baseClassName . "Controller"; $controller_name = $p; $controller_path .= "/{$p}"; $controller_type = Controller::TYPE_MODULE; $package_main .= $p; add_include_path("{$redirect_path}/{$controller_path}/"); break; } else { $controller_path .= "/{$p}"; if ($redirected) { $package_main .= "{$p}."; } } } } } } } } } } // Check the type of controller and load it. switch ($controller_type) { case Controller::TYPE_MODULE: // Load a module controller which would be a subclass of this // class if ($controller_class_name == "") { require_once SOFTWARE_HOME . "app/modules{$controller_path}/{$controller_name}.php"; $controller = new $controller_name(); } else { $controller_name = $controller_class_name; $controller = new $controller_class_name(); $controller->redirected = $redirected; $controller->redirectPath = $redirect_path; $controller->redirectedPackage = $package_path; $controller->mainRedirectedPackage = $package_main; $controller->redirectedPackageName = $package_name; } break; case Controller::TYPE_MODEL: // Load the ModelController wrapper around an existing model class. $model = substr(str_replace("/", ".", $controller_path), 1); $controller_name = "ModelController"; $controller = new ModelController($model, $package_path); break; case Controller::TYPE_REPORT: $controller = new XmlDefinedReportController($redirect_path . $controller_path . "/report.xml", $redirected); $controller_name = "XmlDefinedReportController"; break; default: // Load a package controller for this folder if (is_dir("app/modules{$controller_path}")) { $controller = new PackageController($path); $controller_name = "PackageController"; $get_contents = true; $force_output = true; } else { if ($redirected === true && is_dir(SOFTWARE_HOME . "{$redirect_path}/{$controller_path}")) { $controller = new PackageController($path); $controller_name = "PackageController"; $get_contents = true; $force_output = true; } else { $controller = new ErrorController(); $controller_name = "ErrorController"; } } } // If the get contents flag has been set return all the contents of this // controller. $controller->path = $previousControllerPath . $controller_path; if ($get_contents) { if ($i == count($path) - 1 || $force_output) { $ret = $controller->getContents(); } else { if (method_exists($controller, $path[$i + 1])) { $controller_class = new ReflectionClass($controller_name); $method = $controller_class->GetMethod($path[$i + 1]); $ret = $method->invoke($controller, array_slice($path, $i + 2)); } else { $ret = "<h2>Error</h2> Method does not exist. [" . $path[$i + 1] . "]"; } } if (is_array($ret)) { $t = new TemplateEngine(); $t->assign('controller_path', $controller_path); $t->assign($ret["data"]); $controller->content = $t->fetch(isset($ret["template"]) ? $ret["template"] : $path[$i + 1] . ".tpl"); } else { if (is_string($ret)) { $controller->content = $ret; } } } return $controller; }
/** * * @param string $filename */ public function uploadBulk($filename) { // Open file if (!stat($filename)) { throw new \Application\Exceptions\UnexpectedException("Error opening file {$filename}"); } $fd = fopen($filename, 'r'); $sep = \App_Parser_CsvParser::getCsvSeparator($fd); // Request $sims = array(); $validator = new SimBulkValidate(); $validHeaders = $this->getUploadBulkHeaders(); $filter = \Zend_Controller_Action_HelperBroker::getStaticHelper('FilterNotAllowedFields'); // CSV $header = fgetcsv($fd, 0, $sep); // Header $prows = 0; // Packet rows $irows = 1; // Iteration rows $nrows = 1; // Total rows $ncols = count($header); // Total columns $validH = false; foreach ($header as $h) { if (isset($validHeaders[$h])) { $validH = true; break; } } // Check lines readed if (!$validH) { \App::log()->debug("[UpdateBulk] No valid headers"); throw new ValidateException("No valid headers", ValidationCodes::FILE_NO_VALID_HEADERS); } if (in_array('locationManual_latitude', $header) && !in_array('locationManual_longitude', $header) || in_array('locationManual_longitude', $header) && !in_array('locationManual_latitude', $header)) { \App::log()->debug("[UpdateBulk] No valid headers: location requires latitude and longitude"); throw new ValidateException("No valid headers: location requires latitude and longitude", ValidationCodes::FILE_NO_VALID_HEADERS_LOCATION); } $bulkCount = \App::config('ericssonserviceCallItemCount', self::BULK_UPDATE_DEFAULT); // I'm not sure... I don't like it. set_time_limit(0); $watcher = $this->getMapper()->createFileWatcher(); $txId = uniqid("bulk"); $watcher->entityIds = array($txId); $watcher->params->action = "bulkSimUpdate"; WatcherService::getInstance()->create($watcher); $errors = array(); $warnings = array(); $ntxs = 0; // Rows while (($line = fgetcsv($fd, 0, $sep)) !== false) { // Next line has been readed $nrows++; // Check columns if (count($line) !== $ncols) { $errors[] = new Model\ErrorModel(array('line' => $nrows, 'description' => "Incorrect format (number of columns)", 'level' => Model\ErrorModel::ERROR_LEVEL_ERROR, 'code' => ValidationCodes::FILE_READING_ERR)); continue; } // Create sim $data = array(); foreach ($header as $key => $name) { // \App::log()->debug("[UpdateBulk] $name : $key"); if (!isset($validHeaders[$name])) { // Ignore invalid columns // \App::log()->warn("[UpdateBulk] Ignoring $name column"); continue; } $value = $line[$key]; if (preg_match('/^=\\"(?P<value>.*)\\"$/', $value, $matches)) { $value = $matches['value']; } // GLOBALPORTAL-28668 // if (!empty($value)) { // \App::log()->debug("[UpdateBulk] $name : $value"); if (isset($value) && (!empty($value) || is_numeric($value))) { // \App::log()->debug("[UpdateBulk] TRUE $name : $value"); // Remove field? // See SimBaseMapper _mapModelToEricssonModel method, // SimValidate and App_Validate_ReferenceIndex to understand it if ($value === '-' && $name !== 'staticIpApnIndex') { $value = ''; } // Process field if (strpos($name, 'apn_') !== false) { // In order to remove the current value of a SIM´s field, // the character - must be indicated $index = (int) substr($name, strlen('apn_apn')) - 1; $data['apns'][$index] = $value; } else { if (strpos($name, 'locationManual_') !== false) { $value = str_replace(',', '.', $value); if (!is_numeric($value)) { $warnings[] = new Model\ErrorModel(array('line' => $nrows, 'column' => $name, 'description' => "Invalid value", 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => ValidationCodes::INVALID_VALUE)); } else { $subname = substr($name, strlen('locationManual_')); $value = floatval(str_replace(',', '.', $value)); $data['locationManual'][$subname] = (int) round($value * pow(10, 6)); } } else { if ($name == 'LTE_status') { if ($value != SimModel::LTE_ACTIVE && $value != SimModel::LTE_INACTIVE) { $warnings[] = new Model\ErrorModel(array('line' => $nrows, 'column' => $name, 'description' => "Invalid value", 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => ValidationCodes::INVALID_VALUE)); } else { $data['lteEnabled'] = $value == SimModel::LTE_ACTIVE ? true : false; } } else { $data[$name] = $value; } } } } } // Create and validate sim $sim = new SimModel($data); $v = $this->validate($sim, false, $validator); if ($v === true) { // Backup id $ids = $sim->getIds(); $type = key($ids); $value = current($ids); //Inject organization $org = \App::getOrgUserLogged(); switch ($org->getType()) { case OrgMasterModel::ORG_TYPE: $sim->setMaster($org); break; case OrgServiceProviderModel::ORG_TYPE: $sim->setServiceProviderCommercial($org); $sim->setServiceProviderEnabler($org); break; case OrgCustomerModel::ORG_TYPE: $sim->setCustomer($org); break; case OrgAggregatorModel::ORG_TYPE: $sim->setAggregator($org); break; case OrgEndUserModel::ORG_TYPE: $sim->setEndUser($org); break; } // Filter by permissions $filter->direct('update_field', $sim); // Recover id and add sim to request $sim->{$type} = $value; $sims[] = $sim; $prows++; } else { \App::log()->warn("[UpdateBulk] Ignoring invalid sim: " . json_encode($v)); // Sending first validation error ONLY? foreach ($validator->getValidationCodes() as $field => $code) { $errors[] = new Model\ErrorModel(array('line' => $nrows, 'description' => $field, 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => $code ?: ValidationCodes::MODEL_SIM)); } } // Wait until packet is full if ($prows == $bulkCount) { // Send to Ericsson $this->_uploadBulk($sims, $errors, $irows, $nrows, $watcher); $ntxs++; // Reset packet list $sims = array(); $prows = 0; // Update CSV line position $irows = $nrows + 1; } } // Ensure all sims have been sent (last packet) if (!empty($sims)) { // Send to Ericsson $this->_uploadBulk($sims, $errors, $irows, $nrows, $watcher); $ntxs++; // Reset packet list (memory propouses) $sims = array(); } // Check lines readed if ($nrows < 2) { \App::log()->debug("[UpdateBulk] Ignoring empty file"); $watcher->delete(); throw new ValidateException("Missing file rows"); } $event = $this->getMapper()->constructEventToTransaction(); $event->entityId = $txId; // Add error code suffix if (isset($errors) && is_array($errors)) { foreach ($errors as $errMess) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; $errMess->code = \ErrorController::finishErrorCode($errMess->code); } } $eventData = array('simParsed' => $nrows - 1); if (!empty($errors) || !empty($warnings)) { $eventData['hasFailures'] = true; if (!empty($errors)) { $eventData['message']['failed'] = $errors; } if (!empty($warnings)) { $eventData['message']['warnings'] = $warnings; } } else { $eventData['hasFailures'] = false; } $event->eventData = $eventData; $compressor = new ErrorModelCompressEvent(); $compressor->compress($event); WatcherService::getInstance()->publishEvent($event); $nerr = count($errors); \App::audit("Bulk update ({$nrows} sims in {$ntxs} requests with {$nerr} errors)", null); return $watcher->reload(); }
public function __call($name, $arguments) { $errorController = new \ErrorController(); $errorController->error("404 unknown method {$name}"); }
private static function setRoute() { $controller = isset($_GET['c']) ? $_GET['c'] : "Index"; $controller .= 'Controller'; $action = isset($_GET['a']) ? $_GET['a'] : "index"; $action .= "Action"; define('CONTROLLER', $controller); define('ACTION', $action); if (class_exists($controller)) { $object = new $controller(); if (!method_exists($object, $action)) { $objects = new ErrorController(); if (method_exists($objects, 'emptyAction') && !DEBUG) { $objects->emptyAction(); } else { halt($controller . '控制器中,' . $action . '方法不存在'); } } else { $object->{$action}(); } } else { $object = new ErrorController(); $object->indexAction(); } }
require_once BASE_DIR . '/vendor/Slim/Slim/Slim.php'; require_once BASE_DIR . '/vendor/Slim-Extras/Log Writers/TimestampLogFileWriter.php'; $app = new Slim(array('mode' => defined('PRODUCTION') ? 'production' : 'development', 'debug' => false, 'log.enabled' => true, 'log.writer' => new TimestampLogFileWriter(array('path' => BASE_DIR, 'name_format' => '\\s\\l\\i\\m\\_\\l\\o\\g')))); $app->configureMode('development', function () use($app) { $app->config(array('debug' => true)); }); $app->configureMode('production', function () use($app) { error_reporting(0); $app->notFound(function () use($app) { $page = new ErrorController(404); $page->render(); }); $app->error(function (Exception $e) use($app) { $app->response()->status(500); if (!$app->request()->isAjax()) { $page = new ErrorController(500); $page->render(); } $app->stop(); if (file_exists(BASE_DIR . '/.gbemail')) { foreach (explode('\\n', file_get_contents(BASE_DIR . '/.gbemail')) as $email) { mail(trim($email), "GetchaBooks Error", get_error_message($e)); } } }); }); $app->hook('slim.before', function () use($app) { global $referrers; $request = $app->request(); define('BASE_URL', $request->getUrl() . $request->getRootUri() . '/'); define('CURRENT_URL', $request->getUrl() . $request->getPath());
$front = Pfw_Controller_Front::getInstance(); $front->getRouter()->setRoutes($_pfw_routes)->setModules($_pfw_modules); $four_oh_four = false; try { $front->dispatch(); } catch (Pfw_Exception_System $e) { $e->emitLog(); if ($_ENVIRONMENT == "development") { objp($e); exit; } $four_oh_four = true; } catch (Pfw_Exception_User $e) { $e->emitLog(); if ($_ENVIRONMENT == "development") { objp($e); exit; } $four_oh_four = true; } catch (Exception $e) { if ($_ENVIRONMENT == "development") { objp($e); exit; } $four_oh_four = true; } if ($four_oh_four) { Pfw_Loader::loadController('ErrorController'); $c = new ErrorController(); $c->fourohfourAction(); }
<?php define('SITE_PATH', realpath(dirname(__FILE__)) . '/'); // Require necessary files require_once SITE_PATH . 'application/Request.php'; require_once SITE_PATH . 'application/Router.php'; require_once SITE_PATH . 'application/BaseController.php'; require_once SITE_PATH . 'application/BaseModel.php'; require_once SITE_PATH . 'application/Load.php'; require_once SITE_PATH . 'application/Registry.php'; require_once SITE_PATH . 'controllers/ErrorController.php'; try { Router::route(new Request()); } catch (Exception $e) { $controller = new ErrorController(); $controller->error($e->getMessage()); }