/**
      * INDEX PRINCIPAL SU RUTA ES :
      * 
      *    $route['0']  = 'dashboard/index';
      *    $route['0/([a-z_-]+)' 
     .                   system_token() 
     .                   '([a-z_-]+)'] = 'dashboard/index/$1=$2';
      * 
      * 
      * VERSION 1.5.5
      * 
      *          IMPLEMENTACION DE RUTAS ... O PRETTY ROUTES
      * 
      * 
      * **/
 public function index($model = NULL)
 {
     error_reporting(0);
     //reporte de errores reportar todos los errores
     ob_start();
     //bufer de salida inicio
     /**
      * Documentacion acerca la logica del sistema dashboard/index 
      * 
      *  Rutas en las cuales se utilizaran: 
      *  $route['0/([a-z_-]+)=([a-z_-]+)']   = 'dashboard/index/$1=$2';
      *  $route['0']                         = 'dashboard/index';
      * 
      *  Esta funcion realiza lo que es el paradigma MVA (modelo vista adaptador)
      *  El controlador que estamos refiriendo lo transformaremos en adaptador
      * 
      *  las instrucciones que pasan por el filtro son las siguientes:
      * 
      *          patron : directorio/model == directorio=model == direcrorio(token)model
      *          patron : model == model 
      *  
      *  el primer patron es el mas importante ya que realiza una jerarquia 
      *          primer nivel : directorio (donde alojas el model)
      *          segundo nivel: model (nombre del modelo) 
      * 
      *   ejemplo : usuario=user_name / usuario = directorio / user_name = model
      * 
      */
     $init_time = $this->GetTime();
     //INTRODUCIDO EN LA VERSION 1.5.6
     $this->load->model("dashboard/main", "main");
     //verifica si existe una conexion a internet ,
     //en dado caso no exista tira el error
     $conection = internet_conection();
     if (!$conection) {
         $this->main->_500(array("route" => site_url()));
         return;
     }
     //verifica si existe un bloqueo de sesion
     if (isset($_SESSION['block'])) {
         if ($this->session->block == TRUE) {
             redirect("/block");
             return;
         }
     }
     /*
      * ESTABLECEMOS LOS NOMBRES DE LOS OBJETOS PARA LAS FUNCIONES 
      * DENTRO DEL HEADER , FOOTER ETC...
      * 
      * HAY QUE RECORDAR QUE EL MVA NECESITA UNAS VARAIBLES PREDEFINIDAS
      * LA VENTAJA QUE HOY SE PODRA ESTABLECER UN NOMBRE DISTINTA A ESAS VARIABLES
      * 
      * VERSION 1.5.7
      * **/
     //OBJETOS PREDEFINIDOS
     //SI LAS VARIABLES CAMBIAN SU NOMBRE CAMBIAR SU VALOR
     $this->main->SetObject("route", "route")->SetObject("styles", "styles")->SetObject("user", "user_data")->SetObject("ajax", "js_loader")->SetObject("javascript", "javascript")->SetObject("title", "title")->SetObject("stopwatch", "ttl");
     /***
      *  objetos que no son del todo necesario
      *  por ejemplo son objetos que dependen del view y del template
      * ****/
     $this->main->SetObject("copen", "open_container");
     $this->main->SetObject("cclose", "close_container");
     /**
      * 
      * Importante 
      * 
      * $vars :
      *          arreglo que contiene datos especificos que cargara 
      *          en todas las vistas , si se agrega un nuevo dato o parametro
      *          la variable de arreglo se encargara de cargarlo a la vista
      * **/
     $object = $this->main->GetObject();
     $vars = array($object->route => $this->base_url->GetBaseUrl(), $object->user => $this->user_p, $object->copen => '<div class="page-container">', $object->cclose => '</div>');
     /**
      * Condicional :
      * 
      *          si el controlador no envia ningun dato entonces model = NULL
      *          carga el dashboard como por defecto.
      * 
      * **/
     if ($model === NULL || $model == $this->main->Route()) {
         //Libreria agregada en version 1.5.4
         //DEPRECADA 1.5.6
         //$this->load->library("dashboard_system");
         /**
          * DASHBOARD SE HA TRANSFORMADO TIPO INTERFAZ PERO 
          * CON CIERTAS LIMITACIONES EN ELLA. SE AGREGO LA FUNCIONES 
          * QUE PERMITE AGREGAR MAS CSS , TITULO Y CARGA EN JAVASCRIPT 
          * ***/
         //VERSION 1.5.6
         $vars[$object->styles] = $this->main->CSS();
         $vars[$object->title] = $this->main->TITLE();
         //INICIAMOS EL HEADER VERSION 1.5.6
         $this->main->Header($vars);
         //INICIAMOS LOS COMPLEMENTOS ANTES DEL MAIN EJEMPLO UN SIDEBAR
         $this->main->Complements($vars);
         //$(document).ready() JAVASCRIPT CARGAS
         $vars[$object->ajax] = $this->main->JS();
         //MAIN DEL DASHBOARD
         $this->main->Main($vars);
         //TTL O CRONOMETRO
         $ttl = round($this->GetTime() - $init_time, 6);
         $vars[$object->stopwatch] = $ttl;
         //VISTA DEL FOOTER
         $this->main->Footer($vars);
     } else {
         //DIVIDIMOS EN PARTES LA RUTA POR MEDIO DEL TOKEN ASIGNADO
         //OBTENEMOS LA RUTA SEGUN EL VALOR DEL MODEL
         //VERSION 1.5.5
         $MVA_ROUTES = $this->routes->Get($model);
         // DECLARAMOS PARTS COMO NULL
         $parts = NULL;
         /***
          * PEQUEÑO CODIGO QUE VERIFICA SI EXISTE LA 
          * RUTA EN DADO CASO NO ES UNA RUTA Y ES UN MVA
          * VERSION 1.5.5
          * **/
         $cluser = function () use(&$MVA_ROUTES, &$model, &$parts) {
             $parts = !is_null($MVA_ROUTES) ? explode(system_token(), $MVA_ROUTES[$model]) : explode(system_token(), $model);
         };
         $cluser();
         try {
             //AGREGAMOS EL NOMBRE DEL MODEL ACTUAL
             $model = sizeof($parts) == 1 ? $parts[0] : $parts[1];
             //ALGORITMO CAMBIADO DESDE LA VERSION 1.5.7
             //BUG FIXED VERSION 1.5.8
             if (!check_model(sizeof($parts) == 1 ? array($parts[0]) : array($parts[0], $parts[1]))) {
                 $this->main->_404($vars);
                 return;
             }
             //DEVUELVE EL MODEL CARGADO SIENDO UN DIRECTORIO O NO
             $load_ = function () use(&$parts) {
                 $this->load->model(count($parts) == 1 ? $parts[0] : $parts[0] . "/" . $parts[1]);
             };
             //CARGAMOS LA FUNCION
             $load_();
         } catch (Exception $ex) {
             //CONTROL DE EXCEPCIONES
             trigger_error("Error Critico del sistema : " . $ex->getMessage());
             $this->main->_404($vars);
             return;
         }
         //OTRO NIVEL DE SEGURIDAD ...
         /**
          * como cada modelo que se carga necesita de una interfaz 
          * la interfaz esta desarrollada y agregada en interfaces 
          * se genera mediante un loader
          */
         //VERIFICAMOS SI SE IMPLEMENTA UNA INTERFAZ
         $class_implement = class_implements($this->{$model});
         if (sizeof($class_implement) == 0) {
             $this->main->_404($vars);
             return;
         }
         /**
          * Seguridad en los roles , quien ve el que ?
          *  ok : esta parte del codigo suele ser como que opcional 
          *       si el nivel de seguridad sea como de la udb 
          *  desarrollo:
          *        la interfaz _rols() se desarrolla con el fin 
          *        de limitar los accesos mediante obtencion de la url 
          *        la interfaz se puede programar de forma distinta siguien 
          *        patrones de diseño como un array() , string e incluso un db 
          */
         //VERIFICA LOS PRIVILEGIOS ACTIVOS ... SI DEVUELVE NULL ENTONCES LA URL ES PUBLICA ...
         $privs = $this->{$model}->_rols();
         $priv_flag = $this->system->VerifyPrivs($privs);
         //CONTROL DE PERMISOS SI NO EXISTEN ....
         if (!$priv_flag) {
             $this->main->Header($vars);
             $this->main->Complements($vars);
             $this->main->Priv($vars);
             $this->main->Footer($vars);
             return;
         }
         //DEPENDENCIAS DEL CSS
         $header_dependence = $this->{$model}->_css();
         if (!is_null($header_dependence)) {
             if (is_array($header_dependence)) {
                 $vars[$object->styles] = $header_dependence;
             } else {
                 $vars[$object->styles] = array($header_dependence);
             }
         }
         //TITULO DEL HEADER
         $vars[$object->title] = $this->{$model}->_title();
         //CARGA DE LAS VISTAS HEADER , SIDEBAR
         $this->main->Header($vars);
         $this->main->Complements($vars);
         //DEPENDENCIAS DEL JS
         $footer_dependencies = $this->{$model}->_js();
         //VERSION 1.1.0 -> 1.5.6
         if (!is_null($footer_dependencies)) {
             if (is_array($footer_dependencies)) {
                 $vars[$object->javascript] = $footer_dependencies;
             } else {
                 $vars[$object->javascript] = array($footer_dependencies);
             }
         }
         //TODO LO QUE CARGARA DENTRO DEL JQUERY.READY ...
         $javascript_loaders = $this->{$model}->_jsLoader();
         if (!is_null($javascript_loaders) && is_array($javascript_loaders)) {
             $vars[$object->ajax] = $javascript_loaders;
         }
         //INICIAMOS EL MODELO
         $this->{$model}->_init();
         //CARGAMOS EL FOOTER .. SOLO ESO FALTABA YEAH !!
         $ttl = round($this->GetTime() - $init_time, 6);
         $vars[$object->stopwatch] = $ttl;
         //EJECUTANDO LA VISTA DEL FOOTER
         $this->main->Footer($vars);
     }
     ob_end_flush();
     //bufer de salida
 }
 public function save()
 {
     $user = M('Users');
     $user->create();
     //如果不是管理员或者没有传id,则改自己的资料
     if (!isset($_POST['id']) || !$_SESSION['login_user']['is_admin']) {
         $user->id = $_SESSION['login_user']['id'];
     } else {
         $user->id = $_POST['id'];
     }
     if (!$_SESSION['login_user']['is_admin']) {
         $user->is_admin = 0;
     }
     if (!check_model()) {
         flash('您提交的内容中可能有不合适的地方,请重新编辑');
         $this->display('newUser');
     } else {
         $user->save();
         $result = $user->where(array('id' => $_SESSION['login_user']['id']))->find();
         if ($result) {
             $_SESSION['login_user'] = $result;
             flash('您的个人信息已修改成功!');
         } else {
             flash('信息更新失败');
         }
         $this->redirect('edit');
         //写好User/home后定位到该目标
     }
     $this->redirect('edit');
     //写好User/home后定位到该目标
 }
 public function insert()
 {
     $event_model = new EventsModel();
     $error_message = '';
     if (!$event_model->create()) {
         $error_message = '所填信息不完整';
     }
     if (!user()) {
         $error_message = '请先登录';
     }
     if (!check_model()) {
         flash('您提交的内容中可能有不合适的地方,请重新编辑');
     }
     if ($error_message != '') {
         $this->assign('event', $_POST);
         $this->assign('target_url', 'insert');
         flash($error_message);
         $this->display('add');
         return;
     }
     if (!isset($_POST['type'])) {
         $event_model->type = user('type');
     }
     //        $event_model->type = user('type');
     //        if(user('is_admin') && isset($_POST['type'])){
     //            $event_model->type = $_POST['type'];
     //        }
     //        print_r($_POST);die();
     // case: the admin want to assign this event to another person (rare)
     if ($_POST['creator'] && user('is_admin')) {
     } else {
         $event_model->user_id = user('id');
     }
     $this_id = $event_model->add();
     $event_model->create_tags($this_id);
     $event_model->create_image_records($this_id);
     $map_data_model = D('MapData');
     $map_data_model->invalidate_tile($_POST['longitute'], $_POST['latitude']);
     flash('事件已成功添加');
     $this->redirect('Event/view', array('id' => $this_id));
 }