コード例 #1
0
ファイル: Settings.php プロジェクト: foreverphp/framework
 /**
  * Obtiene o crea la instancia singleton de Settings.
  *
  * @return \ForeverPHP\Core\Settings
  */
 public static function getInstance()
 {
     if (is_null(static::$instance)) {
         static::$instance = new static();
         static::$instance->load();
     }
     return static::$instance;
 }
コード例 #2
0
 private function sessionStart()
 {
     session_name(Settings::getInstance()->get('sessionName'));
     if (!$this->isSessionStarted()) {
         session_start();
     }
 }
コード例 #3
0
ファイル: SQLSRVEngine.php プロジェクト: foreverphp/framework
 public function connect()
 {
     $db = Settings::getInstance()->get('dbs');
     $db = $db[$this->dbSetting];
     $dbName = $this->database != false ? $this->database : $db['database'];
     $server = $db['server'] . ',' . $db['port'];
     $connectionInfo = array('UID' => $db['user'], 'PWD' => $db['password'], 'Database' => $dbName);
     // Me conecto a la base de datos
     $this->link = sqlsrv_connect($server, $connectionInfo);
     if (!$this->link) {
         $this->error = sqlsrv_errors();
         return false;
     }
     return true;
 }
コード例 #4
0
ファイル: Request.php プロジェクト: foreverphp/framework
 private function loadRequest()
 {
     $requestParams = null;
     if ($this->params == null) {
         $requestMethod = $_SERVER['REQUEST_METHOD'];
         $this->files = array();
         $this->params = array();
         if ($requestMethod == 'GET') {
             $this->method = 'get';
             $requestParams = $_GET;
         } elseif ($requestMethod == 'POST') {
             $this->method = 'post';
             $requestParams = $_POST;
         } elseif ($requestMethod == 'PUT' || $requestMethod == 'DELETE') {
             /*
              * PHP no tiene un método propiamente dicho para leer una petición PUT o DELETE,
              * por lo que se usa un "truco".
              * Leer el stream de entrada file_get_contents("php://input") que transfiere un
              * fichero a una cadena.
              * Con ello obtenemos una cadena de pares clave valor de variables
              * (variable1=dato1&variable2=data2...) que evidentemente tendremos que
              * transformarla a un array asociativo.
              */
             $requestContent = file_get_contents("php://input");
             parse_str($requestContent, $requestParams);
             if ($requestMethod == 'PUT') {
                 $this->method = 'put';
             } else {
                 $this->method = 'delete';
             }
         }
         // Verifica si hay archivos enviados
         if (count($_FILES) != 0) {
             foreach ($_FILES as $name => $value) {
                 $this->files[$name] = new RequestFile($value);
             }
         }
         foreach ($requestParams as $name => $value) {
             if ($name == 'csrfToken') {
                 // Almaceno el token CSRF para luego validarlo
                 Settings::getInstance()->set($name, $value);
             } else {
                 $this->params[$name] = $value;
             }
         }
     }
 }
コード例 #5
0
ファイル: MSSQLEngine.php プロジェクト: foreverphp/framework
 public function connect()
 {
     $db = Settings::getInstance()->get('dbs');
     $db = $db[$this->dbSetting];
     $dbName = $this->database != false ? $this->database : $db['database'];
     $server = $db['server'] . ':' . $db['port'];
     // Me conecto a la base de datos
     $this->link = mssql_pconnect($server, $db['user'], $db['password']);
     if (!$this->link) {
         $this->error = mssql_get_last_message();
         return false;
     }
     if (!mssql_select_db($dbName, $this->link)) {
         $this->error = mssql_get_last_message();
         return false;
     }
     return true;
 }
コード例 #6
0
ファイル: Mailer.php プロジェクト: foreverphp/framework
 public function send($to, $subject, $message, $from)
 {
     $this->to = $to;
     $this->subject = $subject;
     $this->message = $message;
     $this->from = $from;
     $this->mail = new PHPMailer();
     $settings = Settings::getInstance()->get('mail');
     $this->mail->isSMTP();
     $this->mail->Host = $settings['server'];
     $this->mail->Port = $settings['port'];
     if ($settings['smtpAuth']) {
         $this->mail->SMTPAuth = true;
         $this->mail->Username = $settings['username'];
         $this->mail->Password = $settings['password'];
         if ($settings['smtpSecure'] != 'none') {
             $this->mail->SMTPSecure = $settings['smtpSecure'];
         }
     }
     $this->mail->From = $this->from;
     $this->mail->FromName = $this->from;
     //$mail->addAddress('*****@*****.**', 'Joe User');
     $this->mail->addAddress($this->to);
     //$mail->addReplyTo('*****@*****.**', 'Information');
     //$mail->addCC('*****@*****.**');
     //$mail->addBCC('*****@*****.**');
     $this->mail->WordWrap = 50;
     //$mail->addAttachment('/var/tmp/file.tar.gz');
     //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
     $this->mail->isHTML(true);
     $this->mail->Subject = $this->subject;
     $this->mail->Body = $this->message;
     $this->mail->AltBody = $this->message;
     if (!$this->mail->send()) {
         $this->error = $this->mail->ErrorInfo;
         return false;
     }
     return true;
 }
