PageRenderTime 28ms CodeModel.GetById 11ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 0ms

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