'mysql', 'db_server' => 'localhost', 'db_name' => 'test', 'db_user' => 'root', 'db_pass' => 'toor', 'db_charset' => 'latin2', 'page_charset' => 'iso-8859-2', 'remember' => 1 ); foreach ($cookie as $k => $v) { if ('db_pass' == $k) { $v = base64_encode($v); } $k = COOKIE_PREFIX.$k; if (!isset($_COOKIE[$k])) { $_COOKIE[$k] = $v; } } require './dbkiss.php'; --------------------------------------------------------------------- */ /* Changelog: 1.09 * CSV export in sql editor and table view (feature sponsored by Patrick McGovern) 1.08 * date.timezone E_STRICT error fixed 1.07 * mysql tables with dash in the name generated errors, now all tables in mysql driver are enquoted with backtick. 1.06 * postgresql fix 1.05 * export of all structure and data does take into account the table name filter on the main page, so you can filter the tables that you want to export. 1.04 * exporting all structure/data didn't work (ob_gzhandler flush bug) * cookies are now set using httponly option * text editor complained about bad cr/lf in exported sql files (mysql create table uses \n, so insert queries need to be seperated by \n and not \r\n) 1.03 * re-created array_walk_recursive for php4 compatibility * removed stripping slashes from displayed content * added favicon (using base64_encode to store the icon in php code, so it is still one-file database browser) 1.02 * works with short_open_tag disabled * code optimizations/fixes * postgresql error fix for large tables 1.01 * fix for mysql 3.23, which doesnt understand "LIMIT x OFFSET z" 1.00 * bug fixes * minor feature enhancements * this release is stable and can be used in production environment 0.61 * upper casing keywords in submitted sql is disabled (it also modified quoted values) * sql error when displaying table with 0 rows * could not connect to database that had upper case characters */ // todo: connect screen: [x] create database (if not exists) [charset] // todo: connect screen: database (optional, if none provided will select the first database the user has access to) // todo: mysqli driver (check if mysql extension is loaded, if not try to use mysqli) // todo: support for the enum field type when editing row // todo: search whole database form should appear also on main page // todo: improve detecting primary keys when editing row (querying information_schema , for mysql > 4) // todo: when dbkiss_sql dir is missing, display a message in sql editor that some features won't work (templates, pagination) currently it displays a message to create that dir and EXIT, but should allow basic operations // todo: "Insert" on table view page // todo: edit table structure error_reporting(-1); ini_set('display_errors', true); if (!ini_get('date.timezone')) { ini_set('date.timezone', 'Europe/Warsaw'); } if (isset($_GET['dbkiss_favicon'])) { $favicon = 'AAABAAIAEBAAAAEACABoBQAAJgAAABAQAAABACAAaAQAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wDQcRIAAGaZAL5mCwCZ//8Av24SAMVwEgCa//8AvmcLAKn//wAV0/8Awf//AErL5QDGcBIAvnESAHCpxgDf7PIA37aIAMNpDQDHcRIAZO7/AErl/wAdrNYAYMbZAI/1+QDouYkAO+D/AIT4/wDHcBIAjPr/AMJvEgDa//8AQIyzAMNvEgCfxdkA8v//AEzl/wB46fQAMLbZACms1gAAeaYAGou1AJfX6gAYo84AHrLbAN+zhgCXxtkAv/P5AI30+ADv9fkAFH2pABja/wDGaw4AwXASAAVwoQDjuIkAzXARADCmyQAAe64Ade35AMBxEgC+aQ0AAKnGACnw/wAngqwAxW8RABBwnwAAg6wAxW4QAL7w9wCG7PIAHKnSAMFsDwC/ZwwADnWkAASQwgAd1v8Aj7zSAMZvEQDv+fwABXSmABZ+qgAC6fIAAG+iAMhsDwAcz/kAvmsOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICOTUTCQQECRMQEQACAgICVUpJEgEfBxRCJ1FOAgEBGgQ4AQEGAQEBDhZWAwICAgEEASIBBgEHFA4WTQMCAgECBAE2AQ8BDw89QDQDAgECAgQBVwEJAQQJPj9TKQIaAQEELgESBgEHHUU6N0QCAgICBA4iBgYfBx1PDUgDAAAAAAMcJQsLGxUeJg0XAwAAAAADHCULCxsVHiYNFwMAAAAAAzwtTDtUAwNLKiwDAAAAAAMoK0YMCggFRxgzAwAAAAADUCQgDAoIBQUFGQMAAAAAQzIkIAwKCAUFBRkDAAAAACNBLzAMCggFMRhSIwAAAAAAERAhAwMDAyEQEQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPAAAADwAAAA8AAAAPAAAADwAAAA8AAAAPAAAAD4AQAAKAAAABAAAAAgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMxmAO3MZgDtzGYA7cxmAO3MZgDtymYB78RmBvfCZgj6vmYK/r5mC/++Zgv/vmYK/sJmCPoAZpmPAGaZIAAAAADMZgDtzGYA7cxmAO3MZgDtxmYF9b9nDP/BbA//37aI///////CbxL/xXAS/8dxEv/FbxH/MLbZ/wV0pv8AZplwzGYA7f//////////57aF9r5mC//juIn///////////+/bhL/////////////////xnAS/0rl//8cz/n/AGaZ/8xmAO3MZgDtzGYA7f////++Zgv//////8NvEv//////v24S///////FcBL/x3ES/8ZwEv9K5f//Hdb//wBmmf/MZgDtzGYA7f/////MZgDtvmYL///////BcBL//////75xEv//////vnES/75xEv/AcRL/KfD//xja//8AZpn/zGYA7f/////MZgDtzGYA7b5mC///////vmsO//////++Zwv//////75mC/++Zwv/vmkN/wCpxv8C6fL/AHmm/8xmAO3ntoX2//////////++Zgv/37OG///////ftoj/v24S///////FcBL/x3AS/8VuEP8wpsn/BXCh/wCDrP/MZgDtzGYA7cxmAO3MZgDtvmYL/8ZwEv/DbxL/v24S/79uEv/CbxL/xXAS/8dwEv/GbxH/Ssvl/xyp0v8AZpn/AAAAAAAAAAAAAAAAAAAAAABmmf+E+P//TOX//xXT//8V0///O+D//2Tu//+M+v//eOn0/0rL5f8drNb/AGaZ/wAAAAAAAAAAAAAAAAAAAAAAZpn/hPj//0zl//8V0///FdP//zvg//9k7v//jPr//3jp9P9Ky+X/HazW/wBmmf8AAAAAAAAAAAAAAAAAAAAAAGaZ/3Xt+f8estv/BJDC/wB7rv8Ab6L/AGaZ/wBmmf8OdaT/Gou1/xijzv8AZpn/AAAAAAAAAAAAAAAAAAAAAABmmf8prNb/l9fq/77w9//B////qf///5r///+Z////huzy/2DG2f8Ufan/AGaZ/wAAAAAAAAAAAAAAAAAAAAAAZpn/7/n8//L////a////wf///6n///+a////mf///5n///+Z////j/X5/wBmmf8AAAAAAAAAAAAAAAAAAAAAAGaZ7+/1+f/y////2v///8H///+p////mv///5n///+Z////mf///4/1+f8AZpn/AAAAAAAAAAAAAAAAAAAAAABmmWAngqz/l8bZ/7/z+f/B////qf///5r///+Z////jfT4/2DG2f8Wfqr/AGaZYAAAAAAAAAAAAAAAAAAAAAAAAAAAAGaZIABmmY8AZpm/AGaZ/wBmmf8AZpn/AGaZ/wBmmb8AZpmPAGaZIAAAAAAAAQICAAA1EwAABAkAABEAAAACAgAASRIAAAcUAABRTvAAARrwAAEB8AABAfAAVgPwAAIB8AAiAfAABxT4AU0D'; header('Content-type: image/vnd.microsoft.icon'); echo base64_decode($favicon); exit(); } if (!function_exists('array_walk_recursive')) { function array_walk_recursive(&$array, $func) { foreach ($array as $k => $v) { if (is_array($v)) { array_walk_recursive($array[$k], $func); } else { $func($array[$k], $k); } } } } function table_filter($tables, $filter) { $filter = trim($filter); if ($filter) { foreach ($tables as $k => $table) { if (!str_has_any($table, $filter, $ignore_case = true)) { unset($tables[$k]); } } } return $tables; } function get($key, $type='string') { if (is_string($key)) { $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null; if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]); settype($_GET[$key], $type); if ('string' == $type) $_GET[$key] = trim($_GET[$key]); return $_GET[$key]; } $vars = $key; foreach ($vars as $key => $type) { $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null; if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]); settype($_GET[$key], $type); if ('string' == $type) $_GET[$key] = trim($_GET[$key]); $vars[$key] = $_GET[$key]; } return $vars; } function post($key, $type='string') { if (is_string($key)) { $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null; if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]); settype($_POST[$key], $type); if ('string' == $type) $_POST[$key] = trim($_POST[$key]); return $_POST[$key]; } $vars = $key; foreach ($vars as $key => $type) { $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null; if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]); settype($_POST[$key], $type); if ('string' == $type) $_POST[$key] = trim($_POST[$key]); $vars[$key] = $_POST[$key]; } return $vars; } $_ENV['IS_GET'] = ('GET' == $_SERVER['REQUEST_METHOD']); $_ENV['IS_POST'] = ('POST' == $_SERVER['REQUEST_METHOD']); function req_gpc_has($str) { /* finds if value exists in GPC data, used in filter_() functions, to check whether use html_tags_undo() on the data */ foreach ($_GET as $k => $v) { if ($str == $v) { return true; } } foreach ($_POST as $k => $v) { if ($str == $v) { return true; } } foreach ($_COOKIE as $k => $v) { if ($str == $v) { return true; } } return false; } if (ini_get('magic_quotes_gpc')) { ini_set('magic_quotes_runtime', 0); array_walk_recursive($_GET, 'db_magic_quotes_gpc'); array_walk_recursive($_POST, 'db_magic_quotes_gpc'); array_walk_recursive($_COOKIE, 'db_magic_quotes_gpc'); } function db_magic_quotes_gpc(&$val) { $val = stripslashes($val); } $sql_font = 'font-size: 12px; font-family: courier new;'; $sql_area = $sql_font.' width: 708px; height: 182px; border: #ccc 1px solid; background: #f9f9f9; padding: 3px;'; if (!isset($db_name_style)) { $db_name_style = ''; } if (!isset($db_name_h1)) { $db_name_h1 = ''; } global $db_link, $db_name; if (!defined('COOKIE_PREFIX')) { define('COOKIE_PREFIX', 'dbkiss_'); } define('COOKIE_WEEK', 604800); // 3600*24*7 define('COOKIE_SESS', 0); function cookie_get($key) { $key = COOKIE_PREFIX.$key; if (isset($_COOKIE[$key])) return $_COOKIE[$key]; return null; } function cookie_set($key, $val, $time = COOKIE_SESS) { $key = COOKIE_PREFIX.$key; $expire = $time ? time() + $time : 0; if (version_compare(PHP_VERSION, '5.2.0', '>=')) { setcookie($key, $val, $expire, '', '', false, true); } else { setcookie($key, $val, $expire); } $_COOKIE[$key] = $val; } function cookie_del($key) { $key = COOKIE_PREFIX.$key; if (version_compare(PHP_VERSION, '5.2.0', '>=')) { setcookie($key, '', time()-3600*24, '', '', false, true); } else { setcookie($key, '', time()-3600*24); } unset($_COOKIE[$key]); } conn_modify('db_name'); conn_modify('db_charset'); conn_modify('page_charset'); function conn_modify($key) { if (array_key_exists($key, $_GET)) { cookie_set($key, $_GET[$key], cookie_get('remember') ? COOKIE_WEEK : COOKIE_SESS); if (isset($_GET['from']) && $_GET['from']) { header('Location: '.$_GET['from']); } else { header('Location: '.$_SERVER['PHP_SELF']); } exit; } } $db_driver = cookie_get('db_driver'); $db_server = cookie_get('db_server'); $db_name = cookie_get('db_name'); $db_user = cookie_get('db_user'); $db_pass = base64_decode(cookie_get('db_pass')); $db_charset = cookie_get('db_charset'); $page_charset = cookie_get('page_charset'); $charset1 = array('latin1', 'latin2', 'utf8', 'cp1250'); $charset2 = array('iso-8859-1', 'iso-8859-2', 'utf-8', 'windows-1250'); $charset1[] = $db_charset; $charset2[] = $page_charset; $charset1 = charset_assoc($charset1); $charset2 = charset_assoc($charset2); $driver_arr = array('mysql', 'pgsql'); $driver_arr = array_assoc($driver_arr); function array_assoc($a) { $ret = array(); foreach ($a as $v) { $ret[$v] = $v; } return $ret; } function charset_assoc($arr) { sort($arr); $ret = array(); foreach ($arr as $v) { if (!$v) { continue; } $v = strtolower($v); $ret[$v] = $v; } return $ret; } if (isset($_GET['disconnect']) && $_GET['disconnect']) { cookie_del('db_pass'); header('Location: '.$_SERVER['PHP_SELF']); exit; } if (!$db_pass || (!$db_driver || !$db_server || !$db_name || !$db_user)) { if ('POST' == $_SERVER['REQUEST_METHOD']) { $db_driver = post('db_driver'); $db_server = post('db_server'); $db_name = post('db_name'); $db_user = post('db_user'); $db_pass = post('db_pass'); $db_charset = post('db_charset'); $page_charset = post('page_charset'); if ($db_driver && $db_server && $db_name && $db_user) { $db_test = true; db_connect($db_server, $db_name, $db_user, $db_pass); if (is_resource($db_link)) { $time = post('remember') ? COOKIE_WEEK : COOKIE_SESS; cookie_set('db_driver', $db_driver, $time); cookie_set('db_server', $db_server, $time); cookie_set('db_name', $db_name, $time); cookie_set('db_user', $db_user, $time); cookie_set('db_pass', base64_encode($db_pass), $time); cookie_set('db_charset', $db_charset, $time); cookie_set('page_charset', $page_charset, $time); cookie_set('remember', post('remember'), $time); header('Location: '.$_SERVER['PHP_SELF']); exit; } } } else { $_POST['db_driver'] = $db_driver; $_POST['db_server'] = $db_server ? $db_server : 'localhost'; $_POST['db_name'] = $db_name; $_POST['db_user'] = $db_user; $_POST['db_charset'] = $db_charset; $_POST['page_charset'] = $page_charset; $_POST['db_driver'] = $db_driver; } ?> .:.::DiaGraM::.:..