コード例 #7
0
 public function connect()
 {
     $db = Settings::getInstance()->get('dbs');
     $db = $db[$this->dbSetting];
     $dbName = $this->database != false ? $this->database : $db['database'];
     $socket = false;
     if ($db['usingSocket']) {
         $socket = $db['socket'];
     }
     // Me conecto a la base de datos
     if (!$socket) {
         $this->link = mysqli_connect($db['server'], $db['user'], $db['password'], $dbName, $db['port']);
     } else {
         $this->link = mysqli_connect($db['server'], $db['user'], $db['password'], $dbName, $db['port'], $socket);
     }
     if (mysqli_connect_errno()) {
         $this->errno = mysqli_errno($this->link);
         $this->error = mysqli_connect_error();
         return false;
     }
     return true;
 }
コード例 #8
0
 /**
  * Manipulador de errores, por ejemplo para controlar
  * errores fatales (E_ERROR).
  *
  * @param  int    $errno
  * @param  string $errstr
  * @param  string $errfile
  * @param  int    $errline
  * @return void
  */
 public static function errorHandler($errno, $errstr, $errfile, $errline)
 {
     /*
      * Si la configuración "debugHideNotices" existe, indica si se
      * muestran o no los errores de tipo E_NOTICE.
      */
     if (Settings::getInstance()->exists('debugHideNotices')) {
         if ($errno == E_NOTICE && Settings::getInstance()->get('debugHideNotices')) {
             return;
         }
     }
     switch ($errno) {
         case E_ERROR:
             // 1
             $type = 'E_ERROR';
             break;
         case E_WARNING:
             // 2
             $type = 'E_WARNING';
             break;
         case E_PARSE:
             // 4
             $type = 'E_PARSE';
             break;
         case E_NOTICE:
             // 8
             $type = 'E_NOTICE';
             break;
         case E_CORE_ERROR:
             // 16
             $type = 'E_CORE_ERROR';
             break;
         case E_CORE_WARNING:
             // 32
             $type = 'E_CORE_WARNING';
             break;
         case E_COMPILE_ERROR:
             // 64
             $type = 'E_COMPILE_ERROR';
             break;
         case E_CORE_WARNING:
             // 128
             $type = 'E_COMPILE_WARNING';
             break;
         case E_USER_ERROR:
             // 256
             $type = 'E_USER_ERROR';
             break;
         case E_USER_WARNING:
             // 512
             $type = 'E_USER_WARNING';
             break;
         case E_USER_NOTICE:
             // 1024
             $type = 'E_USER_NOTICE';
             break;
         case E_STRICT:
             // 2048
             $type = 'E_STRICT';
             break;
         case E_RECOVERABLE_ERROR:
             // 4096
             $type = 'E_RECOVERABLE_ERROR';
             break;
         case E_DEPRECATED:
             // 8192
             $type = 'E_DEPRECATED';
             break;
         case E_USER_DEPRECATED:
             // 16384
             $type = 'E_USER_DEPRECATED';
             break;
     }
     array_push(static::$errors, array('type' => $type, 'message' => $errstr, 'file' => $errfile, 'line' => $errline));
 }
