PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/trasweb/common/helpers/Debug.class.php

https://bitbucket.org/trasweb/trasweb-framework
PHP | 395 lines | 193 code | 66 blank | 136 comment | 20 complexity | 1fd3d529d4a2f0655c933975c6732a3c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. New Licence bsd:
  4. Copyright (c) <2012>, Manuel Jesus Canga Muñoz
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. * Neither the name of the Trasweb.net nor the
  14. names of its contributors may be used to endorse or promote products
  15. derived from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL Manuel Jesus Canga Muñoz BE LIABLE FOR ANY
  20. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. /** ******************************************************************************
  28. Class for debugging, of course.
  29. @package util
  30. ******************************************************************************** */
  31. error_reporting(E_ALL ^E_NOTICE); /** Activamos los errores. Ninguno: error_reporting(0) */
  32. class Debug
  33. {
  34. public static function __initialize() {
  35. \config\Debug::load();
  36. }
  37. private function __construct() { /* prohibida instanciar una clase */ }
  38. //Obtenemos la fila y linea desde donde se hizo debug
  39. public static function getFileLine(&$_file, &$_line) {
  40. if( NULL == $_file && NULL == $_line ) {
  41. $backtrace = debug_backtrace();
  42. $_file = $backtrace[1]["file"];
  43. $_line = $backtrace[1]["line"];
  44. }
  45. }
  46. //Load debug function & class
  47. public static function load() {
  48. if(!function_exists("Debug") ) {
  49. function Debug($_var = NULL, $_label = NULL, $_file = NULL, $_line = NULL) {
  50. \Debug::getFileLine($_file, $_line);
  51. \Debug::info($_var, $_label, $_file, $_line);
  52. }
  53. }
  54. }
  55. /**
  56. Creamos una traza de depuracion
  57. */
  58. public static function info($_var, $_label = false, $_file = null, $_line = null) {
  59. self::getFileLine($_file, $_line);
  60. if(!SHOW_ERRORS) {
  61. self::log($_var, $_label, $_file, $_line);
  62. }else {
  63. self::display($_var, $_label, $_file, $_line);
  64. }
  65. }
  66. /**
  67. Visualizamos el valor de una variable, metidos en una tabla con borde
  68. @param $_var es la variable que se visualizará
  69. @param $_label texto que aparecerá antes del valor de la variable.
  70. TODO: Hacer una visualización más bonita.
  71. */
  72. public static function display( $_var, $_label = false, $_file = null, $_line = null) {
  73. self::getFileLine($_file, $_line);
  74. self::formatDisplay($_var, $_label, $_file, $_line);
  75. }
  76. private static function formatDisplay( $_var, $_label, $_file, $_line) {
  77. 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; ">';
  78. if($_label)
  79. echo "<p><strong>$_label</strong>:</p>";
  80. if(is_array($_var) ) {
  81. echo '<pre>';
  82. echo var_export($_var);
  83. echo '</pre>';
  84. } else if( is_object($_var) ) {
  85. echo "<p><strong>Class: ".get_class($_var).":</strong></p>";
  86. }else {
  87. echo $_var;
  88. }
  89. if(null != $_file && null != $_line) {
  90. echo "<div align='right' style='font-size: 11px;font-weight: bold; margin: 8px 0 -8px 0;'>{$_file}: {$_line}</div>";
  91. }
  92. echo '</div>';
  93. }
  94. /**
  95. Permite visualizar una traza en un archivo log
  96. */
  97. public static function log($_var, $_label = false, $_file = null, $_line = null) {
  98. if(\LOGS_WRITE) {
  99. self::getFileLine($_file, $_line);
  100. Log::insertLog("debug", $_var, "<strong> $_label", $_file, $_file );
  101. }
  102. }
  103. /**
  104. @name constants
  105. @param $_label texto que aparecerá antes de la visualizción de constantes
  106. Visualizamos el valor de las constantes definidas por nosotros(user)
  107. */
  108. public static function constants($_label = "Constants")
  109. {
  110. $backtrace = debug_backtrace();
  111. $_constants = get_defined_constants(true);
  112. self::info($_constants["user"], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  113. }
  114. /**
  115. @name functions
  116. @param $_label Texto etiqueta que aparecerá junto a la información
  117. Visualizamos las funciones definidas por nosotros(user)
  118. */
  119. public static function functions($_label = "Functions")
  120. {
  121. $backtrace = debug_backtrace();
  122. $_functrions = get_defined_functions();
  123. self::info($_functrions[user], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  124. }
  125. /**
  126. @name infoObject
  127. @param $_obj objeto del que queremos obtener la información
  128. @param $_label Texto etiqueta que aparecerá junto a la información
  129. Mostramos la información sobre un object
  130. */
  131. public static function infoObject(& $_obj)
  132. {
  133. $backtrace = debug_backtrace();
  134. $_attrs = get_object_vars($_obj);
  135. // var_dump($_obj);
  136. $_class = get_class( $_obj );
  137. self::info($_attrs, "Atributos de la clase $_class", $backtrace[0]["file"], $backtrace[0]["line"]);
  138. $_methods = get_class_methods($_obj);
  139. self::info($_methods, "Methods of $_class", $backtrace[0]["file"], $backtrace[0]["line"]);
  140. }
  141. /**
  142. @name vars
  143. @param $_label Texto etiqueta que aparecerá junto a la información
  144. Visualizamos las variables definidas por nosotros(user)
  145. */
  146. public static function vars($_label = false)
  147. {
  148. $backtrace = debug_backtrace();
  149. $_variables = get_defined_vars();
  150. self::info($_variables[user], $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  151. }
  152. /**
  153. @name params
  154. Visualizamos los parametros $_GET, $_POST, $_FILES y $_SESSION
  155. */
  156. public static function params()
  157. {
  158. self::info($_GET, 'GET VARS');
  159. self::info($_POST, 'POST VARS');
  160. self::info($_FILES, 'FILES VARS');
  161. self::info($_SESSION, 'SESSION VARS');
  162. }
  163. /**
  164. @name args
  165. Esta función sirve de guía. Visualiza los parametros con los que se ha llamado a una funcion.
  166. Para usar copiar y pegar el texto " Debug::display(func_get_args() );" dentro de la función
  167. de la que queramos información sobre los parámetros.
  168. */
  169. public static function args($_arg)
  170. {
  171. //Esta función hay que usarla como Debug::display(func_get_args() );
  172. self::info($_arg );
  173. }
  174. public static function origin($_msg = NULL, $_label = NULL) {
  175. $backtrace = debug_backtrace();
  176. $file = $backtrace[1]["file"];
  177. $line = $backtrace[1]["line"];
  178. self::info($_msg, $_label, $fie, $line);
  179. }
  180. /**
  181. @name trace
  182. @param $_label Texto etiqueta que aparecerá junto a la información
  183. Hacemos una traza hacia atrás de nuestro script
  184. */
  185. public static function trace($_label = "Trace")
  186. {
  187. $backtrace = debug_backtrace();
  188. self::info($backtrace, $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  189. }
  190. /**
  191. @name allTrace
  192. @param $_label Texto etiqueta que aparecerá junto a la información
  193. Hacemos una traza hacia atrás, en modo extendido, de nuestro script
  194. */
  195. public static function allTrace($_label = "AllTrace")
  196. {
  197. $backtrace = debug_backtrace();
  198. self::info(debug_backtrace(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  199. }
  200. /**
  201. @name cronos
  202. @param $_op =reset(pone a 0 el cronometro), =stop(pone en marcha el cronómetro ),
  203. =start(O empezamos el cronómetro o continuamos si ya estaba parado )
  204. @param $_display =true( visualiza el tiempo) =false( no lo visualiza )
  205. Función cronómetro para calculos de tiempos(en microsegundos )
  206. */
  207. public static function cronos($_op = "start", $_display = 0)
  208. {
  209. $backtrace = debug_backtrace();
  210. static $start = 0; //Especifica el tiempo en que se empezó el conteo.
  211. static $time = 0; //Especifica el tiempo actual, si esta parado ( = 0 ) o en marcha( != 0 )
  212. switch($_op)
  213. {
  214. //Ponemos el cronómetro a 0
  215. case "reset": $time = 0; $start = 0; break;
  216. //Parámos el cronómetro.
  217. case "stop":
  218. if($start) $time = ($start)? microtime(true) - $start: 0;
  219. $start = 0;
  220. break;
  221. //O empezamos el cronómetro o continuamos(si ya estaba antes parado ).
  222. case "start":
  223. default:
  224. if($time != 0) {
  225. $start = microtime(true) - $time;
  226. $time = 0;
  227. }else {
  228. $start = microtime(true);
  229. }
  230. }
  231. //Toca ver el tiempo, o devolverlo. (pasándolo antes a una numeración más clara )
  232. if($_display)
  233. Debug::display($time*10000, $_op, $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  234. else
  235. return $time*10000;
  236. }
  237. /**
  238. @TODO: Ahora mismo no funciona, pero habria que habilitarlo
  239. @param $_label Texto etiqueta que aparecerá junto a la información
  240. Visualizamos todas las variables que hemos mandado a smarty
  241. */
  242. public static function varSmarty($_label = false)
  243. {
  244. global $web;
  245. $backtrace = debug_backtrace();
  246. self::info($web->get_template_vars(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  247. }
  248. /**
  249. @TODO: Ahora mismo no funciona, pero habria que habilitarlo
  250. Mostramos popup de información de smarty
  251. */
  252. public static function infoSmarty()
  253. {
  254. global $web;
  255. $web->debugging = true;
  256. }
  257. /**
  258. Visualizamos toda la información disponible sobre el sistema que estamos utilizando.
  259. */
  260. public static function infoWeb()
  261. {
  262. phpinfo();
  263. }
  264. /**
  265. @param $_text es el texto a buscar en los archivos.
  266. Look for $_text in all file from working directory
  267. */
  268. public static function grep($_text = "Trasweb")
  269. {
  270. $backtrace = debug_backtrace();
  271. $label = "Grep {$_text} ";
  272. exec("grep -iR ".escapeshellarg($_text)." ".PATH, $_out);
  273. self::info($_out, $label, $backtrace[0]["file"], $backtrace[0]["line"]);
  274. }
  275. /**
  276. @param $_find texto a buscar
  277. @param $_replace texto a remplazar por $_find
  278. @param $_archives es el patrón de archivos en los que se buscara y reemplazara $_find
  279. @param $_path es el directorio a partir del cual se buscará el texto
  280. Find word $_find and replace it for $_replace in $_archives with path $_path
  281. VERY DANGEROUS
  282. */
  283. public static function findReplace($_find = NULL, $_replace= NULL, $_archives = "*" , $_path = PATH )
  284. {
  285. $backtrace = debug_backtrace();
  286. $label = " Replace {$_find} / {$_replace} ";
  287. if(strlen($_find) > 4) {
  288. $_cmd = "find $_path -name ".escapeshellarg($_archives)." -type f -exec sed -i 's/$_find/$_replace/g' {} \;";
  289. exec($_cmd, $_salida);
  290. self::info($_cmd, $label, $backtrace[0]["file"], $backtrace[0]["line"]);
  291. }else{
  292. 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"]);
  293. }
  294. }
  295. /**
  296. @param $_label Texto etiqueta que aparecerá junto a la información
  297. Visualizamos todos los errores ocasionados del uso del cms
  298. */
  299. public static function notices($_label = "Notices")
  300. {
  301. $backtrace = debug_backtrace();
  302. self::info(Notice::get(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  303. }
  304. /**
  305. @param $_label Texto etiqueta que aparecerá junto a la información
  306. Visualizamos todos los errores, avisos, informaciones, ocasionados del uso del cms
  307. */
  308. public static function allNotices($_label = "All Notices" )
  309. {
  310. $backtrace = debug_backtrace();
  311. self::info(Notice::all(), $_label, $backtrace[0]["file"], $backtrace[0]["line"]);
  312. }
  313. /**
  314. Muestra información de la consulta sql realizada
  315. @TODO: Ahora no funciona pero deberiamos de arreglarlo
  316. */
  317. public static function sql($_label = "Last")
  318. {
  319. $backtrace = debug_backtrace();
  320. $result = \DB::getResult();
  321. $rows = \DB::getRows();
  322. $id = \DB::getLastId();
  323. self::info(DB::getLastSql()."| Result: {$result} | Rows Affected {$rows} | id : {$id} ", $_label." sql", $backtrace[0]["file"], $backtrace[0]["line"]);
  324. self::info(DB::getLastRows(), $_label." rows", $backtrace[0]["file"], $backtrace[0]["line"]);
  325. }
  326. }