/upload/bt/includes/init_tr.php

http://torrentpier2.googlecode.com/ · PHP · 492 lines · 341 code · 78 blank · 73 comment · 50 complexity · 8206d161b6336277a2f1220e057c827b MD5 · raw file

  1. <?php
  2. if (!defined('IN_TRACKER')) die(basename(__FILE__));
  3. // Exit if tracker is disabled
  4. if ($tr_cfg['off']) tr_die($tr_cfg['off_reason']);
  5. //
  6. // Functions
  7. //
  8. function tracker_exit ()
  9. {
  10. global $DBS;
  11. if (DBG_LOG && DBG_LOG_GENTIME)
  12. {
  13. if ($gen_time = utime() - TIMESTART)
  14. {
  15. $sql_init_perc = round($DBS->sql_inittime*100/$gen_time);
  16. $sql_total_perc = round($DBS->sql_timetotal*100/$gen_time);
  17. $str = array();
  18. $str[] = substr(TIMENOW, -4, 4);
  19. $str[] = sprintf('%.4f', $gen_time);
  20. $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_inittime, $sql_init_perc);
  21. $str[] = sprintf('%.4f'. LOG_SEPR .'%02d%%', $DBS->sql_timetotal, $sql_total_perc);
  22. $str[] = $DBS->num_queries;
  23. $str[] = sprintf('%.1f', sys('la'));
  24. $str = join(LOG_SEPR, $str) . LOG_LF;
  25. dbg_log($str, '!!gentime');
  26. }
  27. }
  28. exit;
  29. }
  30. function silent_exit ()
  31. {
  32. while (@ob_end_clean());
  33. tracker_exit();
  34. }
  35. function error_exit ($msg = '')
  36. {
  37. if (DBG_LOG) dbg_log(' ', '!err-'. clean_filename($msg));
  38. if (!DEBUG)
  39. {
  40. silent_exit();
  41. }
  42. echo bencode(array('failure reason' => str_compact($msg)));
  43. tracker_exit();
  44. }
  45. // Database
  46. class sql_db
  47. {
  48. var $cfg = array();
  49. var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist');
  50. var $link = null;
  51. var $result = null;
  52. var $db_server = '';
  53. var $selected_db = null;
  54. var $locked = false;
  55. var $num_queries = 0;
  56. var $sql_starttime = 0;
  57. var $sql_inittime = 0;
  58. var $sql_timetotal = 0;
  59. var $sql_last_time = 0;
  60. var $slow_time = 0;
  61. var $dbg = array();
  62. var $dbg_id = 0;
  63. var $dbg_enabled = false;
  64. var $cur_query = null;
  65. var $DBS = array();
  66. /**
  67. * Constructor
  68. */
  69. function sql_db ($cfg_values)
  70. {
  71. global $DBS;
  72. $this->cfg = array_combine($this->cfg_keys, $cfg_values);
  73. $this->dbg_enabled = sql_dbg_enabled();
  74. $this->slow_time = SQL_SLOW_QUERY_TIME;
  75. $this->DBS['num_queries'] =& $DBS->num_queries;
  76. $this->DBS['sql_inittime'] =& $DBS->sql_inittime;
  77. $this->DBS['sql_timetotal'] =& $DBS->sql_timetotal;
  78. }
  79. /**
  80. * Initialize connection
  81. */
  82. function init ()
  83. {
  84. // Connect to server
  85. $this->link = $this->connect();
  86. // Select database
  87. $this->selected_db = $this->select_db();
  88. // Set charset
  89. if ($this->cfg['charset'] && !@mysql_set_charset($this->cfg['charset'], $this->link))
  90. {
  91. if (!$this->sql_query("SET NAMES {$this->cfg['charset']}"))
  92. {
  93. error_exit("Could not set charset {$this->cfg['charset']}");
  94. }
  95. }
  96. $this->num_queries = 0;
  97. $this->sql_inittime = $this->sql_timetotal;
  98. $this->DBS['sql_inittime'] += $this->sql_inittime;
  99. }
  100. /**
  101. * Open connection
  102. */
  103. function connect ()
  104. {
  105. $this->cur_query = 'connect';
  106. $this->debug('start');
  107. $connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect';
  108. if (!$link = $connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd']))
  109. {
  110. $this->log_error();
  111. }
  112. register_shutdown_function(array(&$this, 'close'));
  113. $this->debug('end');
  114. $this->cur_query = null;
  115. # if (DBG_LOG) dbg_log(' ', 'DB-connect'. ($link ? '' : '-FAIL'));
  116. if (!$link)
  117. {
  118. if (function_exists('dummy_exit'))
  119. {
  120. dummy_exit(mt_rand(1200, 2400));
  121. }
  122. else
  123. {
  124. die;
  125. }
  126. }
  127. return $link;
  128. }
  129. /**
  130. * Select database
  131. */
  132. function select_db ()
  133. {
  134. $this->cur_query = 'select db';
  135. $this->debug('start');
  136. if (!mysql_select_db($this->cfg['dbname'], $this->link))
  137. {
  138. $this->log_error();
  139. error_exit("Could not select database '{$this->cfg['dbname']}'");
  140. }
  141. $this->debug('end');
  142. $this->cur_query = null;
  143. return $this->cfg['dbname'];
  144. }
  145. /**
  146. * Base query method
  147. */
  148. function sql_query ($query)
  149. {
  150. if (!is_resource($this->link))
  151. {
  152. $this->init();
  153. }
  154. $this->cur_query = $query;
  155. $this->debug('start');
  156. if (!$this->result = mysql_query($query, $this->link))
  157. {
  158. $this->log_error();
  159. }
  160. $this->debug('end');
  161. $this->cur_query = null;
  162. $this->num_queries++;
  163. $this->DBS['num_queries']++;
  164. return $this->result;
  165. }
  166. /**
  167. * Execute query WRAPPER (with error handling)
  168. */
  169. function query ($query)
  170. {
  171. if (!$result = $this->sql_query($query))
  172. {
  173. $this->trigger_error();
  174. }
  175. return $result;
  176. }
  177. /**
  178. * Return number of rows
  179. */
  180. function num_rows ($result = false)
  181. {
  182. $num_rows = false;
  183. if ($result OR $result = $this->result)
  184. {
  185. $num_rows = is_resource($result) ? mysql_num_rows($result) : false;
  186. }
  187. return $num_rows;
  188. }
  189. /**
  190. * Return number of affected rows
  191. */
  192. function affected_rows ()
  193. {
  194. return is_resource($this->link) ? mysql_affected_rows($this->link) : -1;
  195. }
  196. /**
  197. * Fetch current row
  198. */
  199. function sql_fetchrow ($result)
  200. {
  201. return is_resource($result) ? mysql_fetch_assoc($result) : false;
  202. }
  203. /**
  204. * Alias of sql_fetchrow()
  205. */
  206. function fetch_next ($result)
  207. {
  208. return $this->sql_fetchrow($result);
  209. }
  210. /**
  211. * Fetch row WRAPPER (with error handling)
  212. */
  213. function fetch_row ($query)
  214. {
  215. if (!$result = $this->sql_query($query))
  216. {
  217. $this->trigger_error();
  218. }
  219. return $this->sql_fetchrow($result);
  220. }
  221. /**
  222. * Fetch all rows
  223. */
  224. function sql_fetchrowset ($result)
  225. {
  226. $rowset = array();
  227. while ($row = mysql_fetch_assoc($result))
  228. {
  229. $rowset[] = $row;
  230. }
  231. return $rowset;
  232. }
  233. /**
  234. * Fetch all rows WRAPPER (with error handling)
  235. */
  236. function fetch_rowset ($query)
  237. {
  238. if (!$result = $this->sql_query($query))
  239. {
  240. $this->trigger_error();
  241. }
  242. return $this->sql_fetchrowset($result);
  243. }
  244. /**
  245. * Escape string used in sql query
  246. */
  247. function escape ($v, $check_type = false)
  248. {
  249. if (!is_resource($this->link))
  250. {
  251. $this->init();
  252. }
  253. if (!$check_type)
  254. {
  255. return mysql_real_escape_string($v);
  256. }
  257. switch (true)
  258. {
  259. case is_string ($v): return "'". mysql_real_escape_string($v) ."'";
  260. case is_int ($v): return "$v";
  261. case is_bool ($v): return ($v) ? '1' : '0';
  262. case is_float ($v): return "'$v'";
  263. case is_null ($v): return 'NULL';
  264. }
  265. // if $v has unsuitable type
  266. $this->trigger_error(__FUNCTION__ .' - wrong params');
  267. }
  268. /**
  269. * Return sql error array
  270. */
  271. function sql_error ()
  272. {
  273. $return_ary = array(
  274. 'code' => '',
  275. 'message' => 'not connected',
  276. );
  277. if (is_resource($this->link))
  278. {
  279. $return_ary = array(
  280. 'code' => mysql_errno($this->link),
  281. 'message' => mysql_error($this->link),
  282. );
  283. }
  284. return $return_ary;
  285. }
  286. /**
  287. * Close sql connection
  288. */
  289. function close ()
  290. {
  291. if (is_resource($this->link))
  292. {
  293. mysql_close($this->link);
  294. }
  295. $this->link = $this->selected_db = null;
  296. if (DBG_LOG) dbg_log(str_repeat(' ', $this->num_queries), 'DB-num_queries-'. php_sapi_name());
  297. }
  298. /**
  299. * Get info about last query
  300. */
  301. function query_info ()
  302. {
  303. $info = array();
  304. if ($num = $this->num_rows($this->result))
  305. {
  306. $info[] = "$num rows";
  307. }
  308. if (is_resource($this->link) AND $ext = mysql_info($this->link))
  309. {
  310. $info[] = "$ext";
  311. }
  312. elseif (!$num && ($aff = $this->affected_rows($this->result) AND $aff != -1))
  313. {
  314. $info[] = "$aff rows";
  315. }
  316. return join(', ', $info);
  317. }
  318. /**
  319. * Store debug info
  320. */
  321. function debug ($mode)
  322. {
  323. if (!SQL_DEBUG) return;
  324. if ($mode == 'start')
  325. {
  326. if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES)
  327. {
  328. $this->sql_starttime = utime();
  329. $this->sql_last_time = 0;
  330. }
  331. }
  332. elseif ($mode == 'end')
  333. {
  334. if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES)
  335. {
  336. $this->sql_last_time = utime() - $this->sql_starttime;
  337. $this->sql_timetotal += $this->sql_last_time;
  338. $this->DBS['sql_timetotal'] += $this->sql_last_time;
  339. if (SQL_LOG_SLOW_QUERIES && $this->sql_last_time > $this->slow_time)
  340. {
  341. $msg = date('m-d H:i:s') . LOG_SEPR;
  342. $msg .= sprintf('%03d', round($this->sql_last_time));
  343. $msg .= LOG_SEPR . sprintf('%.1f', sys('la'));
  344. $msg .= LOG_SEPR . str_compact($this->cur_query);
  345. $msg .= LOG_SEPR .' # '. $this->query_info();
  346. $msg .= LOG_SEPR . $this->debug_find_source();
  347. bb_log($msg . LOG_LF, 'sql_slow_tr');
  348. }
  349. }
  350. }
  351. return;
  352. }
  353. /**
  354. * Trigger error
  355. */
  356. function trigger_error ($msg = '')
  357. {
  358. if (error_reporting())
  359. {
  360. if (!$msg) $msg = 'DB Error';
  361. if (DEBUG === true)
  362. {
  363. $err = $this->sql_error();
  364. $msg .= trim(sprintf(' #%06d %s', $err['code'], $err['message']));
  365. }
  366. else
  367. {
  368. $msg .= " [". $this->debug_find_source() ."]";
  369. }
  370. error_exit($msg);
  371. }
  372. }
  373. /**
  374. * Find caller source
  375. */
  376. function debug_find_source ()
  377. {
  378. $source = '';
  379. $backtrace = debug_backtrace();
  380. foreach ($backtrace as $trace)
  381. {
  382. if ($trace['file'] !== __FILE__)
  383. {
  384. $source = str_replace(BB_PATH . DIRECTORY_SEPARATOR, '', $trace['file']) .'('. $trace['line'] .')';
  385. break;
  386. }
  387. }
  388. return $source;
  389. }
  390. /**
  391. * Log error
  392. */
  393. function log_error ()
  394. {
  395. if (!SQL_LOG_ERRORS) return;
  396. if (!error_reporting()) return;
  397. $msg = array();
  398. $err = $this->sql_error();
  399. $msg[] = str_compact(sprintf('#%06d %s', $err['code'], $err['message']));
  400. $msg[] = '';
  401. $msg[] = str_compact($this->cur_query);
  402. $msg[] = '';
  403. $msg[] = 'Source : '. $this->debug_find_source();
  404. $msg[] = 'IP : '. @$_SERVER['REMOTE_ADDR'];
  405. $msg[] = 'Date : '. date('Y-m-d H:i:s');
  406. $msg[] = 'Agent : '. @$_SERVER['HTTP_USER_AGENT'];
  407. $msg[] = 'Req_URI : '. @$_SERVER['REQUEST_URI'];
  408. $msg[] = 'Referer : '. @$_SERVER['HTTP_REFERER'];
  409. $msg[] = 'Method : '. @$_SERVER['REQUEST_METHOD'];
  410. $msg[] = 'Request : '. trim(print_r($_REQUEST, true)) . str_repeat('_', 78) . LOG_LF;
  411. $msg[] = '';
  412. bb_log($msg, 'sql_error_tr');
  413. }
  414. }