コード例 #9
0
ファイル: QuerySQL.php プロジェクト: foreverphp/framework
 public function execute($returnType = 'array')
 {
     $this->dbInstance = null;
     $this->hasError = false;
     $this->errno = 0;
     $this->error = '';
     $return = false;
     // Obtengo la configuracion de la base de datos a utilizar
     $selectDb = Settings::getInstance()->get('dbs');
     $selectDb[$this->dbSetting];
     $dbEngine = $selectDb[$this->dbSetting]['engine'];
     if ($dbEngine == 'mariadb') {
         $this->dbInstance = new namespace\SQLEngines\MariaDBEngine($this->dbSetting);
     } elseif ($dbEngine == 'mssql') {
         $this->dbInstance = new namespace\SQLEngines\MSSQLEngine($this->dbSetting);
     } elseif ($dbEngine == 'postgresql') {
         $this->dbInstance = new namespace\SQLEngines\PostgreSQLEngine($this->dbSetting);
     } elseif ($dbEngine == 'sqlsrv') {
         $this->dbInstance = new namespace\SQLEngines\SQLSRVEngine($this->dbSetting);
     } else {
         $this->error = 'Database engine not found.';
     }
     if ($this->dbInstance != null) {
         if ($this->database != false) {
             $this->dbInstance->selectDatabase($this->database);
         }
         // Me conecto al motor de datos
         if ($this->dbInstance->connect()) {
             $this->dbInstance->query($this->query, $this->queryType, $this->queryReturn == 'object' ? 'assoc' : $this->queryReturn);
             $this->dbInstance->setParameters($this->parameters);
             if ($result = $this->dbInstance->execute()) {
                 if (lower($returnType) == 'json') {
                     $return = json_encode($result, JSON_FORCE_OBJECT);
                 } else {
                     if ($this->queryReturn == 'object') {
                         // object
                         //$return = (object)$result;
                         $return = json_decode(json_encode($result));
                     } else {
                         // array
                         $return = $result;
                     }
                 }
             }
             // Me desconecto
             $this->dbInstance->disconnect();
         }
         // Recupera el ultimo error ocurrido en el motor de datos
         $this->errno = $this->dbInstance->getErrorNumber();
         $this->error = $this->dbInstance->getError();
         if (!empty($this->error)) {
             $this->hasError = true;
             $return = false;
         }
     }
     // Se limpian las variables
     $this->dbInstance = null;
     $this->parameters = array();
     $this->query = '';
     $this->queryType = 'select';
     $this->queryReturn = 'num';
     return $return;
 }
コード例 #10
0
ファイル: HtmlResponse.php プロジェクト: foreverphp/framework
 public function make()
 {
     $data = array();
     // Valido el token CSRF, el cual solo esta disponible en GET o POST
     //if (Settings::getInstance()->inDebug()) {
     if (Settings::getInstance()->exists('csrfToken')) {
         if (!CSRF::validateToken()) {
             throw new SecurityException('Access denied, invalid token. It becomes impossible to process your request to start or close this page.');
         }
     }
     /*} else {
           Redirect::toError(500);
       }*/
     // Obtienen los contextos
     $data = Context::all();
     // Se limpian los contextos
     Context::removeAll();
     // Valida si el render solo esta disponible en DEBUG
     //if ($only_debug) {
     //    Router::redirectToError(500);
     //} else {
     $tplEngine = Settings::getInstance()->get('templateEngine');
     if ($tplEngine == 'chameleon') {
         $tpl = new Chameleon();
     }
     // Comienza la captura del buffer de salida
     ob_start();
     // Se construye la ruta del template
     $templatesDir = '';
     $staticDir = '';
     $templatePath = '';
     $appAndTemplate = null;
     // Se definen las rutas de los templates y de los archivos estaticos
     if (Settings::getInstance()->get('ForeverPHPTemplate')) {
         // Se usaran templates de foreverPHP
         $templatesDir = FOREVERPHP_TEMPLATES_PATH;
         $staticDir = str_replace(DS, '/', FOREVERPHP_STATIC_PATH);
     } else {
         $templatesDir = TEMPLATES_PATH;
         $staticDir = str_replace(DS, '/', STATIC_PATH);
     }
     $tpl->setTemplatesDir($templatesDir);
     // Verifica si el template maneja aplicacion diferente y subdirectorios
     if (strpos($this->template, '@')) {
         $appAndTemplate = explode('@', $this->template);
     }
     if ($appAndTemplate != null) {
         $templatesDir = APPS_ROOT . DS . $appAndTemplate[0] . DS . 'Templates' . DS;
         $this->template = $appAndTemplate[1];
     }
     $subdirectories = explode('.', $this->template);
     $totalSubdirectories = count($subdirectories);
     if ($totalSubdirectories > 1) {
         $this->template = $subdirectories[$totalSubdirectories - 1];
         array_pop($subdirectories);
         foreach ($subdirectories as $subdirectory) {
             $templatesDir .= $subdirectory . DS;
         }
     } else {
         $this->template = $subdirectories[0];
     }
     // Se define la ruta del template
     $templatePath = $templatesDir . $this->template;
     // Le indico al motor de templates la ruta de los archivos estaticos
     $tpl->setStaticDir($staticDir);
     // Renderea el template
     echo $tpl->render($templatePath, $data);
     /*
      * Aca se controla el cache de templates.
      */
     if (ob_get_length() > 0) {
         if ($this->usingCache) {
             // Obtiene el contenido del template renderizado
             $cacheValue = ob_get_contents();
             // POR AHORA SOLO GUARDA EL CACHE PARA PRUEBAS NO VALIDA DURACION, NI SI EXISTE
             // Guarda el template en el cache
             Cache::set($this->template . '.template.cache', $cacheValue);
         }
     }
     //}
     // Rendereo el template
     //echo $this->_template->render($template, $data);
     /*
      * Guardo en la configuracion el estado de la vista para evitar
      * conflictos, por ejemplo intentar acceder a la session despues de
      * haber rendereado.
      */
     // NOTA: al paracer esto ya no es necesario, validar despues
     Settings::getInstance()->set('viewState', 'render_ok');
 }
