Mikailxminp

MySQLi

Jun 12th, 2018
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 115.35 KB | None | 0 0
  1. <?php
  2. ob_start('ob_gzhandler');
  3. if (!defined('DBKISS_SQL_DIR')) {
  4. define('DBKISS_SQL_DIR', 'dbkiss_sql');
  5. }
  6. error_reporting(-1);
  7. ini_set('display_errors', true);
  8. if (!ini_get('date.timezone')) {
  9. ini_set('date.timezone', 'Europe/Warsaw');
  10. }
  11. if (isset($_GET['dbkiss_favicon'])) {
  12. $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';
  13. header('Content-type: image/vnd.microsoft.icon');
  14. echo base64_decode($favicon);
  15. exit();
  16. }
  17. if (!function_exists('array_walk_recursive')){
  18. function array_walk_recursive(&$array, $func){
  19. foreach ($array as $k => $v) {
  20. if (is_array($v)) {
  21. array_walk_recursive($array[$k], $func);
  22. } else {
  23. $func($array[$k], $k);
  24. }}}}
  25. function table_filter($tables, $filter){
  26. $filter = trim($filter);
  27. if ($filter) {
  28. foreach ($tables as $k => $table) {
  29. if (!str_has_any($table, $filter, $ignore_case = true)) {
  30. unset($tables[$k]);
  31. }}}
  32. return $tables;
  33. }
  34. function get($key, $type='string'){
  35. if (is_string($key)) {
  36. $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
  37. if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
  38. settype($_GET[$key], $type);
  39. if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
  40. return $_GET[$key];
  41. }
  42. $vars = $key;
  43. foreach ($vars as $key => $type) {
  44. $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
  45. if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
  46. settype($_GET[$key], $type);
  47. if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
  48. $vars[$key] = $_GET[$key];
  49. }
  50. return $vars;
  51. }
  52. function post($key, $type='string'){
  53. if (is_string($key)) {
  54. $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
  55. if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
  56. settype($_POST[$key], $type);
  57. if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
  58. return $_POST[$key];
  59. }
  60. $vars = $key;
  61. foreach ($vars as $key => $type) {
  62. $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
  63. if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
  64. settype($_POST[$key], $type);
  65. if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
  66. $vars[$key] = $_POST[$key];
  67. }
  68. return $vars;
  69. }
  70. $_ENV['IS_GET'] = ('GET' == $_SERVER['REQUEST_METHOD']);
  71. $_ENV['IS_POST'] = ('POST' == $_SERVER['REQUEST_METHOD']);
  72. function req_gpc_has($str){
  73. foreach ($_GET as $k => $v) {
  74. if ($str == $v) {
  75. return true;
  76. }}
  77. foreach ($_POST as $k => $v) {
  78. if ($str == $v) {
  79. return true;
  80. }}
  81. foreach ($_COOKIE as $k => $v) {
  82. if ($str == $v) {
  83. return true;
  84. }}
  85. return false;
  86. }
  87. if (ini_get('magic_quotes_gpc')) {
  88. ini_set('magic_quotes_runtime', 0);
  89. array_walk_recursive($_GET, 'db_magic_quotes_gpc');
  90. array_walk_recursive($_POST, 'db_magic_quotes_gpc');
  91. array_walk_recursive($_COOKIE, 'db_magic_quotes_gpc');
  92. }
  93. function db_magic_quotes_gpc(&$val){
  94. $val = stripslashes($val);
  95. }
  96. $sql_font = 'font-size: 12px; font-family: courier new;';
  97. $sql_area = $sql_font.' width: 708px; height: 182px; border: #ccc 1px solid; background: #f9f9f9; padding: 3px;';
  98. if (!isset($db_name_style)) {
  99. $db_name_style = '';
  100. }
  101. if (!isset($db_name_h1)) {
  102. $db_name_h1 = '';
  103. }
  104. global $db_link, $db_name;
  105. if (!defined('COOKIE_PREFIX')) {
  106. define('COOKIE_PREFIX', 'dbkiss_');
  107. }
  108. define('COOKIE_WEEK', 604800);
  109. define('COOKIE_SESS', 0);
  110. function cookie_get($key){
  111. $key = COOKIE_PREFIX.$key;
  112. if (isset($_COOKIE[$key])) return $_COOKIE[$key];
  113. return null;
  114. }
  115. function cookie_set($key, $val, $time = COOKIE_SESS){
  116. $key = COOKIE_PREFIX.$key;
  117. $expire = $time ? time() + $time : 0;
  118. if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  119. setcookie($key, $val, $expire, '', '', false, true);
  120. } else {
  121. setcookie($key, $val, $expire);
  122. }
  123. $_COOKIE[$key] = $val;
  124. }
  125. function cookie_del($key){
  126. $key = COOKIE_PREFIX.$key;
  127. if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  128. setcookie($key, '', time()-3600*24, '', '', false, true);
  129. } else {
  130. setcookie($key, '', time()-3600*24);
  131. }
  132. unset($_COOKIE[$key]);
  133. }
  134. conn_modify('db_name');
  135. conn_modify('db_charset');
  136. conn_modify('page_charset');
  137. function conn_modify($key){
  138. if (array_key_exists($key, $_GET)) {
  139. cookie_set($key, $_GET[$key], cookie_get('remember') ? COOKIE_WEEK : COOKIE_SESS);
  140. if (isset($_GET['from']) && $_GET['from']) {
  141. header('Location: '.$_GET['from']);
  142. } else {
  143. header('Location: '.$_SERVER['PHP_SELF']);
  144. }
  145. exit;
  146. }}
  147. $db_driver = cookie_get('db_driver');
  148. $db_server = cookie_get('db_server');
  149. $db_name = cookie_get('db_name');
  150. $db_user = cookie_get('db_user');
  151. $db_pass = base64_decode(cookie_get('db_pass'));
  152. $db_charset = cookie_get('db_charset');
  153. $page_charset = cookie_get('page_charset');
  154. $charset1 = array('latin1', 'latin2', 'utf8', 'cp1250');
  155. $charset2 = array('iso-8859-1', 'iso-8859-2', 'utf-8', 'windows-1250');
  156. $charset1[] = $db_charset;
  157. $charset2[] = $page_charset;
  158. $charset1 = charset_assoc($charset1);
  159. $charset2 = charset_assoc($charset2);
  160. $driver_arr = array('mysql', 'pgsql');
  161. $driver_arr = array_assoc($driver_arr);
  162. function array_assoc($a){
  163. $ret = array();
  164. foreach ($a as $v) {
  165. $ret[$v] = $v;
  166. }
  167. return $ret;
  168. }
  169. function charset_assoc($arr){
  170. sort($arr);
  171. $ret = array();
  172. foreach ($arr as $v) {
  173. if (!$v) { continue; }
  174. $v = strtolower($v);
  175. $ret[$v] = $v;
  176. }
  177. return $ret;
  178. }
  179. if (isset($_GET['disconnect']) && $_GET['disconnect']){
  180. cookie_del('db_pass');
  181. header('Location: '.$_SERVER['PHP_SELF']);
  182. exit;
  183. }
  184. if (!$db_pass || (!$db_driver || !$db_server || !$db_name || !$db_user)){
  185. if ('POST' == $_SERVER['REQUEST_METHOD']){
  186. $db_driver = post('db_driver');
  187. $db_server = post('db_server');
  188. $db_name = post('db_name');
  189. $db_user = post('db_user');
  190. $db_pass = post('db_pass');
  191. $db_charset = post('db_charset');
  192. $page_charset = post('page_charset');
  193. if ($db_driver && $db_server && $db_name && $db_user){
  194. $db_test = true;
  195. db_connect($db_server, $db_name, $db_user, $db_pass);
  196. if (is_resource($db_link)){
  197. $time = post('remember') ? COOKIE_WEEK : COOKIE_SESS;
  198. cookie_set('db_driver', $db_driver, $time);
  199. cookie_set('db_server', $db_server, $time);
  200. cookie_set('db_name', $db_name, $time);
  201. cookie_set('db_user', $db_user, $time);
  202. cookie_set('db_pass', base64_encode($db_pass), $time);
  203. cookie_set('db_charset', $db_charset, $time);
  204. cookie_set('page_charset', $page_charset, $time);
  205. cookie_set('remember', post('remember'), $time);
  206. header('Location: '.$_SERVER['PHP_SELF']);
  207. exit;
  208. }}}else{
  209. $_POST['db_driver'] = $db_driver;
  210. $_POST['db_server'] = $db_server ? $db_server : 'localhost';
  211. $_POST['db_name'] = $db_name;
  212. $_POST['db_user'] = $db_user;
  213. $_POST['db_charset'] = $db_charset;
  214. $_POST['page_charset'] = $page_charset;
  215. $_POST['db_driver'] = $db_driver;
  216. }
  217. ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>MySQL</title><link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1"></head><body><?php layout(); ?><h1>Connect</h1><?php if (isset($db_test) && is_string($db_test)): ?><div style="background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em;"><span style="color: red; font-weight: bold;">Error:</span>&nbsp;
  218. <?php echo $db_test;?></div><?php endif; ?><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><table class="ls ls2" cellspacing="1"><tr><th>Driver:</th><td><select name="db_driver"><?php echo options($driver_arr, post('db_driver'));?></select></td></tr><tr><th>Server:</th><td><input type="text" name="db_server" value="<?php echo post('db_server');?>"></td></tr><tr><th>Database:</th><td><input type="text" name="db_name" value="<?php echo post('db_name');?>"></td></tr><tr><th>User:</th><td><input type="text" name="db_user" value="<?php echo post('db_user');?>"></td></tr><tr><th>Password:</th><td><input type="password" name="db_pass" value=""></td></tr><tr><th>Db charset:</th><td><input type="text" name="db_charset" value="<?php echo post('db_charset');?>" size="10"> (optional)</td></tr><tr><th>Page charset:</th><td><input type="text" name="page_charset" value="<?php echo post('page_charset');?>" size="10"> (optional)</td></tr><tr><td colspan="2" class="none" style="padding: 0; background: none; padding-top: 0.3em;"><table cellspacing="0" cellpadding="0"><tr><td><input type="checkbox" name="remember" id="remember" value="1" <?php echo checked(post('remember'));?>></td><td><label for="remember">remember me on this computer</label></td></tr></table></td></tr><tr><td class="none" colspan="2" style="padding-top: 0.4em;"><input type="submit" value="Connect"></td></tr></table></form><?php powered_by(); ?></body></html><?php
  219. exit;
  220. }
  221. db_connect($db_server, $db_name, $db_user, $db_pass);
  222. if ($db_charset && 'mysql' == $db_driver) {
  223. db_exe("SET NAMES $db_charset");
  224. }
  225. if (isset($_GET['dump_all']) && 1 == $_GET['dump_all']){
  226. dump_all($data = false);
  227. }
  228. if (isset($_GET['dump_all']) && 2 == $_GET['dump_all']){
  229. dump_all($data = true);
  230. }
  231. if (isset($_GET['dump_table']) && $_GET['dump_table']){
  232. dump_table($_GET['dump_table']);
  233. }
  234. if (isset($_GET['export']) && 'csv' == $_GET['export']){
  235. export_csv(base64_decode($_GET['query']), $_GET['separator']);
  236. }
  237. if (isset($_POST['sqlfile']) && $_POST['sqlfile']){
  238. $files = sql_files_assoc();
  239. if (!isset($files[$_POST['sqlfile']])) {
  240. exit('File not found. md5 = '.$_POST['sqlfile']);
  241. }
  242. $sqlfile = $files[$_POST['sqlfile']];
  243. layout();
  244. echo '<div>Importing: <b>'.$sqlfile.'</b> ('.size(filesize($sqlfile)).')</div>';
  245. echo '<div>Database: <b>'.$db_name.'</b></div>';
  246. flush();
  247. import($sqlfile, post('ignore_errors'), post('transaction'), post('force_myisam'), post('query_start','int'));
  248. exit;
  249. }
  250. if (isset($_POST['drop_table']) && $_POST['drop_table']){
  251. $drop_table_enq = quote_table($_POST['drop_table']);
  252. db_exe('DROP TABLE '.$drop_table_enq);
  253. header('Location: '.$_SERVER['PHP_SELF']);
  254. exit;
  255. }
  256. if (isset($_POST['drop_view']) && $_POST['drop_view']){
  257. $drop_view_enq = quote_table($_POST['drop_view']);
  258. db_exe('DROP VIEW '.$drop_view_enq);
  259. header('Location: '.$_SERVER['PHP_SELF']);
  260. exit;
  261. }
  262. function db_connect($db_server, $db_name, $db_user, $db_pass){
  263. global $db_driver, $db_link, $db_test;
  264. if (!extension_loaded($db_driver)) {
  265. trigger_error($db_driver.' extension not loaded', E_USER_ERROR);
  266. }
  267. if ('mysql' == $db_driver){
  268. $db_link = @mysql_connect($db_server, $db_user, $db_pass);
  269. if (!is_resource($db_link)) {
  270. if ($db_test) {
  271. $db_test = 'mysql_connect() failed: '.db_error();
  272. return;
  273. } else {
  274. cookie_del('db_pass');
  275. cookie_del('db_name');
  276. die('mysql_connect() failed: '.db_error());
  277. }}
  278. if (!@mysql_select_db($db_name, $db_link)) {
  279. $error = db_error();
  280. db_close();
  281. if ($db_test) {
  282. $db_test = 'mysql_select_db() failed: '.$error;
  283. return;
  284. } else {
  285. cookie_del('db_pass');
  286. cookie_del('db_name');
  287. die('mysql_select_db() failed: '.$error);
  288. }}}
  289. if ('pgsql' == $db_driver){
  290. $conn = sprintf("host='%s' dbname='%s' user='%s' password='%s'", $db_server, $db_name, $db_user, $db_pass);
  291. $db_link = @pg_connect($conn);
  292. if (!is_resource($db_link)) {
  293. if ($db_test) {
  294. $db_test = 'pg_connect() failed: '.db_error();
  295. return;
  296. } else {
  297. cookie_del('db_pass');
  298. cookie_del('db_name');
  299. die('pg_connect() failed: '.db_error());
  300. }}}
  301. register_shutdown_function('db_cleanup');
  302. }
  303. function db_cleanup(){
  304. db_close();
  305. }
  306. function db_close(){
  307. global $db_driver, $db_link;
  308. if (is_resource($db_link)) {
  309. if ('mysql' == $db_driver) {
  310. mysql_close($db_link);
  311. }
  312. if ('pgsql' == $db_driver) {
  313. pg_close($db_link);
  314. }}}
  315. function db_query($query, $dat = false){
  316. global $db_driver, $db_link;
  317. $query = db_bind($query, $dat);
  318. if (!db_is_safe($query)) {
  319. return false;
  320. }
  321. if ('mysql' == $db_driver){
  322. $rs = mysql_query($query, $db_link);
  323. return $rs;
  324. }
  325. if ('pgsql' == $db_driver){
  326. $rs = pg_query($db_link, $query);
  327. return $rs;
  328. }}
  329. function db_is_safe($q, $ret = false){
  330. $upd = 'update';
  331. $del = 'delete';
  332. $q = ltrim($q);
  333. if (strtolower(substr($q, 0, strlen($upd))) == $upd
  334. || strtolower(substr($q, 0, strlen($del))) == $del) {
  335. if (!preg_match('#\swhere\s#i', $q)) {
  336. if ($ret) {
  337. return false;
  338. } else {
  339. trigger_error(sprintf('db_is_safe() failed. Detected UPDATE/DELETE without WHERE condition. Query: %s.', $q), E_USER_ERROR);
  340. return false;
  341. }}}
  342. return true;
  343. }
  344. function db_exe($query, $dat = false){
  345. $rs = db_query($query, $dat);
  346. db_free($rs);
  347. }
  348. function db_one($query, $dat = false){
  349. $row = db_row_num($query, $dat);
  350. if ($row) {
  351. return $row[0];
  352. } else {
  353. return false;
  354. }}
  355. function db_row($query, $dat = false){
  356. global $db_driver, $db_link;
  357. if ('mysql' == $db_driver){
  358. if (is_resource($query)) {
  359. $rs = $query;
  360. return mysql_fetch_assoc($rs);
  361. } else {
  362. $query = db_limit($query, 0, 1);
  363. $rs = db_query($query, $dat);
  364. $row = mysql_fetch_assoc($rs);
  365. db_free($rs);
  366. if ($row) {
  367. return $row;
  368. }}
  369. return false;
  370. }
  371. if ('pgsql' == $db_driver){
  372. if (is_resource($query) || is_object($query)) {
  373. $rs = $query;
  374. return pg_fetch_assoc($rs);
  375. } else {
  376. $query = db_limit($query, 0, 1);
  377. $rs = db_query($query, $dat);
  378. $row = pg_fetch_assoc($rs);
  379. db_free($rs);
  380. if ($row) {
  381. return $row;
  382. }}
  383. return false;
  384. }}
  385. function db_row_num($query, $dat = false){
  386. global $db_driver, $db_link;
  387. if ('mysql' == $db_driver){
  388. if (is_resource($query)) {
  389. $rs = $query;
  390. return mysql_fetch_row($rs);
  391. } else {
  392. $rs = db_query($query, $dat);
  393. if (!$rs) {
  394. }
  395. $row = mysql_fetch_row($rs);
  396. db_free($rs);
  397. if ($row) {
  398. return $row;
  399. }
  400. return false;
  401. }}
  402. if ('pgsql' == $db_driver){
  403. if (is_resource($query) || is_object($query)) {
  404. $rs = $query;
  405. return pg_fetch_row($rs);
  406. } else {
  407. $rs = db_query($query, $dat);
  408. $row = pg_fetch_row($rs);
  409. db_free($rs);
  410. if ($row) {
  411. return $row;
  412. }
  413. return false;
  414. }}}
  415. function db_list($query){
  416. global $db_driver, $db_link;
  417. $rs = db_query($query);
  418. $ret = array();
  419. if ('mysql' == $db_driver) {
  420. while ($row = mysql_fetch_assoc($rs)) {
  421. $ret[] = $row;
  422. }}
  423. if ('pgsql' == $db_driver) {
  424. while ($row = pg_fetch_assoc($rs)) {
  425. $ret[] = $row;
  426. }}
  427. db_free($rs);
  428. return $ret;
  429. }
  430. function db_assoc($query){
  431. global $db_driver, $db_link;
  432. $rs = db_query($query);
  433. $rows = array();
  434. $num = db_row_num($rs);
  435. if (!is_array($num)) {
  436. return array();
  437. }
  438. if (!array_key_exists(0, $num)) {
  439. return array();
  440. }
  441. if (1 == count($num)) {
  442. $rows[] = $num[0];
  443. while ($num = db_row_num($rs)) {
  444. $rows[] = $num[0];
  445. }
  446. return $rows;
  447. }
  448. if ('mysql' == $db_driver){
  449. mysql_data_seek($rs, 0);
  450. }
  451. if ('pgsql' == $db_driver){
  452. pg_result_seek($rs, 0);
  453. }
  454. $row = db_row($rs);
  455. if (!is_array($row)) {
  456. return array();
  457. }
  458. if (count($num) < 2) {
  459. trigger_error(sprintf('db_assoc() failed. Two fields required. Query: %s.', $query), E_USER_ERROR);
  460. }
  461. if (count($num) > 2 && count($row) <= 2) {
  462. 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);
  463. }
  464. foreach ($row as $k => $v) {
  465. $first_key = $k;
  466. break;
  467. }
  468. if (count($row) > 2) {
  469. $rows[$row[$first_key]] = $row;
  470. while ($row = db_row($rs)) {
  471. $rows[$row[$first_key]] = $row;
  472. }} else {
  473. $rows[$num[0]] = $num[1];
  474. while ($num = db_row_num($rs)) {
  475. $rows[$num[0]] = $num[1];
  476. }}
  477. db_free($rs);
  478. return $rows;
  479. }
  480. function db_limit($query, $offset, $limit){
  481. global $db_driver;
  482. $offset = (int) $offset;
  483. $limit = (int) $limit;
  484. $query = trim($query);
  485. if (str_ends_with($query, ';')) {
  486. $query = str_cut_end($query, ';');
  487. }
  488. $query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s+OFFSET\s+\d+\s*$#i', '$1', $query);
  489. $query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s*,\s*\d+\s*$#i', '$1', $query);
  490. if ('mysql' == $db_driver) {
  491. // mysql 3.23 doesn't understand "LIMIT x OFFSET z"
  492. return $query." LIMIT $offset, $limit";
  493. } else {
  494. return $query." LIMIT $limit OFFSET $offset";
  495. }}
  496. function db_escape($value){
  497. global $db_driver, $db_link;
  498. if ('mysql' == $db_driver) {
  499. return mysql_real_escape_string($value, $db_link);
  500. }
  501. if ('pgsql' == $db_driver) {
  502. return pg_escape_string($value);
  503. }}
  504. function db_quote($s){
  505. switch (true) {
  506. case is_null($s): return 'NULL';
  507. case is_int($s): return $s;
  508. case is_float($s): return $s;
  509. case is_bool($s): return (int) $s;
  510. case is_string($s): return "'" . db_escape($s) . "'";
  511. case is_object($s): return $s->getValue();
  512. default:
  513. trigger_error(sprintf("db_quote() failed. Invalid data type: '%s'.", gettype($s)), E_USER_ERROR);
  514. return false;
  515. }}
  516. function db_strlen_cmp($a, $b){
  517. if (strlen($a) == strlen($b)) {
  518. return 0;
  519. }
  520. return strlen($a) > strlen($b) ? -1 : 1;
  521. }
  522. function db_bind($q, $dat){
  523. if (false === $dat) {
  524. return $q;
  525. }
  526. if (!is_array($dat)) {
  527. //return trigger_error('db_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
  528. $dat = array($dat);
  529. }
  530. $qBase = $q;
  531. // special case: LIKE '%asd%', need to ignore that
  532. $q_search = array("'%", "%'");
  533. $q_replace = array("'\$", "\$'");
  534. $q = str_replace($q_search, $q_replace, $q);
  535. preg_match_all('#%\w+#', $q, $match);
  536. if ($match) {
  537. $match = $match[0];
  538. }
  539. if (!$match || !count($match)) {
  540. return trigger_error('db_bind() failed. No binding keys found in the query.', E_USER_ERROR);
  541. }
  542. $keys = $match;
  543. usort($keys, 'db_strlen_cmp');
  544. $num = array();
  545. foreach ($keys as $key){
  546. $key2 = str_replace('%', '', $key);
  547. if (is_numeric($key2)) $num[$key] = true;
  548. if (!array_key_exists($key2, $dat)) {
  549. return trigger_error(sprintf('db_bind() failed. No data found for key: %s. Query: %s.', $key, $qBase), E_USER_ERROR);
  550. }
  551. $q = str_replace($key, db_quote($dat[$key2]), $q);
  552. }
  553. if (count($num)) {
  554. if (count($dat) != count($num)) {
  555. 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);
  556. }}
  557. $q = str_replace($q_replace, $q_search, $q);
  558. return $q;
  559. }
  560. function db_free($rs){
  561. global $db_driver;
  562. if (db_is_result($rs)) {
  563. if ('mysql' == $db_driver) return mysql_free_result($rs);
  564. if ('pgsql' == $db_driver) return pg_free_result($rs);
  565. }}
  566. function db_is_result($rs){
  567. global $db_driver;
  568. if ('mysql' == $db_driver) return is_resource($rs);
  569. if ('pgsql' == $db_driver) return is_object($rs) || is_resource($rs);
  570. }
  571. function db_error(){
  572. global $db_driver, $db_link;
  573. if ('mysql' == $db_driver) {
  574. if (is_resource($db_link)) {
  575. if (mysql_error($db_link)) {
  576. return mysql_error($db_link). ' ('. mysql_errno($db_link).')';
  577. } else {
  578. return false;
  579. }} else {
  580. if (mysql_error()) {
  581. return mysql_error(). ' ('. mysql_errno().')';
  582. } else {
  583. return false;
  584. }}}
  585. if ('pgsql' == $db_driver) {
  586. if (is_resource($db_link)) {
  587. return pg_last_error($db_link);
  588. }}}
  589. function db_begin(){
  590. global $db_driver;
  591. if ('mysql' == $db_driver) {
  592. db_exe('SET AUTOCOMMIT=0');
  593. db_exe('BEGIN');
  594. }
  595. if ('pgsql' == $db_driver) {
  596. db_exe('BEGIN');
  597. }}
  598. function db_end(){
  599. global $db_driver;
  600. if ('mysql' == $db_driver) {
  601. db_exe('COMMIT');
  602. db_exe('SET AUTOCOMMIT=1');
  603. }
  604. if ('pgsql' == $db_driver) {
  605. db_exe('COMMIT');
  606. }}
  607. function db_rollback(){
  608. global $db_driver;
  609. if ('mysql' == $db_driver) {
  610. db_exe('ROLLBACK');
  611. db_exe('SET AUTOCOMMIT=1');
  612. }
  613. if ('pgsql' == $db_driver) {
  614. db_exe('ROLLBACK');
  615. }}
  616. function db_in_array($arr){
  617. $in = '';
  618. foreach ($arr as $v) {
  619. if ($in) $in .= ',';
  620. $in .= db_quote($v);
  621. }
  622. return $in;
  623. }
  624. function db_where($where_array, $field_prefix = null, $omit_where = false){
  625. $field_prefix = str_replace('.', '', $field_prefix);
  626. $where = '';
  627. if (count($where_array)) {
  628. foreach ($where_array as $wh_k => $wh){
  629. if (is_numeric($wh_k)) {
  630. if ($wh) {
  631. if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
  632. $wh = $field_prefix.'.'.trim($wh);
  633. }
  634. if ($where) $where .= ' AND ';
  635. $where .= $wh;
  636. }} else {
  637. if ($wh_k) {
  638. if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh_k) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
  639. $wh_k = $field_prefix.'.'.$wh_k;
  640. }
  641. $wh = db_cond($wh_k, $wh);
  642. if ($where) $where .= ' AND ';
  643. $where .= $wh;
  644. }}}
  645. if ($where) {
  646. if (!$omit_where) {
  647. $where = ' WHERE '.$where;
  648. }}}
  649. return $where;
  650. }
  651. function db_insert($tbl, $dat){
  652. global $db_driver;
  653. if (!count($dat)) {
  654. trigger_error('db_insert() failed. Data is empty.', E_USER_ERROR);
  655. return false;
  656. }
  657. $cols = '';
  658. $vals = '';
  659. $first = true;
  660. foreach ($dat as $k => $v) {
  661. if ($first) {
  662. $cols .= $k;
  663. $vals .= db_quote($v);
  664. $first = false;
  665. } else {
  666. $cols .= ',' . $k;
  667. $vals .= ',' . db_quote($v);
  668. }}
  669. if ('mysql' == $db_driver) {
  670. $tbl = "`$tbl`";
  671. }
  672. $q = "INSERT INTO $tbl ($cols) VALUES ($vals)";
  673. db_exe($q);
  674. }
  675. function db_update($tbl, $dat, $wh){
  676. global $db_driver;
  677. if (!count($dat)) {
  678. trigger_error('db_update() failed. Data is empty.', E_USER_ERROR);
  679. return false;
  680. }
  681. $set = '';
  682. $first = true;
  683. foreach ($dat as $k => $v) {
  684. if ($first) {
  685. $set .= $k . '=' . db_quote($v);
  686. $first = false;
  687. } else {
  688. $set .= ',' . $k . '=' . db_quote($v);
  689. }}
  690. if (is_array($wh)) {
  691. $wh = db_where($wh, null, $omit_where = true);
  692. }
  693. if ('mysql' == $db_driver) {
  694. $tbl = "`$tbl`";
  695. }
  696. $q = "UPDATE $tbl SET $set WHERE $wh";
  697. return db_exe($q);
  698. }
  699. function db_insert_id($table = null, $pk = null){
  700. global $db_driver, $db_link;
  701. if ('mysql' == $db_driver) {
  702. return mysql_insert_id($_db['conn_id']);
  703. }
  704. if ('pgsql' == $db_driver) {
  705. if (!$table || !$pk) {
  706. trigger_error('db_insert_id(): table & pk required', E_USER_ERROR);
  707. }
  708. $seq_id = $table.'_'.$pk.'_seq';
  709. return db_seq_id($seq_id);
  710. }}
  711. function db_seq_id($seqName){
  712. return db_one('SELECT currval(%seqName)', array('seqName'=>$seqName));
  713. }
  714. function db_cond($k, $v){
  715. if (is_null($v)) return sprintf('%s IS NULL', $k);
  716. else return sprintf('%s = %s', $k, db_quote($v));
  717. }
  718. function list_dbs(){
  719. global $db_driver, $db_link;
  720. if ('mysql' == $db_driver){
  721. $result = mysql_query('SHOW DATABASES', $db_link);
  722. $ret = array();
  723. while ($row = mysql_fetch_row($result)) {
  724. $ret[$row[0]] = $row[0];
  725. }
  726. return $ret;
  727. }
  728. if ('pgsql' == $db_driver){
  729. return db_assoc('SELECT datname, datname FROM pg_database');
  730. }}
  731. function views_supported(){
  732. static $ret;
  733. if (isset($ret)) {
  734. return $ret;
  735. }
  736. global $db_driver, $db_link;
  737. if ('mysql' == $db_driver) {
  738. $version = mysql_get_server_info($db_link);
  739. if (strpos($version, "-") !== false) {
  740. $version = substr($version, 0, strpos($version, "-"));
  741. }
  742. if (version_compare($version, "5.0.2", ">=")) {
  743. $ret = true;
  744. return true;
  745. } else {
  746. $ret = false;
  747. return false;
  748. }}
  749. if ('pgsql' == $db_driver) {
  750. $ret = true;
  751. return true;
  752. }}
  753. function list_tables($views_mode=false){
  754. global $db_driver, $db_link, $db_name;
  755. if ($views_mode && !views_supported()) {
  756. return array();
  757. }
  758. static $cache_tables;
  759. static $cache_views;
  760. if ($views_mode) {
  761. if (isset($cache_views)) {
  762. return $cache_views;
  763. }} else {
  764. if (isset($cache_tables)) {
  765. return $cache_tables;
  766. }}
  767. static $all_tables;
  768. if ('mysql' == $db_driver){
  769. if (!isset($all_tables)) {
  770. $all_tables = db_assoc("SHOW FULL TABLES");
  771. }
  772. if ($views_mode) {
  773. $views = array();
  774. foreach ($all_tables as $view => $type) {
  775. if ($type != 'VIEW') { continue; }
  776. $views[] = $view;
  777. }
  778. $cache_views = $views;
  779. return $views;
  780. } else {
  781. $tables = array();
  782. foreach ($all_tables as $table => $type) {
  783. if ($type != 'BASE TABLE') { continue; }
  784. $tables[] = $table;
  785. }
  786. $cache_tables = $tables;
  787. return $tables;
  788. }}
  789. if ('pgsql' == $db_driver){
  790. if (!isset($all_tables)) {
  791. $query = "SELECT table_name, table_type ";
  792. $query .= "FROM information_schema.tables ";
  793. $query .= "WHERE table_schema = 'public' ";
  794. $query .= "AND (table_type = 'BASE TABLE' OR table_type = 'VIEW') ";
  795. $query .= "ORDER BY table_name ";
  796. $all_tables = db_assoc($query);
  797. }
  798. if ($views_mode) {
  799. $views = array();
  800. foreach ($all_tables as $view => $type) {
  801. if ($type != 'VIEW') { continue; }
  802. $views[] = $view;
  803. }
  804. $cache_views = $views;
  805. return $views;
  806. } else {
  807. $tables = array();
  808. foreach ($all_tables as $table => $type) {
  809. if ($type != 'BASE TABLE') { continue; }
  810. $tables[] = $table;
  811. }
  812. $cache_tables = $tables;
  813. return $tables;
  814. }}}
  815. function quote_table($table){
  816. global $db_driver;
  817. if ('mysql' == $db_driver) {
  818. return "`$table`";
  819. } else {
  820. return $table;
  821. }}
  822. function table_structure($table){
  823. global $db_driver;
  824. if ('mysql' == $db_driver){
  825. $query = "SHOW CREATE TABLE `$table`";
  826. $row = db_row_num($query);
  827. echo $row[1].';';
  828. echo "\n\n";
  829. }
  830. if ('pgsql' == $db_driver){
  831. return '';
  832. }}
  833. function table_data($table){
  834. global $db_driver;
  835. set_time_limit(0);
  836. if ('mysql' == $db_driver) {
  837. $query = "SELECT * FROM `$table`";
  838. } else {
  839. $query = "SELECT * FROM $table";
  840. }
  841. $result = db_query($query);
  842. $count = 0;
  843. while ($row = db_row($result)){
  844. if ('mysql' == $db_driver) {
  845. echo 'INSERT INTO `'.$table.'` VALUES (';
  846. }
  847. if ('pgsql' == $db_driver) {
  848. echo 'INSERT INTO '.$table.' VALUES (';
  849. }
  850. $x = 0;
  851. foreach($row as $key => $value){
  852. if ($x == 1) { echo ', '; }else { $x = 1; }
  853. if (is_numeric($value)) { echo "'".$value."'"; }elseif (is_null($value)) { echo 'NULL'; }else { echo '\''. escape($value) .'\''; }}
  854. echo ");\n";
  855. $count++;
  856. if ($count % 100 == 0) { flush(); }}
  857. db_free($result);
  858. if ($count) {
  859. echo "\n";
  860. }}
  861. function table_status(){
  862. global $db_driver, $db_link, $db_name;
  863. if ('mysql' == $db_driver){
  864. $status = array();
  865. $status['total_size'] = 0;
  866. $result = mysql_query("SHOW TABLE STATUS FROM `$db_name`", $db_link);
  867. while ($row = mysql_fetch_assoc($result)) {
  868. if (!is_numeric($row['Data_length'])) {
  869. continue;
  870. }
  871. $status['total_size'] += $row['Data_length'];
  872. $status[$row['Name']]['size'] = $row['Data_length'];
  873. $status[$row['Name']]['count'] = $row['Rows'];
  874. }
  875. return $status;
  876. }
  877. if ('pgsql' == $db_driver){
  878. $status = array();
  879. $status['total_size'] = 0;
  880. $tables = list_tables();
  881. if (!count($tables)) {
  882. return $status;
  883. }
  884. $tables_in = db_in_array($tables);
  885. $rels = db_list("SELECT relname, reltuples, (relpages::decimal + 1) * 8 * 2 * 1024 AS relsize FROM pg_class WHERE relname IN ($tables_in)");
  886. foreach ($rels as $rel) {
  887. $status['total_size'] += $rel['relsize'];
  888. $status[$rel['relname']]['size'] = $rel['relsize'];
  889. $status[$rel['relname']]['count'] = $rel['reltuples'];
  890. }
  891. return $status;
  892. }}
  893. function table_columns($table){
  894. global $db_driver;
  895. static $cache = array();
  896. if (isset($cache[$table])) {
  897. return $cache[$table];
  898. }
  899. if ('mysql' == $db_driver) {
  900. $row = db_row("SELECT * FROM `$table`");
  901. } else {
  902. $row = db_row("SELECT * FROM $table");
  903. }
  904. if (!$row) {
  905. $cache[$table] = array();
  906. return array();
  907. }
  908. foreach ($row as $k => $v) {
  909. $row[$k] = $k;
  910. }
  911. $cache[$table] = $row;
  912. return $row;
  913. }
  914. function table_types($table){
  915. global $db_driver;
  916. if ('mysql' == $db_driver){
  917. $rows = db_list("SHOW COLUMNS FROM `$table`");
  918. $types = array();
  919. foreach ($rows as $row) {
  920. $type = $row['Type'];
  921. $types[$row['Field']] = $type;
  922. }
  923. return $types;
  924. }
  925. if ('pgsql' == $db_driver){
  926. return db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
  927. }}
  928. function table_types2($table){
  929. global $db_driver;
  930. if ('mysql' == $db_driver){
  931. $types = array();
  932. $rows = @db_list("SHOW COLUMNS FROM `$table`");
  933. if (!($rows && count($rows))) {
  934. return false;
  935. }
  936. foreach ($rows as $row) {
  937. $type = $row['Type'];
  938. preg_match('#^[a-z]+#', $type, $match);
  939. $type = $match[0];
  940. $types[$row['Field']] = $type;
  941. }}
  942. if ('pgsql' == $db_driver){
  943. $types = db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
  944. if (!count($types)) {
  945. return false;
  946. }
  947. foreach ($types as $col => $type) {
  948. preg_match('#^[a-z_]+#', $type, $match);
  949. $type = $match[0];
  950. $types[$col] = $type;
  951. }}
  952. foreach ($types as $col => $type) {
  953. if ('varchar' == $type) { $type = 'char'; }
  954. if ('integer' == $type) { $type = 'int'; }
  955. if ('timestamp' == $type) { $type = 'time'; }
  956. $types[$col] = $type;
  957. }
  958. return $types;
  959. }
  960. function table_types_group($types){
  961. foreach ($types as $k => $type) {
  962. preg_match('#^\w+#', $type, $match);
  963. $type = $match[0];
  964. $types[$k] = $type;
  965. }
  966. $types = array_unique($types);
  967. $types = array_values($types);
  968. $types2 = array();
  969. foreach ($types as $type) {
  970. $types2[$type] = $type;
  971. }
  972. return $types2;
  973. }
  974. function table_pk($table){
  975. $cols = table_columns($table);
  976. if (!$cols) return null;
  977. foreach ($cols as $col) {
  978. return $col;
  979. }}
  980. function escape($text){
  981. $text = addslashes($text);
  982. $search = array("\r", "\n", "\t");
  983. $replace = array('\r', '\n', '\t');
  984. return str_replace($search, $replace, $text);
  985. }
  986. function ob_cleanup(){
  987. while (ob_get_level()) {
  988. ob_end_clean();
  989. }
  990. if (headers_sent()) {
  991. return;
  992. }
  993. if (function_exists('headers_list')) {
  994. foreach (headers_list() as $header) {
  995. if (preg_match('/Content-Encoding:/i', $header)) {
  996. header('Content-encoding: none');
  997. break;
  998. }}} else {
  999. header('Content-encoding: none');
  1000. }}
  1001. function query_color($query){
  1002. $color = 'red';
  1003. $words = array('SELECT', 'UPDATE', 'DELETE', 'FROM', 'LIMIT', 'OFFSET', 'AND', 'LEFT JOIN', 'WHERE', 'SET',
  1004. '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');
  1005. $words = implode('|', $words);
  1006. $query = preg_replace("#^({$words})(\s)#i", '<font color="'.$color.'">$1</font>$2', $query);
  1007. $query = preg_replace("#(\s)({$words})$#i", '$1<font color="'.$color.'">$2</font>', $query);
  1008. $query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1<font color="'.$color.'">$2</font>$3', $query);
  1009. $query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1<font color="'.$color.'">$2</font>$3', $query);
  1010. $query = preg_replace("#^($words)$#i", '<font color="'.$color.'">$1</font>', $query);
  1011. preg_match_all('#<font[^>]+>('.$words.')</font>#i', $query, $matches);
  1012. foreach ($matches[0] as $k => $font) {
  1013. $font2 = str_replace($matches[1][$k], strtoupper($matches[1][$k]), $font);
  1014. $query = str_replace($font, $font2, $query);
  1015. }
  1016. return $query;
  1017. }
  1018. function query_upper($sql){
  1019. return $sql;
  1020. // todo: don't upper quoted ' and ' values
  1021. $queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $sql);
  1022. foreach ($queries as $k => $query) {
  1023. $strip = query_strip($query);
  1024. $color = query_color($strip);
  1025. $sql = str_replace($strip, $color, $sql);
  1026. }
  1027. $sql = preg_replace('#<font color="\w+">([^>]+)</font>#iU', '$1', $sql);
  1028. return $sql;
  1029. }
  1030. function html_spaces($string){
  1031. $inside_tag = false;
  1032. for ($i = 0; $i < strlen($string); $i++){
  1033. $c = $string{$i};
  1034. if ('<' == $c) {
  1035. $inside_tag = true;
  1036. }
  1037. if ('>' == $c) {
  1038. $inside_tag = false;
  1039. }
  1040. if (' ' == $c && !$inside_tag) {
  1041. $string = substr($string, 0, $i).'&nbsp;'.substr($string, $i+1);
  1042. $i += strlen('&nbsp;')-1;
  1043. }}
  1044. return $string;
  1045. }
  1046. function query_cut($query){
  1047. $brace_start = '(';
  1048. $brace_end = ')';
  1049. $quote = "'";
  1050. $inside_brace = false;
  1051. $inside_quote = false;
  1052. $depth = 0;
  1053. $ret = '';
  1054. $query = str_replace('\\\\', '', $query);
  1055. for ($i = 0; $i < strlen($query); $i++){
  1056. $prev_char = isset($query{$i-1}) ? $query{$i-1} : null;
  1057. $char = $query{$i};
  1058. if ($char == $brace_start) {
  1059. if (!$inside_quote) {
  1060. $depth++;
  1061. }}
  1062. if ($char == $brace_end) {
  1063. if (!$inside_quote) {
  1064. $depth--;
  1065. if ($depth == 0) {
  1066. $ret .= '(...)';
  1067. }
  1068. continue;
  1069. }}
  1070. if ($char == $quote) {
  1071. if ($inside_quote) {
  1072. if ($prev_char != '\\') {
  1073. $inside_quote = false;
  1074. if (!$depth) {
  1075. $ret .= "'...'";
  1076. }
  1077. continue;
  1078. }} else {
  1079. $inside_quote = true;
  1080. }}
  1081. if (!$depth && !$inside_quote) {
  1082. $ret .= $char;
  1083. }}
  1084. return $ret;
  1085. }
  1086. function table_from_query($query){
  1087. if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $query, $match)) {
  1088. $cut = query_cut($query);
  1089. if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $cut, $match2)) {
  1090. $table = $match2[1];
  1091. } else {
  1092. $table = $match[1];
  1093. }} else if (preg_match('#UPDATE\s+"?(\w+)"?#i', $query, $match)) {
  1094. $table = $match[1];
  1095. } else if (preg_match('#INSERT\s+INTO\s+"?(\w+)"?#', $query, $match)) {
  1096. $table = $match[1];
  1097. } else {
  1098. $table = false;
  1099. }
  1100. return $table;
  1101. }
  1102. function is_select($query){
  1103. return preg_match('#^\s*SELECT\s+#i', $query);
  1104. }
  1105. function query_strip($query){
  1106. $query = trim($query);
  1107. if (str_ends_with($query, ';')) {
  1108. $query = str_cut_end($query, ';');
  1109. }
  1110. $lines = preg_split("#(\r\n|\n|\r)#", $query);
  1111. foreach ($lines as $k => $line) {
  1112. $line = trim($line);
  1113. if (!$line || str_starts_with($line, '--')) {
  1114. unset($lines[$k]);
  1115. }}
  1116. $query = implode("\r\n", $lines);
  1117. return $query;
  1118. }
  1119. function dump_table($table){
  1120. ob_cleanup();
  1121. define('DEBUG_CONSOLE_HIDE', 1);
  1122. set_time_limit(0);
  1123. global $db_name;
  1124. header("Cache-control: private");
  1125. header("Content-type: application/octet-stream");
  1126. header('Content-Disposition: attachment; filename='.$db_name.'_'.$table.'.sql');
  1127. table_structure($table);
  1128. table_data($table);
  1129. exit;
  1130. }
  1131. function dump_all($data = false){
  1132. global $db_name;
  1133. ob_cleanup();
  1134. define('DEBUG_CONSOLE_HIDE', 1);
  1135. set_time_limit(0);
  1136. $tables = list_tables();
  1137. $table_filter = get('table_filter');
  1138. $tables = table_filter($tables, $table_filter);
  1139. header("Cache-control: private");
  1140. header("Content-type: application/octet-stream");
  1141. header('Content-Disposition: attachment; filename='.date('Ymd').'_'.$db_name.'.sql');
  1142. foreach ($tables as $key => $table){
  1143. table_structure($table);
  1144. if ($data) {
  1145. table_data($table);
  1146. }
  1147. flush();
  1148. }
  1149. exit;
  1150. }
  1151. function export_csv($query, $separator){
  1152. ob_cleanup();
  1153. set_time_limit(0);
  1154. if (!is_select($query)) {
  1155. trigger_error('export_csv() failed: not a SELECT query: '.$query, E_USER_ERROR);
  1156. }
  1157. $table = table_from_query($query);
  1158. if (!$table) {
  1159. $table = 'unknown';
  1160. }
  1161. header("Cache-control: private");
  1162. header("Content-type: application/octet-stream");
  1163. header('Content-Disposition: attachment; filename='.$table.'_'.date('Ymd').'.csv');
  1164. $rs = db_query($query);
  1165. $first = true;
  1166. while ($row = db_row($rs)) {
  1167. if ($first) {
  1168. echo csv_row(array_keys($row), $separator);
  1169. $first = false;
  1170. }
  1171. echo csv_row($row, $separator);
  1172. flush();
  1173. }
  1174. exit();
  1175. }
  1176. function csv_row($row, $separator){
  1177. foreach ($row as $key => $val) {
  1178. $enquote = false;
  1179. if (false !== strpos($val, $separator)) {
  1180. $enquote = true;
  1181. }
  1182. if (false !== strpos($val, "\"")) {
  1183. $enquote = true;
  1184. $val = str_replace("\"", "\"\"", $val);
  1185. }
  1186. if (false !== strpos($val, "\r") || false !== strpos($val, "\n")) {
  1187. $enquote = true;
  1188. $val = preg_replace('#(\r\n|\r|\n)#', "\n", $val);
  1189. }
  1190. if ($enquote) {
  1191. $row[$key] = "\"".$val."\"";
  1192. }}
  1193. $out = implode($separator, $row);
  1194. $out .= "\r\n";
  1195. return $out;
  1196. }
  1197. function import($file, $ignore_errors = false, $transaction = false, $force_myisam = false, $query_start = false){
  1198. global $db_driver, $db_link, $db_charset;
  1199. if ($ignore_errors && $transaction) {
  1200. echo '<div>You cannot select both: ignoring errors and transaction</div>';
  1201. exit;
  1202. }
  1203. $count_errors = 0;
  1204. set_time_limit(0);
  1205. $fp = fopen($file, 'r');
  1206. if (!$fp) { exit('fopen('.$file.') failed'); }
  1207. flock($fp, 1);
  1208. $text = trim(fread($fp, filesize($file)));
  1209. flock($fp, 3);
  1210. fclose($fp);
  1211. if ($db_charset == 'latin2') {
  1212. $text = charset_fix($text);
  1213. }
  1214. if ($force_myisam) {
  1215. $text = preg_replace('#TYPE\s*=\s*InnoDB#i', 'TYPE=MyISAM', $text);
  1216. }
  1217. $text = preg_split("#;(\r\n|\n|\r)#", $text);
  1218. $x = 0;
  1219. echo '<div>Ignoring errors: <b>'.($ignore_errors?'Yes':'No').'</b></div>';
  1220. echo '<div>Transaction: <b>'.($transaction?'Yes':'No').'</b></div>';
  1221. echo '<div>Force MyIsam: <b>'.($force_myisam?'Yes':'No').'</b></div>';
  1222. echo '<div>Query start: <b>#'.$query_start.'</b></div>';
  1223. echo '<div>Queries found: <b>'.count($text).'</b></div>';
  1224. echo '<div>Executing ...</div>';
  1225. flush();
  1226. if ($transaction) {
  1227. echo '<div>BEGIN;</div>';
  1228. db_begin();
  1229. }
  1230. $time = time_start();
  1231. $query_start = (int) $query_start;
  1232. if (!$query_start) {
  1233. $query_start = 1;
  1234. }
  1235. $query_no = 0;
  1236. foreach($text as $key => $value){
  1237. $x++;
  1238. $query_no++;
  1239. if ($query_start > $query_no) {
  1240. continue;
  1241. }
  1242. if ('mysql' == $db_driver){
  1243. $result = @mysql_query($value.';', $db_link);
  1244. }
  1245. if ('pgsql' == $db_driver){
  1246. $result = @pg_query($db_link, $value.';');
  1247. }
  1248. if(!$result) {
  1249. $x--;
  1250. if (!$count_errors) {
  1251. echo '<table class="ls" cellspacing="1"><tr><th width="25%">Error</th><th>Query</th></tr>';
  1252. }
  1253. $count_errors++;
  1254. echo '<tr><td>#'.$query_no.' '.db_error() .')'.'</td><td>'.nl2br(html_once($value)).'</td></tr>';
  1255. flush();
  1256. if (!$ignore_errors) {
  1257. echo '</table>';
  1258. echo '<div><span style="color: red;"><b>Import failed.</b></span></div>';
  1259. echo '<div>Queries executed: <b>'.($x-$query_start+1).'</b>.</div>';
  1260. if ($transaction) {
  1261. echo '<div>ROLLBACK;</div>';
  1262. db_rollback();
  1263. }
  1264. echo '<br><div><a href="'.$_SERVER['PHP_SELF'].'?import=1">&lt;&lt; go back</a></div>';
  1265. exit;
  1266. }}}
  1267. if ($count_errors) {
  1268. echo '</table>';
  1269. }
  1270. if ($transaction) {
  1271. echo '<div>COMMIT;</div>';
  1272. db_end();
  1273. }
  1274. echo '<div><span style="color: green;"><b>Import finished.</b></span></div>';
  1275. echo '<div>Queries executed: <b>'.($x-$query_start+1).'</b>.</div>';
  1276. echo '<div>Time: <b>'.time_end($time).'</b> sec</div>';
  1277. echo '<br><div><a href="'.$_SERVER['PHP_SELF'].'?import=1">&lt;&lt; go back</a></div>';
  1278. }
  1279. function layout(){
  1280. global $sql_area;
  1281. ?><style>
  1282. body,table,input,select,textarea { font-family: tahoma; font-size: 11px; }
  1283. body { margin: 1em; padding: 0; margin-top: 0.5em; }
  1284. h1, h2 { font-family: arial; margin: 1em 0; }
  1285. h1 { font-size: 150%; margin: 0.7em 0; }
  1286. h2 { font-size: 125%; }
  1287. .ls th { background: #ccc; }
  1288. .ls th th { background-color: none; }
  1289. .ls td { background: #f5f5f5; }
  1290. .ls td td { background-color: none; }
  1291. .ls th, .ls td { padding: 0.1em 0.5em; }
  1292. .ls th th, .ls td td { padding: 0; }
  1293. .ls2 th { text-align: left; vertical-align: top; line-height: 1.7em; background: #e0e0e0; font-weight: normal; }
  1294. .ls2 th th { line-height: normal; background-color: none; }
  1295. p { margin: 0.8em 0; }
  1296. form { margin: 0; }
  1297. form th { text-align: left; }
  1298. a, a:visited { text-decoration: none; }
  1299. a:hover { text-decoration: underline; }
  1300. a, a.blue { color: blue; }
  1301. a:visited { color: purple; }
  1302. a.blue:visited { color: blue; }
  1303. form .none td, form .none th { background: none; padding: 0 0.25em; }
  1304. label { padding-left: 2px; padding-right: 4px; }
  1305. .checkbox { padding-left: 0; margin-left: 0; margin-top: 1px; }
  1306. .none, .ls .none { background: none; padding-top: 0.4em; }
  1307. .button { cursor: pointer; }
  1308. .button_click { background: #e0e0e0; }
  1309. .error { background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1310. .msg { background: #eee; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1311. .sql_area { <?php echo $sql_area;?> }
  1312. div.query { background: #eee; padding: 0.35em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1313. </style><script>
  1314. function mark_col(td){
  1315. }
  1316. function popup(url, width, height, more){
  1317. if (!width) width = 750;
  1318. if (!height) height = 500;
  1319. var x = (screen.width/2-width/2);
  1320. var y = (screen.height/2-height/2);
  1321. window.open(url, "", "scrollbars=yes,resizable=yes,width="+width+",height="+height+",screenX="+(x)+",screenY="+y+",left="+x+",top="+y+(more ? ","+more : ""));
  1322. }
  1323. function is_ie(){
  1324. return navigator.appVersion.indexOf("MSIE") != -1;
  1325. }
  1326. function event_add(el, event, func){
  1327. if (is_ie()) {
  1328. if (el.attachEvent) {
  1329. el.attachEvent("on"+event, func);
  1330. }} else {
  1331. if (el.addEventListener) {
  1332. el.addEventListener(event, func, false);
  1333. } else if (el.attachEvent) {
  1334. el.attachEvent("on"+event, func);
  1335. } else {
  1336. var oldfunc = el["on"+event];
  1337. el["on"+event] = function() { oldfunc(); func(); }}}}
  1338. function event_target(event){
  1339. var el;
  1340. if (window.event) el = window.event.srcElement;
  1341. else if (event) el = event.target;
  1342. if (el.nodeType == 3) el = el.parentNode;
  1343. return el;
  1344. }
  1345. function button_init(){
  1346. event_add(window, "load", function() {
  1347. for (var i = 0; i < document.forms.length; i++) {
  1348. event_add(document.forms[i], "submit", function(event) {
  1349. var form = event_target(event);
  1350. if (form.tagName != 'FORM') form = this;
  1351. for (var k = 0; k < form.elements.length; k++) {
  1352. if ("button" == form.elements[k].type || "submit" == form.elements[k].type) {
  1353. button_click(form.elements[k], true);
  1354. }}});
  1355. var form = document.forms[i];
  1356. for (var j = 0; j < form.elements.length; j++) {
  1357. if ("button" == form.elements[j].type || "submit" == form.elements[j].type) {
  1358. event_add(form.elements[j], "click", button_click);
  1359. }}}
  1360. var inputs = document.getElementsByTagName('INPUT');
  1361. for (var i = 0; i < inputs.length; i++) {
  1362. if (('button' == inputs[i].type || 'submit' == inputs[i].type) && !inputs[i].form) {
  1363. event_add(inputs[i], 'click', button_click);
  1364. }}});
  1365. }
  1366. function button_click(but, calledFromOnSubmit){
  1367. but = but.nodeName ? but : event_target(but);
  1368. if ('button' == this.type || 'submit' == this.type) {
  1369. but = this;
  1370. }
  1371. if (but.getAttribute('button_click') == 1 || but.form && but.form.getAttribute("button_click") == 1) {
  1372. return;
  1373. }
  1374. if (button_click_sess_done(but)) {
  1375. return;
  1376. }
  1377. if ("button" == but.type) {
  1378. if (but.getAttribute("wait")) {
  1379. button_wait(but);
  1380. but.setAttribute("button_click", 1);
  1381. if (but.form) {
  1382. but.form.setAttribute("button_click", 1);
  1383. }}} else if ("submit" == but.type) {
  1384. if (but.getAttribute("wait")) {
  1385. button_wait(but);
  1386. but.setAttribute("button_click", 1);
  1387. }
  1388. if (but.form) {
  1389. but.form.setAttribute("button_click", 1);
  1390. }
  1391. if (calledFromOnSubmit) {
  1392. if (but.getAttribute("block")) {
  1393. button_disable(but);
  1394. }} else {
  1395. if (!but.form.getAttribute('button_disable_onsubmit')){
  1396. event_add(but.form, "submit", function(event) {
  1397. var form = event_target(event);
  1398. if (form.tagName != 'FORM') form = this;
  1399. if (!button_disable_sess_done(form)) {
  1400. for (var i = 0; i < form.elements.length; i++) {
  1401. if (form.elements[i].getAttribute("block")) {
  1402. button_disable(form.elements[i]);
  1403. }}}});
  1404. but.form.setAttribute('button_disable_onsubmit', 1);
  1405. }}} else {
  1406. }}
  1407. function button_click_sess_done(but){
  1408. if (but.getAttribute('button_click_sess_done') == 1 || but.form && but.form.getAttribute('button_click_sess_done') == 1) {
  1409. if (but.getAttribute('button_click_sess_done') == 1) {
  1410. but.setAttribute('button_click_sess_done', 0);
  1411. }
  1412. if (but.form && but.form.getAttribute('button_click_sess_done') == 1) {
  1413. but.form.setAttribute('button_click_sess_done', 0);
  1414. }
  1415. return true;
  1416. }
  1417. return false;
  1418. }
  1419. function button_disable_sess_done(but){
  1420. if (but.getAttribute('button_disable_sess_done') == 1 || but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
  1421. if (but.getAttribute('button_disable_sess_done') == 1) {
  1422. but.setAttribute('button_disable_sess_done', 0);
  1423. }
  1424. if (but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
  1425. but.form.setAttribute('button_disable_sess_done', 0);
  1426. }
  1427. return true;
  1428. }
  1429. return false;
  1430. }
  1431. function button_disable(button){
  1432. button.disabled = true;
  1433. if (button.name){
  1434. var form = button.form;
  1435. var input = document.createElement('input');
  1436. input.setAttribute('type', 'hidden');
  1437. input.setAttribute('name', button.name);
  1438. input.setAttribute('value', button.value);
  1439. form.appendChild(input);
  1440. }}
  1441. function button_wait(but){
  1442. but.className = but.className + ' button_click';
  1443. }
  1444. function button_clear(but){
  1445. if (but.tagName == 'FORM') {
  1446. var form = but;
  1447. for (var i = 0; i < form.elements.length; i++) {
  1448. button_clear(form.elements[i]);
  1449. }
  1450. form.setAttribute('button_click', 0);
  1451. form.setAttribute('button_click_sess_done', 1);
  1452. form.setAttribute('button_disable_sess_done', 1);
  1453. } else {
  1454. if (but.type == 'submit' || but.type == 'button'){
  1455. if (but.getAttribute('button_click') == 1) {
  1456. but.className = but.className.replace('button_click', '');
  1457. but.setAttribute('button_click', 0);
  1458. but.setAttribute('button_click_sess_done', 1);
  1459. but.setAttribute('button_disable_sess_done', 1);
  1460. }
  1461. if (but.form && but.form.getAttribute('button_click') == 1) {
  1462. but.form.setAttribute('button_click', 0);
  1463. but.form.setAttribute('button_click_sess_done', 1);
  1464. but.form.setAttribute('button_disable_sess_done', 1);
  1465. }}}}
  1466. button_init();
  1467. </script><?php
  1468. }
  1469. function conn_info(){
  1470. global $db_driver, $db_server, $db_name, $db_user, $db_charset, $page_charset, $charset1, $charset2;
  1471. $dbs = list_dbs();
  1472. $db_name = $db_name;
  1473. ?><p>
  1474. Driver: <b><?php echo $db_driver;?></b>
  1475. &nbsp;-&nbsp;
  1476. Server: <b><?php echo $db_server;?></b>
  1477. &nbsp;-&nbsp;
  1478. User: <b><?php echo $db_user;?></b>
  1479. &nbsp;-&nbsp;
  1480. <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1">Execute SQL</a>
  1481. ( open in <a class=blue href="javascript:void(0)" onclick="popup('<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1&popup=1')">Popup</a> )
  1482. &nbsp;-&nbsp;
  1483. Database: <select name="db_name" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_name='+this.value"><?php echo options($dbs, $db_name);?></select>
  1484. &nbsp;-&nbsp;
  1485. Db charset: <select name="db_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'"><option value=""></option><?php echo options($charset1, $db_charset);?></select>
  1486. &nbsp;-&nbsp;
  1487. Page charset: <select name="page_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?page_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'"><option value=""></option><?php echo options($charset2, $page_charset);?></select>
  1488. &nbsp;-&nbsp;
  1489. <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?disconnect=1">Disconnect</a></p><?php
  1490. }
  1491. function size($bytes){
  1492. return number_format(ceil($bytes / 1024),0,'',',').' KB';
  1493. }
  1494. function html($s){
  1495. $html = array(
  1496. '&' => '&amp;',
  1497. '<' => '&lt;',
  1498. '>' => '&gt;',
  1499. '"' => '&quot;',
  1500. '\'' => '&#039;'
  1501. );
  1502. $s = preg_replace('/&#(\d+)/', '@@@@@#$1', $s);
  1503. $s = str_replace(array_keys($html), array_values($html), $s);
  1504. $s = preg_replace('/@@@@@#(\d+)/', '&#$1', $s);
  1505. return trim($s);
  1506. }
  1507. function html_undo($s){
  1508. $html = array(
  1509. '&' => '&amp;',
  1510. '<' => '&lt;',
  1511. '>' => '&gt;',
  1512. '"' => '&quot;',
  1513. '\'' => '&#039;'
  1514. );
  1515. return str_replace(array_values($html), array_keys($html), $s);
  1516. }
  1517. function html_once($s){
  1518. $s = str_replace(array('&lt;','&gt;','&amp;lt;','&amp;gt;'),array('<','>','&lt;','&gt;'),$s);
  1519. return str_replace(array('&lt;','&gt;','<','>'),array('&amp;lt;','&amp;gt;','&lt;','&gt;'),$s);
  1520. }
  1521. function html_tags($s){
  1522. return str_replace(array('&lt;','&gt;','<','>'), array('&amp;lt;','&amp;gt;','&lt;','&gt;'), $s);
  1523. }
  1524. function html_tags_undo($s){
  1525. return str_replace(array('&lt;','&gt;','&amp;lt;', '&amp;gt;'), array('<','>','&lt;','&gt;'), $s);
  1526. }
  1527. function html_allow_tags($s, $allow){
  1528. $s = html_once(trim($s));
  1529. preg_match_all('#<([a-z]+)>#i', $allow, $match);
  1530. foreach ($match[1] as $tag) {
  1531. $s = preg_replace('#&lt;'.$tag.'\s+style\s*=\s*&quot;([^"<>]+)&quot;\s*&gt;#i', '<'.$tag.' style="$1">', $s);
  1532. $s = str_replace('&lt;'.$tag.'&gt;', '<'.$tag.'>', $s);
  1533. $s = str_replace('&lt;/'.$tag.'&gt;', '</'.$tag.'>', $s);
  1534. }
  1535. return $s;
  1536. }
  1537. function str_truncate($string, $length, $etc = ' ..', $break_words = true){
  1538. if ($length == 0) {
  1539. return '';
  1540. }
  1541. if (strlen($string) > $length + strlen($etc)) {
  1542. if (!$break_words) {
  1543. $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
  1544. }
  1545. return substr($string, 0, $length) . $etc;
  1546. }
  1547. return $string;
  1548. }
  1549. function str_bind($s, $dat = array(), $strict = false, $recur = 0){
  1550. if (!is_array($dat)) {
  1551. return trigger_error('str_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
  1552. }
  1553. if ($strict) {
  1554. foreach ($dat as $k => $v) {
  1555. if (strpos($s, "%$k%") === false) {
  1556. 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);
  1557. }
  1558. $s = str_replace("%$k%", $v, $s);
  1559. }
  1560. if (preg_match('#%\w+%#', $s, $match)) {
  1561. return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s.', $match[0], $sBase), E_USER_ERROR);
  1562. }
  1563. return $s;
  1564. }
  1565. $sBase = $s;
  1566. preg_match_all('#%\w+%#', $s, $match);
  1567. $keys = $match[0];
  1568. $num = array();
  1569. foreach ($keys as $key){
  1570. $key2 = str_replace('%', '', $key);
  1571. if (is_numeric($key2)) $num[$key] = true;
  1572. $val = $dat[$key2];
  1573. $s = str_replace($key, $val, $s);
  1574. }
  1575. if (count($num)) {
  1576. if (count($dat) != count($num)) {
  1577. 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);
  1578. }}
  1579. if (preg_match('#%\w+%#', $s, $match)) {
  1580. }
  1581. return $s;
  1582. }
  1583. function dir_read($dir, $ignore_ext = array(), $allow_ext = array(), $sort = null){
  1584. if (is_null($ignore_ext)) $ignore_ext = array();
  1585. if (is_null($allow_ext)) $allow_ext = array();
  1586. foreach ($allow_ext as $k => $ext) {
  1587. $allow_ext[$k] = str_replace('.', '', $ext);
  1588. }
  1589. $ret = array();
  1590. if ($handle = opendir($dir)) {
  1591. while (($file = readdir($handle)) !== false) {
  1592. if ($file != '.' && $file != '..') {
  1593. $ignore = false;
  1594. foreach ($ignore_ext as $ext) {
  1595. if (file_ext_has($file, $ext)) {
  1596. $ignore = true;
  1597. }}
  1598. if (is_array($allow_ext) && count($allow_ext) && !in_array(file_ext($file), $allow_ext)) {
  1599. $ignore = true;
  1600. }
  1601. if (!$ignore) {
  1602. $ret[] = array(
  1603. 'file' => $dir.'/'.$file,
  1604. 'time' => filemtime($dir.'/'.$file)
  1605. );
  1606. }}}
  1607. closedir($handle);
  1608. }
  1609. if ('date_desc' == $sort) {
  1610. $ret = array_sort_desc($ret, 'time');
  1611. }
  1612. return array_col($ret, 'file');
  1613. }
  1614. function array_col($arr, $col){
  1615. $ret = array();
  1616. foreach ($arr as $k => $row) {
  1617. $ret[] = $row[$col];
  1618. }
  1619. return $ret;
  1620. }
  1621. function array_sort($arr, $col_key){
  1622. if (is_array($col_key)) {
  1623. foreach ($arr as $k => $v) {
  1624. $arr[$k]['__array_sort'] = '';
  1625. foreach ($col_key as $col) {
  1626. $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
  1627. }}
  1628. $col_key = '__array_sort';
  1629. }
  1630. 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.'"]);'));
  1631. if ('__array_sort' == $col_key) {
  1632. foreach ($arr as $k => $v) {
  1633. unset($arr[$k]['__array_sort']);
  1634. }}
  1635. return $arr;
  1636. }
  1637. function array_sort_desc($arr, $col_key){
  1638. if (is_array($col_key)) {
  1639. foreach ($arr as $k => $v) {
  1640. $arr[$k]['__array_sort'] = '';
  1641. foreach ($col_key as $col) {
  1642. $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
  1643. }}
  1644. $col_key = '__array_sort';
  1645. }
  1646. uasort($arr, create_function('$a,$b', 'return strnatcasecmp($b["'.$col_key.'"], $a["'.$col_key.'"]);'));
  1647. if ('__array_sort' == $col_key) {
  1648. foreach ($arr as $k => $v) {
  1649. unset($arr[$k]['__array_sort']);
  1650. }}
  1651. return $arr;
  1652. }
  1653. function options($options, $selected = null, $ignore_type = false){
  1654. $ret = '';
  1655. foreach ($options as $k => $v) {
  1656. $ret .= '<option value="'.$k.'"';
  1657. if ((is_array($selected) && in_array($k, $selected)) || (!is_array($selected) && $k == $selected && $selected !== '' && $selected !== null)) {
  1658. if ($ignore_type) {
  1659. $ret .= ' selected="selected"';
  1660. } else {
  1661. if (!(is_numeric($k) xor is_numeric($selected))) {
  1662. $ret .= ' selected="selected"';
  1663. }}}
  1664. $ret .= '>'.$v.' </option>';
  1665. }
  1666. return $ret;
  1667. }
  1668. function sql_files(){
  1669. $files = dir_read('.', null, array('.sql'));
  1670. $files2 = array();
  1671. foreach ($files as $file) {
  1672. $files2[md5($file)] = $file.sprintf(' (%s)', size(filesize($file)));
  1673. }
  1674. return $files2;
  1675. }
  1676. function sql_files_assoc(){
  1677. $files = dir_read('.', null, array('.sql'));
  1678. $files2 = array();
  1679. foreach ($files as $file) {
  1680. $files2[md5($file)] = $file;
  1681. }
  1682. return $files2;
  1683. }
  1684. function file_ext($name){
  1685. $ext = null;
  1686. if (($pos = strrpos($name, '.')) !== false) {
  1687. $len = strlen($name) - ($pos+1);
  1688. $ext = substr($name, -$len);
  1689. if (!preg_match('#^[a-z0-9]+$#i', $ext)) {
  1690. return null;
  1691. }}
  1692. return $ext;
  1693. }
  1694. function checked($bool){
  1695. if ($bool) return 'checked="checked"';
  1696. }
  1697. function radio_assoc($checked, $assoc, $input_name, $link = false){
  1698. $ret = '<table cellspacing="0" cellpadding="0"><tr>';
  1699. foreach ($assoc as $id => $name){
  1700. $params = array(
  1701. 'id' => $id,
  1702. 'name' => $name,
  1703. 'checked' => checked($checked == $id),
  1704. 'input_name' => $input_name
  1705. );
  1706. if ($link) {
  1707. if (is_array($link)) {
  1708. $params['link'] = $link[$id];
  1709. } else {
  1710. $params['link'] = sprintf($link, $id, $name);
  1711. }
  1712. $ret .= str_bind('<td><input class="checkbox" type="radio" name="%input_name%" id="%input_name%_%id%" value="%id%" %checked%></td><td>%link%&nbsp;</td>', $params);
  1713. } else {
  1714. $ret .= str_bind('<td><input class="checkbox" type="radio" name="%input_name%" id="%input_name%_%id%" value="%id%" %checked%></td><td><label for="%input_name%_%id%">%name%</label>&nbsp;</td>', $params);
  1715. }}
  1716. $ret .= '</tr></table>';
  1717. return $ret;
  1718. }
  1719. function self($cut_query = false){
  1720. $uri = $_SERVER['REQUEST_URI'];
  1721. if ($cut_query) {
  1722. $before = str_before($uri, '?');
  1723. if ($before) {
  1724. return $before;
  1725. }}
  1726. return $uri;
  1727. }
  1728. function url($script, $params = array()){
  1729. $query = '';
  1730. foreach ($params as $k => $v) {
  1731. $exp = sprintf('#(\?|&)%s=[^&]*#i', $k);
  1732. if (preg_match($exp, $script)) {
  1733. $script = preg_replace($exp, '', $script);
  1734. }}
  1735. /* repair url like 'script.php&id=12&asd=133' */
  1736. $exp = '#\?\w+=[^&]*#i';
  1737. $exp2 = '#&(\w+=[^&]*)#i';
  1738. if (!preg_match($exp, $script) && preg_match($exp2, $script)) {
  1739. $script = preg_replace($exp2, '?$1', $script, 1);
  1740. }
  1741. foreach ($params as $k => $v) {
  1742. if (!strlen($v)) continue;
  1743. if ($query) { $query .= '&'; }else {
  1744. if (strpos($script, '?') === false) {
  1745. $query .= '?';
  1746. } else {
  1747. $query .= '&';
  1748. }}
  1749. if ('%s' != $v) {
  1750. $v = urlencode($v);
  1751. }
  1752. $v = preg_replace('#%25(\w+)%25#i', '%$1%', $v);
  1753. $query .= sprintf('%s=%s', $k, $v);
  1754. }
  1755. return $script.$query;
  1756. }
  1757. function url_offset($offset, $params = array()){
  1758. $url = $_SERVER['REQUEST_URI'];
  1759. if (preg_match('#&offset=\d+#', $url)) {
  1760. $url = preg_replace('#&offset=\d+#', '&offset='.$offset, $url);
  1761. } else {
  1762. $url .= '&offset='.$offset;
  1763. }
  1764. return $url;
  1765. }
  1766. function str_wrap($s, $width, $break = ' ', $omit_tags = false){
  1767. $restart = array();
  1768. $cnt = 0;
  1769. $ret = '';
  1770. $open_tag = false;
  1771. for ($i=0; $i<strlen($s); $i++){
  1772. $char = $s{$i};
  1773. if ($omit_tags){
  1774. if ($char == '<') {
  1775. $open_tag = true;
  1776. }
  1777. if ($char == '>') {
  1778. $open_tag = false;
  1779. }
  1780. if ($open_tag) {
  1781. $ret .= $char;
  1782. continue;
  1783. }}
  1784. if (in_array($char, $restart)) {
  1785. $cnt = 0;
  1786. } else {
  1787. $cnt++;
  1788. }
  1789. $ret .= $char;
  1790. if ($cnt > $width) {
  1791. $ret .= $break;
  1792. $cnt = 0;
  1793. }}
  1794. return $ret;
  1795. }
  1796. function time_micro(){
  1797. list($usec, $sec) = explode(" ", microtime());
  1798. return ((float)$usec + (float)$sec);
  1799. }
  1800. function time_start(){
  1801. return time_micro();
  1802. }
  1803. function time_end($start){
  1804. $end = time_micro();
  1805. $end = round($end - $start, 3);
  1806. $end = pad_zeros($end, 3);
  1807. return $end;
  1808. }
  1809. function str_has($str, $needle, $ignore_case = false){
  1810. if (is_array($needle)) {
  1811. foreach ($needle as $n) {
  1812. if (!str_has($str, $n, $ignore_case)) {
  1813. return false;
  1814. }}
  1815. return true;
  1816. }
  1817. if ($ignore_case) {
  1818. $str = str_lower($str);
  1819. $needle = str_lower($needle);
  1820. }
  1821. return strpos($str, $needle) !== false;
  1822. }
  1823. function str_has_any($str, $arr_needle, $ignore_case = false){
  1824. if (is_string($arr_needle)) {
  1825. $arr_needle = preg_replace('#\s+#', ' ', $arr_needle);
  1826. $arr_needle = explode(' ', $arr_needle);
  1827. }
  1828. foreach ($arr_needle as $needle) {
  1829. if (str_has($str, $needle, $ignore_case)) {
  1830. return true;
  1831. }}
  1832. return false;
  1833. }
  1834. function str_before($str, $needle){
  1835. $pos = strpos($str, $needle);
  1836. if ($pos !== false) {
  1837. $before = substr($str, 0, $pos);
  1838. return strlen($before) ? $before : false;
  1839. } else {
  1840. return false;
  1841. }}
  1842. function pad_zeros($number, $zeros){
  1843. if (str_has($number, '.')) {
  1844. preg_match('#\.(\d+)$#', $number, $match);
  1845. $number .= str_repeat('0', $zeros-strlen($match[1]));
  1846. return $number;
  1847. } else {
  1848. return $number.'.'.str_repeat('0', $zeros);
  1849. }}
  1850. function charset_fix_invalid($s){
  1851. $fix = '???????????';
  1852. $s = str_replace(str_array($fix), '', $s);
  1853. return $s;
  1854. }
  1855. function charset_is_invalid($s){
  1856. $fix = '???????????';
  1857. $fix = str_array($fix);
  1858. foreach ($fix as $char) {
  1859. if (str_has($s, $char)) {
  1860. return true;
  1861. }}
  1862. return false;
  1863. }
  1864. function charset_fix($string){
  1865. if (charset_win_is($string)) {
  1866. $string = charset_win_fix($string);
  1867. }
  1868. if (charset_utf_is($string)) {
  1869. $string = charset_utf_fix($string);
  1870. }
  1871. return $string;
  1872. }
  1873. function charset_win_is($string){
  1874. $win = '??????????????????';
  1875. $iso = '??????????????????';
  1876. for ($i=0; $i<strlen($win); $i++) {
  1877. if ($win{$i} != $iso{$i}) {
  1878. if (strstr($string, $win{$i}) !== false) {
  1879. return true;
  1880. }}}
  1881. return false;
  1882. }
  1883. function charset_win_fix($string){
  1884. $win = '??????????????????';
  1885. $iso = '??????????????????';
  1886. $srh = array();
  1887. $rpl = array();
  1888. for ($i = 0; $i < strlen($win); $i++) {
  1889. if ($win{$i} != $iso{$i}) {
  1890. $srh[] = $win{$i};
  1891. $rpl[] = $iso{$i};
  1892. }}
  1893. $string = str_replace($srh, $rpl, $string);
  1894. return $string;
  1895. }
  1896. function charset_utf_is($string){
  1897. $utf_iso = array(
  1898. "\xc4\x85" => "\xb1",
  1899. "\xc4\x84" => "\xa1",
  1900. "\xc4\x87" => "\xe6",
  1901. "\xc4\x86" => "\xc6",
  1902. "\xc4\x99" => "\xea",
  1903. "\xc4\x98" => "\xca",
  1904. "\xc5\x82" => "\xb3",
  1905. "\xc5\x81" => "\xa3",
  1906. "\xc3\xb3" => "\xf3",
  1907. "\xc3\x93" => "\xd3",
  1908. "\xc5\x9b" => "\xb6",
  1909. "\xc5\x9a" => "\xa6",
  1910. "\xc5\xba" => "\xbc",
  1911. "\xc5\xb9" => "\xac",
  1912. "\xc5\xbc" => "\xbf",
  1913. "\xc5\xbb" => "\xaf",
  1914. "\xc5\x84" => "\xf1",
  1915. "\xc5\x83" => "\xd1",
  1916. "%u0104" => "\xA1",
  1917. "%u0106" => "\xC6",
  1918. "%u0118" => "\xCA",
  1919. "%u0141" => "\xA3",
  1920. "%u0143" => "\xD1",
  1921. "%u00D3" => "\xD3",
  1922. "%u015A" => "\xA6",
  1923. "%u0179" => "\xAC",
  1924. "%u017B" => "\xAF",
  1925. "%u0105" => "\xB1",
  1926. "%u0107" => "\xE6",
  1927. "%u0119" => "\xEA",
  1928. "%u0142" => "\xB3",
  1929. "%u0144" => "\xF1",
  1930. "%u00D4" => "\xF3",
  1931. "%u015B" => "\xB6",
  1932. "%u017A" => "\xBC",
  1933. "%u017C" => "\xBF"
  1934. );
  1935. foreach ($utf_iso as $k => $v) {
  1936. if (strpos($string, $k) !== false) {
  1937. return true;
  1938. }}
  1939. return false;
  1940. }
  1941. function charset_utf_fix($string){
  1942. $utf_iso = array(
  1943. "\xc4\x85" => "\xb1",
  1944. "\xc4\x84" => "\xa1",
  1945. "\xc4\x87" => "\xe6",
  1946. "\xc4\x86" => "\xc6",
  1947. "\xc4\x99" => "\xea",
  1948. "\xc4\x98" => "\xca",
  1949. "\xc5\x82" => "\xb3",
  1950. "\xc5\x81" => "\xa3",
  1951. "\xc3\xb3" => "\xf3",
  1952. "\xc3\x93" => "\xd3",
  1953. "\xc5\x9b" => "\xb6",
  1954. "\xc5\x9a" => "\xa6",
  1955. "\xc5\xba" => "\xbc",
  1956. "\xc5\xb9" => "\xac",
  1957. "\xc5\xbc" => "\xbf",
  1958. "\xc5\xbb" => "\xaf",
  1959. "\xc5\x84" => "\xf1",
  1960. "\xc5\x83" => "\xd1",
  1961. // xmlhttprequest uses different encoding
  1962. "%u0104" => "\xA1",
  1963. "%u0106" => "\xC6",
  1964. "%u0118" => "\xCA",
  1965. "%u0141" => "\xA3",
  1966. "%u0143" => "\xD1",
  1967. "%u00D3" => "\xD3",
  1968. "%u015A" => "\xA6",
  1969. "%u0179" => "\xAC",
  1970. "%u017B" => "\xAF",
  1971. "%u0105" => "\xB1",
  1972. "%u0107" => "\xE6",
  1973. "%u0119" => "\xEA",
  1974. "%u0142" => "\xB3",
  1975. "%u0144" => "\xF1",
  1976. "%u00D4" => "\xF3",
  1977. "%u015B" => "\xB6",
  1978. "%u017A" => "\xBC",
  1979. "%u017C" => "\xBF"
  1980. );
  1981. return str_replace(array_keys($utf_iso), array_values($utf_iso), $string);
  1982. }
  1983. function str_starts_with($str, $start, $ignore_case = false){
  1984. if ($ignore_case) {
  1985. $str = str_upper($str);
  1986. $start = str_upper($start);
  1987. }
  1988. if (!strlen($str) && !strlen($start)) {
  1989. return true;
  1990. }
  1991. if (!strlen($start)) {
  1992. trigger_error('str_starts_with() failed, start arg cannot be empty', E_USER_ERROR);
  1993. }
  1994. if (strlen($start) > strlen($str)) {
  1995. return false;
  1996. }
  1997. for ($i = 0; $i < strlen($start); $i++) {
  1998. if ($start{$i} != $str{$i}) {
  1999. return false;
  2000. }}
  2001. return true;
  2002. }
  2003. function str_ends_with($str, $end, $ignore_case = false){
  2004. if ($ignore_case) {
  2005. $str = str_upper($str);
  2006. $end = str_upper($end);
  2007. }
  2008. if (!strlen($str) && !strlen($end)) {
  2009. return true;
  2010. }
  2011. if (!strlen($end)) {
  2012. trigger_error('str_ends_with() failed, end arg cannot be empty', E_USER_ERROR);
  2013. }
  2014. if (strlen($end) > strlen($str)) {
  2015. return false;
  2016. }
  2017. return str_starts_with(strrev($str), strrev($end));
  2018. return true;
  2019. }
  2020. function str_cut_start($str, $start){
  2021. if (str_starts_with($str, $start)) {
  2022. $str = substr($str, strlen($start));
  2023. }
  2024. return $str;
  2025. }
  2026. function str_cut_end($str, $end){
  2027. if (str_ends_with($str, $end)) {
  2028. $str = substr($str, 0, -strlen($end));
  2029. }
  2030. return $str;
  2031. }
  2032. function file_get($file){
  2033. return file_get_contents($file);
  2034. }
  2035. function file_put($file, $s){
  2036. $fp = fopen($file, 'wb') or trigger_error('fopen() failed: '.$file, E_USER_ERROR);
  2037. if ($fp) {
  2038. fwrite($fp, $s);
  2039. fclose($fp);
  2040. }}
  2041. function file_date($file){
  2042. return date('Y-m-d H:i:s', filemtime($file));
  2043. }
  2044. function dir_exists($dir){
  2045. return file_exists($dir) && !is_file($dir);
  2046. }
  2047. function dir_delete_old_files($dir, $ext = array(), $sec){
  2048. // NOT USED right now.
  2049. // older than x seconds
  2050. $files = dir_read($dir, null, $ext);
  2051. $time = time() - $sec;
  2052. foreach ($files as $file) {
  2053. if (file_time($file) < $time) {
  2054. unlink($file);
  2055. }}}
  2056. global $_error, $_error_style;
  2057. $_error = array();
  2058. $_error_style = '';
  2059. function error($msg = null){
  2060. if (isset($msg) && func_num_args() > 1) {
  2061. $args = func_get_args();
  2062. $msg = call_user_func_array('sprintf', $args);
  2063. }
  2064. global $_error, $_error_style;
  2065. if (isset($msg)) {
  2066. $_error[] = $msg;
  2067. }
  2068. if (!count($_error)) {
  2069. return null;
  2070. }
  2071. if (count($_error) == 1) {
  2072. return sprintf('<div class="error" style="%s">%s</div>', $_error_style, $_error[0]);
  2073. }
  2074. $ret = '<div class="error" style="'.$_error_style.'">Following errors appeared:<ul>';
  2075. foreach ($_error as $msg) {
  2076. $ret .= sprintf('<li>%s</li>', $msg);
  2077. }
  2078. $ret .= '</ul></div>';
  2079. return $ret;
  2080. }
  2081. function timestamp($time, $span = true){
  2082. $time_base = $time;
  2083. $time = substr($time, 0, 16);
  2084. $time2 = substr($time, 0, 10);
  2085. $today = date('Y-m-d');
  2086. $yesterday = date('Y-m-d', time()-3600*24);
  2087. if ($time2 == $today) {
  2088. if (substr($time_base, -8) == '00:00:00') {
  2089. $time = 'Today';
  2090. } else {
  2091. $time = 'Today'.substr($time, -6);
  2092. }} else if ($time2 == $yesterday) {
  2093. $time = 'Yesterday'.substr($time, -6);
  2094. }
  2095. return '<span style="white-space: nowrap;">'.$time.'</span>';
  2096. }
  2097. function str_lower($str){
  2098. $lower = str_array(iso_chars_lower());
  2099. $upper = str_array(iso_chars_upper());
  2100. $str = str_replace($upper, $lower, $str);
  2101. $str = strtolower($str);
  2102. return $str;
  2103. }
  2104. function str_upper($str){
  2105. $lower = str_array(iso_chars_lower());
  2106. $upper = str_array(iso_chars_upper());
  2107. $str = str_replace($lower, $upper, $str);
  2108. $str = strtoupper($str);
  2109. return $str;
  2110. }
  2111. function str_array($str){
  2112. $arr = array();
  2113. for ($i = 0; $i < strlen($str); $i++) {
  2114. $arr[$i] = $str{$i};
  2115. }
  2116. return $arr;
  2117. }
  2118. function iso_chars(){
  2119. return iso_chars_lower().iso_chars_upper();
  2120. }
  2121. function iso_chars_lower(){
  2122. return '?????????';
  2123. }
  2124. function iso_chars_upper(){
  2125. return '?????????';
  2126. }
  2127. function array_first_key($arr){
  2128. $arr2 = $arr;
  2129. reset($arr);
  2130. list($key, $val) = each($arr);
  2131. return $key;
  2132. }
  2133. function array_first($arr){
  2134. return array_first_value($arr);
  2135. }
  2136. function array_first_value($arr){
  2137. $arr2 = $arr;
  2138. return array_shift($arr2);
  2139. }
  2140. function array_col_values($arr, $col){
  2141. $ret = array();
  2142. foreach ($arr as $k => $row) {
  2143. $ret[] = $row[$col];
  2144. }
  2145. return $ret;
  2146. }
  2147. function array_col_values_unique($arr, $col){
  2148. return array_unique(array_col_values($arr, $col));
  2149. }
  2150. function array_col_match($rows, $col, $pattern){
  2151. if (!count($rows)) {
  2152. trigger_error('array_col_match(): array is empty', E_USER_ERROR);
  2153. }
  2154. $ret = true;
  2155. foreach ($rows as $row) {
  2156. if (!preg_match($pattern, $row[$col])) {
  2157. return false;
  2158. }}
  2159. return true;
  2160. }
  2161. function array_col_match_unique($rows, $col, $pattern){
  2162. if (!array_col_match($rows, $col, $pattern)) {
  2163. return false;
  2164. }
  2165. return count($rows) == count(array_col_values_unique($rows, $col));
  2166. }
  2167. function redirect($url){
  2168. $url = url($url);
  2169. header("Location: $url");
  2170. exit;
  2171. }
  2172. function redirect_notify($url, $msg){
  2173. if (strpos($msg, '<') === false) {
  2174. $msg = sprintf('<b>%s</b>', $msg);
  2175. }
  2176. cookie_set('flash_notify', $msg);
  2177. redirect($url);
  2178. }
  2179. function redirect_ok($url, $msg){
  2180. if (strpos($msg, '<') === false) {
  2181. $msg = sprintf('<b>%s</b>', $msg);
  2182. }
  2183. cookie_set('flash_ok', $msg);
  2184. redirect($url);
  2185. }
  2186. function redirect_error($url, $msg){
  2187. if (strpos($msg, '<') === false) {
  2188. $msg = sprintf('<b>%s</b>', $msg);
  2189. }
  2190. cookie_set('flash_error', $msg);
  2191. redirect($url);
  2192. }
  2193. function flash(){
  2194. static $is_style = false;
  2195. $flash_error = cookie_get('flash_error');
  2196. $flash_ok = cookie_get('flash_ok');
  2197. $flash_notify = cookie_get('flash_notify');
  2198. $flash_error = filter_allow_tags($flash_error, '<b><i><u><br><span>');
  2199. $flash_ok = filter_allow_tags($flash_ok, '<b><i><u><br><span>');
  2200. $flash_notify = filter_allow_tags($flash_notify, '<b><i><u><br><span>');
  2201. if (!($flash_error || $flash_ok || $flash_notify)) {
  2202. return false;
  2203. }
  2204. ob_start();
  2205. ?><?php if (!$is_style): ?><style type="text/css">
  2206. #flash { background: #ffffd7; padding: 0.3em; padding-bottom: 0.15em; border: #ddd 1px solid; margin-bottom: 1em; }
  2207. #flash div { padding: 0em 0em; }
  2208. #flash table { font-weight: normal; }
  2209. #flash td { text-align: left; }
  2210. </style><?php endif; ?><div id="flash" ondblclick="document.getElementById('flash').style.display='none';"><table width="100%" ondblclick="document.getElementById('flash').style.display='none';"><tr><td style="line-height: 14px;"><?php echo $flash_error ? $flash_error : ($flash_ok ? $flash_ok : $flash_notify); ?></td></tr></table></div><?php
  2211. $cont = ob_get_contents();
  2212. ob_end_clean();
  2213. if ($flash_error) cookie_del('flash_error');
  2214. else if ($flash_ok) cookie_del('flash_ok');
  2215. else if ($flash_notify) cookie_del('flash_notify');
  2216. $is_style = true;
  2217. return $cont;
  2218. }
  2219. function filter($post, $filters){
  2220. if (is_string($filters)){
  2221. $filter = $filters;
  2222. $func = 'filter_'.$filter;
  2223. foreach ($post as $key => $val) {
  2224. $post[$key] = call_user_func($func, $post[$key]);
  2225. }
  2226. return $post;
  2227. }
  2228. foreach ($filters as $key => $filter){
  2229. if (!array_key_exists($key, $post)) {
  2230. return trigger_error(sprintf('filter() failed. Key missing = %s.', $key), E_USER_ERROR);
  2231. }
  2232. $func = 'filter_'.$filter;
  2233. if (!function_exists($func)) {
  2234. return trigger_error(sprintf('filter() failed. Filter missing = %s.', $func), E_USER_ERROR);
  2235. }
  2236. $post[$key] = call_user_func($func, $post[$key]);
  2237. }
  2238. return $post;
  2239. }
  2240. function filter_html($s){
  2241. if (req_gpc_has($s)) {
  2242. $s = html_tags_undo($s);
  2243. }
  2244. return html(trim($s));
  2245. }
  2246. function filter_allow_tags($s, $allow){
  2247. if (req_gpc_has($s)) {
  2248. $s = html_tags_undo($s);
  2249. }
  2250. return html_allow_tags($s, $allow);
  2251. }
  2252. function filter_allow_html($s){
  2253. global $SafeHtml;
  2254. if (!isset($SafeHtml)) {
  2255. include_once 'inc/SafeHtml.php';
  2256. }
  2257. if (req_gpc_has($s)) {
  2258. $s = html_tags_undo($s);
  2259. }
  2260. if (in_array(trim(strtolower($s)), array('<br>', '<p>&nbsp;</p>'))) {
  2261. return '';
  2262. }
  2263. $SafeHtml->clear();
  2264. $s = $SafeHtml->parse($s);
  2265. return trim($s);
  2266. }
  2267. function filter_allow_html_script($s){
  2268. if (in_array(trim(strtolower($s)), array('<br>', '<p>&nbsp;</p>'))) {
  2269. return '';
  2270. }
  2271. if (req_gpc_has($s)) {
  2272. $s = html_tags_undo($s);
  2273. }
  2274. return trim($s);
  2275. }
  2276. function filter_editor($s){
  2277. return filter_allow_html($s);
  2278. }
  2279. function date_now(){
  2280. return date('Y-m-d H:i:s');
  2281. }
  2282. function guess_pk($rows){
  2283. if (!count($rows)) {
  2284. return false;
  2285. }
  2286. $patterns = array('#^\d+$#', '#^[^\s]+$#');
  2287. $row = array_first($rows);
  2288. foreach ($patterns as $pattern){
  2289. foreach ($row as $col => $v) {
  2290. if ($v && preg_match($pattern, $v)) {
  2291. if (array_col_match_unique($rows, $col, $pattern)) {
  2292. return $col;
  2293. }}}}
  2294. return false;
  2295. }
  2296. function layout_start($title=''){
  2297. global $page_charset;
  2298. $flash = flash();
  2299. ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>"><title><?php echo $title;?></title><link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1"><script>
  2300. function $(id){
  2301. if (typeof id == 'string') return document.getElementById(id);
  2302. return id;
  2303. }
  2304. </script></head><body><?php layout(); ?><?php if ($flash) { echo $flash; } ?><?php
  2305. }
  2306. function layout_end(){
  2307. ?><?php powered_by(); ?></body></html><?php
  2308. }
  2309. function powered_by(){
  2310. ?><script>
  2311. function link_noreferer(link){
  2312. var w = window.open("about:blank", "_blank");
  2313. w.document.open();
  2314. w.document.write("<"+"!doctype html>");
  2315. w.document.write("<"+"html><"+"head>");
  2316. w.document.write("<"+"title>Secure redirection - no referer</title>");
  2317. w.document.write("<"+"style>body { font: 11px Tahoma; }<"+"/style>");
  2318. w.document.write("<"+"meta http-equiv=refresh content='10;url="+link+"'>");
  2319. w.document.write("<"+"script>function redirect() { if (navigator.userAgent.indexOf('MSIE') != -1) { location.replace('"+link+"'); } else { document.open(); document.write('<"+"meta http-equiv=refresh content=\"0;"+link+"\">'); document.close(); } }<"+"/script>");
  2320. w.document.write("<"+"/head><"+"body>");
  2321. w.document.write("<"+"h1>Secure redirection - no referer<"+"/h1>");
  2322. w.document.write("<"+"p>This is a secure redirection that hides the HTTP REFERER header - using javascript and meta refresh combination.");
  2323. w.document.write("<br>The site you are being redirected will not know the location of the dbkiss script on your site.<"+"/p>");
  2324. w.document.write("<"+"p>In a few seconds you will be redirected or you can click the link (also secure): <"+"a href='javascript:void(0)' onclick='redirect()'>"+link+"<"+"/a><"+"/p>");
  2325. w.document.write("<"+"/body><"+"/html>");
  2326. w.document.close();
  2327. }
  2328. </script><div style="text-align: center; margin-top: 2em; border-top: #ccc 1px solid; padding-top: 0.5em;">Powered by <a href="javascript:void(0)" onclick="link_noreferer('https://www.instagram.com/xminp_')">Xminp</a></div><?php
  2329. }
  2330. ?><?php if (get('import')): ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>"><title><?php echo $db_name_h1?$db_name_h1:$db_name;?> &gt; Import</title><link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1"></head><body><?php layout(); ?><h1><a class=blue style="<?php echo $db_name_style;?>" href="<?php echo $_SERVER['PHP_SELF'];?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></a> &gt; Import</h1><?php conn_info(); ?><?php $files = sql_files(); ?><?php if (count($files)): ?><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"><table class="none" cellspacing="0" cellpadding="0"><tr><td>SQL file:</th><td><select name="sqlfile"><option value="" selected="selected"></option><?php echo options($files);?></select></td><td><input type="checkbox" name="ignore_errors" id="ignore_errors" value="1"></td><td><label for="ignore_errors">ignore errors</label></td><td><input type="checkbox" name="transaction" id="transaction" value="1"></td><td><label for="transaction">transaction</label></td><td><input type="checkbox" name="force_myisam" id="force_myisam" value="1"></td><td><label for="force_myisam">force myisam</label></td><td><input type="text" size="5" name="query_start" value=""></td><td>query start</td><td><input type="submit" value="Import"></td></tr></table></form><br><?php else: ?>
  2331. No sql files found in current directory.
  2332. <?php endif; ?><?php powered_by(); ?></body></html><?php exit; endif; ?><?php if ('editrow' == get('action')): ?><?php
  2333. function dbkiss_filter_id($id){
  2334. if (preg_match('#^[_a-z][a-z0-9_\-]*$#i', $id)) {
  2335. return $id;
  2336. }
  2337. return false;
  2338. }
  2339. $get = get(array(
  2340. 'table' => 'string',
  2341. 'pk' => 'string',
  2342. 'id' => 'string'
  2343. ));
  2344. $get['table'] = html_once($get['table']);
  2345. $get['pk'] = html_once($get['pk']);
  2346. $title_edit = sprintf('Edit row (%s=%s)', $get['pk'], $get['id']);
  2347. $title = ' &gt; '.$get['table'].' &gt; '.$title_edit;
  2348. if (!dbkiss_filter_id($get['table'])) {
  2349. error('Invalid table name');
  2350. }
  2351. if (!dbkiss_filter_id($get['pk'])) {
  2352. error('Invalid pk');
  2353. }
  2354. $row = false;
  2355. if (!error()){
  2356. $table_enq = quote_table($get['table']);
  2357. $test = db_row("SELECT * FROM $table_enq");
  2358. if ($test) {
  2359. if (!array_key_exists($get['pk'], $test)) {
  2360. error('Invalid pk');
  2361. }}
  2362. if (!error()){
  2363. $table_enq = quote_table($get['table']);
  2364. $query = db_bind("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
  2365. $query = db_limit($query, 0, 2);
  2366. $rows = db_list($query);
  2367. if (count($rows) > 1) {
  2368. error('Invalid pk: found more than one row with given id');
  2369. } else if (count($rows) == 0) {
  2370. error('Row not found');
  2371. } else {
  2372. $row = $rows[0];
  2373. $row_id = $row[$get['pk']];
  2374. }}}
  2375. if ($row) {
  2376. $types = table_types2($get['table']);
  2377. }
  2378. $edit_actions_assoc = array(
  2379. 'update' => 'Update',
  2380. 'update_pk' => 'Overwrite pk',
  2381. 'insert' => 'Copy row (insert)',
  2382. 'delete' => 'Delete'
  2383. );
  2384. $edit_action = post('dbkiss_action');
  2385. if ($_ENV['IS_GET']){
  2386. $edit_action = array_first_key($edit_actions_assoc);
  2387. $post = $row;
  2388. }
  2389. if ($_ENV['IS_POST']){
  2390. if (!array_key_exists($edit_action, $edit_actions_assoc)) {
  2391. $edit_action = '';
  2392. error('Invalid action');
  2393. }
  2394. $post = array();
  2395. foreach ($row as $k => $v) {
  2396. if (array_key_exists($k, $_POST)) {
  2397. $val = (string) $_POST[$k];
  2398. if ('null' == $val) {
  2399. $val = null;
  2400. }
  2401. if ('int' == $types[$k]) {
  2402. if (!strlen($val)) {
  2403. $val = null;
  2404. }
  2405. if (!(preg_match('#^-?\d+$#', $val) || is_null($val))) {
  2406. error('%s: invalid value', $k);
  2407. }}
  2408. if ('float' == $types[$k]) {
  2409. if (!strlen($val)) {
  2410. $val = null;
  2411. }
  2412. $val = str_replace(',', '.', $val);
  2413. if (!(is_numeric($val) || is_null($val))) {
  2414. error('%s: invalid value', $k);
  2415. }}
  2416. if ('time' == $types[$k]) {
  2417. if (!strlen($val)) {
  2418. $val = null;
  2419. }
  2420. if ('now' == $val) {
  2421. $val = date_now();
  2422. }}
  2423. $post[$k] = $val;
  2424. } else {
  2425. error('Missing key: %s in POST', $k);
  2426. }}
  2427. if ('update' == $edit_action){
  2428. if ($post[$get['pk']] != $row[$get['pk']]) {
  2429. if (count($row) != 1) { // Case: more than 1 column
  2430. error('%s: cannot change pk on UPDATE', $get['pk']);
  2431. }}}
  2432. if ('update_pk' == $edit_action){
  2433. if ($post[$get['pk']] == $row[$get['pk']]) {
  2434. error('%s: selected action Overwrite pk, but pk value has not changed', $get['pk']);
  2435. }}
  2436. if ('insert' == $edit_action){
  2437. if (strlen($post[$get['pk']])) {
  2438. $table_enq = quote_table($get['table']);
  2439. $test = db_row("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", array($post[$get['pk']]));
  2440. if ($test) {
  2441. error('%s: there is already a record with that id', $get['pk']);
  2442. }}}
  2443. if (!error()){
  2444. $post2 = $post;
  2445. if ('update' == $edit_action){
  2446. if (count($row) != 1) {
  2447. unset($post2[$get['pk']]);
  2448. }
  2449. db_update($get['table'], $post2, array($get['pk'] => $row_id));
  2450. if (db_error()) {
  2451. error('<font color="red"><b>DB error</b></font>: '.db_error());
  2452. } else {
  2453. if (count($row) == 1) {
  2454. redirect_ok(url(self(), array('id'=>$post[$get['pk']])), 'Row updated');
  2455. } else {
  2456. redirect_ok(self(), 'Row updated');
  2457. }}}
  2458. if ('update_pk' == $edit_action){
  2459. @db_update($get['table'], $post2, array($get['pk'] => $row_id));
  2460. if (db_error()) {
  2461. error('<font color="red"><b>DB error</b></font>: '.db_error());
  2462. } else {
  2463. $url = url(self(), array('id' => $post[$get['pk']]));
  2464. redirect_ok($url, 'Row updated (pk overwritten)');
  2465. }}
  2466. if ('insert' == $edit_action){
  2467. $new_id = false;
  2468. if (!strlen($post2[$get['pk']])) {
  2469. unset($post2[$get['pk']]);
  2470. } else {
  2471. $new_id = $post2[$get['pk']];
  2472. }
  2473. @db_insert($get['table'], $post2);
  2474. if (db_error()) {
  2475. error('<font color="red"><b>DB error</b></font>: '.db_error());
  2476. } else {
  2477. if (!$new_id) {
  2478. $new_id = db_insert_id($get['table'], $get['pk']);
  2479. }
  2480. $url = url(self(), array('id'=>$new_id));
  2481. $msg = sprintf('Row inserted (%s=%s)', $get['pk'], $new_id);
  2482. redirect_ok($url, $msg);
  2483. }}
  2484. if ('delete' == $edit_action){
  2485. $table_enq = quote_table($get['table']);
  2486. @db_exe("DELETE FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
  2487. if (db_error()) {
  2488. error('<font color="red"><b>DB error</b></font>: '.db_error());
  2489. } else {
  2490. redirect_ok(self(), 'Row deleted');
  2491. }}}}
  2492. ?><?php layout_start($title_edit); ?><h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span><?php echo $title;?></h1><?php echo error();?><?php if ($row): ?><form action="<?php echo self();?>" method="post"><?php echo radio_assoc($edit_action, $edit_actions_assoc, 'dbkiss_action');?></td><br><table cellspacing="1" class="ls ls2"><?php foreach ($post as $k => $v): if (is_null($v)) { $v = 'null'; } $v = htmlspecialchars($v); ?><tr><th><?php echo $k;?>:</th><td><?php if ('int' == $types[$k]): ?><input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="11"><?php elseif ('char' == $types[$k]): ?><input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="50"><?php elseif (in_array($types[$k], array('text', 'mediumtext', 'longtext')) || str_has($types[$k], 'blob')): ?><textarea name="<?php echo $k;?>" cols="80" rows="<?php echo $k=='notes'?10:10;?>"><?php echo html_once($v);?></textarea><?php else: ?><input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="30"><?php endif; ?></td><td valign="top"><?php echo $types[$k];?></td></tr><?php endforeach; ?><tr><td colspan="3" class="none"><input type="submit" wait="1" block="1" class="button" value="Edit"></td></tr></table></form><?php endif; ?><?php layout_end(); ?><?php exit; endif; ?><?php if (isset($_GET['execute_sql']) && $_GET['execute_sql']): ?><?php
  2493. function listing($base_query, $md5_get = false){
  2494. global $db_driver, $db_link;
  2495. $md5_i = false;
  2496. if ($md5_get) {
  2497. preg_match('#_(\d+)$#', $md5_get, $match);
  2498. $md5_i = $match[1];
  2499. }
  2500. $base_query = trim($base_query);
  2501. $base_query = str_cut_end($base_query, ';');
  2502. $query = $base_query;
  2503. $ret = array('msg'=>'', 'error'=>'', 'data_html'=>false);
  2504. $limit = 25;
  2505. $offset = get('offset','int');
  2506. $page = floor($offset / $limit + 1);
  2507. if ($query) {
  2508. if (is_select($query) && !preg_match('#\s+LIMIT\s+\d+#i', $query) && !preg_match('#into\s+outfile\s+#', $query)) {
  2509. $query = db_limit($query, $offset, $limit);
  2510. } else {
  2511. $limit = false;
  2512. }
  2513. $time = time_start();
  2514. if (!db_is_safe($query, true)) {
  2515. $ret['error'] = 'Detected UPDATE/DELETE without WHERE condition (put WHERE 1=1 if you want to execute this query)';
  2516. return $ret;
  2517. }
  2518. $rs = @db_query($query);
  2519. if ($rs) {
  2520. if ($rs === true) {
  2521. if ('mysql' == $db_driver){
  2522. $affected = mysql_affected_rows($db_link);
  2523. $time = time_end($time);
  2524. $ret['data_html'] = '<b>'.$affected.'</b> rows affected.<br>Time: <b>'.$time.'</b> sec';
  2525. return $ret;
  2526. }} else {
  2527. if ('pgsql' == $db_driver){
  2528. $affected = @pg_affected_rows($rs);
  2529. if ($affected || preg_match('#^\s*(DELETE|UPDATE)\s+#i', $query)) {
  2530. $time = time_end($time);
  2531. $ret['data_html'] = '<p><b>'.$affected.'</b> rows affected. Time: <b>'.$time.'</b> sec</p>';
  2532. return $ret;
  2533. }}}
  2534. $rows = array();
  2535. while ($row = db_row($rs)) {
  2536. $rows[] = $row;
  2537. if ($limit) {
  2538. if (count($rows) == $limit) { break; }}}
  2539. db_free($rs);
  2540. if (is_select($base_query)) {
  2541. $found = @db_one("SELECT COUNT(*) FROM ($base_query) AS sub");
  2542. if (!is_numeric($found) || (count($rows) && !$found)) {
  2543. global $COUNT_ERROR;
  2544. $COUNT_ERROR = ' (COUNT ERROR) ';
  2545. $found = count($rows);
  2546. }} else {
  2547. if (count($rows)) {
  2548. $found = count($rows);
  2549. } else {
  2550. $found = false;
  2551. }}
  2552. if ($limit) {
  2553. $pages = ceil($found / $limit);
  2554. } else {
  2555. $pages = 1;
  2556. }
  2557. $time = time_end($time);
  2558. } else {
  2559. $ret['error'] = db_error();
  2560. return $ret;
  2561. }} else {
  2562. $ret['error'] = 'No query found.';
  2563. return $ret;
  2564. }
  2565. ob_start();
  2566. ?><?php if (is_numeric($found)): ?><p>
  2567. Found: <b><?php echo $found;?></b><?php echo isset($GLOBALS['COUNT_ERROR'])?$GLOBALS['COUNT_ERROR']:'';?>.
  2568. Time: <b><?php echo $time;?></b> sec.
  2569. <?php
  2570. $params = array('md5'=>$md5_get, 'offset'=>get('offset','int'));
  2571. if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  2572. if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  2573. ?>
  2574. / <a href="<?php echo url(self(), $params);?>">Refetch</a>
  2575. / Export to CSV:&nbsp;
  2576. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
  2577. -
  2578. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
  2579. -
  2580. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
  2581. -
  2582. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a></p><?php else: ?><p>Result: <b>OK</b>. Time: <b><?php echo $time;?></b> sec</p><?php endif; ?><?php if (is_numeric($found)): ?><?php if ($pages > 1): ?><p><?php if ($page > 1): ?><?php $ofs = ($page-1)*$limit-$limit; ?><?php
  2583. $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  2584. if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  2585. if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  2586. ?><a href="<?php echo url(self(), $params);?>">&lt;&lt; Prev</a> &nbsp;
  2587. <?php endif; ?>
  2588. Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  2589. <?php if ($pages > $page): ?><?php $ofs = $page*$limit; ?><?php
  2590. $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  2591. if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  2592. if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  2593. ?><a href="<?php echo url(self(), $params);?>">Next &gt;&gt;</a><?php endif; ?></p><?php endif; ?><script>
  2594. function mark_row(tr){
  2595. var els = tr.getElementsByTagName('td');
  2596. if (tr.marked) {
  2597. for (var i = 0; i < els.length; i++) {
  2598. els[i].style.backgroundColor = '';
  2599. }
  2600. tr.marked = false;
  2601. } else {
  2602. tr.marked = true;
  2603. for (var i = 0; i < els.length; i++) {
  2604. els[i].style.backgroundColor = '#ddd';
  2605. }}}
  2606. </script><?php if ($found): ?><?php
  2607. $edit_table = table_from_query($base_query);
  2608. if ($edit_table) {
  2609. $edit_pk = array_first_key($rows[0]);
  2610. if (is_numeric($edit_pk)) { $edit_table = false; }}
  2611. if ($edit_table) {
  2612. $types = table_types2($edit_table);
  2613. if ($types && count($types)) {
  2614. if (in_array($edit_pk, array_keys($types))) {
  2615. if (!array_col_match_unique($rows, $edit_pk, '#^\d+$#')) {
  2616. $edit_pk = guess_pk($rows);
  2617. if (!$edit_pk) {
  2618. $edit_table = false;
  2619. }}} else {
  2620. $edit_table = false;
  2621. }} else {
  2622. $edit_table = false;
  2623. }}
  2624. $edit_url = '';
  2625. if ($edit_table) {
  2626. $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$edit_table, 'pk'=>$edit_pk, 'id'=>'%s'));
  2627. }
  2628. ?><table class="ls" cellspacing="1"><tr><?php if ($edit_url): ?><th>#</th><?php endif; ?><?php foreach ($rows[0] as $col => $v): ?><th><?php echo $col;?></th><?php endforeach; ?></tr><?php foreach ($rows as $row): ?><tr ondblclick="mark_row(this)"><?php if ($edit_url): ?><td><a href="javascript:void(0)" onclick="popup('<?php echo sprintf($edit_url, $row[$edit_pk]);?>', 620, 500)">Edit</a>&nbsp;</td><?php endif; ?><?php
  2629. $count_cols = 0;
  2630. foreach ($row as $v) { $count_cols++; }
  2631. ?><?php foreach ($row as $k => $v): ?><?php
  2632. if (preg_match('#^\s*<a[^>]+>[^<]+</a>\s*$#iU', $v) && strlen(strip_tags($v)) < 50) {
  2633. $v = strip_tags($v, '<a>');
  2634. } else {
  2635. $v = strip_tags($v);
  2636. $v = str_replace('&nbsp;', ' ', $v);
  2637. $v = preg_replace('#[ ]+#', ' ', $v);
  2638. if (!get('full_content') && strlen($v) > 50) {
  2639. if (1 == $count_cols) {
  2640. $v = str_truncate($v, 255);
  2641. } else {
  2642. $v = str_truncate($v, 50);
  2643. }}
  2644. $v = html_once($v);
  2645. }
  2646. $nl2br = get('nl2br');
  2647. if (get('full_content')) {
  2648. $v = str_wrap($v, 80, '<br>');
  2649. }
  2650. if (get('nl2br')) {
  2651. $v = nl2br($v);
  2652. }
  2653. if (@$types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
  2654. && preg_match('#^\d+$#', $v)){
  2655. $tmp = @date('Y-m-d H:i', $v);
  2656. if ($tmp) {
  2657. $v = $tmp;
  2658. }}
  2659. global $post;
  2660. if (str_has($post['sql'], '@gethostbyaddr') && (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $v))) {
  2661. $v = $v.'<br>'.@gethostbyaddr($v);
  2662. }
  2663. ?><td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td><?php endforeach; ?></tr><?php endforeach; ?></table><?php endif; ?><?php if ($pages > 1): ?><p><?php if ($page > 1): ?><?php $ofs = ($page-1)*$limit-$limit; ?><?php
  2664. $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  2665. if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  2666. if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  2667. ?><a href="<?php echo url(self(), $params);?>">&lt;&lt; Prev</a> &nbsp;
  2668. <?php endif; ?>
  2669. Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  2670. <?php if ($pages > $page): ?><?php $ofs = $page*$limit; ?><?php
  2671. $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  2672. if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  2673. if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  2674. ?><a href="<?php echo url(self(), $params);?>">Next &gt;&gt;</a><?php endif; ?></p><?php endif; ?><?php endif; ?><?php
  2675. $cont = ob_get_contents();
  2676. ob_end_clean();
  2677. $ret['data_html'] = $cont;
  2678. return $ret;
  2679. }
  2680. set_time_limit(0);
  2681. $template = get('template');
  2682. $msg = '';
  2683. $error = '';
  2684. $top_html = '';
  2685. $data_html = '';
  2686. $get = get(array(
  2687. 'popup'=> 'int',
  2688. 'md5' => 'string',
  2689. 'only_marked' => 'bool',
  2690. 'only_select' => 'bool'
  2691. ));
  2692. $post = post(array(
  2693. 'sql' => 'string',
  2694. 'perform' => 'string',
  2695. 'only_marked' => 'bool',
  2696. 'only_select' => 'bool',
  2697. 'save_as' => 'string',
  2698. 'load_from' => 'string'
  2699. ));
  2700. if ($get['md5']) {
  2701. $get['only_select'] = true;
  2702. $post['only_select'] = true;
  2703. }
  2704. if ($get['only_marked']) { $post['only_marked'] = 1; }
  2705. if ($get['only_select']) { $post['only_select'] = 1; }
  2706. $sql_dir = false;
  2707. if (defined('DBKISS_SQL_DIR')) {
  2708. $sql_dir = DBKISS_SQL_DIR;
  2709. }
  2710. if ($sql_dir) {
  2711. if (!(dir_exists($sql_dir) && is_writable($sql_dir))) {
  2712. if (!dir_exists($sql_dir) && is_writable('.')) {
  2713. mkdir($sql_dir);
  2714. } else {
  2715. exit('You must create "'.$sql_dir.'" directory with write permission.');
  2716. }}
  2717. if (!file_exists($sql_dir.'/.htaccess')) {
  2718. file_put($sql_dir.'/.htaccess', 'deny from all');
  2719. }
  2720. if (!file_exists($sql_dir.'/index.html')) {
  2721. file_put($sql_dir.'/index.html', '');
  2722. }}
  2723. if ('GET' == $_SERVER['REQUEST_METHOD']) {
  2724. if ($sql_dir){
  2725. if ($get['md5'] && preg_match('#^(\w{32,32})_(\d+)$#', $get['md5'], $match)) {
  2726. $md5_i = $match[2];
  2727. $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
  2728. $post['sql'] = file_get($md5_tmp);
  2729. $_SERVER['REQUEST_METHOD'] = 'POST';
  2730. $post['perform'] = 'execute';
  2731. } else if ($get['md5'] && preg_match('#^(\w{32,32})$#', $get['md5'], $match)) {
  2732. $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
  2733. $post['sql'] = file_get($md5_tmp);
  2734. $get['md5'] = '';
  2735. } else {
  2736. if ($get['md5']) {
  2737. trigger_error('invalid md5', E_USER_ERROR);
  2738. }}}} else {
  2739. $get['md5'] = '';
  2740. }
  2741. if (str_has($post['sql'], '@nl2br')) {
  2742. $_GET['nl2br'] = 1;
  2743. }
  2744. if (str_has($post['sql'], '@full_content')) {
  2745. $_GET['full_content'] = 1;
  2746. }
  2747. $post['sql'] = trim($post['sql']);
  2748. $md5 = md5($post['sql']);
  2749. $md5_file = sprintf($sql_dir.'/zzz_%s.dat', $md5);
  2750. if ($sql_dir && $post['sql']) {
  2751. file_put($md5_file, $post['sql']);
  2752. }
  2753. if ($sql_dir && 'save' == $post['perform'] && $post['save_as'] && $post['sql']){
  2754. $post['save_as'] = str_replace('.sql', '', $post['save_as']);
  2755. if (preg_match('#^[\w ]+$#', $post['save_as'])) {
  2756. $file = $sql_dir.'/'.$post['save_as'].'.sql';
  2757. $overwrite = '';
  2758. if (file_exists($file)) {
  2759. $overwrite = ' - <b>overwritten</b>';
  2760. $bak = $sql_dir.'/zzz_'.$post['save_as'].'_'.md5(file_get($file)).'.dat';
  2761. copy($file, $bak);
  2762. }
  2763. $msg .= sprintf('<div>Sql saved: %s %s</div>', basename($file), $overwrite);
  2764. file_put($file, $post['sql']);
  2765. } else {
  2766. error('Saving sql failed: only alphanumeric chars are allowed');
  2767. }}
  2768. if ($sql_dir) {
  2769. $load_files = dir_read($sql_dir, null, array('.sql'), 'date_desc');
  2770. }
  2771. $load_assoc = array();
  2772. if ($sql_dir) {
  2773. foreach ($load_files as $file) {
  2774. $file_path = $file;
  2775. $file = basename($file);
  2776. $load_assoc[$file] = '('.substr(file_date($file_path), 0, 10).')'.' ' .$file;
  2777. }}
  2778. if ($sql_dir && 'load' == $post['perform']){
  2779. $file = $sql_dir.'/'.$post['load_from'];
  2780. if (array_key_exists($post['load_from'], $load_assoc) && file_exists($file)) {
  2781. $msg .= sprintf('<div>Sql loaded: %s (%s)</div>', basename($file), timestamp(file_date($file)));
  2782. $post['sql'] = file_get($file);
  2783. $post['save_as'] = basename($file);
  2784. $post['save_as'] = str_replace('.sql', '', $post['save_as']);
  2785. } else {
  2786. error('<div>File not found: %s</div>', $file);
  2787. }}
  2788. // after load - md5 may change
  2789. $md5 = md5($post['sql']);
  2790. if ($sql_dir && 'load' == $post['perform'] && !error()) {
  2791. $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $md5);
  2792. file_put($md5_tmp, $post['sql']);
  2793. }
  2794. $is_sel = false;
  2795. $queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $post['sql']);
  2796. foreach ($queries as $k => $query) {
  2797. $query = query_strip($query);
  2798. if (str_starts_with($query, '@')) {
  2799. $is_sel = true;
  2800. }
  2801. $queries[$k] = $query;
  2802. if (!trim($query)) { unset($queries[$k]); }}
  2803. $sql_assoc = array();
  2804. $sql_selected = false;
  2805. $i = 0;
  2806. $params = array(
  2807. 'md5' => $md5,
  2808. 'only_marked' => $post['only_marked'],
  2809. 'only_select' => $post['only_select'],
  2810. 'offset' => ''
  2811. );
  2812. $sql_main_url = url(self(), $params);
  2813. foreach ($queries as $query) {
  2814. $i++;
  2815. $query = str_cut_start($query, '@');
  2816. if (!is_select($query)) {
  2817. continue;
  2818. }
  2819. $query = preg_replace('#\s+#', ' ', $query);
  2820. $params = array(
  2821. 'md5' => $md5.'_'.$i,
  2822. 'only_marked' => $post['only_marked'],
  2823. 'only_select' => $post['only_select'],
  2824. 'offset' => ''
  2825. );
  2826. $url = url(self(), $params);
  2827. if ($get['md5'] && $get['md5'] == $params['md5']) {
  2828. $sql_selected = $url;
  2829. }
  2830. $sql_assoc[$url] = str_truncate(strip_tags($query), 80);
  2831. }
  2832. if ('POST' == $_SERVER['REQUEST_METHOD']){
  2833. if (!$post['perform']) {
  2834. $error = 'No action selected.';
  2835. }
  2836. if (!$error){
  2837. $time = time_start();
  2838. switch ($post['perform']) {
  2839. case 'execute':
  2840. $i = 0;
  2841. db_begin();
  2842. $commit = true;
  2843. foreach ($queries as $query){
  2844. $i++;
  2845. if ($post['only_marked'] && !$is_sel) {
  2846. if (!$get['md5']) { continue; }}
  2847. if ($is_sel) {
  2848. if (str_starts_with($query, '@')) {
  2849. $query = str_cut_start($query, '@');
  2850. } else {
  2851. if (!$get['md5']) { continue; }}}
  2852. if ($post['only_select'] && !is_select($query)) {
  2853. continue;
  2854. }
  2855. if ($get['md5'] && $i != $md5_i) {
  2856. continue;
  2857. }
  2858. if ($get['md5'] && $i == $md5_i) {
  2859. if (!is_select($query)) {
  2860. trigger_error('not select query', E_USER_ERROR);
  2861. }}
  2862. $exec = listing($query, $md5.'_'.$i);
  2863. $query_trunc = str_truncate(html_once($query), 1000);
  2864. $query_trunc = query_color($query_trunc);
  2865. $query_trunc = nl2br($query_trunc);
  2866. $query_trunc = html_spaces($query_trunc);
  2867. if ($exec['error']) {
  2868. $exec['error'] = preg_replace('#error:#i', '', $exec['error']);
  2869. $top_html .= sprintf('<div style="background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em;"><b style="color:red">Error</b>: %s<div style="margin-top: 0.25em;"><b>Query %s</b>: %s</div></div>', $exec['error'], $i, $query_trunc);
  2870. $commit = false;
  2871. break;
  2872. } else {
  2873. $query_html = sprintf('<div class="query"><b style="font-size: 10px;">Query %s</b>:<div style="'.$sql_font.' margin-top: 0.35em;">%s</div></div>', $i, $query_trunc);
  2874. $data_html .= $query_html;
  2875. $data_html .= $exec['data_html'];
  2876. }}
  2877. if ($commit) {
  2878. db_end();
  2879. } else {
  2880. db_rollback();
  2881. }
  2882. break;
  2883. }
  2884. $time = time_end($time);
  2885. }}
  2886. if ($post['only_marked'] && !$is_sel) {
  2887. error('No queries marked');
  2888. }
  2889. ?><?php layout_start(($db_name_h1?$db_name_h1:$db_name).' &gt; Execute SQL'); ?><?php if ($get['popup']): ?><h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span> &gt; Execute SQL</h1><?php else: ?><h1><a class=blue style="<?php echo $db_name_style;?>" href="<?php echo $_SERVER['PHP_SELF'];?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></a> &gt; Execute SQL</h1><?php endif; ?><?php echo error();?><script>
  2890. function sql_submit(form){
  2891. if (form.perform.value.length) {
  2892. return true;
  2893. }
  2894. return false;
  2895. }
  2896. function sql_execute(form){
  2897. form.perform.value='execute';
  2898. form.submit();
  2899. }
  2900. function sql_preview(form){
  2901. form.perform.value='preview';
  2902. form.submit();
  2903. }
  2904. function sql_save(form){
  2905. form.perform.value='save';
  2906. form.submit();
  2907. }
  2908. function sql_load(form){
  2909. if (form.load_from.selectedIndex){
  2910. form.perform.value='load';
  2911. form.submit();
  2912. return true;
  2913. }
  2914. button_clear(form);
  2915. return false;
  2916. }
  2917. </script><?php if ($msg): ?><div class="msg"><?php echo $msg;?></div><?php endif; ?><?php echo $top_html;?><?php if (count($sql_assoc)): ?><p>
  2918. SELECT queries:
  2919. <select name="sql_assoc" onchange="if (this.value.length) location=this.value"><option value="<?php echo html_once($sql_main_url);?>"></option><?php echo options($sql_assoc, $sql_selected);?></select></p><?php endif; ?><?php if ($get['md5']): ?><?php echo $data_html;?><?php endif; ?><form action="<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1&popup=<?php echo $get['popup'];?>" method="post" onsubmit="return sql_submit(this);" style="margin-top: 1em;"><input type="hidden" name="perform" value=""><div style="margin-bottom: 0.25em;"><textarea id="sql_area" name="sql" class="sql_area"><?php echo htmlspecialchars(query_upper($post['sql']));?></textarea></div><table cellspacing="0" cellpadding="0"><tr><td nowrap><input type="button" wait="1" class="button" value="Execute" onclick="sql_execute(this.form); "></td><td nowrap>
  2920. &nbsp;
  2921. <input type="button" wait="1" class="button" value="Preview" onclick="sql_preview(this.form); "></td><td nowrap>
  2922. &nbsp;
  2923. <input type="checkbox" name="only_marked" id="only_marked" value="1" <?php echo checked($post['only_marked'] || $get['only_marked']);?>></td><td nowrap><label for="only_marked">only marked</label></td><td nowrap>
  2924. &nbsp;
  2925. <input type="checkbox" name="only_select" id="only_select" value="1" <?php echo checked($post['only_select'] || $get['only_select']);?>></td><td nowrap><label for="only_select">only SELECT</label>
  2926. &nbsp;&nbsp;&nbsp;
  2927. </td><td nowrap><input type="text" name="save_as" value="<?php echo html_once($post['save_as']);?>">
  2928. &nbsp;
  2929. </td><td nowrap><input type="button" wait="1" class="button" value="Save" onclick="sql_save(this.form); ">
  2930. &nbsp;&nbsp;&nbsp;
  2931. </td><td nowrap><select name="load_from" style="width: 140px;"><option value=""></option><?php echo options($load_assoc);?></select>
  2932. &nbsp;
  2933. </td><td nowrap><input type="button" wait="1" class="button" value="Load" onclick="return sql_load(this.form);"></td></tr></table></form><?php
  2934. if ('preview' == $post['perform']){
  2935. echo '<h2>Preview</h2>';
  2936. $i = 0;
  2937. foreach ($queries as $query){
  2938. $i++;
  2939. $query = str_cut_start($query, '@');
  2940. $query = html_once($query);
  2941. $query = query_color($query);
  2942. $query = nl2br($query);
  2943. $query = html_spaces($query);
  2944. printf('<div class="query"><b style="font-size: 10px;">Query %s</b>:<div style="'.$sql_font.' margin-top: 0.35em;">%s</div></div>', $i, $query);
  2945. }}
  2946. ?><?php if (!$get['md5']): ?><script>$('sql_area').focus();</script><?php echo $data_html;?><?php endif; ?><?php layout_end(); ?><?php exit; endif; ?><?php if (isset($_GET['viewtable']) && $_GET['viewtable']): ?><?php
  2947. set_time_limit(0);
  2948. // ----------------------------------------------------------------
  2949. // VIEW TABLE
  2950. // ----------------------------------------------------------------
  2951. $table = $_GET['viewtable'];
  2952. $table_enq = quote_table($table);
  2953. $count = db_one("SELECT COUNT(*) FROM $table_enq");
  2954. $types = table_types2($table);
  2955. $columns = table_columns($table);
  2956. if (!count($columns)) {
  2957. $columns = array_assoc(array_keys($types));
  2958. }
  2959. $columns2 = $columns;
  2960. foreach ($columns2 as $k => $v) {
  2961. $columns2[$k] = $v.' ('.$types[$k].')';
  2962. }
  2963. $types_group = table_types_group($types);
  2964. $_GET['search'] = get('search');
  2965. $where = '';
  2966. $found = $count;
  2967. if ($_GET['search']) {
  2968. $search = $_GET['search'];
  2969. $cols2 = array();
  2970. if (get('column')) {
  2971. $cols2[] = $_GET['column'];
  2972. } else {
  2973. $cols2 = $columns;
  2974. }
  2975. $where = '';
  2976. $search = db_escape($search);
  2977. $column_type = '';
  2978. if (!get('column')) {
  2979. $column_type = get('column_type');
  2980. } else {
  2981. $_GET['column_type'] = '';
  2982. }
  2983. $ignore_int = false;
  2984. $ignore_time = false;
  2985. foreach ($columns as $col){
  2986. if (!get('column') && $column_type) {
  2987. if ($types[$col] != $column_type) {
  2988. continue;
  2989. }}
  2990. if (!$column_type && !is_numeric($search) && str_has($types[$col], 'int')) {
  2991. $ignore_int = true;
  2992. continue;
  2993. }
  2994. if (!$column_type && is_numeric($search) && str_has($types[$col], 'time')) {
  2995. $ignore_time = true;
  2996. continue;
  2997. }
  2998. if (get('column') && $col != $_GET['column']) {
  2999. continue;
  3000. }
  3001. if ($where) { $where .= ' OR '; }
  3002. if (is_numeric($search)) {
  3003. $where .= "$col = '$search'";
  3004. } else {
  3005. if ('mysql' == $db_driver) {
  3006. $where .= "$col LIKE '%$search%'";
  3007. } else if ('pgsql' == $db_driver) {
  3008. $where .= "$col ILIKE '%$search%'";
  3009. } else {
  3010. trigger_error('db_driver not implemented');
  3011. }}}
  3012. if (($ignore_int || $ignore_time) && !$where) {
  3013. $where .= ' 1=2 ';
  3014. }
  3015. $where = 'WHERE '.$where;
  3016. }
  3017. if ($where) {
  3018. $table_enq = quote_table($table);
  3019. $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
  3020. }
  3021. $limit = 50;
  3022. $offset = get('offset','int');
  3023. $page = floor($offset / $limit + 1);
  3024. $pages = ceil($found / $limit);
  3025. $pk = table_pk($table);
  3026. $order = "ORDER BY";
  3027. if (get('order_by')) {
  3028. $order .= ' '.$_GET['order_by'];
  3029. } else {
  3030. if ($pk) {
  3031. $order .= ' '.$pk;
  3032. } else {
  3033. $order = '';
  3034. }}
  3035. if (get('order_desc')) { $order .= ' DESC'; }
  3036. $table_enq = quote_table($table);
  3037. $base_query = "SELECT * FROM $table_enq $where $order";
  3038. $rs = db_query(db_limit($base_query, $offset, $limit));
  3039. if ($count && $rs) {
  3040. $rows = array();
  3041. while ($row = db_row($rs)) {
  3042. $rows[] = $row;
  3043. }
  3044. db_free($rs);
  3045. if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
  3046. $pk = guess_pk($rows);
  3047. }}
  3048. function indenthead($str){
  3049. if (is_array($str)) {
  3050. $str2 = '';
  3051. foreach ($str as $k => $v) {
  3052. $str2 .= sprintf('%s: %s'."\r\n", $k, $v);
  3053. }
  3054. $str = $str2;
  3055. }
  3056. $lines = explode("\n", $str);
  3057. $max_len = 0;
  3058. foreach ($lines as $k => $line) {
  3059. $lines[$k] = trim($line);
  3060. if (preg_match('#^[^:]+:#', $line, $match)) {
  3061. if ($max_len < strlen($match[0])) {
  3062. $max_len = strlen($match[0]);
  3063. }}}
  3064. foreach ($lines as $k => $line) {
  3065. if (preg_match('#^[^:]+:#', $line, $match)) {
  3066. $lines[$k] = str_replace($match[0], $match[0].str_repeat('&nbsp;', $max_len - strlen($match[0])), $line);
  3067. }}
  3068. return implode("\r\n", $lines);
  3069. }
  3070. if (get('indenthead')) {
  3071. echo '<pre>';
  3072. echo 'Table: '.get('viewtable')."\r\n";
  3073. echo str_repeat('-', 80)."\r\n";
  3074. foreach ($rows as $row) {
  3075. echo indenthead($row);
  3076. echo str_repeat('-', 80)."\r\n";
  3077. }
  3078. echo '</pre>';
  3079. exit;
  3080. }
  3081. ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>"><title><?php echo $db_name_h1?$db_name_h1:$db_name;?> &gt; Table: <?php echo $table;?></title><link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1"></head><body><?php layout(); ?><h1><a class=blue style="<?php echo $db_name_style;?>" href="<?php echo $_SERVER['PHP_SELF'];?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></a> &gt; Table: <?php echo $table;?></h1><?php conn_info(); ?><p><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>">All tables</a>
  3082. &nbsp;&gt;&nbsp;
  3083. <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><b><?php echo $table;?></b></a> (<?php echo $count;?>)
  3084. &nbsp;&nbsp;/&nbsp;&nbsp;
  3085. Export to CSV:&nbsp;
  3086. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
  3087. -
  3088. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
  3089. -
  3090. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
  3091. -
  3092. <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a>
  3093. &nbsp;&nbsp;/&nbsp;&nbsp;
  3094. Functions:
  3095. <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&indenthead=1">indenthead()</a></p><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" style="margin-bottom: 1em;"><input type="hidden" name="viewtable" value="<?php echo $table;?>"><table class="ls" cellspacing="1"><tr><td><input type="text" name="search" value="<?php echo html_once(get('search'));?>"></td><td><select name="column"><option value=""></option><?php echo options($columns2, get('column'));?></select></td><td><select name="column_type"><option value=""></option><?php echo options($types_group, get('column_type'));?></select></td><td><input type="submit" value="Search"></td><td>
  3096. order by:
  3097. <select name="order_by"><option value=""></option><?php echo options($columns, get('order_by'));?></select><input type="checkbox" name="order_desc" id="order_desc" value="1" <?php echo checked(get('order_desc'));?>><label for="order_desc">desc</label></td><td><input type="checkbox" name="full_content" id="full_content" <?php echo checked(get('full_content'));?>><label for="full_content">full content</label></td><td><input type="checkbox" name="nl2br" id="nl2br" <?php echo checked(get('nl2br'));?>><label for="nl2br">nl2br</label></td></tr></table></form><?php if ($count): ?><?php if ($count && $count != $found): ?><p>Found: <b><?php echo $found;?></b></p><?php endif; ?><?php if ($found): ?><?php if ($pages > 1): ?><p><?php if ($page > 1): ?><a href="<?php echo url_offset(($page-1)*$limit-$limit);?>">&lt;&lt; Prev</a> &nbsp;
  3098. <?php endif; ?>
  3099. Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  3100. <?php if ($pages > $page): ?><a href="<?php echo url_offset($page*$limit);?>">Next &gt;&gt;</a><?php endif; ?></p><?php endif; ?><script>
  3101. function mark_row(tr){
  3102. var els = tr.getElementsByTagName('td');
  3103. if (tr.marked) {
  3104. for (var i = 0; i < els.length; i++) {
  3105. els[i].style.backgroundColor = '';
  3106. }
  3107. tr.marked = false;
  3108. } else {
  3109. tr.marked = true;
  3110. for (var i = 0; i < els.length; i++) {
  3111. els[i].style.backgroundColor = '#ddd';
  3112. }}}
  3113. </script><table class="ls" cellspacing="1"><tr><?php if ($pk): ?><th>#</th><?php endif; ?><?php foreach ($columns as $col): ?><?php
  3114. $params = array('order_by'=>$col);
  3115. $params['order_desc'] = 0;
  3116. if (get('order_by') == $col) {
  3117. $params['order_desc'] = get('order_desc') ? 0 : 1;
  3118. }
  3119. ?><th><a style="color: #000;" href="<?php echo url(self(), $params);?>"><?php echo $col;?></a></th><?php endforeach; ?></tr><?php
  3120. $get_full_content = get('full_content');
  3121. $get_nl2br = get('nl2br');
  3122. $get_search = get('search');
  3123. ?><?php
  3124. $edit_url_tpl = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>'%s'));
  3125. ?><?php foreach ($rows as $row): ?><tr ondblclick="mark_row(this)"><?php if ($pk): ?><?php $edit_url = sprintf($edit_url_tpl, $row[$pk]); ?><td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a>&nbsp;</td><?php endif; ?><?php foreach ($row as $k => $v): ?><?php
  3126. if (!$get_full_content) {
  3127. $v = str_truncate($v, 50);
  3128. }
  3129. $v = htmlspecialchars($v);
  3130. $nl2br = $get_nl2br;
  3131. if ($get_full_content) {
  3132. $v = str_wrap($v, 80, '<br>');
  3133. }
  3134. if ($get_nl2br) {
  3135. $v = nl2br($v);
  3136. }
  3137. if ($get_search) {
  3138. $search = $_GET['search'];
  3139. $search_quote = preg_quote($search);
  3140. $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
  3141. }
  3142. if ($types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
  3143. && preg_match('#^\d+$#', $v)){
  3144. $tmp = @date('Y-m-d H:i', $v);
  3145. if ($tmp) {
  3146. $v = $tmp;
  3147. }}
  3148. ?><td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td><?php endforeach; ?></tr><?php endforeach; ?></table><?php if ($pages > 1): ?><p><?php if ($page > 1): ?><a href="<?php echo url_offset(($page-1)*$limit-$limit);?>">&lt;&lt; Prev</a> &nbsp;
  3149. <?php endif; ?>
  3150. Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  3151. <?php if ($pages > $page): ?><a href="<?php echo url_offset($page*$limit);?>">Next &gt;&gt;</a><?php endif; ?></p><?php endif; ?><?php endif; ?><?php endif; ?><?php powered_by(); ?></body></html><?php exit; endif; ?><?php if (get('searchdb')): ?><?php
  3152. $get = get(array(
  3153. 'types' => 'array',
  3154. 'search' => 'string',
  3155. 'md5' => 'bool',
  3156. 'table_filter' => 'string'
  3157. ));
  3158. $get['search'] = trim($get['search']);
  3159. $tables = list_tables();
  3160. if ($get['table_filter']) {
  3161. foreach ($tables as $k => $table) {
  3162. if (!str_has_any($table, $get['table_filter'], $ignore_case = true)) {
  3163. unset($tables[$k]);
  3164. }}}
  3165. $all_types = array();
  3166. $columns = array();
  3167. foreach ($tables as $table) {
  3168. $types = table_types2($table);
  3169. $columns[$table] = $types;
  3170. $types = array_values($types);
  3171. $all_types = array_merge($all_types, $types);
  3172. }
  3173. $all_types = array_unique($all_types);
  3174. if ($get['search'] && $get['md5']) {
  3175. $get['search'] = md5($get['search']);
  3176. }
  3177. ?><?php layout_start(sprintf('%s &gt; Search', $db_name)); ?><h1><a class=blue style="<?php echo $db_name_style;?>" href="<?php echo $_SERVER['PHP_SELF'];?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></a> &gt; Search</h1><?php conn_info(); ?><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get"><input type="hidden" name="searchdb" value="1"><table class="ls" cellspacing="1"><tr><th>Search:</th><td><input type="text" name="search" value="<?php echo html_once($get['search']);?>" size="40"><?php if ($get['search'] && $get['md5']): ?>
  3178. md5(<?php echo html_once(get('search'));?>)
  3179. <?php endif; ?><input type="checkbox" name="md5" id="md5_label" value="1"><label for="md5_label">md5</label></td></tr><tr><th>Table filter:</th><td><input type="text" name="table_filter" value="<?php echo html_once($get['table_filter']);?>"></tr><tr><th>Columns:</th><td><?php foreach ($all_types as $type): ?><input type="checkbox" id="type_<?php echo $type;?>" name="types[<?php echo $type;?>]" value="1" <?php echo checked(isset($get['types'][$type]));?>><label for="type_<?php echo $type;?>"><?php echo $type;?></label><?php endforeach; ?></td></tr><tr><td colspan="2" class="none"><input type="submit" value="Search"></td></tr></table></form><?php if ($get['search'] && !count($get['types'])): ?><p>No columns selected.</p><?php endif; ?><?php if ($get['search'] && count($get['types'])): ?><p>Searching <b><?php echo count($tables);?></b> tables for: <b><?php echo html_once($get['search']);?></b></p><?php $found_any = false; ?><?php set_time_limit(0); ?><?php foreach ($tables as $table): ?><?php
  3180. $where = '';
  3181. $cols2 = array();
  3182. $where = '';
  3183. $search = db_escape($get['search']);
  3184. foreach ($columns[$table] as $col => $type){
  3185. if (!in_array($type, array_keys($get['types']))) {
  3186. continue;
  3187. }
  3188. if ($where) {
  3189. $where .= ' OR ';
  3190. }
  3191. if (is_numeric($search)) {
  3192. $where .= "$col = '$search'";
  3193. } else {
  3194. if ('mysql' == $db_driver) {
  3195. $where .= "$col LIKE '%$search%'";
  3196. } else if ('pgsql' == $db_driver) {
  3197. $where .= "$col ILIKE '%$search%'";
  3198. } else {
  3199. trigger_error('db_driver not implemented');
  3200. }}}
  3201. $found = false;
  3202. if ($where) {
  3203. $where = 'WHERE '.$where;
  3204. $table_enq = quote_table($table);
  3205. $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
  3206. }
  3207. if ($found) {
  3208. $found_any = true;
  3209. }
  3210. if ($where && $found) {
  3211. $limit = 10;
  3212. $offset = 0;
  3213. $pk = table_pk($table);
  3214. $order = "ORDER BY $pk";
  3215. $table_enq = quote_table($table);
  3216. $rs = db_query(db_limit("SELECT * FROM $table_enq $where $order", $offset, $limit));
  3217. $rows = array();
  3218. while ($row = db_row($rs)) {
  3219. $rows[] = $row;
  3220. }
  3221. db_free($rs);
  3222. if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
  3223. $pk = guess_pk($rows);
  3224. }}
  3225. ?><?php if ($where && $found): ?><p>
  3226. Table: <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&search=<?php echo urlencode($get['search']);?>"><b><?php echo $table;?></b></a><br>
  3227. Found: <b><?php echo $found;?></b><?php if ($found > $limit): ?>
  3228. &nbsp;<a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&search=<?php echo urlencode($get['search']);?>">show all &gt;&gt;</a><?php endif; ?></p><table class="ls" cellspacing="1"><tr><?php if ($pk): ?><th>#</th><?php endif; ?><?php foreach ($columns[$table] as $col => $type): ?><th><?php echo $col;?></th><?php endforeach; ?></tr><?php foreach ($rows as $row): ?><tr><?php if ($pk): ?><?php $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>$row[$pk])); ?><td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a>&nbsp;</td><?php endif; ?><?php foreach ($row as $k => $v): ?><?php
  3229. $v = str_truncate($v, 50);
  3230. $v = html_once($v);
  3231. $search = $get['search'];
  3232. $search_quote = preg_quote($search);
  3233. if ($columns[$table][$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k)) && preg_match('#^\d+$#', $v)) {
  3234. $tmp = @date('Y-m-d H:i', $v);
  3235. if ($tmp) {
  3236. $v = $tmp;
  3237. }}
  3238. $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
  3239. ?><td nowrap><?php echo $v;?></td><?php endforeach; ?></tr><?php endforeach; ?></table><?php endif; ?><?php endforeach; ?><?php if (!$found_any): ?><p>No rows found.</p><?php endif; ?><?php endif; ?><?php layout_end(); ?><?php exit; endif; ?><?php
  3240. $get = get(array('table_filter'=>'string'));
  3241. ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>"><title><?php echo $db_name_h1?$db_name_h1:$db_name;?></title><link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1"></head><body><?php layout(); ?><h1 style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></h1><?php conn_info(); ?><?php $tables = list_tables(); ?><?php $status = table_status(); ?><?php $views = list_tables(true); ?><p>
  3242. Tables: <b><?php echo count($tables);?></b>
  3243. &nbsp;-&nbsp;
  3244. Total size: <b><?php echo number_format(ceil($status['total_size']/1024),0,'',',').' KB';?></b>
  3245. &nbsp;-&nbsp;
  3246. Views: <b><?php echo count($views);?></b>
  3247. &nbsp;-&nbsp;
  3248. <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?searchdb=1&table_filter=<?php echo html_once($get['table_filter']);?>">Search</a>
  3249. &nbsp;-&nbsp;
  3250. <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?import=1">Import</a>
  3251. &nbsp;-&nbsp;
  3252. Export all:
  3253. <?php if ('pgsql' == $db_driver): ?>
  3254. &nbsp;<a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?dump_all=2&table_filter=<?php echo urlencode(html_once($get['table_filter']));?>">Data only</a><?php else: ?>
  3255. &nbsp;<a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?dump_all=1&table_filter=<?php echo urlencode(html_once($get['table_filter']));?>">Structure</a> ,
  3256. <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?dump_all=2&table_filter=<?php echo urlencode(html_once($get['table_filter']));?>">Data & structure</a><?php endif; ?></p><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" name=table_filter_form style="margin-bottom: 0.5em;"><table cellspacing="0" cellpadding="0"><tr><td style="padding-right: 3px;">Table or View:</td><td style="padding-right: 3px;"><input type="text" name="table_filter" id=table_filter value="<?php echo html_once($get['table_filter']);?>"></td><td style="padding-right: 3px;"><input type="submit" class="button" wait="1" value="Filter"> <a href="javascript:void(0)" onclick="alert('You just start typing on the page and the Input will be focused automatically. ALT+R will Reset the Input and submit the form.')">[?]</a></td></tr></table></form><script>
  3257. function table_filter_keydown(e){
  3258. if (!e) { e = window.event; }
  3259. if (e.keyCode == 27 || e.keyCode == 33 || e.keyCode == 34 || e.keyCode == 38 || e.keyCode == 40) {
  3260. document.getElementById('table_filter').blur();
  3261. return;
  3262. }
  3263. if (e.keyCode == 82 && e.altKey) {
  3264. document.getElementById('table_filter').value = "";
  3265. document.forms["table_filter_form"].submit();
  3266. return;
  3267. }
  3268. if (e.keyCode >= 48 && e.keyCode <= 57 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3269. document.getElementById('table_filter').focus();
  3270. }
  3271. if (e.keyCode >= 65 && e.keyCode <= 90 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3272. document.getElementById('table_filter').focus();
  3273. }}
  3274. document.onkeydown = table_filter_keydown;
  3275. </script><div style="float: left;"><?php
  3276. $tables = table_filter($tables, $get['table_filter']);
  3277. ?><?php if ($get['table_filter']): ?><p>Tables found: <b><?php echo count($tables);?></b></p><?php endif; ?><table class="ls" cellspacing="1"><tr><th>Table</th><th>Count</th><th>Size</th><th>Options</th></tr><?php foreach ($tables as $table): ?><tr><td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><?php echo $table;?></a></td><?php
  3278. if ('mysql' == $db_driver) {
  3279. $count = $status[$table]['count'];
  3280. }
  3281. if ('pgsql' == $db_driver) {
  3282. $count = $status[$table]['count'];
  3283. if (!$count) {
  3284. $table_enq = quote_table($table);
  3285. $count = db_one("SELECT COUNT(*) FROM $table_enq");
  3286. }}
  3287. ?><td align="right"><?php echo number_format($count,0,'',',');?></td><td align="right"><?php echo number_format(ceil($status[$table]['size']/1024),0,'',',').' KB';?></td><td><a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $table;?>">Export</a>
  3288. &nbsp;-&nbsp;
  3289. <?php $table_enq = quote_table($table); ?><form action="<?php echo $_SERVER['PHP_SELF'];?>" name="drop_<?php echo $table;?>" method="post" style="display: inline;"><input type="hidden" name="drop_table" value="<?php echo $table;?>"></form><a href="javascript:void(0)" onclick="if (confirm('DROP TABLE <?php echo $table_enq;?> ?')) document.forms['drop_<?php echo $table;?>'].submit();">Drop</a></td></tr><?php endforeach; ?></table><?php unset($table); ?></div><?php if (views_supported() && count($views)): ?><div style="float: left; margin-left: 2em;"><?php
  3290. $views = table_filter($views, $get['table_filter']);
  3291. ?><?php if ($get['table_filter']): ?><p>Views found: <b><?php echo count($views);?></b></p><?php endif; ?><table class="ls" cellspacing="1"><tr><th>View</th><th><a class=blue href="<?php echo $_SERVER['PHP_SELF']; ?>?table_filter=<?php echo urlencode($get['table_filter']);?>&views_count=<?php echo (isset($_GET['views_count']) && $_GET['views_count']) ? 0 : 1; ?>" style="color: #000; text-decoration: underline;" title="Click to enable/disable counting in Views">Count</a></th><th>Options</th></tr><?php foreach ($views as $view): ?><?php $view_enq = quote_table($view); ?><tr><td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $view;?>"><?php echo $view;?></a></td><?php
  3292. if (isset($_GET['views_count']) && $_GET['views_count']) {
  3293. $count = db_one("SELECT COUNT(*) FROM $view_enq");
  3294. } else {
  3295. $count = null;
  3296. }
  3297. ?><td align=right><?php echo isset($count) ? $count : '-'; ?></td><td><a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $view;?>">Export</a>
  3298. &nbsp;-&nbsp;
  3299. <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="drop_<?php echo $view;?>" method="post" style="display: inline;"><input type="hidden" name="drop_view" value="<?php echo $view;?>"></form><a href="javascript:void(0)" onclick="if (confirm('DROP VIEW <?php echo $view_enq;?> ?')) document.forms['drop_<?php echo $view;?>'].submit();">Drop</a></td></tr><?php endforeach; ?></table></div><?php endif; ?><div style="clear: both;"></div><?php powered_by(); ?></body></html>
Add Comment
Please, Sign In to add comment