Connect

Error: 
Driver:
Server:
Database:
User:
Password:
Db charset: (optional)
Page charset: (optional)
>
Importing: '.$sqlfile.' ('.size(filesize($sqlfile)).')'; echo '
Database: '.$db_name.'
'; flush(); import($sqlfile, post('ignore_errors'), post('transaction'), post('force_myisam'), post('query_start','int')); exit; } if (isset($_POST['drop_table']) && $_POST['drop_table']) { $drop_table_enq = quote_table($_POST['drop_table']); db_exe('DROP TABLE '.$drop_table_enq); header('Location: '.$_SERVER['PHP_SELF']); exit; } function db_connect($db_server, $db_name, $db_user, $db_pass) { global $db_driver, $db_link, $db_test; if (!extension_loaded($db_driver)) { trigger_error($db_driver.' extension not loaded', E_USER_ERROR); } if ('mysql' == $db_driver) { $db_link = @mysql_connect($db_server, $db_user, $db_pass); if (!is_resource($db_link)) { if ($db_test) { $db_test = 'mysql_connect() failed: '.db_error(); return; } else { cookie_del('db_pass'); cookie_del('db_name'); die('mysql_connect() failed: '.db_error()); } } if (!@mysql_select_db($db_name, $db_link)) { $error = db_error(); db_close(); if ($db_test) { $db_test = 'mysql_select_db() failed: '.$error; return; } else { cookie_del('db_pass'); cookie_del('db_name'); die('mysql_select_db() failed: '.$error); } } } if ('pgsql' == $db_driver) { $conn = sprintf("host='%s' dbname='%s' user='%s' password='%s'", $db_server, $db_name, $db_user, $db_pass); $db_link = @pg_connect($conn); if (!is_resource($db_link)) { if ($db_test) { $db_test = 'pg_connect() failed: '.db_error(); return; } else { cookie_del('db_pass'); cookie_del('db_name'); die('pg_connect() failed: '.db_error()); } } } register_shutdown_function('db_cleanup'); } function db_cleanup() { db_close(); } function db_close() { global $db_driver, $db_link; if (is_resource($db_link)) { if ('mysql' == $db_driver) { mysql_close($db_link); } if ('pgsql' == $db_driver) { pg_close($db_link); } } } function db_query($query, $dat = false) { global $db_driver, $db_link; $query = db_bind($query, $dat); if (!db_is_safe($query)) { return false; } if ('mysql' == $db_driver) { $rs = mysql_query($query, $db_link); return $rs; } if ('pgsql' == $db_driver) { $rs = pg_query($db_link, $query); return $rs; } } function db_is_safe($q, $ret = false) { // currently only checks UPDATE's/DELETE's if WHERE condition is not missing $upd = 'update'; $del = 'delete'; $q = ltrim($q); if (strtolower(substr($q, 0, strlen($upd))) == $upd || strtolower(substr($q, 0, strlen($del))) == $del) { if (!preg_match('#\swhere\s#i', $q)) { if ($ret) { return false; } else { trigger_error(sprintf('db_is_safe() failed. Detected UPDATE/DELETE without WHERE condition. Query: %s.', $q), E_USER_ERROR); return false; } } } return true; } function db_exe($query, $dat = false) { $rs = db_query($query, $dat); db_free($rs); } function db_one($query, $dat = false) { $row = db_row_num($query, $dat); if ($row) { return $row[0]; } else { return false; } } function db_row($query, $dat = false) { global $db_driver, $db_link; if ('mysql' == $db_driver) { if (is_resource($query)) { $rs = $query; return mysql_fetch_assoc($rs); } else { $query = db_limit($query, 0, 1); $rs = db_query($query, $dat); $row = mysql_fetch_assoc($rs); db_free($rs); if ($row) { return $row; } } return false; } if ('pgsql' == $db_driver) { if (is_resource($query) || is_object($query)) { $rs = $query; return pg_fetch_assoc($rs); } else { $query = db_limit($query, 0, 1); $rs = db_query($query, $dat); $row = pg_fetch_assoc($rs); db_free($rs); if ($row) { return $row; } } return false; } } function db_row_num($query, $dat = false) { global $db_driver, $db_link; if ('mysql' == $db_driver) { if (is_resource($query)) { $rs = $query; return mysql_fetch_row($rs); } else { $rs = db_query($query, $dat); if (!$rs) { /* echo '
';
				print_r($rs);
				echo "\r\n";
				print_r($query);
				echo "\r\n";
				print_r($dat);
				exit;
				*/
			}
			$row = mysql_fetch_row($rs);
			db_free($rs);
			if ($row) {
				return $row;
			}
			return false;
		}
	}
	if ('pgsql' == $db_driver)
	{
		if (is_resource($query) || is_object($query)) {
			$rs = $query;
			return pg_fetch_row($rs);
		} else {
			$rs = db_query($query, $dat);
			$row = pg_fetch_row($rs);
			db_free($rs);
			if ($row) {
				return $row;
			}
			return false;
		}
	}
}
function db_list($query)
{
	global $db_driver, $db_link;
	$rs = db_query($query);
	$ret = array();
	if ('mysql' == $db_driver) {
		while ($row = mysql_fetch_assoc($rs)) {
			$ret[] = $row;
		}
	}
	if ('pgsql' == $db_driver) {
		while ($row = pg_fetch_assoc($rs)) {
			$ret[] = $row;
		}		
	}	
	db_free($rs);
	return $ret;
}
function db_assoc($query)
{
	global $db_driver, $db_link;
	$rs = db_query($query);
	$rows = array();
	$num = db_row_num($rs);
	if (!is_array($num)) {
		return array();
	}
	if (!array_key_exists(0, $num)) {
		return array();
	}
	if (1 == count($num)) {
		$rows[] = $num[0];
		while ($num = db_row_num($rs)) {
			$rows[] = $num[0];
		}
		return $rows;
	}
	if ('mysql' == $db_driver)
	{
		mysql_data_seek($rs, 0);
	}
	if ('pgsql' == $db_driver)
	{
		pg_result_seek($rs, 0);
	}
	$row = db_row($rs);
	if (!is_array($row)) {
		return array();
	}
	if (count($num) < 2) {
		trigger_error(sprintf('db_assoc() failed. Two fields required. Query: %s.', $query), E_USER_ERROR);
	}
	if (count($num) > 2 && count($row) <= 2) {
		trigger_error(sprintf('db_assoc() failed. If specified more than two fields, then each of them must have a unique name. Query: %s.', $query), E_USER_ERROR);
	}
	foreach ($row as $k => $v) {
		$first_key = $k;
		break;
	}
	if (count($row) > 2) {
		$rows[$row[$first_key]] = $row;
		while ($row = db_row($rs)) {
			$rows[$row[$first_key]] = $row;
		}
	} else {
		$rows[$num[0]] = $num[1];
		while ($num = db_row_num($rs)) {
			$rows[$num[0]] = $num[1];
		}
	}
	db_free($rs);
	return $rows;
}
function db_limit($query, $offset, $limit)
{
	global $db_driver;

	$offset = (int) $offset;
	$limit = (int) $limit;

	$query = trim($query);
	if (str_ends_with($query, ';')) {
		$query = str_cut_end($query, ';');
	}

	$query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s+OFFSET\s+\d+\s*$#i', '$1', $query);
	$query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s*,\s*\d+\s*$#i', '$1', $query);

	if ('mysql' == $db_driver) {
		// mysql 3.23 doesn't understand "LIMIT x OFFSET z"
		return $query." LIMIT $offset, $limit";
	} else {
		return $query." LIMIT $limit OFFSET $offset";
	}
}
function db_escape($value)
{
	global $db_driver, $db_link;
	if ('mysql' == $db_driver) {
		return mysql_real_escape_string($value, $db_link);
	}
	if ('pgsql' == $db_driver) {
		return pg_escape_string($value);
	}
}
function db_quote($s)
{
	switch (true) {
		case is_null($s): return 'NULL';
		case is_int($s): return $s;
		case is_float($s): return $s;
		case is_bool($s): return (int) $s;
		case is_string($s): return "'" . db_escape($s) . "'";
		case is_object($s): return $s->getValue();
		default:
			trigger_error(sprintf("db_quote() failed. Invalid data type: '%s'.", gettype($s)), E_USER_ERROR);
			return false;
	}
}
function db_strlen_cmp($a, $b)
{
	if (strlen($a) == strlen($b)) {
		return 0;
	}
	return strlen($a) > strlen($b) ? -1 : 1;
}
function db_bind($q, $dat)
{
	if (false === $dat) {
		return $q;
	}
	if (!is_array($dat)) {
		//return trigger_error('db_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
		$dat = array($dat);
	}

	$qBase = $q;

	// special case: LIKE '%asd%', need to ignore that
	$q_search = array("'%", "%'");
	$q_replace = array("'\$", "\$'");
	$q = str_replace($q_search, $q_replace, $q);

	preg_match_all('#%\w+#', $q, $match);
	if ($match) {
		$match = $match[0];
	}
	if (!$match || !count($match)) {
		return trigger_error('db_bind() failed. No binding keys found in the query.', E_USER_ERROR);
	}
	$keys = $match;
	usort($keys, 'db_strlen_cmp');
	$num = array();

	foreach ($keys as $key)
	{
		$key2 = str_replace('%', '', $key);
		if (is_numeric($key2)) $num[$key] = true;
		if (!array_key_exists($key2, $dat)) {
			return trigger_error(sprintf('db_bind() failed. No data found for key: %s. Query: %s.', $key, $qBase), E_USER_ERROR);
		}
		$q = str_replace($key, db_quote($dat[$key2]), $q);
	}
	if (count($num)) {
		if (count($dat) != count($num)) {
			return trigger_error('db_bind() failed. When using numeric data binding you need to use all data passed to the query. You also cannot mix numeric and name binding.', E_USER_ERROR);
		}
	}

	$q = str_replace($q_replace, $q_search, $q);

	return $q;
}
function db_free($rs)
{
	global $db_driver;
	if (db_is_result($rs)) {
		if ('mysql' == $db_driver) return mysql_free_result($rs);
		if ('pgsql' == $db_driver) return pg_free_result($rs);
	}
}
function db_is_result($rs)
{
	global $db_driver;
	if ('mysql' == $db_driver) return is_resource($rs);
	if ('pgsql' == $db_driver) return is_object($rs) || is_resource($rs);
}
function db_error()
{
	global $db_driver, $db_link;
	if ('mysql' == $db_driver) {
		if (is_resource($db_link)) {
			if (mysql_error($db_link)) {
				return mysql_error($db_link). ' ('. mysql_errno($db_link).')';
			} else {
				return false;
			}
		} else {
			if (mysql_error()) {
				return mysql_error(). ' ('. mysql_errno().')';
			} else {
				return false;
			}
		}
	}
	if ('pgsql' == $db_driver) {
		if (is_resource($db_link)) {
			return pg_last_error($db_link);
		}
	}
}
function db_begin()
{
	global $db_driver;
	if ('mysql' == $db_driver) {
		db_exe('SET AUTOCOMMIT=0');
		db_exe('BEGIN');
	}
	if ('pgsql' == $db_driver) {
		db_exe('BEGIN');
	}
}
function db_end()
{
	global $db_driver;
	if ('mysql' == $db_driver) {
		db_exe('COMMIT');
		db_exe('SET AUTOCOMMIT=1');
	}
	if ('pgsql' == $db_driver) {
		db_exe('COMMIT');
	}
}
function db_rollback()
{
	global $db_driver;
	if ('mysql' == $db_driver) {
		db_exe('ROLLBACK');
		db_exe('SET AUTOCOMMIT=1');
	}
	if ('pgsql' == $db_driver) {
		db_exe('ROLLBACK');
	}
}
function db_in_array($arr)
{
	$in = '';
	foreach ($arr as $v) {
		if ($in) $in .= ',';
		$in .= db_quote($v);
	}
	return $in;
}
function db_where($where_array, $field_prefix = null, $omit_where = false)
{
	$field_prefix = str_replace('.', '', $field_prefix);
	$where = '';
	if (count($where_array)) {
		foreach ($where_array as $wh_k => $wh)
		{
			if (is_numeric($wh_k)) {
				if ($wh) {
					if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
						$wh = $field_prefix.'.'.trim($wh);
					}
					if ($where) $where .= ' AND ';
					$where .= $wh;
				}
			} else {
				if ($wh_k) {
					if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh_k) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
						$wh_k = $field_prefix.'.'.$wh_k;
					}
					$wh = db_cond($wh_k, $wh);
					if ($where) $where .= ' AND ';
					$where .= $wh;
				}
			}
		}
		if ($where) {
			if (!$omit_where) {
				$where = ' WHERE '.$where;
			}
		}
	}
	return $where;
}
function db_insert($tbl, $dat)
{
	global $db_driver;
	if (!count($dat)) {
		trigger_error('db_insert() failed. Data is empty.', E_USER_ERROR);
		return false;
	}
	$cols = '';
	$vals = '';
	$first = true;
	foreach ($dat as $k => $v) {
		if ($first) {
			$cols .= $k;
			$vals .= db_quote($v);
			$first = false;
		} else {
			$cols .= ',' . $k;
			$vals .= ',' . db_quote($v);
		}
	}
	if ('mysql' == $db_driver) {
		$tbl = "`$tbl`";
	}
	$q = "INSERT INTO $tbl ($cols) VALUES ($vals)";
	db_exe($q);
}
// $wh = WHERE condition, might be (string) or (array)
function db_update($tbl, $dat, $wh)
{
	global $db_driver;
	if (!count($dat)) {
		trigger_error('db_update() failed. Data is empty.', E_USER_ERROR);
		return false;
	}
	$set = '';
	$first = true;
	foreach ($dat as $k => $v) {
		if ($first) {
			$set   .= $k . '=' . db_quote($v);
			$first = false;
		} else {
			$set .= ',' . $k . '=' . db_quote($v);
		}
	}
	if (is_array($wh)) {
		$wh = db_where($wh, null, $omit_where = true);
	}
	if ('mysql' == $db_driver) {
		$tbl = "`$tbl`";
	}
	$q = "UPDATE $tbl SET $set WHERE $wh";
	return db_exe($q);
}
function db_insert_id($table = null, $pk = null)
{
	global $db_driver, $db_link;
	if ('mysql' == $db_driver) {
		return mysql_insert_id($_db['conn_id']);
	}
	if ('pgsql' == $db_driver) {
		if (!$table || !$pk) {
			trigger_error('db_insert_id(): table & pk required', E_USER_ERROR);
		}
		$seq_id = $table.'_'.$pk.'_seq';
		return db_seq_id($seq_id);
	}
}
function db_seq_id($seqName)
{
	return db_one('SELECT currval(%seqName)', array('seqName'=>$seqName));
}
function db_cond($k, $v)
{
	if (is_null($v)) return sprintf('%s IS NULL', $k);
	else return sprintf('%s = %s', $k, db_quote($v));
}
function list_dbs()
{
	global $db_driver, $db_link;
	if ('mysql' == $db_driver)
	{
		$result = mysql_query('SHOW DATABASES', $db_link);
		$ret = array();
		while ($row = mysql_fetch_row($result)) {
			$ret[$row[0]] = $row[0];
		}
		return $ret;
	}
	if ('pgsql' == $db_driver)
	{
		return db_assoc('SELECT datname, datname FROM pg_database');
	}
}
function list_tables()
{
	global $db_driver, $db_link, $db_name;
	static $cache;
	if (isset($cache)) {
		return $cache;
	}
	if ('mysql' == $db_driver)
	{
		$result = mysql_unbuffered_query('SHOW TABLES', $db_link);
		$tables = array();
		while ($row = mysql_fetch_row($result)) {
			$tables[] = $row[0];
		}
		$cache = $tables;
		return $tables;
	}
	if ('pgsql' == $db_driver)
	{
		$tables = db_assoc("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name");
		$cache = $tables;
		return $tables;
	}
}
function quote_table($table)
{
	global $db_driver;
	if ('mysql' == $db_driver) {
		return "`$table`";
	} else {
		return $table;
	}
}
function table_structure($table)
{
	global $db_driver;
	if ('mysql' == $db_driver)
	{
		$query = "SHOW CREATE TABLE `$table`";
		$row = db_row_num($query);
		echo $row[1].';';
		echo "\n\n";
	}
	if ('pgsql' == $db_driver)
	{
		return '';
	}
}
function table_data($table)
{
	global $db_driver;
	set_time_limit(0);
	if ('mysql' == $db_driver) {
		$query = "SELECT * FROM `$table`";
	} else {
		$query = "SELECT * FROM $table";
	}	
	$result = db_query($query);
	$count = 0;
	while ($row = db_row($result))
	{
		if ('mysql' == $db_driver) {
			echo 'INSERT INTO `'.$table.'` VALUES (';
		}
		if ('pgsql' == $db_driver) {
			echo 'INSERT INTO '.$table.' VALUES (';
		}
		$x = 0;
		foreach($row as $key => $value)
		{
			if ($x == 1) { echo ', '; }
			else  { $x = 1; }
			if (is_numeric($value)) { echo "'".$value."'"; }
			elseif (is_null($value))  { echo 'NULL'; }
			else { echo '\''. escape($value) .'\''; }
		}
		echo ");\n";
		$count++;
		if ($count % 100 == 0) { flush(); }
	}
	db_free($result);
	if ($count) {
		echo "\n";
	}	
}
function table_status()
{
	global $db_driver, $db_link, $db_name;
	if ('mysql' == $db_driver)
	{
		$status = array();
		$status['total_size'] = 0;
		$result = mysql_query("SHOW TABLE STATUS FROM `$db_name`", $db_link);
		while ($row = mysql_fetch_assoc($result)) {
			$status['total_size'] += $row['Data_length']; // + Index_length
			$status[$row['Name']]['size'] = $row['Data_length'];
			$status[$row['Name']]['count'] = $row['Rows'];
		}
		return $status;
	}
	if ('pgsql' == $db_driver)
	{
		$status = array();
		$status['total_size'] = 0;
		$tables = list_tables();
		if (!count($tables)) {
			return $status;
		}
		$tables_in = db_in_array($tables);
		$rels = db_list("SELECT relname, reltuples, (relpages::decimal + 1) * 8 * 2 * 1024 AS relsize FROM pg_class WHERE relname IN ($tables_in)");
		foreach ($rels as $rel) {
			$status['total_size'] += $rel['relsize'];
			$status[$rel['relname']]['size'] = $rel['relsize'];
			$status[$rel['relname']]['count'] = $rel['reltuples'];
		}
		return $status;
	}
}
function table_columns($table)
{
	global $db_driver;
	static $cache = array();
	if (isset($cache[$table])) {
		return $cache[$table];
	}
	if ('mysql' == $db_driver) {
		$row = db_row("SELECT * FROM `$table`");
	} else {
		$row = db_row("SELECT * FROM $table");
	}
	if (!$row) {
		$cache[$table] = array();
		return array();
	}
	foreach ($row as $k => $v) {
		$row[$k] = $k;
	}
	$cache[$table] = $row;
	return $row;
}
function table_types($table)
{
	global $db_driver;
	if ('mysql' == $db_driver)
	{
		$rows = db_list("SHOW COLUMNS FROM `$table`");
		$types = array();
		foreach ($rows as $row) {
			$type = $row['Type'];
			$types[$row['Field']] = $type;
		}
		return $types;
	}
	if ('pgsql' == $db_driver)
	{
		return db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
	}
}
function table_types2($table)
{
	global $db_driver;
	if ('mysql' == $db_driver)
	{
		$types = array();
		$rows = @db_list("SHOW COLUMNS FROM `$table`");
		if (!($rows && count($rows))) {
			return false;
		}
		foreach ($rows as $row) {
			$type = $row['Type'];
			preg_match('#^[a-z]+#', $type, $match);
			$type = $match[0];
			$types[$row['Field']] = $type;
		}
	}
	if ('pgsql' == $db_driver)
	{
		$types = db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
		if (!count($types)) {
			return false;
		}
		foreach ($types as $col => $type) {
			preg_match('#^[a-z]+#', $type, $match);
			$type = $match[0];
			$types[$col] = $type;
		}
	}
	foreach ($types as $col => $type) {
		if ('varchar' == $type) { $type = 'char'; }
		if ('integer' == $type) { $type = 'int'; }
		if ('timestamp' == $type) { $type = 'time'; }
		$types[$col] = $type;
	}
	return $types;
}
function table_types_group($types)
{
	foreach ($types as $k => $type) {
		preg_match('#^\w+#', $type, $match);
		$type = $match[0];
		$types[$k] = $type;
	}
	$types = array_unique($types);
	$types = array_values($types);
	$types2 = array();
	foreach ($types as $type) {
		$types2[$type] = $type;
	}
	return $types2;
}
function table_pk($table)
{
	$cols = table_columns($table);
	if (!$cols) return null;
	foreach ($cols as $col) {
		return $col;
	}
}
function escape($text)
{
	$text = addslashes($text);
	$search = array("\r", "\n", "\t");
	$replace = array('\r', '\n', '\t');
	return str_replace($search, $replace, $text);
}
function ob_cleanup()
{
	while (ob_get_level()) {
		ob_end_clean();
	}
	if (headers_sent()) {
		return;
	}
	if (function_exists('headers_list')) {
		foreach (headers_list() as $header) {
			if (preg_match('/Content-Encoding:/i', $header)) {
				header('Content-encoding: none');
				break;
			}
		}
	} else {
		header('Content-encoding: none');
	}
}
function query_color($query)
{
	$color = 'red';
	$words = array('SELECT', 'UPDATE', 'DELETE', 'FROM', 'LIMIT', 'OFFSET', 'AND', 'LEFT JOIN', 'WHERE', 'SET',
		'ORDER BY', 'GROUP BY', 'GROUP', 'DISTINCT', 'COUNT', 'COUNT\(\*\)', 'IS', 'NULL', 'IS NULL', 'AS', 'ON', 'INSERT INTO', 'VALUES', 'BEGIN', 'COMMIT', 'CASE', 'WHEN', 'THEN', 'END', 'ELSE', 'IN', 'NOT', 'LIKE', 'ILIKE', 'ASC', 'DESC', 'LOWER', 'UPPER');
	$words = implode('|', $words);

	$query = preg_replace("#^({$words})(\s)#i", '$1$2', $query);
	$query = preg_replace("#(\s)({$words})$#i", '$1$2', $query);
	// replace twice, some words when preceding other are not replaced
	$query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1$2$3', $query);
	$query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1$2$3', $query);
	$query = preg_replace("#^($words)$#i", '$1', $query);

	preg_match_all('#]+>('.$words.')#i', $query, $matches);
	foreach ($matches[0] as $k => $font) {
		$font2 = str_replace($matches[1][$k], strtoupper($matches[1][$k]), $font);
		$query = str_replace($font, $font2, $query);
	}

	return $query;
}
function query_upper($sql)
{
	return $sql;
	// todo: don't upper quoted ' and ' values
	$queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $sql);
	foreach ($queries as $k => $query) {
		$strip = query_strip($query);
		$color = query_color($strip);
		$sql = str_replace($strip, $color, $sql);
	}
	$sql = preg_replace('#([^>]+)#iU', '$1', $sql);
	return $sql;
}
function html_spaces($string)
{
	$inside_tag = false;
	for ($i = 0; $i < strlen($string); $i++)
	{
		$c = $string{$i};
		if ('<' == $c) {
			$inside_tag = true;
		}
		if ('>' == $c) {
			$inside_tag = false;
		}
		if (' ' == $c && !$inside_tag) {
			$string = substr($string, 0, $i).' '.substr($string, $i+1);
			$i += strlen(' ')-1;
		}
	}
	return $string;
}
function query_cut($query)
{
	// removes sub-queries and string values from query
	$brace_start = '(';
	$brace_end = ')';
	$quote = "'";
	$inside_brace = false;
	$inside_quote = false;
	$depth = 0;
	$ret = '';
	$query = str_replace('\\\\', '', $query);

	for ($i = 0; $i < strlen($query); $i++)
	{
		$prev_char = isset($query{$i-1}) ? $query{$i-1} : null;
		$char = $query{$i};
		if ($char == $brace_start) {
			if (!$inside_quote) {
				$depth++;
			}
		}
		if ($char == $brace_end) {
			if (!$inside_quote) {
				$depth--;
				if ($depth == 0) {
					$ret .= '(...)';
				}
				continue;
			}
		}
		if ($char == $quote) {
			if ($inside_quote) {
				if ($prev_char != '\\') {
					$inside_quote = false;
					if (!$depth) {
						$ret .= "'...'";
					}
					continue;
				}
			} else {
				$inside_quote = true;
			}
		}
		if (!$depth && !$inside_quote) {
			$ret .= $char;
		}
	}
	return $ret;
}
function table_from_query($query)
{
	if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $query, $match)) {
		$cut = query_cut($query);
		if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $cut, $match2)) {
			$table = $match2[1];
		} else {
			$table = $match[1];
		}
	} else if (preg_match('#UPDATE\s+"?(\w+)"?#i', $query, $match)) {
		$table = $match[1];
	} else if (preg_match('#INSERT\s+INTO\s+"?(\w+)"?#', $query, $match)) {
		$table = $match[1];
	} else {
		$table = false;
	}
	return $table;
}
function is_select($query)
{
	return preg_match('#^\s*SELECT\s+#i', $query);
}
function query_strip($query)
{
	// strip comments and ';' from the end of query
	$query = trim($query);
	if (str_ends_with($query, ';')) {
		$query = str_cut_end($query, ';');
	}
	$lines = preg_split("#(\r\n|\n|\r)#", $query);
	foreach ($lines as $k => $line) {
		$line = trim($line);
		if (!$line || str_starts_with($line, '--')) {
			unset($lines[$k]);
		}
	}
	$query = implode("\r\n", $lines);
	return $query;
}
function dump_table($table)
{
	ob_cleanup();
	define('DEBUG_CONSOLE_HIDE', 1);
	set_time_limit(0);
	global $db_name;
	header("Cache-control: private");
	header("Content-type: application/octet-stream");
	header('Content-Disposition: attachment; filename='.$db_name.'_'.$table.'.sql');
	table_structure($table);
	table_data($table);
	exit;
}
function dump_all($data = false)
{
	global $db_name;

	ob_cleanup();
	define('DEBUG_CONSOLE_HIDE', 1);
	set_time_limit(0);
	
	$tables = list_tables();
	$table_filter = get('table_filter');
	$tables = table_filter($tables, $table_filter);

	header("Cache-control: private");
	header("Content-type: application/octet-stream");
	header('Content-Disposition: attachment; filename='.date('Ymd').'_'.$db_name.'.sql');	
	
	foreach ($tables as $key => $table)
	{
		table_structure($table);
		if ($data) {
			table_data($table);
		}
		flush();
	}
	exit;
}
function export_csv($query, $separator)
{
	ob_cleanup();
	set_time_limit(0);
	
	if (!is_select($query)) {
		trigger_error('export_csv() failed: not a SELECT query: '.$query, E_USER_ERROR);
	}
	
	$table = table_from_query($query);
	if (!$table) {
		$table = 'unknown';
	}

	header("Cache-control: private");
	header("Content-type: application/octet-stream");
	header('Content-Disposition: attachment; filename='.$table.'_'.date('Ymd').'.csv');
	
	$rs = db_query($query);
	$first = true;
	
	while ($row = db_row($rs)) {
		if ($first) {
			echo csv_row(array_keys($row), $separator);
			$first = false;
		}
		echo csv_row($row, $separator);
		flush();
	}

	exit();
}
function csv_row($row, $separator)
{
	foreach ($row as $key => $val) {
		$enquote = false;
		if (false !== strpos($val, $separator)) {
			$enquote = true;
		}
		if (false !== strpos($val, "\"")) {
			$enquote = true;
			$val = str_replace("\"", "\"\"", $val);
		}
		if (false !== strpos($val, "\r") || false !== strpos($val, "\n")) {
			$enquote = true;
			$val = preg_replace('#(\r\n|\r|\n)#', "\n", $val); // excel needs \n instead of \r\n
		}
		if ($enquote) {
			$row[$key] = "\"".$val."\"";
		}
	}
	$out = implode($separator, $row);
	$out .= "\r\n";
	return $out;
}
function import($file, $ignore_errors = false, $transaction = false, $force_myisam = false, $query_start = false)
{
	global $db_driver, $db_link, $db_charset;
	if ($ignore_errors && $transaction) {
		echo '
You cannot select both: ignoring errors and transaction
'; exit; } $count_errors = 0; set_time_limit(0); $fp = fopen($file, 'r'); if (!$fp) { exit('fopen('.$file.') failed'); } flock($fp, 1); $text = trim(fread($fp, filesize($file))); flock($fp, 3); fclose($fp); if ($db_charset == 'latin2') { $text = charset_fix($text); } if ($force_myisam) { $text = preg_replace('#TYPE\s*=\s*InnoDB#i', 'TYPE=MyISAM', $text); } $text = preg_split("#;(\r\n|\n|\r)#", $text); $x = 0; echo '
Ignoring errors: '.($ignore_errors?'Yes':'No').'
'; echo '
Transaction: '.($transaction?'Yes':'No').'
'; echo '
Force MyIsam: '.($force_myisam?'Yes':'No').'
'; echo '
Query start: #'.$query_start.'
'; echo '
Queries found: '.count($text).'
'; echo '
Executing ...
'; flush(); if ($transaction) { echo '
BEGIN;
'; db_begin(); } $time = time_start(); $query_start = (int) $query_start; if (!$query_start) { $query_start = 1; } $query_no = 0; foreach($text as $key => $value) { $x++; $query_no++; if ($query_start > $query_no) { continue; } if ('mysql' == $db_driver) { $result = @mysql_query($value.';', $db_link); } if ('pgsql' == $db_driver) { $result = @pg_query($db_link, $value.';'); } if(!$result) { $x--; if (!$count_errors) { echo ''; } $count_errors++; echo ''; flush(); if (!$ignore_errors) { echo '
ErrorQuery
#'.$query_no.' '.db_error() .')'.''.nl2br(html_once($value)).'
'; echo '
Import failed.
'; echo '
Queries executed: '.($x-$query_start+1).'.
'; if ($transaction) { echo '
ROLLBACK;
'; db_rollback(); } echo '
<< go back
'; exit; } } } if ($count_errors) { echo ''; } if ($transaction) { echo '
COMMIT;
'; db_end(); } echo '
Import finished.
'; echo '
Queries executed: '.($x-$query_start+1).'.
'; echo '
Time: '.time_end($time).' sec
'; echo '
<< go back
'; } function layout() { global $sql_area; ?>

Driver:  -  Server:  -  User:  -  Database:  -  Execute SQL ( popup )  -  Db charset:  -  Page charset:  -  Disconnect

'&', '<' => '<', '>' => '>', '"' => '"', '\'' => ''' ); $s = preg_replace('/&#(\d+)/', '@@@@@#$1', $s); $s = str_replace(array_keys($html), array_values($html), $s); $s = preg_replace('/@@@@@#(\d+)/', '&#$1', $s); return trim($s); } function html_undo($s) { $html = array( '&' => '&', '<' => '<', '>' => '>', '"' => '"', '\'' => ''' ); return str_replace(array_values($html), array_keys($html), $s); } function html_once($s) { $s = str_replace(array('<','>','&lt;','&gt;'),array('<','>','<','>'),$s); return str_replace(array('<','>','<','>'),array('&lt;','&gt;','<','>'),$s); } function html_tags($s) { // succession of str_replace array is important! double escape bug.. return str_replace(array('<','>','<','>'), array('&lt;','&gt;','<','>'), $s); } function html_tags_undo($s) { return str_replace(array('<','>','&lt;', '&gt;'), array('<','>','<','>'), $s); } function html_allow_tags($s, $allow) { $s = html_once(trim($s)); preg_match_all('#<([a-z]+)>#i', $allow, $match); foreach ($match[1] as $tag) { $s = preg_replace('#<'.$tag.'\s+style\s*=\s*"([^"<>]+)"\s*>#i', '<'.$tag.' style="$1">', $s); $s = str_replace('<'.$tag.'>', '<'.$tag.'>', $s); $s = str_replace('</'.$tag.'>', '', $s); } return $s; } function str_truncate($string, $length, $etc = ' ..', $break_words = true) { if ($length == 0) { return ''; } if (strlen($string) > $length + strlen($etc)) { if (!$break_words) { $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1)); } return substr($string, 0, $length) . $etc; } return $string; } function str_bind($s, $dat = array(), $strict = false, $recur = 0) { if (!is_array($dat)) { return trigger_error('str_bind() failed. Second argument expects to be an array.', E_USER_ERROR); } if ($strict) { foreach ($dat as $k => $v) { if (strpos($s, "%$k%") === false) { return trigger_error(sprintf('str_bind() failed. Strict mode On. Key not found = %s. String = %s. Data = %s.', $k, $s, print_r($dat, 1)), E_USER_ERROR); } $s = str_replace("%$k%", $v, $s); } if (preg_match('#%\w+%#', $s, $match)) { return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s.', $match[0], $sBase), E_USER_ERROR); } return $s; } $sBase = $s; preg_match_all('#%\w+%#', $s, $match); $keys = $match[0]; $num = array(); foreach ($keys as $key) { $key2 = str_replace('%', '', $key); if (is_numeric($key2)) $num[$key] = true; /* ignore! if (!array_key_exists($key2, $dat)) { return trigger_error(sprintf('str_bind() failed. No data found for key: %s. String: %s.', $key, $sBase), E_USER_ERROR); } */ $val = $dat[$key2]; /* insecure! if (preg_match('#%\w+%#', $val) && $recur < 5) { $val = str_bind($val, $dat, $strict, ++$recur); } */ $s = str_replace($key, $val, $s); } if (count($num)) { if (count($dat) != count($num)) { return trigger_error('str_bind() failed. When using numeric data binding you need to use all data passed to the string. You also cannot mix numeric and name binding.', E_USER_ERROR); } } if (preg_match('#%\w+%#', $s, $match)) { /* ignore! return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s. Data = %s.', $match[0], htmlspecialchars(print_r($sBase, true)), print_r($dat, true)), E_USER_ERROR);*/ } return $s; } function dir_read($dir, $ignore_ext = array(), $allow_ext = array(), $sort = null) { if (is_null($ignore_ext)) $ignore_ext = array(); if (is_null($allow_ext)) $allow_ext = array(); foreach ($allow_ext as $k => $ext) { $allow_ext[$k] = str_replace('.', '', $ext); } $ret = array(); if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if ($file != '.' && $file != '..') { $ignore = false; foreach ($ignore_ext as $ext) { if (file_ext_has($file, $ext)) { $ignore = true; } } if (is_array($allow_ext) && count($allow_ext) && !in_array(file_ext($file), $allow_ext)) { $ignore = true; } if (!$ignore) { $ret[] = array( 'file' => $dir.'/'.$file, 'time' => filemtime($dir.'/'.$file) ); } } } closedir($handle); } if ('date_desc' == $sort) { $ret = array_sort_desc($ret, 'time'); } return array_col($ret, 'file'); } function array_col($arr, $col) { $ret = array(); foreach ($arr as $k => $row) { $ret[] = $row[$col]; } return $ret; } function array_sort($arr, $col_key) { if (is_array($col_key)) { foreach ($arr as $k => $v) { $arr[$k]['__array_sort'] = ''; foreach ($col_key as $col) { $arr[$k]['__array_sort'] .= $arr[$k][$col].'_'; } } $col_key = '__array_sort'; } uasort($arr, create_function('$a,$b', 'if (is_null($a["'.$col_key.'"]) && !is_null($b["'.$col_key.'"])) return 1; if (!is_null($a["'.$col_key.'"]) && is_null($b["'.$col_key.'"])) return -1; return strnatcasecmp($a["'.$col_key.'"], $b["'.$col_key.'"]);')); if ('__array_sort' == $col_key) { foreach ($arr as $k => $v) { unset($arr[$k]['__array_sort']); } } return $arr; } function array_sort_desc($arr, $col_key) { if (is_array($col_key)) { foreach ($arr as $k => $v) { $arr[$k]['__array_sort'] = ''; foreach ($col_key as $col) { $arr[$k]['__array_sort'] .= $arr[$k][$col].'_'; } } $col_key = '__array_sort'; } uasort($arr, create_function('$a,$b', 'return strnatcasecmp($b["'.$col_key.'"], $a["'.$col_key.'"]);')); if ('__array_sort' == $col_key) { foreach ($arr as $k => $v) { unset($arr[$k]['__array_sort']); } } return $arr; } function options($options, $selected = null, $ignore_type = false) { $ret = ''; foreach ($options as $k => $v) { //str_replace('"', '\"', $k) $ret .= '