/trasweb/common/helpers/Debug.class.php
PHP | 395 lines | 193 code | 66 blank | 136 comment | 20 complexity | 1fd3d529d4a2f0655c933975c6732a3c MD5 | raw file
Possible License(s): BSD-3-Clause
- <?php
- /**
- New Licence bsd:
- Copyright (c) <2012>, Manuel Jesus Canga Muñoz
- All rights reserved.
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- * Neither the name of the Trasweb.net nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL Manuel Jesus Canga Muñoz BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- /** ******************************************************************************
- Class for debugging, of course.
- @package util
- ******************************************************************************** */
- error_reporting(E_ALL ^E_NOTICE); /** Activamos los errores. Ninguno: error_reporting(0) */
- class Debug
- {
-
- public static function __initialize() {
- \config\Debug::load();
- }
- private function __construct() { /* prohibida instanciar una clase */ }
-
- //Obtenemos la fila y linea desde donde se hizo debug
- public static function getFileLine(&$_file, &$_line) {
- if( NULL == $_file && NULL == $_line ) {
- $backtrace = debug_backtrace();
- $_file = $backtrace[1]["file"];
- $_line = $backtrace[1]["line"];
- }
-
-
- }
-
- //Load debug function & class
- public static function load() {
- if(!function_exists("Debug") ) {
- function Debug($_var = NULL, $_label = NULL, $_file = NULL, $_line = NULL) {
- \Debug::getFileLine($_file, $_line);
-
- \Debug::info($_var, $_label, $_file, $_line);
- }
- }
- }
- /**
- Creamos una traza de depuracion
- */
- public static function info($_var, $_label = false, $_file = null, $_line = null) {
- self::getFileLine($_file, $_line);
- if(!SHOW_ERRORS) {
- self::log($_var, $_label, $_file, $_line);
- }else {
- self::display($_var, $_label, $_file, $_line);
- }
- }
- /**
- Visualizamos el valor de una variable, metidos en una tabla con borde
- @param $_var es la variable que se visualizará
- @param $_label texto que aparecerá antes del valor de la variable.
- TODO: Hacer una visualización más bonita.
- */
- public static function display( $_var, $_label = false, $_file = null, $_line = null) {
- self::getFileLine($_file, $_line);
- self::formatDisplay($_var, $_label, $_file, $_line);
- }
-
- private static function formatDisplay( $_var, $_label, $_file, $_line) {
-
- echo '<div style="border: 2px solid #008000; background-color: #FAFFF6; color: black; padding: 15px; margin: 7px; border-radius: 7px; font-family: Verdana; font-size: 14px; ">';
- if($_label)
- echo "<p><strong>$_label</strong>:</p>";
- if(is_array($_var) ) {
- echo '<pre>';
- echo var_export($_var);
- echo '</pre>';
- } else if( is_object($_var) ) {
- echo "<p><strong>Class: ".get_class($_var).":</strong></p>";
- }else {
- echo $_var;
- }
- if(null != $_file && null != $_line) {
- echo "<div align='right' style='font-size: 11px;font-weight: bold; margin: 8px 0 -8px 0;'>{$_file}: {$_line}</div>";
- }
-
- echo '</div>';
- }
- /**
- Permite visualizar una traza en un archivo log
- */
- public static function log($_var, $_label = false, $_file = null, $_line = null) {
- if(\LOGS_WRITE) {
- self::getFileLine($_file, $_line);
- Log::insertLog("debug", $_var, "<strong> $_label", $_file, $_file );
- }
- }
- /**
- @name constants
- @param $_label texto que aparecerá antes de la visualizción de constantes
- Visualizamos el valor de las constantes definidas por nosotros(user)
- */
- public static function constants($_label = "Constants")
- {
- $backtrace = debug_backtrace();
- $_constants = get_defined_constants(true);
- self::info($_constants["user"], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name functions
- @param $_label Texto etiqueta que aparecerá junto a la información
- Visualizamos las funciones definidas por nosotros(user)
- */
- public static function functions($_label = "Functions")
- {
- $backtrace = debug_backtrace();
-
- $_functrions = get_defined_functions();
- self::info($_functrions[user], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name infoObject
- @param $_obj objeto del que queremos obtener la información
- @param $_label Texto etiqueta que aparecerá junto a la información
- Mostramos la información sobre un object
- */
- public static function infoObject(& $_obj)
- {
- $backtrace = debug_backtrace();
-
- $_attrs = get_object_vars($_obj);
- // var_dump($_obj);
- $_class = get_class( $_obj );
- self::info($_attrs, "Atributos de la clase $_class", $backtrace[0]["file"], $backtrace[0]["line"]);
- $_methods = get_class_methods($_obj);
- self::info($_methods, "Methods of $_class", $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name vars
- @param $_label Texto etiqueta que aparecerá junto a la información
- Visualizamos las variables definidas por nosotros(user)
- */
- public static function vars($_label = false)
- {
- $backtrace = debug_backtrace();
- $_variables = get_defined_vars();
- self::info($_variables[user], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name params
- Visualizamos los parametros $_GET, $_POST, $_FILES y $_SESSION
- */
- public static function params()
- {
- self::info($_GET, 'GET VARS');
- self::info($_POST, 'POST VARS');
- self::info($_FILES, 'FILES VARS');
- self::info($_SESSION, 'SESSION VARS');
- }
- /**
- @name args
- Esta función sirve de guía. Visualiza los parametros con los que se ha llamado a una funcion.
- Para usar copiar y pegar el texto " Debug::display(func_get_args() );" dentro de la función
- de la que queramos información sobre los parámetros.
- */
- public static function args($_arg)
- {
- //Esta función hay que usarla como Debug::display(func_get_args() );
- self::info($_arg );
- }
-
- public static function origin($_msg = NULL, $_label = NULL) {
- $backtrace = debug_backtrace();
- $file = $backtrace[1]["file"];
- $line = $backtrace[1]["line"];
- self::info($_msg, $_label, $fie, $line);
- }
- /**
- @name trace
- @param $_label Texto etiqueta que aparecerá junto a la información
- Hacemos una traza hacia atrás de nuestro script
- */
- public static function trace($_label = "Trace")
- {
- $backtrace = debug_backtrace();
- self::info($backtrace, $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name allTrace
- @param $_label Texto etiqueta que aparecerá junto a la información
- Hacemos una traza hacia atrás, en modo extendido, de nuestro script
- */
- public static function allTrace($_label = "AllTrace")
- {
-
- $backtrace = debug_backtrace();
- self::info(debug_backtrace(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @name cronos
- @param $_op =reset(pone a 0 el cronometro), =stop(pone en marcha el cronómetro ),
- =start(O empezamos el cronómetro o continuamos si ya estaba parado )
- @param $_display =true( visualiza el tiempo) =false( no lo visualiza )
- Función cronómetro para calculos de tiempos(en microsegundos )
- */
- public static function cronos($_op = "start", $_display = 0)
- {
- $backtrace = debug_backtrace();
- static $start = 0; //Especifica el tiempo en que se empezó el conteo.
- static $time = 0; //Especifica el tiempo actual, si esta parado ( = 0 ) o en marcha( != 0 )
- switch($_op)
- {
- //Ponemos el cronómetro a 0
- case "reset": $time = 0; $start = 0; break;
- //Parámos el cronómetro.
- case "stop":
- if($start) $time = ($start)? microtime(true) - $start: 0;
- $start = 0;
- break;
- //O empezamos el cronómetro o continuamos(si ya estaba antes parado ).
- case "start":
- default:
- if($time != 0) {
- $start = microtime(true) - $time;
- $time = 0;
- }else {
- $start = microtime(true);
- }
- }
- //Toca ver el tiempo, o devolverlo. (pasándolo antes a una numeración más clara )
- if($_display)
- Debug::display($time*10000, $_op, $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- else
- return $time*10000;
- }
- /**
- @TODO: Ahora mismo no funciona, pero habria que habilitarlo
- @param $_label Texto etiqueta que aparecerá junto a la información
- Visualizamos todas las variables que hemos mandado a smarty
- */
- public static function varSmarty($_label = false)
- {
- global $web;
-
- $backtrace = debug_backtrace();
- self::info($web->get_template_vars(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @TODO: Ahora mismo no funciona, pero habria que habilitarlo
- Mostramos popup de información de smarty
- */
- public static function infoSmarty()
- {
- global $web;
- $web->debugging = true;
- }
- /**
- Visualizamos toda la información disponible sobre el sistema que estamos utilizando.
- */
- public static function infoWeb()
- {
- phpinfo();
- }
- /**
- @param $_text es el texto a buscar en los archivos.
- Look for $_text in all file from working directory
- */
- public static function grep($_text = "Trasweb")
- {
- $backtrace = debug_backtrace();
- $label = "Grep {$_text} ";
-
- exec("grep -iR ".escapeshellarg($_text)." ".PATH, $_out);
- self::info($_out, $label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @param $_find texto a buscar
- @param $_replace texto a remplazar por $_find
- @param $_archives es el patrón de archivos en los que se buscara y reemplazara $_find
- @param $_path es el directorio a partir del cual se buscará el texto
- Find word $_find and replace it for $_replace in $_archives with path $_path
- VERY DANGEROUS
- */
- public static function findReplace($_find = NULL, $_replace= NULL, $_archives = "*" , $_path = PATH )
- {
-
- $backtrace = debug_backtrace();
- $label = " Replace {$_find} / {$_replace} ";
- if(strlen($_find) > 4) {
- $_cmd = "find $_path -name ".escapeshellarg($_archives)." -type f -exec sed -i 's/$_find/$_replace/g' {} \;";
- exec($_cmd, $_salida);
- self::info($_cmd, $label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }else{
- self::info("<p>Interrumpido 'Buscar y reemplazar'.</p><p>Por seguridad es necesario buscar por una palabra de más de 4 letras</p>",$label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- }
- /**
- @param $_label Texto etiqueta que aparecerá junto a la información
- Visualizamos todos los errores ocasionados del uso del cms
- */
- public static function notices($_label = "Notices")
- {
-
- $backtrace = debug_backtrace();
- self::info(Notice::get(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- @param $_label Texto etiqueta que aparecerá junto a la información
- Visualizamos todos los errores, avisos, informaciones, ocasionados del uso del cms
- */
- public static function allNotices($_label = "All Notices" )
- {
- $backtrace = debug_backtrace();
- self::info(Notice::all(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- /**
- Muestra información de la consulta sql realizada
- @TODO: Ahora no funciona pero deberiamos de arreglarlo
- */
- public static function sql($_label = "Last")
- {
- $backtrace = debug_backtrace();
- $result = \DB::getResult();
- $rows = \DB::getRows();
- $id = \DB::getLastId();
- self::info(DB::getLastSql()."| Result: {$result} | Rows Affected {$rows} | id : {$id} ", $_label." sql", $backtrace[0]["file"], $backtrace[0]["line"]);
- self::info(DB::getLastRows(), $_label." rows", $backtrace[0]["file"], $backtrace[0]["line"]);
- }
- }