PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/library/error_functions.php

https://gitlab.com/tutaalexandr/bot_local
PHP | 373 lines | 258 code | 14 blank | 101 comment | 31 complexity | 9d41c73eaa34b9a12f5c5ca24725c3ae MD5 | raw file
  1. <?php
  2. /***************************************
  3. * http://www.program-o.com
  4. * PROGRAM O
  5. * Version: 2.4.8
  6. * FILE: library/error_functions.php
  7. * AUTHOR: Elizabeth Perreau and Dave Morton
  8. * DATE: MAY 17TH 2014
  9. * DETAILS: common library of debugging functions
  10. ***************************************/
  11. /**
  12. * function myErrorHandler()
  13. * Process PHP errors
  14. * @param string $errno - the severity of the error
  15. * @param string $errstr - the file the error came from
  16. * @param string $errfile - the file the error came from
  17. * @param string $errline - the line of code
  18. **/
  19. function myErrorHandler($errno, $errstr, $errfile, $errline)
  20. {
  21. switch ($errno)
  22. {
  23. case E_NOTICE :
  24. case E_USER_NOTICE :
  25. $errors = 'Notice';
  26. break;
  27. case E_DEPRECATED :
  28. case E_USER_DEPRECATED :
  29. $errors = 'Deprecated';
  30. break;
  31. case E_WARNING :
  32. case E_USER_WARNING :
  33. $errors = 'Warning';
  34. break;
  35. case E_ERROR :
  36. case E_USER_ERROR :
  37. $errors = 'Fatal Error';
  38. break;
  39. default :
  40. $errors = 'Unknown';
  41. break;
  42. }
  43. $info = "PHP ERROR [$errors] -$errstr in $errfile on Line $errline";
  44. //a little hack to hide 'deprecated' errors of which there may be ~MORE~ than a few, depending on PHP version
  45. if (!stripos($errstr, 'deprecated'))
  46. {
  47. runDebug($errfile, '', $errline, $info, 1);
  48. }
  49. $current_DateTime = date('m/d/Y H:i:s');
  50. save_file(_LOG_PATH_ . 'error.log', "$current_DateTime - $info\r\n", true);
  51. }
  52. /**
  53. * function runDebug()
  54. * Building to a global debug array
  55. *
  56. * @param string $fileName - the file the error came from
  57. * @param string $functionName - the function that triggered the error
  58. * @param string $line - the line of code
  59. * @param string $info - the message to display
  60. * @param int $level
  61. */
  62. function runDebug($fileName, $functionName, $line, $info, $level = 0)
  63. {
  64. global $debugArr, $srai_iterations, $quickdebug, $writetotemp, $convoArr, $last_timestamp, $debug_level;
  65. $debug_level = (isset($convoArr['conversation']['debug_level'])) ? $convoArr['conversation']['debug_level'] : $debug_level;
  66. if (empty ($functionName)) $functionName = 'Called outside of function';
  67. //only log the debug info if the info level is equal to or less than the chosen level
  68. if (($level <= $debug_level))// && ($level != 0) && ($debug_level != 0)
  69. {
  70. // Set elapsed time from last debug call and update last timestamp
  71. if ($quickdebug == 1)
  72. {
  73. outputDebug($fileName, $functionName, $line, $info);
  74. }
  75. $current_timestamp = microtime(true);
  76. $usecN = round($current_timestamp - floor($current_timestamp), 5);
  77. //Lose the decimal point and everything to the left of it
  78. $usecD = str_replace('0.', '', $usecN);
  79. $et = $current_timestamp - $last_timestamp;
  80. $elapsed_time = number_format($et * 1000, 3);
  81. $last_timestamp = $current_timestamp;
  82. //build timestamp index for the debug array
  83. $index = date('d-m-Y H:i:s.') . $usecD . "[$level][$debug_level] - Elapsed time: $elapsed_time milliseconds";
  84. //If there's already an index in the debug array with the same value, just add a space, to make a new, unique index that is visually identical.
  85. while (array_key_exists($index, $debugArr))
  86. {
  87. $index .= ' ';
  88. }
  89. //mem_tracer($fileName, $functionName, $line); # only uncomment this to trace memory leaks!
  90. //add to array
  91. $debugArr[$index]['fileName'] = basename($fileName);
  92. $debugArr[$index]['functionName'] = $functionName;
  93. $debugArr[$index]['line'] = $line;
  94. $debugArr[$index]['info'] = $info;
  95. if ($srai_iterations < 1)
  96. {
  97. $sr_it = 0;
  98. }
  99. else
  100. {
  101. $sr_it = $srai_iterations;
  102. }
  103. $debugArr[$index]['srai_iteration'] = $sr_it;
  104. //if we are logging to file then build a log file. This will be overwriten if the program completes
  105. if ($writetotemp == 1)
  106. {
  107. writefile_debug(implode("\n",$debugArr), $convoArr);
  108. }
  109. }
  110. }
  111. /**
  112. * function handleDebug()
  113. * Handle the debug array at the end of the process
  114. * @param array $convoArr - conversation arrau
  115. * @return array $convoArr;
  116. **/
  117. function handleDebug($convoArr, $et)
  118. {
  119. global $debugArr, $debug_level, $debug_mode;
  120. $debug_level = (isset($convoArr['conversation']['debug_level'])) ? $convoArr['conversation']['debug_level'] : $debug_level;
  121. $debug_mode = (isset($convoArr['conversation']['debugmode'])) ? $convoArr['conversation']['debugmode'] : $debug_mode;
  122. $convoArr['debug'] = $debugArr;
  123. $log = '';
  124. foreach ($debugArr as $time => $subArray)
  125. {
  126. $log .= $time . '[NEWLINE]';
  127. foreach ($subArray as $index => $value)
  128. {
  129. if (($index == 'fileName') || ($index == 'functionName') || ($index == 'line'))
  130. {
  131. $log .= "[$value]";
  132. }
  133. elseif ($index == 'info')
  134. {
  135. $log .= "[NEWLINE]$value [NEWLINE]-----------------------[NEWLINE]";
  136. }
  137. }
  138. }
  139. $log = rtrim($log);
  140. if ($debug_level == 4)
  141. {
  142. //show the full array
  143. $showArr = $convoArr;
  144. unset ($showArr['debug']);
  145. }
  146. else
  147. {
  148. //show a reduced array
  149. $showArr = reduceConvoArr($convoArr);
  150. }
  151. if ($debug_level != 0)
  152. {
  153. //$log .= '[NEWLINE]-----------------------[NEWLINE]';
  154. $log .= "Debug Level: $debug_level";
  155. $log .= '[NEWLINE]-----------------------[NEWLINE]';
  156. $log .= "Debug Mode: $debug_mode";
  157. $log .= '[NEWLINE]-----------------------[NEWLINE]';
  158. $log .= 'CONVERSATION ARRAY';
  159. $log .= '[NEWLINE]-----------------------[NEWLINE]';
  160. $log .= str_replace("\n", PHP_EOL, print_r($showArr, true));
  161. $log .= '[NEWLINE]-----------------------[NEWLINE]';
  162. $log .= "Total execution time: $et Milliseconds. Goodbye.";
  163. }
  164. switch ($debug_mode)
  165. {
  166. case 0 :
  167. //show in source code
  168. $log = str_replace('[NEWLINE]', "\n", $log);
  169. display_on_page(0, $log);
  170. break;
  171. case 1 :
  172. //write to log file
  173. $log = str_replace('[NEWLINE]', PHP_EOL, $log);
  174. writefile_debug($log, $convoArr);
  175. break;
  176. case 2 :
  177. //show in webpage
  178. $log = str_replace('[NEWLINE]', '<br/>', $log);
  179. display_on_page(1, $log);
  180. break;
  181. case 3 :
  182. //email to user
  183. $log = str_replace('[NEWLINE]', "\r\n", $log);
  184. email_debug($convoArr['conversation']['debugemail'], $log);
  185. break;
  186. }
  187. return $convoArr;
  188. }
  189. /** reduceConvoArr()
  190. * A small function to create a smaller convoArr just for debuggin!
  191. *
  192. * @param array $convoArr - the big array to be reduced
  193. * @return array
  194. */
  195. function reduceConvoArr($convoArr)
  196. {
  197. runDebug(__FILE__, __FUNCTION__, __LINE__, 'Reducing the conversation array.', 0);
  198. $showConvoArr = array();
  199. $showConvoArr['conversation'] = (isset($convoArr['conversation'])) ? $convoArr['conversation'] : '';
  200. $showConvoArr['aiml'] = (isset($convoArr['aiml'])) ? $convoArr['aiml'] : '';
  201. $showConvoArr['topic'][1] = (isset($convoArr['topic'][1])) ? $convoArr['topic'][1] : '';
  202. $showConvoArr['that'][1] = (isset($convoArr['that'][1])) ? $convoArr['that'][1] : '';
  203. if (isset($convoArr['star']))
  204. {
  205. foreach ($convoArr['star'] as $index => $star)
  206. {
  207. if (!empty ($star))
  208. $showConvoArr['star'][$index] = $star;
  209. }
  210. }
  211. $showConvoArr['input'][1] = (isset($convoArr['input'][1])) ? $convoArr['input'][1] : '';
  212. $showConvoArr['stack']['top'] = (isset($convoArr['stack']['top'])) ? $convoArr['stack']['top'] : '';
  213. $showConvoArr['stack']['last'] = (isset($convoArr['stack']['last'])) ? $convoArr['stack']['last'] : '';
  214. $showConvoArr['client_properties'] = (isset($convoArr['client_properties'])) ? $convoArr['client_properties'] : '';
  215. $showConvoArr['aiml']['user_raw'] = (isset($convoArr['aiml']['user_raw'])) ? $convoArr['aiml']['user_raw'] : '';
  216. $showConvoArr['aiml']['lookingfor'] = (isset($convoArr['aiml']['lookingfor'])) ? $convoArr['aiml']['lookingfor'] : '';
  217. $showConvoArr['aiml']['pattern'] = (isset($convoArr['aiml']['pattern'])) ? $convoArr['aiml']['pattern'] : '';
  218. $showConvoArr['aiml']['thatpattern'] = (isset($convoArr['aiml']['thatpattern'])) ? $convoArr['aiml']['thatpattern'] : '';
  219. $showConvoArr['aiml']['topic'] = (isset($convoArr['aiml']['topic'])) ? $convoArr['aiml']['topic'] : '';
  220. $showConvoArr['aiml']['score'] = (isset($convoArr['aiml']['score'])) ? $convoArr['aiml']['score'] : '';
  221. $showConvoArr['aiml']['aiml_id'] = (isset($convoArr['aiml']['aiml_id'])) ? $convoArr['aiml']['aiml_id'] : '';
  222. $showConvoArr['aiml']['parsed_template'] = (isset($convoArr['aiml']['parsed_template'])) ? $convoArr['aiml']['parsed_template'] : '';
  223. $showConvoArr['user_say'][1] = (isset($convoArr['aiml']['parsed_template'])) ? $convoArr['user_say'][1] : '';
  224. $showConvoArr['that_raw'][1] = (isset($convoArr['that_raw'][1])) ? $convoArr['that_raw'][1] : '';
  225. $showConvoArr['parsed_template'][1] = (isset($convoArr['parsed_template'][1])) ? $convoArr['parsed_template'][1] : '';
  226. return $showConvoArr;
  227. }
  228. /**
  229. * function writefile_debug()
  230. * Handles the debug when written to a file
  231. *
  232. * @param string $log - the data to write
  233. * @internal param string $myFile - the name of the file which is also the convo id
  234. */
  235. function writefile_debug($log)
  236. {
  237. global $new_convo_id, $old_convo_id;
  238. $session_id = ($new_convo_id === false) ? session_id() : $new_convo_id;
  239. $myFile = _DEBUG_PATH_ . $session_id . '.txt';
  240. if (!IS_WINDOWS)
  241. {
  242. $log = str_replace("\n", "\r\n", $log);
  243. $log = str_replace("\r\r", "\r", $log);
  244. }
  245. file_put_contents($myFile, $log);
  246. }
  247. /**
  248. * function display_on_page()
  249. * Handles the debug when it is displayed on the webpage either in the source or on the page
  250. * @param int $show_on_page - 0=show in source 1=output to user
  251. * @param string $log - the data to show
  252. **/
  253. function display_on_page($show_on_page, $log)
  254. {
  255. if ($show_on_page == 0)
  256. {
  257. echo '<!--<pre>';
  258. print_r($log);
  259. echo '</pre>-->';
  260. }
  261. else
  262. {
  263. echo '<pre>';
  264. print_r($log);
  265. echo '</pre>';
  266. }
  267. }
  268. /**
  269. * function email_debug()
  270. * Handles the debug when it is emailed to the botmaster
  271. * @param string $email - email address
  272. * @param string $log - the data to send
  273. **/
  274. function email_debug($email, $log)
  275. {
  276. $to = $email;
  277. $subject = 'Debug Data';
  278. $message = $log;
  279. $headers = 'From: ' . $email . "\r\nReply-To: $email \r\n" . 'X-Mailer: PHP/' . phpversion();
  280. mail($to, $subject, $message, $headers);
  281. }
  282. /**
  283. * function outputDebug()
  284. * Used in the install/upgrade files will display it straightaway
  285. * @param string $fileName - the file the error came from
  286. * @param string $functionName - the function that triggered the error
  287. * @param string $line - the line of code
  288. * @param string $info - the message to display
  289. **/
  290. function outputDebug($fileName, $functionName, $line, $info)
  291. {
  292. global $srai_iterations;
  293. list($usec, $sec) = explode(' ', microtime());
  294. //build timestamp index for the debug array
  295. $string = ((float) $usec + (float) $sec);
  296. $string2 = explode('.', $string);
  297. $index = date('d-m-Y H:i:s', $string2[0]) . ':' . $string2[1];
  298. if ($srai_iterations < 1)
  299. {
  300. $sr_it = 0;
  301. }
  302. else
  303. {
  304. $sr_it = $srai_iterations;
  305. }
  306. //add to array
  307. print '<br/>----------------------------------------------------';
  308. print '<br/>' . $index . ': ' . $fileName;
  309. print '<br/>' . $index . ': ' . $functionName;
  310. print '<br/>' . $index . ': ' . $line;
  311. print '<br/>' . $index . ': ' . $info;
  312. print '<br/>' . $index . ': srai:' . $sr_it;
  313. print '<br/>----------------------------------------------------';
  314. }
  315. /**
  316. * Function save_file
  317. *
  318. * * @param $file
  319. * @param $content
  320. * @param bool $append
  321. * @return int
  322. * @throws Exception
  323. */
  324. function save_file($file, $content, $append = false)
  325. {
  326. if (function_exists('file_put_contents'))
  327. {
  328. ($append) ? $x = file_put_contents($file, $content, FILE_APPEND) : $x = file_put_contents($file, $content);
  329. }
  330. else
  331. {
  332. $fileMode = ($append === true) ? 'a' : 'w';
  333. if (($fh = fopen($file, $fileMode)) === false) throw new Exception('Can\'t open the file!');
  334. $cLen = strlen($content);
  335. fwrite($fh, $content, $cLen);
  336. fclose($fh);
  337. }
  338. return 1;
  339. }
  340. /**
  341. * Function mem_tracer
  342. *
  343. * * @param $file
  344. * @param $function
  345. * @param $line
  346. * @return void
  347. */
  348. function mem_tracer($file, $function, $line)
  349. {
  350. $file = str_replace(_BOTCORE_PATH_ . 'aiml' . DIRECTORY_SEPARATOR, '', $file);
  351. $mem_state = number_format(memory_get_usage(true));
  352. $trace_file = _DEBUG_PATH_ . session_id() . '.mem_trace.txt';
  353. if (!file_exists($trace_file)) /** @noinspection PhpUndefinedConstantInspection */
  354. save_file($trace_file, 'PHP memory limit = ' . ini_get('memory_limit') . "\nBase folder = " . _BASE_PATH_ . "\n");
  355. $append = true;
  356. $content = "$file.$function.$line: Memory used = $mem_state bytes\r\n";
  357. save_file($trace_file, $content, $append);
  358. }
  359. ?>