コード例 #11
0
ファイル: start.php プロジェクト: foreverphp/foreverphp
if (Settings::getInstance()->inDebug()) {
    error_reporting(-1);
}
/*
 * Deshabilita la salida de errores por pantalla.
 */
ini_set('display_errors', 0);
/*
 * Configura la zona horaria.
 */
date_default_timezone_set(Settings::getInstance()->get('timezone'));
/*
 * Carga los alias.
 * Los alias de clases se definen en el archivo de configuraciones 'settings.php'.
 */
$aliases = Settings::getInstance()->get('aliases');
AliasLoader::getInstance($aliases)->register();
/*
 * Inicializa los requerimientos de ejecución.
 */
Setup::initialize();
/*
 * Carga las rutas.
 */
$routes = APPS_ROOT . '/routes.php';
if (file_exists($routes)) {
    require $routes;
}
/*
 * Todos los objeto propios del framework deberian validad que este define
 * exista de no ser haci es un ataque y se debe matar la ejecucion.
コード例 #12
0
ファイル: Settings.php プロジェクト: foreverphp/framework
 /**
  * Obtiene el nombre registrado del componente o una instancia de el.
  *
  * @return mixed
  */
 protected static function getComponent()
 {
     return \ForeverPHP\Core\Settings::getInstance();
 }
コード例 #13
0
ファイル: Chameleon.php プロジェクト: foreverphp/framework
 /**
  * Realiza el rendereo del template.
  *
  * @param  string $template Nombre del template a compilar.
  * @param  array  $data     Matriz de datos a conbinar con el template.
  * @return string           Retorna el texto HTML ya procesado.
  */
 public function render($template, $data)
 {
     $tplReady = '';
     $this->template = $template;
     $this->data = $data;
     if ($this->loadTemplate()) {
         $tplReady = $this->dataRender;
     }
     // Se verifica si hay que minificar el resultado
     if (Settings::getInstance()->get('minifyTemplate') && !Settings::getInstance()->inDebug()) {
         $tplReady = $this->minify($tplReady);
     }
     $this->release();
     return $tplReady;
 }
コード例 #14
0
ファイル: App.php プロジェクト: foreverphp/framework
 /**
  * Ejecuta la vista solicitada.
  *
  * @param  mixed $route
  * @return void
  */
 public function run($route)
 {
     if (!is_array($route)) {
         $this->makeResponse($route);
     }
     // Se separa la vista por ".", si es que la vista esta en subcarpetas
     // NOTA: En ForeverPHP los niveles de directorios se separan por "."
     $viewSegments = explode('.', $route['view']);
     // Nombre del metodo a ejecutar
     $method = $route['method'];
     Setup::toDefine('TEMPLATES_PATH', APPS_ROOT . DS . $this->appName . DS . 'Templates' . DS);
     Setup::toDefine('STATIC_PATH', APPS_ROOT . DS . 'static' . DS);
     $viewPath = '';
     $view = $viewSegments[0];
     if (count($viewSegments) > 1) {
         $view = $viewSegments[count($viewSegments) - 1];
         // Se elimina el ultimo segmento de la vista, que es el nombre del archivo vista
         array_pop($viewSegments);
         // Se unen los segmentos de la vista con el separador de nombres de espacio
         $viewPath = implode('\\', $viewSegments);
         $viewPath .= '\\';
     }
     // Verifico que la vista hereda de View
     if ($view instanceof \ForeverPHP\View\View) {
         throw new ViewException("La vista ({$view}) no hereda de View.");
     }
     // Creo la vista y la ejecuto y le asigno el request a la vista para manipulacion interna
     if (Settings::getInstance()->get('usingNamespaces')) {
         $view = '\\Apps\\' . $this->appName . '\\Views\\' . $viewPath . $view;
     }
     $v = new $view();
     // Ejecuta la funcion y almacena su valor de retorno
     $returnValue = $v->{$method}();
     // Se construye la respuesta
     $this->makeResponse($returnValue);
 }