Kyuoko

mysqlogindb

Oct 26th, 2017
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 140.40 KB | None | 0 0
  1. <?php
  2. ini_set('zlib.output_compression', 0);
  3. ini_set('output_buffering', 0);
  4.  
  5. if (ini_get('zlib.output_compression')) {
  6.     ob_start();
  7. } else {
  8.     ob_start('ob_gzhandler');
  9. }
  10.  
  11. if (!defined('DBKISS_SQL_DIR')) {
  12.     define('DBKISS_SQL_DIR', 'dbkiss_sql');
  13. }
  14.  
  15. error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);
  16. ini_set('display_errors', true);
  17. if (!ini_get('date.timezone')) {
  18.     ini_set('date.timezone', 'Europe/Warsaw');
  19. }
  20.  
  21. if (!isset($_SERVER['REQUEST_URI'])) {
  22.     $_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'];
  23.     if (isset($_SERVER['QUERY_STRING'])) {
  24.         $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
  25.     }
  26. }
  27. if (!isset($_SERVER['SERVER_ADDR'])) {
  28.     if (isset($_SERVER['LOCAL_ADDR'])) {
  29.         $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR'];
  30.     } else {
  31.         $_SERVER['SERVER_ADDR'] = 'unknown';
  32.     }
  33. }
  34.  
  35. set_error_handler('errorHandler');
  36. register_shutdown_function('errorHandler_last');
  37. ini_set('display_errors', 1);
  38. global $Global_LastError;
  39.  
  40. function errorHandler_last()
  41. {
  42.     if (function_exists("error_get_last")) {
  43.         $error = error_get_last();
  44.         if ($error) {
  45.             errorHandler($error['type'], $error['message'], $error['file'], $error['line']);
  46.         }
  47.     }
  48. }
  49. function errorHandler($errno, $errstr, $errfile, $errline)
  50. {
  51.     global $Global_LastError;
  52.     $Global_LastError = $errstr;
  53.     if (!($errno & error_reporting())) {
  54.         return;
  55.     }
  56.     if (!headers_sent()) {
  57.         header('HTTP/1.0 503 Service Unavailable');
  58.         while (ob_get_level()) { ob_end_clean(); }
  59.         header('Content-Encoding: none');
  60.         header("Content-Type: text/html; charset=utf-8");
  61.         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  62.         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  63.         header("Cache-Control: no-store, no-cache, must-revalidate");
  64.         header("Cache-Control: post-check=0, pre-check=0", false);
  65.         header("Pragma: no-cache");
  66.     }
  67.     $errfile = basename($errfile);
  68.     $msg = sprintf('%s<br>In %s on line %d.', nl2br($errstr), $errfile, $errline);
  69.  
  70.     printf("<!doctype html><html><head><meta charset=utf-8><title>PHP Error</title>");
  71.     printf("<meta name=\"robots\" content=\"noindex,nofollow\">");
  72.     printf("<link rel=\"shortcut icon\" href=\"{$_SERVER['PHP_SELF']}?dbkiss_favicon=1\">");
  73.     printf("<style type=text/css>");
  74.     printf("body { font: 12px Arial, Sans-serif; line-height: 17px; padding: 0em; margin: 2em 3em; }");
  75.     printf("h1 { font: bold 18px Tahoma; border-bottom: rgb(175, 50, 0) 1px solid; margin-bottom: 0.85em; padding-bottom: 0.25em; color: rgb(200, 50, 0); text-shadow: 1px 1px 1px #fff; }");
  76.     print("h2 { font: bold 15px Tahoma; margin-top: 1em; color: #000; text-shadow: 1px 1px 1px #fff; }");
  77.     printf("</style></head><body>");
  78.  
  79.     printf("<h1>PHP Error</h1>");
  80.     printf($msg);
  81.  
  82.     if ("127.0.0.1" == $_SERVER["SERVER_ADDR"] && "127.0.0.1" == $_SERVER["REMOTE_ADDR"])
  83.     {
  84.         printf("<h2>Backtrace</h2>");
  85.         ob_start();
  86.         debug_print_backtrace();
  87.         $trace = ob_get_clean();
  88.         $trace = preg_replace("/^#0[\s\S]+?\n#1/", "#1", $trace);
  89.         $trace = trim($trace);
  90.         print nl2br($trace);
  91.     }
  92.     printf("</body></html>");
  93.     if ("127.0.0.1" == $_SERVER["SERVER_ADDR"] && "127.0.0.1" == $_SERVER["REMOTE_ADDR"]) {
  94.         error_log($msg);
  95.     }
  96.     exit();
  97. } if ("127.0.0.1" == $_SERVER["SERVER_ADDR"] && "127.0.0.1" == $_SERVER["REMOTE_ADDR"]) {
  98.     function dump($data) {
  99.         if (!headers_sent()) {
  100.             header('HTTP/1.0 503 Service Unavailable');
  101.             while (ob_get_level()) { ob_end_clean(); }
  102.             header('Content-encoding: none');
  103.             header("Content-type: text/html");
  104.             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  105.             header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  106.             header("Cache-Control: no-store, no-cache, must-revalidate");
  107.             header("Cache-Control: post-check=0, pre-check=0", false);
  108.             header("Pragma: no-cache");
  109.         } if (func_num_args() > 1) { $data = func_get_args();
  110.         } if ($data && count($data) == 2 && isset($data[1]) && "windows-1250" == strtolower($data[1])) {
  111.             $charset = "windows-1250";
  112.             $data = $data[0];
  113.         } else if ($data && count($data) == 2 && isset($data[1]) && "iso-8859-2" == strtolower($data[1])) {
  114.             $charset = "iso-8859-2";
  115.             $data = $data[0];
  116.         } else {
  117.             $charset = "utf-8";
  118.         } printf('<!doctype html><head><meta charset='.$charset.'><title>dump()</title></head><body>');
  119.         printf('<h1 style="color: rgb(150,15,225);">dump()</h1>');
  120.         ob_start();
  121.         print_r($data);
  122.         $html = ob_get_clean();
  123.         $html = htmlspecialchars($html);
  124.         printf('<pre>%s</pre>', $html);
  125.         printf('</body></html>');
  126.         exit();
  127.     }
  128. } if (isset($_GET['dbkiss_favicon'])) {
  129.     $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';
  130.     header('Content-type: image/vnd.microsoft.icon');
  131.     echo base64_decode($favicon);
  132.     exit();
  133. }
  134.  
  135. if (!function_exists('array_walk_recursive'))
  136. {
  137.     function array_walk_recursive(&$array, $func)
  138.     {
  139.         foreach ($array as $k => $v) {
  140.             if (is_array($v)) {
  141.                 array_walk_recursive($array[$k], $func);
  142.             } else {
  143.                 $func($array[$k], $k);
  144.             }
  145.         }
  146.     }
  147. }
  148. function create_links($text){
  149.     $text = preg_replace('#([a-z]+://[a-zA-Z0-9\.\,\;\:\[\]\{\}\-\_\+\=\!\@\#\%\&\(\)\/\?\`\~]+)#e', 'create_links_eval("\\1")', $text);
  150.     return $text;
  151. } function create_links_eval($link){
  152.     $orig_link = $link;
  153.     $cutted = "";
  154.     if (in_array($link[strlen($link)-1], array(":", ";", ".", ","))) {
  155.         $link = substr($link, 0, -1);
  156.         $cutted = $orig_link[strlen($orig_link)-1];
  157.     }
  158.     if (($pos = strpos($link, "(")) !== false) {
  159.         if (strpos($link, ")") === false) {
  160.             $link = substr($link, 0, $pos);
  161.             $cutted = substr($orig_link, $pos);
  162.         }
  163.     } else if (($pos = strpos($link, ")")) !== false) {
  164.         if (strpos($link, "(") === false) {
  165.             $link = substr($link, 0, $pos);
  166.             $cutted = substr($orig_link, $pos);
  167.         }
  168.     } else if (($pos = strpos($link, "[")) !== false) {
  169.         if (strpos($link, "]") === false) {
  170.             $link = substr($link, 0, $pos);
  171.             $cutted = substr($orig_link, $pos);
  172.         }
  173.     } else if (($pos = strpos($link, "]")) !== false) {
  174.         if (strpos($link, "[") === false) {
  175.             $link = substr($link, 0, $pos);
  176.             $cutted = substr($orig_link, $pos);
  177.         }
  178.     } else if (($pos = strpos($link, "{")) !== false) {
  179.         if (strpos($link, "}") === false) {
  180.             $link = substr($link, 0, $pos);
  181.             $cutted = substr($orig_link, $pos);
  182.         }
  183.     } else if (($pos = strpos($link, "}")) !== false) {
  184.         if (strpos($link, "{") === false) {
  185.             $link = substr($link, 0, $pos);
  186.             $cutted = substr($orig_link, $pos);
  187.         }
  188.     }
  189.     return "<a title=\"$link\" style=\"color: #000; text-decoration: none; border-bottom: #000 1px dotted;\" href=\"javascript:;\" onclick=\"link_noreferer('$link')\">$link</a>$cutted";
  190. }
  191. function truncate_html($string, $length, $break_words = false, $end_str = '..'){
  192.     $inside_tag = false;
  193.     $inside_amp = 0;
  194.     $finished = false;
  195.     $opened = 0;
  196.     $string_len = strlen($string);
  197.     $count = 0;
  198.     $ret = "";
  199.     for ($i = 0; $i < $string_len; $i++){
  200.         $char = $string[$i];
  201.         $nextchar = isset($string[$i+1]) ? $string[$i+1] : null;
  202.         if ('<' == $char && ('/' == $nextchar || ctype_alpha($nextchar))) {
  203.             if ('/' == $nextchar) {
  204.                 $opened--;
  205.             } else {
  206.                 $opened++;
  207.             }
  208.             $inside_tag = true;
  209.         }
  210.         if ('>' == $char) {
  211.             $inside_tag = false;
  212.             $ret .= $char;
  213.             continue;
  214.         }
  215.         if ($inside_tag) {
  216.             $ret .= $char;
  217.             continue;
  218.         }
  219.         if (!$finished)
  220.         {
  221.             if ('&' == $char) {
  222.                 $inside_amp = 1;
  223.                 $ret .= $char;
  224.                 continue;
  225.             }
  226.             if (';' == $char && $inside_amp) {
  227.                 $inside_amp = 0;
  228.                 $count++;
  229.                 $ret .= $char;
  230.                 continue;
  231.             }
  232.             if ($inside_amp) {
  233.                 $inside_amp++;
  234.                 $ret .= $char;
  235.                 if ('#' == $char || ctype_alnum($char)) {
  236.                     if ($inside_amp > 7) {
  237.                         $count += $inside_amp;
  238.                         $inside_amp = 0;
  239.                     }
  240.                 } else {
  241.                     $count += $inside_amp;
  242.                     $inside_amp = 0;
  243.                 }
  244.                 continue;
  245.             }
  246.         }
  247.         $count++;
  248.         if (!$finished) {
  249.             $ret .= $char;
  250.         }
  251.         if ($count >= $length) {
  252.             if (!$inside_tag && !$inside_amp) {
  253.                 if (!$finished) {
  254.                     $ret .= $end_str;
  255.                     $finished = true;
  256.                     if (0 == $opened) {
  257.                         break;
  258.                     }
  259.                 }
  260.                 if (0 == $opened) {
  261.                     break;
  262.                 }
  263.             }
  264.         }
  265.     }
  266.     return $ret;
  267. }
  268. function table_filter($tables, $filter)
  269. {
  270.     $filter = trim($filter);
  271.     if ($filter) {
  272.         foreach ($tables as $k => $table) {
  273.             if (!str_has_any($table, $filter, $ignore_case = true)) {
  274.                 unset($tables[$k]);
  275.             }
  276.         }
  277.     }
  278.     return $tables;
  279. }
  280. function get($key, $type='string')
  281. {
  282.     if (is_string($key)) {
  283.         $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
  284.         if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
  285.         settype($_GET[$key], $type);
  286.         if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
  287.         return $_GET[$key];
  288.     }
  289.     $vars = $key;
  290.     foreach ($vars as $key => $type) {
  291.         $_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
  292.         if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
  293.         settype($_GET[$key], $type);
  294.         if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
  295.         $vars[$key] = $_GET[$key];
  296.     }
  297.     return $vars;
  298. }
  299. function post($key, $type='string')
  300. {
  301.     if (is_string($key)) {
  302.         $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
  303.         if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
  304.         settype($_POST[$key], $type);
  305.         if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
  306.         return $_POST[$key];
  307.     }
  308.     $vars = $key;
  309.     foreach ($vars as $key => $type) {
  310.         $_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
  311.         if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
  312.         settype($_POST[$key], $type);
  313.         if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
  314.         $vars[$key] = $_POST[$key];
  315.     }
  316.     return $vars;
  317. }
  318. $_ENV['IS_GET'] = ('GET' == $_SERVER['REQUEST_METHOD']);
  319. $_ENV['IS_POST'] = ('POST' == $_SERVER['REQUEST_METHOD']);
  320. function req_gpc_has($str)
  321. {
  322.     /* finds if value exists in GPC data, used in filter_() functions, to check whether use html_tags_undo() on the data */
  323.     foreach ($_GET as $k => $v) {
  324.         if ($str == $v) {
  325.             return true;
  326.         }
  327.     }
  328.     foreach ($_POST as $k => $v) {
  329.         if ($str == $v) {
  330.             return true;
  331.         }
  332.     }
  333.     foreach ($_COOKIE as $k => $v) {
  334.        if ($str == $v) {
  335.            return true;
  336.        }
  337.     }
  338.     return false;
  339. }
  340. if (ini_get('magic_quotes_gpc')) {
  341.     ini_set('magic_quotes_runtime', 0);
  342.     array_walk_recursive($_GET, 'db_magic_quotes_gpc');
  343.     array_walk_recursive($_POST, 'db_magic_quotes_gpc');
  344.     array_walk_recursive($_COOKIE, 'db_magic_quotes_gpc');
  345. }
  346. function db_magic_quotes_gpc(&$val)
  347. {
  348.     $val = stripslashes($val);
  349. }
  350. $sql_font = 'font-size: 12px; font-family: courier new;';
  351. $sql_area = $sql_font.' width: 708px; height: 182px; border: #ccc 1px solid; background: #f9f9f9; padding: 3px;';
  352.  
  353. if (!isset($db_name_style)) {
  354.     $db_name_style = '';
  355. }
  356. if (!isset($db_name_h1)) {
  357.     $db_name_h1 = '';
  358. }
  359.  
  360. global $db_link, $db_name;
  361.  
  362. if (!defined('COOKIE_PREFIX')) {
  363.     define('COOKIE_PREFIX', 'dbkiss_');
  364. }
  365.  
  366. define('COOKIE_WEEK', 604800);
  367. define('COOKIE_SESS', 0);
  368. function cookie_get($key)
  369. {
  370.     $key = COOKIE_PREFIX.$key;
  371.     if (isset($_COOKIE[$key])) return $_COOKIE[$key];
  372.     return null;
  373. }
  374. function cookie_set($key, $val, $time = COOKIE_SESS)
  375. {
  376.     $key = COOKIE_PREFIX.$key;
  377.     $expire = $time ? time() + $time : 0;
  378.     if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  379.         setcookie($key, $val, $expire, '', '', false, true);
  380.     } else {
  381.         setcookie($key, $val, $expire);
  382.     }
  383.     $_COOKIE[$key] = $val;
  384. }
  385. function cookie_del($key)
  386. {
  387.     $key = COOKIE_PREFIX.$key;
  388.     if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  389.         setcookie($key, '', time()-3600*24, '', '', false, true);
  390.     } else {
  391.         setcookie($key, '', time()-3600*24);
  392.     }
  393.     unset($_COOKIE[$key]);
  394. }
  395.  
  396. conn_modify('db_name');
  397. conn_modify('db_charset');
  398. conn_modify('page_charset');
  399.  
  400. function conn_modify($key)
  401. {
  402.     if (array_key_exists($key, $_GET)) {
  403.         cookie_set($key, $_GET[$key], cookie_get('remember') ? COOKIE_WEEK : COOKIE_SESS);
  404.         if (isset($_GET['from']) && $_GET['from']) {
  405.             header('Location: '.$_GET['from']);
  406.         } else {
  407.             header('Location: '.$_SERVER['PHP_SELF']);
  408.         }
  409.         exit;
  410.     }
  411. }
  412.  
  413. $db_driver = cookie_get('db_driver');
  414. $db_server = cookie_get('db_server');
  415. $db_name = cookie_get('db_name');
  416. $db_user = cookie_get('db_user');
  417. $db_pass = base64_decode(cookie_get('db_pass'));
  418. $db_charset = cookie_get('db_charset');
  419. $page_charset = cookie_get('page_charset');
  420.  
  421. $charset1 = array('latin1', 'latin2', 'utf8', 'cp1250');
  422. $charset2 = array('iso-8859-1', 'iso-8859-2', 'utf-8', 'windows-1250');
  423. $charset1[] = $db_charset;
  424. $charset2[] = $page_charset;
  425. $charset1 = charset_assoc($charset1);
  426. $charset2 = charset_assoc($charset2);
  427.  
  428. $driver_arr = array('mysql', 'pgsql');
  429. $driver_arr = array_assoc($driver_arr);
  430.  
  431. function array_assoc($a)
  432. {
  433.     $ret = array();
  434.     foreach ($a as $v) {
  435.         $ret[$v] = $v;
  436.     }
  437.     return $ret;
  438. }
  439. function charset_assoc($arr)
  440. {
  441.     sort($arr);
  442.     $ret = array();
  443.     foreach ($arr as $v) {
  444.         if (!$v) { continue; }
  445.         $v = strtolower($v);
  446.         $ret[$v] = $v;
  447.     }
  448.     return $ret;
  449. }
  450.  
  451.  
  452. if (isset($_GET['disconnect']) && $_GET['disconnect'])
  453. {
  454.     cookie_del('db_pass');
  455.     header('Location: '.$_SERVER['PHP_SELF']);
  456.     exit;
  457. }
  458.  
  459. if (!$db_pass || (!$db_driver || !$db_server || !$db_name || !$db_user))
  460. {
  461.     $original_url = post('original_url');
  462.     if (!$original_url) {
  463.         $original_url = $_SERVER['REQUEST_URI'];
  464.     }
  465.  
  466.     if ('POST' == $_SERVER['REQUEST_METHOD'])
  467.     {
  468.         $db_driver = post('db_driver');
  469.         $db_server = post('db_server');
  470.         $db_name = post('db_name');
  471.         $db_user = post('db_user');
  472.         $db_pass = post('db_pass');
  473.         $db_charset = post('db_charset');
  474.         $page_charset = post('page_charset');
  475.  
  476.         if ($db_driver && $db_server && $db_name && $db_user)
  477.         {
  478.             $db_test = true;
  479.             db_connect($db_server, $db_name, $db_user, $db_pass);
  480.             if (is_resource($db_link))
  481.             {
  482.                 $time = post('remember') ? COOKIE_WEEK : COOKIE_SESS;
  483.                 cookie_set('db_driver', $db_driver, $time);
  484.                 cookie_set('db_server', $db_server, $time);
  485.                 cookie_set('db_name', $db_name, $time);
  486.                 cookie_set('db_user', $db_user, $time);
  487.                 cookie_set('db_pass', base64_encode($db_pass), $time);
  488.                 cookie_set('db_charset', $db_charset, $time);
  489.                 cookie_set('page_charset', $page_charset, $time);
  490.                 cookie_set('remember', post('remember'), $time);
  491.                 $redirect_to = $_SERVER['PHP_SELF'];
  492.                 if ($original_url) {
  493.                     $redirect_to = $original_url;
  494.                 }
  495.                 header('Location: '.$redirect_to);
  496.                 exit;
  497.             }
  498.         }
  499.     }
  500.     else
  501.     {
  502.         $_POST['db_driver'] = $db_driver;
  503.         $_POST['db_server'] = $db_server ? $db_server : 'localhost';
  504.         $_POST['db_name'] = $db_name;
  505.         $_POST['db_user'] = $db_user;
  506.         $_POST['db_charset'] = $db_charset;
  507.         $_POST['page_charset'] = $page_charset;
  508.         $_POST['db_driver'] = $db_driver;
  509.     }
  510.     ?>
  511.  
  512.         <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  513.         <html>
  514.         <head>
  515.             <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  516.             <title>Mysql Login DB</title>
  517.             <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
  518.         </head>
  519.         <body>
  520.  
  521.         <?php layout(); ?>
  522.  
  523.         <h1>~= Mysql Login DB =~</h1>
  524.  
  525.         <?php if (isset($db_test) && is_string($db_test)): ?>
  526.             <div style="background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em;">
  527.                 <span style="color: red; font-weight: bold;">Error:</span>&nbsp;
  528.                 <?php echo $db_test;?>
  529.             </div>
  530.         <?php endif; ?>
  531.         <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
  532.         <input type="hidden" name="original_url" value="<?php echo htmlspecialchars($original_url); ?>">
  533.         <table class="ls ls2" cellspacing="1">
  534.         <tr>
  535.             <th>Driver:</th>
  536.             <td><select name="db_driver"><?php echo options($driver_arr, post('db_driver'));?></select></td>
  537.         </tr>
  538.         <tr>
  539.             <th>Server:</th>
  540.             <td><input type="text" name="db_server" value="<?php echo post('db_server');?>"></td>
  541.         </tr>
  542.         <tr>
  543.             <th>Database:</th>
  544.             <td><input type="text" name="db_name" value="<?php echo post('db_name');?>"></td>
  545.         </tr>
  546.         <tr>
  547.             <th>User:</th>
  548.             <td><input type="text" name="db_user" value="<?php echo post('db_user');?>"></td>
  549.         </tr>
  550.         <tr>
  551.             <th>Password:</th>
  552.             <td><input type="password" name="db_pass" value=""></td>
  553.         </tr>
  554.         <tr>
  555.             <th>Db charset:</th>
  556.             <td><input type="text" name="db_charset" value="<?php echo post('db_charset');?>" size="10"> (optional)</td>
  557.         </tr>
  558.         <tr>
  559.             <th>Page charset:</th>
  560.             <td><input type="text" name="page_charset" value="<?php echo post('page_charset');?>" size="10"> (optional)</td>
  561.         </tr>
  562.         <tr>
  563.             <td colspan="2" class="none" style="padding: 0; background: none; padding-top: 0.3em;">
  564.                 <table cellspacing="0" cellpadding="0"><tr><td>
  565.                 <input type="checkbox" name="remember" id="remember" value="1" <?php echo checked(post('remember'));?>></td><td>
  566.                 <label for="remember">remember me on this computer</label></td></tr></table>
  567.             </td>
  568.         </tr>
  569.         <tr>
  570.             <td class="none" colspan="2" style="padding-top: 0.4em;"><input type="submit" value="Connect"></td>
  571.         </tr>
  572.         </table>
  573.         </form>
  574.  
  575.         <?php powered_by(); ?>
  576.  
  577.         </body>
  578.         </html>
  579.  
  580.     <?php
  581.  
  582.     exit;
  583. }
  584.  
  585. db_connect($db_server, $db_name, $db_user, $db_pass);
  586.  
  587. if ($db_charset && 'mysql' == $db_driver) {
  588.     db_exe("SET NAMES $db_charset");
  589. }
  590.  
  591. if (isset($_GET['dump_all']) && 1 == $_GET['dump_all'])
  592. {
  593.     dump_all($data = false);
  594. }
  595. if (isset($_GET['dump_all']) && 2 == $_GET['dump_all'])
  596. {
  597.     dump_all($data = true);
  598. }
  599. if (isset($_GET['dump_table']) && $_GET['dump_table'])
  600. {
  601.     dump_table($_GET['dump_table']);
  602. }
  603. if (isset($_GET['export']) && 'csv' == $_GET['export'])
  604. {
  605.     export_csv(base64_decode($_GET['query']),  $_GET['separator']);
  606. }
  607. if (isset($_POST['sqlfile']) && $_POST['sqlfile'])
  608. {
  609.     $files = sql_files_assoc();
  610.     if (!isset($files[$_POST['sqlfile']])) {
  611.         exit('File not found. md5 = '.$_POST['sqlfile']);
  612.     }
  613.     $sqlfile = $files[$_POST['sqlfile']];
  614.     layout();
  615.     echo '<div>Importing: <b>'.$sqlfile.'</b> ('.size(filesize($sqlfile)).')</div>';
  616.     echo '<div>Database: <b>'.$db_name.'</b></div>';
  617.     flush();
  618.     import($sqlfile, post('ignore_errors'), post('transaction'), post('force_myisam'), post('query_start','int'));
  619.     exit;
  620. }
  621. if (isset($_POST['drop_table']) && $_POST['drop_table'])
  622. {
  623.     $drop_table_enq = quote_table($_POST['drop_table']);
  624.     db_exe('DROP TABLE '.$drop_table_enq);
  625.     header('Location: '.$_SERVER['PHP_SELF']);
  626.     exit;
  627. }
  628. if (isset($_POST['drop_view']) && $_POST['drop_view'])
  629. {
  630.     $drop_view_enq = quote_table($_POST['drop_view']);
  631.     db_exe('DROP VIEW '.$drop_view_enq);
  632.     header('Location: '.$_SERVER['PHP_SELF']);
  633.     exit;
  634. }
  635. function db_connect($db_server, $db_name, $db_user, $db_pass)
  636. {
  637.     global $db_driver, $db_link, $db_test;
  638.     if (!extension_loaded($db_driver)) {
  639.         trigger_error($db_driver.' extension not loaded', E_USER_ERROR);
  640.     }
  641.     if ('mysql' == $db_driver)
  642.     {
  643.         $db_link = @mysql_connect($db_server, $db_user, $db_pass);
  644.         if (!is_resource($db_link)) {
  645.             if ($db_test) {
  646.                 $db_test = 'mysql_connect() failed: '.db_error();
  647.                 return;
  648.             } else {
  649.                 cookie_del('db_pass');
  650.                 cookie_del('db_name');
  651.                 die('mysql_connect() failed: '.db_error());
  652.             }
  653.         }
  654.         if (!@mysql_select_db($db_name, $db_link)) {
  655.             $error = db_error();
  656.             db_close();
  657.             if ($db_test) {
  658.                 $db_test = 'mysql_select_db() failed: '.$error;
  659.                 return;
  660.             } else {
  661.                 cookie_del('db_pass');
  662.                 cookie_del('db_name');
  663.                 die('mysql_select_db() failed: '.$error);
  664.             }
  665.         }
  666.     }
  667.     if ('pgsql' == $db_driver)
  668.     {
  669.         $conn = sprintf("host='%s' dbname='%s' user='%s' password='%s'", $db_server, $db_name, $db_user, $db_pass);
  670.         $db_link = @pg_connect($conn);
  671.         if (!is_resource($db_link)) {
  672.             if ($db_test) {
  673.                 $db_test = 'pg_connect() failed: '.db_error();
  674.                 return;
  675.             } else {
  676.                 cookie_del('db_pass');
  677.                 cookie_del('db_name');
  678.                 die('pg_connect() failed: '.db_error());
  679.             }
  680.         }
  681.     }
  682.     register_shutdown_function('db_cleanup');
  683. }
  684. function db_cleanup()
  685. {
  686.     db_close();
  687. }
  688. function db_close()
  689. {
  690.     global $db_driver, $db_link;
  691.     if (is_resource($db_link)) {
  692.         if ('mysql' == $db_driver) {
  693.             mysql_close($db_link);
  694.         }
  695.         if ('pgsql' == $db_driver) {
  696.             pg_close($db_link);
  697.         }
  698.     }
  699. }
  700. function db_query($query, $dat = false)
  701. {
  702.     global $db_driver, $db_link;
  703.     $query = db_bind($query, $dat);
  704.     if (!db_is_safe($query)) {
  705.         return false;
  706.     }
  707.     if ('mysql' == $db_driver)
  708.     {
  709.         $rs = mysql_query($query, $db_link);
  710.         if (!$rs) {
  711.             trigger_error("mysql_query() failed: $query.<br>Error: ".db_error(), E_USER_ERROR);
  712.         }
  713.         return $rs;
  714.     }
  715.     if ('pgsql' == $db_driver)
  716.     {
  717.         $rs = pg_query($db_link, $query);
  718.         if (!$rs) {
  719.             trigger_error("pg_query() failed: $query.<br>Error: ".db_error(), E_USER_ERROR);
  720.         }
  721.         return $rs;
  722.     }
  723. }
  724. function db_is_safe($q, $ret = false){
  725.     $upd = 'update';
  726.     $del = 'delete';
  727.  
  728.     $q = ltrim($q);
  729.     if (strtolower(substr($q, 0, strlen($upd))) == $upd
  730.         || strtolower(substr($q, 0, strlen($del))) == $del) {
  731.         if (!preg_match('#\swhere\s#i', $q)) {
  732.             if ($ret) {
  733.                 return false;
  734.             } else {
  735.                 trigger_error(sprintf('db_is_safe() failed. Detected UPDATE/DELETE without WHERE condition. Query: %s.', $q), E_USER_ERROR);
  736.                 return false;
  737.             }
  738.         }
  739.     }
  740.  
  741.     return true;
  742. }
  743. function db_exe($query, $dat = false)
  744. {
  745.     $rs = db_query($query, $dat);
  746.     db_free($rs);
  747. }
  748. function db_one($query, $dat = false)
  749. {
  750.     $row = db_row_num($query, $dat);
  751.     if ($row) {
  752.         return $row[0];
  753.     } else {
  754.         return false;
  755.     }
  756. }
  757. function db_row($query, $dat = false)
  758. {
  759.     global $db_driver, $db_link;
  760.     if ('mysql' == $db_driver)
  761.     {
  762.         if (is_resource($query)) {
  763.             $rs = $query;
  764.             return mysql_fetch_assoc($rs);
  765.         } else {
  766.             $query = db_limit($query, 0, 1);
  767.             $rs = db_query($query, $dat);
  768.             $row = mysql_fetch_assoc($rs);
  769.             db_free($rs);
  770.             if ($row) {
  771.                 return $row;
  772.             }
  773.         }
  774.         return false;
  775.     }
  776.     if ('pgsql' == $db_driver)
  777.     {
  778.         if (is_resource($query) || is_object($query)) {
  779.             $rs = $query;
  780.             return pg_fetch_assoc($rs);
  781.         } else {
  782.             $query = db_limit($query, 0, 1);
  783.             $rs = db_query($query, $dat);
  784.             $row = pg_fetch_assoc($rs);
  785.             db_free($rs);
  786.             if ($row) {
  787.                 return $row;
  788.             }
  789.         }
  790.         return false;
  791.     }
  792. }
  793. function db_row_num($query, $dat = false)
  794. {
  795.     global $db_driver, $db_link;
  796.     if ('mysql' == $db_driver)
  797.     {
  798.         if (is_resource($query)) {
  799.             $rs = $query;
  800.             return mysql_fetch_row($rs);
  801.         } else {
  802.             $rs = db_query($query, $dat);
  803.             if (!$rs) {
  804.                 /*
  805.                 echo '<pre>';
  806.                 print_r($rs);
  807.                 echo "\r\n";
  808.                 print_r($query);
  809.                 echo "\r\n";
  810.                 print_r($dat);
  811.                 exit;
  812.                 */
  813.             }
  814.             $row = mysql_fetch_row($rs);
  815.             db_free($rs);
  816.             if ($row) {
  817.                 return $row;
  818.             }
  819.             return false;
  820.         }
  821.     }
  822.     if ('pgsql' == $db_driver)
  823.     {
  824.         if (is_resource($query) || is_object($query)) {
  825.             $rs = $query;
  826.             return pg_fetch_row($rs);
  827.         } else {
  828.             $rs = db_query($query, $dat);
  829.             $row = pg_fetch_row($rs);
  830.             db_free($rs);
  831.             if ($row) {
  832.                 return $row;
  833.             }
  834.             return false;
  835.         }
  836.     }
  837. }
  838. function db_list($query)
  839. {
  840.     global $db_driver, $db_link;
  841.     $rs = db_query($query);
  842.     $ret = array();
  843.     if ('mysql' == $db_driver) {
  844.         while ($row = mysql_fetch_assoc($rs)) {
  845.             $ret[] = $row;
  846.         }
  847.     }
  848.     if ('pgsql' == $db_driver) {
  849.         while ($row = pg_fetch_assoc($rs)) {
  850.             $ret[] = $row;
  851.         }
  852.     }
  853.     db_free($rs);
  854.     return $ret;
  855. }
  856. function db_assoc($query)
  857. {
  858.     global $db_driver, $db_link;
  859.     $rs = db_query($query);
  860.     $rows = array();
  861.     $num = db_row_num($rs);
  862.     if (!is_array($num)) {
  863.         return array();
  864.     }
  865.     if (!array_key_exists(0, $num)) {
  866.         return array();
  867.     }
  868.     if (1 == count($num)) {
  869.         $rows[] = $num[0];
  870.         while ($num = db_row_num($rs)) {
  871.             $rows[] = $num[0];
  872.         }
  873.         return $rows;
  874.     }
  875.     if ('mysql' == $db_driver)
  876.     {
  877.         mysql_data_seek($rs, 0);
  878.     }
  879.     if ('pgsql' == $db_driver)
  880.     {
  881.         pg_result_seek($rs, 0);
  882.     }
  883.     $row = db_row($rs);
  884.     if (!is_array($row)) {
  885.         return array();
  886.     }
  887.     if (count($num) < 2) {
  888.         trigger_error(sprintf('db_assoc() failed. Two fields required. Query: %s.', $query), E_USER_ERROR);
  889.     }
  890.     if (count($num) > 2 && count($row) <= 2) {
  891.         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);
  892.     }
  893.     foreach ($row as $k => $v) {
  894.         $first_key = $k;
  895.         break;
  896.     }
  897.     if (count($row) > 2) {
  898.         $rows[$row[$first_key]] = $row;
  899.         while ($row = db_row($rs)) {
  900.             $rows[$row[$first_key]] = $row;
  901.         }
  902.     } else {
  903.         $rows[$num[0]] = $num[1];
  904.         while ($num = db_row_num($rs)) {
  905.             $rows[$num[0]] = $num[1];
  906.         }
  907.     }
  908.     db_free($rs);
  909.     return $rows;
  910. }
  911. function db_limit($query, $offset, $limit)
  912. {
  913.     global $db_driver;
  914.  
  915.     $offset = (int) $offset;
  916.     $limit = (int) $limit;
  917.  
  918.     $query = trim($query);
  919.     if (str_ends_with($query, ';')) {
  920.         $query = str_cut_end($query, ';');
  921.     }
  922.  
  923.     $query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s+OFFSET\s+\d+\s*$#i', '$1', $query);
  924.     $query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s*,\s*\d+\s*$#i', '$1', $query);
  925.  
  926.     if ('mysql' == $db_driver) {
  927.         // mysql 3.23 doesn't understand "LIMIT x OFFSET z"
  928.         return $query." LIMIT $offset, $limit";
  929.     } else {
  930.         return $query." LIMIT $limit OFFSET $offset";
  931.     }
  932. }
  933. function db_escape($value)
  934. {
  935.     global $db_driver, $db_link;
  936.     if ('mysql' == $db_driver) {
  937.         return mysql_real_escape_string($value, $db_link);
  938.     }
  939.     if ('pgsql' == $db_driver) {
  940.         return pg_escape_string($value);
  941.     }
  942. }
  943. function db_quote($s)
  944. {
  945.     switch (true) {
  946.         case is_null($s): return 'NULL';
  947.         case is_int($s): return $s;
  948.         case is_float($s): return $s;
  949.         case is_bool($s): return (int) $s;
  950.         case is_string($s): return "'" . db_escape($s) . "'";
  951.         case is_object($s): return $s->getValue();
  952.         default:
  953.             trigger_error(sprintf("db_quote() failed. Invalid data type: '%s'.", gettype($s)), E_USER_ERROR);
  954.             return false;
  955.     }
  956. }
  957. function db_strlen_cmp($a, $b)
  958. {
  959.     if (strlen($a) == strlen($b)) {
  960.         return 0;
  961.     }
  962.     return strlen($a) > strlen($b) ? -1 : 1;
  963. }
  964. function db_bind($q, $dat)
  965. {
  966.     if (false === $dat) {
  967.         return $q;
  968.     }
  969.     if (!is_array($dat)) {
  970.         //return trigger_error('db_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
  971.         $dat = array($dat);
  972.     }
  973.  
  974.     $qBase = $q;
  975.  
  976.     // special case: LIKE '%asd%', need to ignore that
  977.     $q_search = array("'%", "%'");
  978.     $q_replace = array("'\$", "\$'");
  979.     $q = str_replace($q_search, $q_replace, $q);
  980.  
  981.     preg_match_all('#%\w+#', $q, $match);
  982.     if ($match) {
  983.         $match = $match[0];
  984.     }
  985.     if (!$match || !count($match)) {
  986.         return trigger_error('db_bind() failed. No binding keys found in the query.', E_USER_ERROR);
  987.     }
  988.     $keys = $match;
  989.     usort($keys, 'db_strlen_cmp');
  990.     $num = array();
  991.  
  992.     foreach ($keys as $key)
  993.     {
  994.         $key2 = str_replace('%', '', $key);
  995.         if (is_numeric($key2)) $num[$key] = true;
  996.         if (!array_key_exists($key2, $dat)) {
  997.             return trigger_error(sprintf('db_bind() failed. No data found for key: %s. Query: %s.', $key, $qBase), E_USER_ERROR);
  998.         }
  999.         $q = str_replace($key, db_quote($dat[$key2]), $q);
  1000.     }
  1001.     if (count($num)) {
  1002.         if (count($dat) != count($num)) {
  1003.             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);
  1004.         }
  1005.     }
  1006.  
  1007.     $q = str_replace($q_replace, $q_search, $q);
  1008.  
  1009.     return $q;
  1010. }
  1011. function db_free($rs)
  1012. {
  1013.     global $db_driver;
  1014.     if (db_is_result($rs)) {
  1015.         if ('mysql' == $db_driver) return mysql_free_result($rs);
  1016.         if ('pgsql' == $db_driver) return pg_free_result($rs);
  1017.     }
  1018. }
  1019. function db_is_result($rs)
  1020. {
  1021.     global $db_driver;
  1022.     if ('mysql' == $db_driver) return is_resource($rs);
  1023.     if ('pgsql' == $db_driver) return is_object($rs) || is_resource($rs);
  1024. }
  1025. function db_error()
  1026. {
  1027.     global $db_driver, $db_link;
  1028.     if ('mysql' == $db_driver) {
  1029.         if (is_resource($db_link)) {
  1030.             if (mysql_error($db_link)) {
  1031.                 return mysql_error($db_link). ' ('. mysql_errno($db_link).')';
  1032.             } else {
  1033.                 return false;
  1034.             }
  1035.         } else {
  1036.             if (mysql_error()) {
  1037.                 return mysql_error(). ' ('. mysql_errno().')';
  1038.             } else {
  1039.                 return false;
  1040.             }
  1041.         }
  1042.     }
  1043.     if ('pgsql' == $db_driver) {
  1044.         if (is_resource($db_link)) {
  1045.             return pg_last_error($db_link);
  1046.         }
  1047.     }
  1048. }
  1049. function db_begin()
  1050. {
  1051.     global $db_driver;
  1052.     if ('mysql' == $db_driver) {
  1053.         db_exe('SET AUTOCOMMIT=0');
  1054.         db_exe('BEGIN');
  1055.     }
  1056.     if ('pgsql' == $db_driver) {
  1057.         db_exe('BEGIN');
  1058.     }
  1059. }
  1060. function db_end()
  1061. {
  1062.     global $db_driver;
  1063.     if ('mysql' == $db_driver) {
  1064.         db_exe('COMMIT');
  1065.         db_exe('SET AUTOCOMMIT=1');
  1066.     }
  1067.     if ('pgsql' == $db_driver) {
  1068.         db_exe('COMMIT');
  1069.     }
  1070. }
  1071. function db_rollback()
  1072. {
  1073.     global $db_driver;
  1074.     if ('mysql' == $db_driver) {
  1075.         db_exe('ROLLBACK');
  1076.         db_exe('SET AUTOCOMMIT=1');
  1077.     }
  1078.     if ('pgsql' == $db_driver) {
  1079.         db_exe('ROLLBACK');
  1080.     }
  1081. }
  1082. function db_in_array($arr)
  1083. {
  1084.     $in = '';
  1085.     foreach ($arr as $v) {
  1086.         if ($in) $in .= ',';
  1087.         $in .= db_quote($v);
  1088.     }
  1089.     return $in;
  1090. }
  1091. function db_where($where_array, $field_prefix = null, $omit_where = false)
  1092. {
  1093.     $field_prefix = str_replace('.', '', $field_prefix);
  1094.     $where = '';
  1095.     if (count($where_array)) {
  1096.         foreach ($where_array as $wh_k => $wh)
  1097.         {
  1098.             if (is_numeric($wh_k)) {
  1099.                 if ($wh) {
  1100.                     if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
  1101.                         $wh = $field_prefix.'.'.trim($wh);
  1102.                     }
  1103.                     if ($where) $where .= ' AND ';
  1104.                     $where .= $wh;
  1105.                 }
  1106.             } else {
  1107.                 if ($wh_k) {
  1108.                     if ($field_prefix && !preg_match('#^\s*\w+\.#i', $wh_k) && !preg_match('#^\s*\w+\s*\(#i', $wh)) {
  1109.                         $wh_k = $field_prefix.'.'.$wh_k;
  1110.                     }
  1111.                     $wh = db_cond($wh_k, $wh);
  1112.                     if ($where) $where .= ' AND ';
  1113.                     $where .= $wh;
  1114.                 }
  1115.             }
  1116.         }
  1117.         if ($where) {
  1118.             if (!$omit_where) {
  1119.                 $where = ' WHERE '.$where;
  1120.             }
  1121.         }
  1122.     }
  1123.     return $where;
  1124. }
  1125. function db_insert($tbl, $dat)
  1126. {
  1127.     global $db_driver;
  1128.     if (!count($dat)) {
  1129.         trigger_error('db_insert() failed. Data is empty.', E_USER_ERROR);
  1130.         return false;
  1131.     }
  1132.     $cols = '';
  1133.     $vals = '';
  1134.     $first = true;
  1135.     foreach ($dat as $k => $v) {
  1136.         if ($first) {
  1137.             $cols .= $k;
  1138.             $vals .= db_quote($v);
  1139.             $first = false;
  1140.         } else {
  1141.             $cols .= ',' . $k;
  1142.             $vals .= ',' . db_quote($v);
  1143.         }
  1144.     }
  1145.     if ('mysql' == $db_driver) {
  1146.         $tbl = "`$tbl`";
  1147.     }
  1148.     $q = "INSERT INTO $tbl ($cols) VALUES ($vals)";
  1149.     db_exe($q);
  1150. }
  1151. // $wh = WHERE condition, might be (string) or (array)
  1152. function db_update($tbl, $dat, $wh)
  1153. {
  1154.     global $db_driver;
  1155.     if (!count($dat)) {
  1156.         trigger_error('db_update() failed. Data is empty.', E_USER_ERROR);
  1157.         return false;
  1158.     }
  1159.     $set = '';
  1160.     $first = true;
  1161.     foreach ($dat as $k => $v) {
  1162.         if ($first) {
  1163.             $set   .= $k . '=' . db_quote($v);
  1164.             $first = false;
  1165.         } else {
  1166.             $set .= ',' . $k . '=' . db_quote($v);
  1167.         }
  1168.     }
  1169.     if (is_array($wh)) {
  1170.         $wh = db_where($wh, null, $omit_where = true);
  1171.     }
  1172.     if ('mysql' == $db_driver) {
  1173.         $tbl = "`$tbl`";
  1174.     }
  1175.     $q = "UPDATE $tbl SET $set WHERE $wh";
  1176.     return db_exe($q);
  1177. }
  1178. function db_insert_id($table = null, $pk = null)
  1179. {
  1180.     global $db_driver, $db_link;
  1181.     if ('mysql' == $db_driver) {
  1182.         return mysql_insert_id($_db['conn_id']);
  1183.     }
  1184.     if ('pgsql' == $db_driver) {
  1185.         if (!$table || !$pk) {
  1186.             trigger_error('db_insert_id(): table & pk required', E_USER_ERROR);
  1187.         }
  1188.         $seq_id = $table.'_'.$pk.'_seq';
  1189.         return db_seq_id($seq_id);
  1190.     }
  1191. }
  1192. function db_seq_id($seqName)
  1193. {
  1194.     return db_one('SELECT currval(%seqName)', array('seqName'=>$seqName));
  1195. }
  1196. function db_cond($k, $v)
  1197. {
  1198.     if (is_null($v)) return sprintf('%s IS NULL', $k);
  1199.     else return sprintf('%s = %s', $k, db_quote($v));
  1200. }
  1201. function list_dbs()
  1202. {
  1203.     global $db_driver, $db_link;
  1204.     if ('mysql' == $db_driver)
  1205.     {
  1206.         $result = mysql_query('SHOW DATABASES', $db_link);
  1207.         $ret = array();
  1208.         while ($row = mysql_fetch_row($result)) {
  1209.             $ret[$row[0]] = $row[0];
  1210.         }
  1211.         return $ret;
  1212.     }
  1213.     if ('pgsql' == $db_driver)
  1214.     {
  1215.         return db_assoc('SELECT datname, datname FROM pg_database');
  1216.     }
  1217. }
  1218. function views_supported()
  1219. {
  1220.     static $ret;
  1221.     if (isset($ret)) {
  1222.         return $ret;
  1223.     }
  1224.     global $db_driver, $db_link;
  1225.     if ('mysql' == $db_driver) {
  1226.         $version = mysql_get_server_info($db_link);
  1227.         if (strpos($version, "-") !== false) {
  1228.             $version = substr($version, 0, strpos($version, "-"));
  1229.         }
  1230.         if (version_compare($version, "5.0.2", ">=")) {
  1231.             // Views are available in 5.0.0 but we need SHOW FULL TABLES
  1232.             // and the FULL syntax was added in 5.0.2, FULL allows us to
  1233.             // to distinct between tables & views in the returned list by
  1234.             // by providing an additional column.
  1235.             $ret = true;
  1236.             return true;
  1237.         } else {
  1238.             $ret = false;
  1239.             return false;
  1240.         }
  1241.     }
  1242.     if ('pgsql' == $db_driver) {
  1243.         $ret = true;
  1244.         return true;
  1245.     }
  1246. }
  1247. function list_tables($views_mode=false)
  1248. {
  1249.     global $db_driver, $db_link, $db_name;
  1250.  
  1251.     if ($views_mode && !views_supported()) {
  1252.         return array();
  1253.     }
  1254.  
  1255.     static $cache_tables;
  1256.     static $cache_views;
  1257.  
  1258.     if ($views_mode) {
  1259.         if (isset($cache_views)) {
  1260.             return $cache_views;
  1261.         }
  1262.     } else {
  1263.         if (isset($cache_tables)) {
  1264.             return $cache_tables;
  1265.         }
  1266.     }
  1267.  
  1268.     static $all_tables; // tables and views
  1269.  
  1270.     if ('mysql' == $db_driver)
  1271.     {
  1272.         if (!isset($all_tables)) {
  1273.             $all_tables = db_assoc("SHOW FULL TABLES");
  1274.             // assoc: table name => table type (BASE TABLE or VIEW)
  1275.         }
  1276.  
  1277.         // This chunk of code is the same as in pgsql driver.
  1278.         if ($views_mode) {
  1279.             $views = array();
  1280.             foreach ($all_tables as $view => $type) {
  1281.                 if ($type != 'VIEW') { continue; }
  1282.                 $views[] = $view;
  1283.             }
  1284.             $cache_views = $views;
  1285.             return $views;
  1286.         } else {
  1287.             $tables = array();
  1288.             foreach ($all_tables as $table => $type) {
  1289.                 if ($type != 'BASE TABLE') { continue; }
  1290.                 $tables[] = $table;
  1291.             }
  1292.             $cache_tables = $tables;
  1293.             return $tables;
  1294.         }
  1295.     }
  1296.     if ('pgsql' == $db_driver)
  1297.     {
  1298.         if (!isset($all_tables)) {
  1299.             $query = "SELECT table_name, table_type ";
  1300.             $query .= "FROM information_schema.tables ";
  1301.             $query .= "WHERE table_schema = 'public' ";
  1302.             $query .= "AND (table_type = 'BASE TABLE' OR table_type = 'VIEW') ";
  1303.             $query .= "ORDER BY table_name ";
  1304.             $all_tables = db_assoc($query);
  1305.         }
  1306.  
  1307.         // This chunk of code is the same as in mysql driver.
  1308.         if ($views_mode) {
  1309.             $views = array();
  1310.             foreach ($all_tables as $view => $type) {
  1311.                 if ($type != 'VIEW') { continue; }
  1312.                 $views[] = $view;
  1313.             }
  1314.             $cache_views = $views;
  1315.             return $views;
  1316.         } else {
  1317.             $tables = array();
  1318.             foreach ($all_tables as $table => $type) {
  1319.                 if ($type != 'BASE TABLE') { continue; }
  1320.                 $tables[] = $table;
  1321.             }
  1322.             $cache_tables = $tables;
  1323.             return $tables;
  1324.         }
  1325.     }
  1326. }
  1327. function IsTableAView($table)
  1328. {
  1329.     // There is no cache here, so call it only once!
  1330.  
  1331.     global $db_driver, $db_name;
  1332.  
  1333.     if ("mysql" == $db_driver) {
  1334.         // Views and information_schema is supported since 5.0
  1335.         if (views_supported()) {
  1336.             $query = "SELECT table_name FROM information_schema.tables WHERE table_schema=%0 AND table_name=%1 AND table_type='VIEW' ";
  1337.             $row = db_row($query, array($db_name, $table));
  1338.             return (bool) $row;
  1339.         }
  1340.         return false;
  1341.     }
  1342.     else if ("pgsql" == $db_driver) {
  1343.         $query = "SELECT table_name, table_type ";
  1344.         $query .= "FROM information_schema.tables ";
  1345.         $query .= "WHERE table_schema = 'public' ";
  1346.         $query .= "AND table_type = 'VIEW' AND table_name = %0 ";
  1347.         $row = db_row($query, $table);
  1348.         return (bool) $row;
  1349.     }
  1350. }
  1351. function quote_table($table)
  1352. {
  1353.     global $db_driver;
  1354.     if ('mysql' == $db_driver) {
  1355.         return "`$table`";
  1356.     } else {
  1357.         return "\"$table\"";
  1358.     }
  1359. }
  1360. function table_structure($table)
  1361. {
  1362.     global $db_driver;
  1363.     if ('mysql' == $db_driver)
  1364.     {
  1365.         $query = "SHOW CREATE TABLE `$table`";
  1366.         $row = db_row_num($query);
  1367.         echo $row[1].';';
  1368.         echo "\n\n";
  1369.     }
  1370.     if ('pgsql' == $db_driver)
  1371.     {
  1372.         return '';
  1373.     }
  1374. }
  1375. function table_data($table)
  1376. {
  1377.     global $db_driver;
  1378.     set_time_limit(0);
  1379.     if ('mysql' == $db_driver) {
  1380.         $query = "SELECT * FROM `$table`";
  1381.     } else {
  1382.         $query = "SELECT * FROM $table";
  1383.     }
  1384.     $result = db_query($query);
  1385.     $count = 0;
  1386.     while ($row = db_row($result))
  1387.     {
  1388.         if ('mysql' == $db_driver) {
  1389.             echo 'INSERT INTO `'.$table.'` VALUES (';
  1390.         }
  1391.         if ('pgsql' == $db_driver) {
  1392.             echo 'INSERT INTO '.$table.' VALUES (';
  1393.         }
  1394.         $x = 0;
  1395.         foreach($row as $key => $value)
  1396.         {
  1397.             if ($x == 1) { echo ', '; }
  1398.             else  { $x = 1; }
  1399.             if (is_numeric($value)) { echo "'".$value."'"; }
  1400.             elseif (is_null($value))  { echo 'NULL'; }
  1401.             else { echo '\''. escape($value) .'\''; }
  1402.         }
  1403.         echo ");\n";
  1404.         $count++;
  1405.         if ($count % 100 == 0) { flush(); }
  1406.     }
  1407.     db_free($result);
  1408.     if ($count) {
  1409.         echo "\n";
  1410.     }
  1411. }
  1412. function table_status()
  1413. {
  1414.     // Size is not supported for Views, only for Tables.
  1415.  
  1416.     global $db_driver, $db_link, $db_name;
  1417.     if ('mysql' == $db_driver)
  1418.     {
  1419.         $status = array();
  1420.         $status['total_size'] = 0;
  1421.         $result = mysql_query("SHOW TABLE STATUS FROM `$db_name`", $db_link);
  1422.         while ($row = mysql_fetch_assoc($result)) {
  1423.             if (!is_numeric($row['Data_length'])) {
  1424.                 // Data_length for Views is NULL.
  1425.                 continue;
  1426.             }
  1427.             $status['total_size'] += $row['Data_length']; // + Index_length
  1428.             $status[$row['Name']]['size'] = $row['Data_length'];
  1429.             $status[$row['Name']]['count'] = $row['Rows'];
  1430.         }
  1431.         return $status;
  1432.     }
  1433.     if ('pgsql' == $db_driver)
  1434.     {
  1435.         $status = array();
  1436.         $status['total_size'] = 0;
  1437.         $tables = list_tables(); // only tables, not views
  1438.         if (!count($tables)) {
  1439.             return $status;
  1440.         }
  1441.         $tables_in = db_in_array($tables);
  1442.         $rels = db_list("SELECT relname, reltuples, (relpages::decimal + 1) * 8 * 2 * 1024 AS relsize FROM pg_class WHERE relname IN ($tables_in)");
  1443.         foreach ($rels as $rel) {
  1444.             $status['total_size'] += $rel['relsize'];
  1445.             $status[$rel['relname']]['size'] = $rel['relsize'];
  1446.             $status[$rel['relname']]['count'] = $rel['reltuples'];
  1447.         }
  1448.         return $status;
  1449.     }
  1450. }
  1451. function table_columns($table)
  1452. {
  1453.     global $db_driver;
  1454.     static $cache = array();
  1455.     if (isset($cache[$table])) {
  1456.         return $cache[$table];
  1457.     }
  1458.     if ('mysql' == $db_driver) {
  1459.         $row = db_row("SELECT * FROM `$table`");
  1460.     } else {
  1461.         $row = db_row("SELECT * FROM $table");
  1462.     }
  1463.     if (!$row) {
  1464.         $cache[$table] = array();
  1465.         return array();
  1466.     }
  1467.     foreach ($row as $k => $v) {
  1468.         $row[$k] = $k;
  1469.     }
  1470.     $cache[$table] = $row;
  1471.     return $row;
  1472. }
  1473. function table_types($table)
  1474. {
  1475.     global $db_driver;
  1476.     if ('mysql' == $db_driver)
  1477.     {
  1478.         $rows = db_list("SHOW COLUMNS FROM `$table`");
  1479.         $types = array();
  1480.         foreach ($rows as $row) {
  1481.             $type = $row['Type'];
  1482.             $types[$row['Field']] = $type;
  1483.         }
  1484.         return $types;
  1485.     }
  1486.     if ('pgsql' == $db_driver)
  1487.     {
  1488.         return db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
  1489.     }
  1490. }
  1491. function table_types2($table)
  1492. {
  1493.     global $db_driver;
  1494.     if ('mysql' == $db_driver)
  1495.     {
  1496.         $types = array();
  1497.         $rows = @db_list("SHOW COLUMNS FROM `$table`");
  1498.         if (!($rows && count($rows))) {
  1499.             return false;
  1500.         }
  1501.         foreach ($rows as $row) {
  1502.             $type = $row['Type'];
  1503.             preg_match('#^[a-z]+#', $type, $match);
  1504.             $type = $match[0];
  1505.             $types[$row['Field']] = $type;
  1506.         }
  1507.     }
  1508.     if ('pgsql' == $db_driver)
  1509.     {
  1510.         $types = db_assoc("SELECT column_name, udt_name FROM information_schema.columns WHERE table_name ='$table' ORDER BY ordinal_position");
  1511.         if (!count($types)) {
  1512.             return false;
  1513.         }
  1514.         foreach ($types as $col => $type) {
  1515.             // "_" also in regexp - error when retrieving column info from "pg_class",
  1516.             // udt_name might be "_aclitem" / "_text".
  1517.             preg_match('#^[a-z_]+#', $type, $match);
  1518.             $type = $match[0];
  1519.             $types[$col] = $type;
  1520.         }
  1521.     }
  1522.     foreach ($types as $col => $type) {
  1523.         if ('varchar' == $type) { $type = 'char'; }
  1524.         if ('integer' == $type) { $type = 'int'; }
  1525.         if ('timestamp' == $type) { $type = 'time'; }
  1526.         $types[$col] = $type;
  1527.     }
  1528.     return $types;
  1529. }
  1530. function table_types_group($types)
  1531. {
  1532.     foreach ($types as $k => $type) {
  1533.         preg_match('#^\w+#', $type, $match);
  1534.         $type = $match[0];
  1535.         $types[$k] = $type;
  1536.     }
  1537.     $types = array_unique($types);
  1538.     $types = array_values($types);
  1539.     $types2 = array();
  1540.     foreach ($types as $type) {
  1541.         $types2[$type] = $type;
  1542.     }
  1543.     return $types2;
  1544. }
  1545. function table_pk($table)
  1546. {
  1547.     $cols = table_columns($table);
  1548.     if (!$cols) return null;
  1549.     foreach ($cols as $col) {
  1550.         return $col;
  1551.     }
  1552. }
  1553. function escape($text)
  1554. {
  1555.     $text = addslashes($text);
  1556.     $search = array("\r", "\n", "\t");
  1557.     $replace = array('\r', '\n', '\t');
  1558.     return str_replace($search, $replace, $text);
  1559. }
  1560. function ob_cleanup()
  1561. {
  1562.     while (ob_get_level()) {
  1563.         ob_end_clean();
  1564.     }
  1565.     if (headers_sent()) {
  1566.         return;
  1567.     }
  1568.     if (function_exists('headers_list')) {
  1569.         foreach (headers_list() as $header) {
  1570.             if (preg_match('/Content-Encoding:/i', $header)) {
  1571.                 header('Content-encoding: none');
  1572.                 break;
  1573.             }
  1574.         }
  1575.     } else {
  1576.         header('Content-encoding: none');
  1577.     }
  1578. }
  1579. function query_color($query)
  1580. {
  1581.     $color = 'red';
  1582.     $words = array('SELECT', 'UPDATE', 'DELETE', 'FROM', 'LIMIT', 'OFFSET', 'AND', 'LEFT JOIN', 'WHERE', 'SET',
  1583.         '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');
  1584.     $words = implode('|', $words);
  1585.  
  1586.     $query = preg_replace("#^({$words})(\s)#i", '<font color="'.$color.'">$1</font>$2', $query);
  1587.     $query = preg_replace("#(\s)({$words})$#i", '$1<font color="'.$color.'">$2</font>', $query);
  1588.     // replace twice, some words when preceding other are not replaced
  1589.     $query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1<font color="'.$color.'">$2</font>$3', $query);
  1590.     $query = preg_replace("#([\s\(\),])({$words})([\s\(\),])#i", '$1<font color="'.$color.'">$2</font>$3', $query);
  1591.     $query = preg_replace("#^($words)$#i", '<font color="'.$color.'">$1</font>', $query);
  1592.  
  1593.     preg_match_all('#<font[^>]+>('.$words.')</font>#i', $query, $matches);
  1594.     foreach ($matches[0] as $k => $font) {
  1595.         $font2 = str_replace($matches[1][$k], strtoupper($matches[1][$k]), $font);
  1596.         $query = str_replace($font, $font2, $query);
  1597.     }
  1598.  
  1599.     return $query;
  1600. }
  1601. function query_upper($sql)
  1602. {
  1603.     return $sql;
  1604.     // todo: don't upper quoted ' and ' values
  1605.     $queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $sql);
  1606.     foreach ($queries as $k => $query) {
  1607.         $strip = query_strip($query);
  1608.         $color = query_color($strip);
  1609.         $sql = str_replace($strip, $color, $sql);
  1610.     }
  1611.     $sql = preg_replace('#<font color="\w+">([^>]+)</font>#iU', '$1', $sql);
  1612.     return $sql;
  1613. }
  1614. function html_spaces($string)
  1615. {
  1616.     $inside_tag = false;
  1617.     for ($i = 0; $i < strlen($string); $i++)
  1618.     {
  1619.         $c = $string{$i};
  1620.         if ('<' == $c) {
  1621.             $inside_tag = true;
  1622.         }
  1623.         if ('>' == $c) {
  1624.             $inside_tag = false;
  1625.         }
  1626.         if (' ' == $c && !$inside_tag) {
  1627.             $string = substr($string, 0, $i).'&nbsp;'.substr($string, $i+1);
  1628.             $i += strlen('&nbsp;')-1;
  1629.         }
  1630.     }
  1631.     return $string;
  1632. }
  1633. function query_cut($query)
  1634. {
  1635.     // removes sub-queries and string values from query
  1636.     $brace_start = '(';
  1637.     $brace_end = ')';
  1638.     $quote = "'";
  1639.     $inside_brace = false;
  1640.     $inside_quote = false;
  1641.     $depth = 0;
  1642.     $ret = '';
  1643.     $query = str_replace('\\\\', '', $query);
  1644.  
  1645.     for ($i = 0; $i < strlen($query); $i++)
  1646.     {
  1647.         $prev_char = isset($query{$i-1}) ? $query{$i-1} : null;
  1648.         $char = $query{$i};
  1649.         if ($char == $brace_start) {
  1650.             if (!$inside_quote) {
  1651.                 $depth++;
  1652.             }
  1653.         }
  1654.         if ($char == $brace_end) {
  1655.             if (!$inside_quote) {
  1656.                 $depth--;
  1657.                 if ($depth == 0) {
  1658.                     $ret .= '(...)';
  1659.                 }
  1660.                 continue;
  1661.             }
  1662.         }
  1663.         if ($char == $quote) {
  1664.             if ($inside_quote) {
  1665.                 if ($prev_char != '\\') {
  1666.                     $inside_quote = false;
  1667.                     if (!$depth) {
  1668.                         $ret .= "'...'";
  1669.                     }
  1670.                     continue;
  1671.                 }
  1672.             } else {
  1673.                 $inside_quote = true;
  1674.             }
  1675.         }
  1676.         if (!$depth && !$inside_quote) {
  1677.             $ret .= $char;
  1678.         }
  1679.     }
  1680.     return $ret;
  1681. }
  1682. function table_from_query($query)
  1683. {
  1684.     if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $query, $match)) {
  1685.         $cut = query_cut($query);
  1686.         if (preg_match('#\sFROM\s+["`]?(\w+)["`]?#i', $cut, $match2)) {
  1687.             $table = $match2[1];
  1688.         } else {
  1689.             $table = $match[1];
  1690.         }
  1691.     } else if (preg_match('#UPDATE\s+"?(\w+)"?#i', $query, $match)) {
  1692.         $table = $match[1];
  1693.     } else if (preg_match('#INSERT\s+INTO\s+"?(\w+)"?#', $query, $match)) {
  1694.         $table = $match[1];
  1695.     } else {
  1696.         $table = false;
  1697.     }
  1698.     return $table;
  1699. }
  1700. function is_select($query)
  1701. {
  1702.     return preg_match('#^\s*SELECT\s+#i', $query);
  1703. }
  1704. function query_strip($query)
  1705. {
  1706.     // strip comments and ';' from the end of query
  1707.     $query = trim($query);
  1708.     if (str_ends_with($query, ';')) {
  1709.         $query = str_cut_end($query, ';');
  1710.     }
  1711.     $lines = preg_split("#(\r\n|\n|\r)#", $query);
  1712.     foreach ($lines as $k => $line) {
  1713.         $line = trim($line);
  1714.         if (!$line || str_starts_with($line, '--')) {
  1715.             unset($lines[$k]);
  1716.         }
  1717.     }
  1718.     $query = implode("\r\n", $lines);
  1719.     return $query;
  1720. }
  1721. function dump_table($table)
  1722. {
  1723.     ob_cleanup();
  1724.     define('DEBUG_CONSOLE_HIDE', 1);
  1725.     set_time_limit(0);
  1726.     global $db_name;
  1727.     header("Cache-control: private");
  1728.     header("Content-type: application/octet-stream");
  1729.     header('Content-Disposition: attachment; filename='.$db_name.'_'.$table.'.sql');
  1730.     table_structure($table);
  1731.     table_data($table);
  1732.     exit;
  1733. }
  1734. function dump_all($data = false)
  1735. {
  1736.     global $db_name;
  1737.  
  1738.     ob_cleanup();
  1739.     define('DEBUG_CONSOLE_HIDE', 1);
  1740.     set_time_limit(0);
  1741.  
  1742.     $tables = list_tables();
  1743.     $table_filter = get('table_filter');
  1744.     $tables = table_filter($tables, $table_filter);
  1745.  
  1746.     header("Cache-control: private");
  1747.     header("Content-type: application/octet-stream");
  1748.     header('Content-Disposition: attachment; filename='.date('Ymd').'_'.$db_name.'.sql');
  1749.  
  1750.     foreach ($tables as $key => $table)
  1751.     {
  1752.         table_structure($table);
  1753.         if ($data) {
  1754.             table_data($table);
  1755.         }
  1756.         flush();
  1757.     }
  1758.     exit;
  1759. }
  1760. function export_csv($query, $separator)
  1761. {
  1762.     ob_cleanup();
  1763.     set_time_limit(0);
  1764.  
  1765.     if (!is_select($query)) {
  1766.         trigger_error('export_csv() failed: not a SELECT query: '.$query, E_USER_ERROR);
  1767.     }
  1768.  
  1769.     $table = table_from_query($query);
  1770.     if (!$table) {
  1771.         $table = 'unknown';
  1772.     }
  1773.  
  1774.     header("Cache-control: private");
  1775.     header("Content-type: application/octet-stream");
  1776.     header('Content-Disposition: attachment; filename='.$table.'_'.date('Ymd').'.csv');
  1777.  
  1778.     $rs = db_query($query);
  1779.     $first = true;
  1780.  
  1781.     while ($row = db_row($rs)) {
  1782.         if ($first) {
  1783.             echo csv_row(array_keys($row), $separator);
  1784.             $first = false;
  1785.         }
  1786.         echo csv_row($row, $separator);
  1787.         flush();
  1788.     }
  1789.  
  1790.     exit();
  1791. }
  1792. function csv_row($row, $separator)
  1793. {
  1794.     foreach ($row as $key => $val) {
  1795.         $enquote = false;
  1796.         if (false !== strpos($val, $separator)) {
  1797.             $enquote = true;
  1798.         }
  1799.         if (false !== strpos($val, "\"")) {
  1800.             $enquote = true;
  1801.             $val = str_replace("\"", "\"\"", $val);
  1802.         }
  1803.         if (false !== strpos($val, "\r") || false !== strpos($val, "\n")) {
  1804.             $enquote = true;
  1805.             $val = preg_replace('#(\r\n|\r|\n)#', "\n", $val); // excel needs \n instead of \r\n
  1806.         }
  1807.         if ($enquote) {
  1808.             $row[$key] = "\"".$val."\"";
  1809.         }
  1810.     }
  1811.     $out = implode($separator, $row);
  1812.     $out .= "\r\n";
  1813.     return $out;
  1814. }
  1815. function import($file, $ignore_errors = false, $transaction = false, $force_myisam = false, $query_start = false)
  1816. {
  1817.     global $db_driver, $db_link, $db_charset;
  1818.     if ($ignore_errors && $transaction) {
  1819.         echo '<div>You cannot select both: ignoring errors and transaction</div>';
  1820.         exit;
  1821.     }
  1822.  
  1823.     $count_errors = 0;
  1824.     set_time_limit(0);
  1825.     $fp = fopen($file, 'r');
  1826.     if (!$fp) { exit('fopen('.$file.') failed'); }
  1827.     flock($fp, 1);
  1828.     $text = trim(fread($fp, filesize($file)));
  1829.     flock($fp, 3);
  1830.     fclose($fp);
  1831.     if ($db_charset == 'latin2') {
  1832.         $text = charset_fix($text);
  1833.     }
  1834.     if ($force_myisam) {
  1835.         $text = preg_replace('#TYPE\s*=\s*InnoDB#i', 'TYPE=MyISAM', $text);
  1836.     }
  1837.     $text = preg_split("#;(\r\n|\n|\r)#", $text);
  1838.     $x = 0;
  1839.     echo '<div>Ignoring errors: <b>'.($ignore_errors?'Yes':'No').'</b></div>';
  1840.     echo '<div>Transaction: <b>'.($transaction?'Yes':'No').'</b></div>';
  1841.     echo '<div>Force MyIsam: <b>'.($force_myisam?'Yes':'No').'</b></div>';
  1842.     echo '<div>Query start: <b>#'.$query_start.'</b></div>';
  1843.     echo '<div>Queries found: <b>'.count($text).'</b></div>';
  1844.     echo '<div>Executing ...</div>';
  1845.     flush();
  1846.  
  1847.     if ($transaction) {
  1848.         echo '<div>BEGIN;</div>';
  1849.         db_begin();
  1850.     }
  1851.  
  1852.     $time = time_start();
  1853.     $query_start = (int) $query_start;
  1854.     if (!$query_start) {
  1855.         $query_start = 1;
  1856.     }
  1857.     $query_no = 0;
  1858.  
  1859.     foreach($text as $key => $value)
  1860.     {
  1861.         $x++;
  1862.         $query_no++;
  1863.         if ($query_start > $query_no) {
  1864.             continue;
  1865.         }
  1866.  
  1867.         if ('mysql' == $db_driver)
  1868.         {
  1869.             $result = @mysql_query($value.';', $db_link);
  1870.         }
  1871.         if ('pgsql' == $db_driver)
  1872.         {
  1873.             $result = @pg_query($db_link, $value.';');
  1874.         }
  1875.         if(!$result) {
  1876.             $x--;
  1877.             if (!$count_errors) {
  1878.                 echo '<table class="ls" cellspacing="1"><tr><th width="25%">Error</th><th>Query</th></tr>';
  1879.             }
  1880.             $count_errors++;
  1881.             echo '<tr><td>#'.$query_no.' '.db_error() .')'.'</td><td>'.nl2br(html_once($value)).'</td></tr>';
  1882.             flush();
  1883.             if (!$ignore_errors) {
  1884.                 echo '</table>';
  1885.                 echo '<div><span style="color: red;"><b>Import failed.</b></span></div>';
  1886.                 echo '<div>Queries executed: <b>'.($x-$query_start+1).'</b>.</div>';
  1887.                 if ($transaction) {
  1888.                     echo '<div>ROLLBACK;</div>';
  1889.                     db_rollback();
  1890.                 }
  1891.                 echo '<br><div><a href="'.$_SERVER['PHP_SELF'].'?import=1">&lt;&lt; go back</a></div>';
  1892.                 exit;
  1893.             }
  1894.         }
  1895.     }
  1896.     if ($count_errors) {
  1897.         echo '</table>';
  1898.     }
  1899.     if ($transaction) {
  1900.         echo '<div>COMMIT;</div>';
  1901.         db_end();
  1902.     }
  1903.     echo '<div><span style="color: green;"><b>Import finished.</b></span></div>';
  1904.     echo '<div>Queries executed: <b>'.($x-$query_start+1).'</b>.</div>';
  1905.     echo '<div>Time: <b>'.time_end($time).'</b> sec</div>';
  1906.     echo '<br><div><a href="'.$_SERVER['PHP_SELF'].'?import=1">&lt;&lt; go back</a></div>';
  1907. }
  1908. function layout()
  1909. {
  1910.     global $sql_area;
  1911.     ?>
  1912.         <style>
  1913.         body,table,input,select,textarea { font-family: tahoma; font-size: 11px; }
  1914.         body { margin: 1em; padding: 0; margin-top: 0.5em; }
  1915.         h1, h2 { font-family: arial; margin: 1em 0; }
  1916.         h1 { font-size: 150%; margin: 0.7em 0; }
  1917.         h2 { font-size: 125%; }
  1918.         .ls th { background: #ccc; }
  1919.         .ls th th { background-color: none; }
  1920.         .ls td { background: #f5f5f5; }
  1921.         .ls td td { background-color: none; }
  1922.         .ls th, .ls td { padding: 0.1em 0.5em; }
  1923.         .ls th th, .ls td td { padding: 0; }
  1924.         .ls2 th { text-align: left; vertical-align: top; line-height: 1.7em; background: #e0e0e0; font-weight: normal; }
  1925.         .ls2 th th { line-height: normal; background-color: none; }
  1926.         p { margin: 0.8em 0; }
  1927.         form { margin: 0; }
  1928.         form th { text-align: left; }
  1929.         a, a:visited { text-decoration: none; }
  1930.         a:hover { text-decoration: underline; }
  1931.         a, a.blue { color: blue; }
  1932.         a:visited { color: purple; }
  1933.         a.blue:visited { color: blue; }
  1934.         form .none td, form .none th { background: none; padding: 0 0.25em; }
  1935.         label { padding-left: 2px; padding-right: 4px; }
  1936.         .checkbox { padding-left: 0; margin-left: 0; margin-top: 1px; }
  1937.         .none, .ls .none { background: none; padding-top: 0.4em; }
  1938.         .button { cursor: pointer; }
  1939.         .button_click { background: #e0e0e0;  }
  1940.         .error { background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1941.         .msg { background: #eee; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1942.         .sql_area { <?php echo $sql_area;?> }
  1943.         div.query { background: #eee; padding: 0.35em; border: #ccc 1px solid; margin-bottom: 1em; margin-top: 1em; }
  1944.         </style>
  1945.         <script>
  1946.         function mark_col(td)
  1947.         {
  1948.         }
  1949.         function popup(url, width, height, more)
  1950.         {
  1951.             if (!width) width = 750;
  1952.             if (!height) height = 500;
  1953.             var x = (screen.width/2-width/2);
  1954.             var y = (screen.height/2-height/2);
  1955.             window.open(url, "", "scrollbars=yes,resizable=yes,width="+width+",height="+height+",screenX="+(x)+",screenY="+y+",left="+x+",top="+y+(more ? ","+more : ""));
  1956.         }
  1957.         function is_ie()
  1958.         {
  1959.             return navigator.appVersion.indexOf("MSIE") != -1;
  1960.         }
  1961.         function event_add(el, event, func)
  1962.         {
  1963.             if (is_ie()) {
  1964.                 if (el.attachEvent) {
  1965.                     el.attachEvent("on"+event, func);
  1966.                 }
  1967.             } else {
  1968.                 if (el.addEventListener) {
  1969.                     el.addEventListener(event, func, false);
  1970.                 } else if (el.attachEvent) {
  1971.                     el.attachEvent("on"+event, func);
  1972.                 } else {
  1973.                     var oldfunc = el["on"+event];
  1974.                     el["on"+event] = function() { oldfunc(); func(); }
  1975.                 }
  1976.             }
  1977.         }
  1978.         function event_target(event)
  1979.         {
  1980.             var el;
  1981.             if (window.event) el = window.event.srcElement;
  1982.             else if (event) el = event.target;
  1983.             if (el.nodeType == 3) el = el.parentNode;
  1984.             return el;
  1985.         }
  1986.  
  1987.         function button_init()
  1988.         {
  1989.             // dependency: event_add(), event_target()
  1990.             event_add(window, "load", function() {
  1991.                 for (var i = 0; i < document.forms.length; i++) {
  1992.                     event_add(document.forms[i], "submit", function(event) {
  1993.                         var form = event_target(event);
  1994.                         if (form.tagName != 'FORM') form = this;
  1995.                         for (var k = 0; k < form.elements.length; k++) {
  1996.                             if ("button" == form.elements[k].type || "submit" == form.elements[k].type) {
  1997.                                 button_click(form.elements[k], true);
  1998.                             }
  1999.                         }
  2000.                     });
  2001.                     var form = document.forms[i];
  2002.                     for (var j = 0; j < form.elements.length; j++) {
  2003.                         if ("button" == form.elements[j].type || "submit" == form.elements[j].type) {
  2004.                             event_add(form.elements[j], "click", button_click);
  2005.                         }
  2006.                     }
  2007.                 }
  2008.                 var inputs = document.getElementsByTagName('INPUT');
  2009.                 for (var i = 0; i < inputs.length; i++) {
  2010.                     if (('button' == inputs[i].type || 'submit' == inputs[i].type) && !inputs[i].form) {
  2011.                         event_add(inputs[i], 'click', button_click);
  2012.                     }
  2013.                 }
  2014.             });
  2015.         }
  2016.         function button_click(but, calledFromOnSubmit)
  2017.         {
  2018.             but = but.nodeName ? but : event_target(but);
  2019.             if ('button' == this.type || 'submit' == this.type) {
  2020.                 but = this;
  2021.             }
  2022.             if (but.getAttribute('button_click') == 1 || but.form && but.form.getAttribute("button_click") == 1) {
  2023.                 return;
  2024.             }
  2025.             if (button_click_sess_done(but)) {
  2026.                 return;
  2027.             }
  2028.             if ("button" == but.type) {
  2029.                 if (but.getAttribute("wait")) {
  2030.                     button_wait(but);
  2031.                     but.setAttribute("button_click", 1);
  2032.                     if (but.form) {
  2033.                         but.form.setAttribute("button_click", 1); // only when WAIT = other buttons in the form Choose From Pop etc.
  2034.                     }
  2035.                 }
  2036.             } else if ("submit" == but.type) {
  2037.                 if (but.getAttribute("wait")) {
  2038.                     button_wait(but);
  2039.                     but.setAttribute("button_click", 1);
  2040.                 }
  2041.                 if (but.form) {
  2042.                     but.form.setAttribute("button_click", 1);
  2043.                 }
  2044.                 if (calledFromOnSubmit) {
  2045.                     if (but.getAttribute("block")) {
  2046.                         button_disable(but);
  2047.                     }
  2048.                 } else {
  2049.                     if (!but.form.getAttribute('button_disable_onsubmit'))
  2050.                     {
  2051.                         event_add(but.form, "submit", function(event) {
  2052.                             var form = event_target(event);
  2053.                             if (form.tagName != 'FORM') form = this;
  2054.                             if (!button_disable_sess_done(form)) {
  2055.                                 for (var i = 0; i < form.elements.length; i++) {
  2056.                                     if (form.elements[i].getAttribute("block")) {
  2057.                                         button_disable(form.elements[i]);
  2058.                                     }
  2059.                                 }
  2060.                             }
  2061.                         });
  2062.                         but.form.setAttribute('button_disable_onsubmit', 1);
  2063.                     }
  2064.                 }
  2065.             } else {
  2066.                  //return alert("button_click() failed, unknown button type");
  2067.             }
  2068.         }
  2069.         function button_click_sess_done(but)
  2070.         {
  2071.             if (but.getAttribute('button_click_sess_done') == 1 || but.form && but.form.getAttribute('button_click_sess_done') == 1) {
  2072.                 if (but.getAttribute('button_click_sess_done') == 1) {
  2073.                     but.setAttribute('button_click_sess_done', 0);
  2074.                 }
  2075.                 if (but.form && but.form.getAttribute('button_click_sess_done') == 1) {
  2076.                     but.form.setAttribute('button_click_sess_done', 0);
  2077.                 }
  2078.                 return true;
  2079.             }
  2080.             return false;
  2081.         }
  2082.         function button_disable_sess_done(but)
  2083.         {
  2084.             if (but.getAttribute('button_disable_sess_done') == 1 || but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
  2085.                 if (but.getAttribute('button_disable_sess_done') == 1) {
  2086.                     but.setAttribute('button_disable_sess_done', 0);
  2087.                 }
  2088.                 if (but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
  2089.                     but.form.setAttribute('button_disable_sess_done', 0);
  2090.                 }
  2091.                 return true;
  2092.             }
  2093.             return false;
  2094.         }
  2095.         function button_disable(button)
  2096.         {
  2097.             button.disabled = true;
  2098.             if (button.name)
  2099.             {
  2100.  
  2101.                 var form = button.form;
  2102.                 var input = document.createElement('input');
  2103.                 input.setAttribute('type', 'hidden');
  2104.                 input.setAttribute('name', button.name);
  2105.                 input.setAttribute('value', button.value);
  2106.                 form.appendChild(input);
  2107.             }
  2108.         }
  2109.         function button_wait(but)
  2110.         {
  2111.             //but.value += " ..";
  2112.             but.className = but.className + ' button_click';
  2113.         }
  2114.         function button_clear(but)
  2115.         {
  2116.             if (but.tagName == 'FORM') {
  2117.                 var form = but;
  2118.                 for (var i = 0; i < form.elements.length; i++) {
  2119.                     button_clear(form.elements[i]);
  2120.                 }
  2121.                 form.setAttribute('button_click', 0);
  2122.                 form.setAttribute('button_click_sess_done', 1);
  2123.                 form.setAttribute('button_disable_sess_done', 1);
  2124.             } else {
  2125.                 if (but.type == 'submit' || but.type == 'button')
  2126.                 {
  2127.                     if (but.getAttribute('button_click') == 1) {
  2128.                         //but.value = but.value.replace(/[ ]?\.{2,}$/, '');
  2129.                         but.className = but.className.replace('button_click', '');
  2130.                         but.setAttribute('button_click', 0);
  2131.                         but.setAttribute('button_click_sess_done', 1);
  2132.                         but.setAttribute('button_disable_sess_done', 1);
  2133.                     }
  2134.                     if (but.form && but.form.getAttribute('button_click') == 1) {
  2135.                         but.form.setAttribute('button_click', 0);
  2136.                         but.form.setAttribute('button_click_sess_done', 1);
  2137.                         but.form.setAttribute('button_disable_sess_done', 1);
  2138.                     }
  2139.                 }
  2140.             }
  2141.         }
  2142.         button_init();
  2143.         </script>
  2144.     <?php
  2145. }
  2146. function conn_info()
  2147. {
  2148.     global $db_driver, $db_server, $db_name, $db_user, $db_charset, $page_charset, $charset1, $charset2;
  2149.     $dbs = list_dbs();
  2150.     $db_name = $db_name;
  2151.     ?>
  2152.     <p>
  2153.         Driver: <b><?php echo $db_driver;?></b>
  2154.         &nbsp;-&nbsp;
  2155.         Server: <b><?php echo $db_server;?></b>
  2156.         &nbsp;-&nbsp;
  2157.         User: <b><?php echo $db_user;?></b>
  2158.         &nbsp;-&nbsp;
  2159.         <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1">Execute SQL</a>
  2160.         ( open in <a class=blue href="javascript:void(0)" onclick="popup('<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1&popup=1')">Popup</a> )
  2161.         &nbsp;-&nbsp;
  2162.         Database: <select name="db_name" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_name='+this.value"><?php echo options($dbs, $db_name);?></select>
  2163.         &nbsp;-&nbsp;
  2164.         Db charset: <select name="db_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'">
  2165.         <option value=""></option><?php echo options($charset1, $db_charset);?></select>
  2166.         &nbsp;-&nbsp;
  2167.         Page charset: <select name="page_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?page_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'">
  2168.         <option value=""></option><?php echo options($charset2, $page_charset);?></select>
  2169.         &nbsp;-&nbsp;
  2170.         <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?disconnect=1">Disconnect</a>
  2171.     </p>
  2172.     <?php
  2173. }
  2174. function size($bytes)
  2175. {
  2176.     return number_format(ceil($bytes / 1024),0,'',',').' KB';
  2177. }
  2178. function html($s)
  2179. {
  2180.     $html = array(
  2181.         '&' => '&amp;',
  2182.         '<' => '&lt;',
  2183.         '>' => '&gt;',
  2184.         '"' => '&quot;',
  2185.         '\'' => '&#039;'
  2186.     );
  2187.     $s = preg_replace('/&#(\d+)/', '@@@@@#$1', $s);
  2188.     $s = str_replace(array_keys($html), array_values($html), $s);
  2189.     $s = preg_replace('/@@@@@#(\d+)/', '&#$1', $s);
  2190.     return trim($s);
  2191. }
  2192. function html_undo($s)
  2193. {
  2194.     $html = array(
  2195.         '&' => '&amp;',
  2196.         '<' => '&lt;',
  2197.         '>' => '&gt;',
  2198.         '"' => '&quot;',
  2199.         '\'' => '&#039;'
  2200.     );
  2201.     return str_replace(array_values($html), array_keys($html), $s);
  2202. }
  2203. function html_once($s)
  2204. {
  2205.     $s = str_replace(array('&lt;','&gt;','&amp;lt;','&amp;gt;'),array('<','>','&lt;','&gt;'),$s);
  2206.     return str_replace(array('&lt;','&gt;','<','>'),array('&amp;lt;','&amp;gt;','&lt;','&gt;'),$s);
  2207. }
  2208. function html_tags($s)
  2209. {
  2210.     // succession of str_replace array is important! double escape bug..
  2211.     return str_replace(array('&lt;','&gt;','<','>'), array('&amp;lt;','&amp;gt;','&lt;','&gt;'), $s);
  2212. }
  2213. function html_tags_undo($s)
  2214. {
  2215.     return str_replace(array('&lt;','&gt;','&amp;lt;', '&amp;gt;'), array('<','>','&lt;','&gt;'), $s);
  2216. }
  2217. function html_allow_tags($s, $allow)
  2218. {
  2219.     $s = html_once(trim($s));
  2220.     preg_match_all('#<([a-z]+)>#i', $allow, $match);
  2221.     foreach ($match[1] as $tag) {
  2222.         $s = preg_replace('#&lt;'.$tag.'\s+style\s*=\s*&quot;([^"<>]+)&quot;\s*&gt;#i', '<'.$tag.' style="$1">', $s);
  2223.         $s = str_replace('&lt;'.$tag.'&gt;', '<'.$tag.'>', $s);
  2224.         $s = str_replace('&lt;/'.$tag.'&gt;', '</'.$tag.'>', $s);
  2225.     }
  2226.     return $s;
  2227. }
  2228. function str_truncate($string, $length, $etc = ' ..', $break_words = true)
  2229. {
  2230.     if ($length == 0) {
  2231.         return '';
  2232.     }
  2233.     if (strlen($string) > $length + strlen($etc)) {
  2234.         if (!$break_words) {
  2235.             $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
  2236.         }
  2237.         return substr($string, 0, $length) . $etc;
  2238.     }
  2239.     return $string;
  2240. }
  2241. function str_bind($s, $dat = array(), $strict = false, $recur = 0)
  2242. {
  2243.     if (!is_array($dat)) {
  2244.         return trigger_error('str_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
  2245.     }
  2246.     if ($strict) {
  2247.         foreach ($dat as $k => $v) {
  2248.             if (strpos($s, "%$k%") === false) {
  2249.                 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);
  2250.             }
  2251.             $s = str_replace("%$k%", $v, $s);
  2252.         }
  2253.         if (preg_match('#%\w+%#', $s, $match)) {
  2254.             return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s.', $match[0], $sBase), E_USER_ERROR);
  2255.         }
  2256.         return $s;
  2257.     }
  2258.  
  2259.     $sBase = $s;
  2260.     preg_match_all('#%\w+%#', $s, $match);
  2261.     $keys = $match[0];
  2262.     $num = array();
  2263.  
  2264.     foreach ($keys as $key)
  2265.     {
  2266.         $key2 = str_replace('%', '', $key);
  2267.         if (is_numeric($key2)) $num[$key] = true;
  2268.         /* ignore!
  2269.         if (!array_key_exists($key2, $dat)) {
  2270.             return trigger_error(sprintf('str_bind() failed. No data found for key: %s. String: %s.', $key, $sBase), E_USER_ERROR);
  2271.         }
  2272.         */
  2273.         $val = $dat[$key2];
  2274.         /* insecure!
  2275.         if (preg_match('#%\w+%#', $val) && $recur < 5) {
  2276.             $val = str_bind($val, $dat, $strict, ++$recur);
  2277.         }
  2278.         */
  2279.         $s = str_replace($key, $val, $s);
  2280.     }
  2281.     if (count($num)) {
  2282.         if (count($dat) != count($num)) {
  2283.             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);
  2284.         }
  2285.     }
  2286.  
  2287.     if (preg_match('#%\w+%#', $s, $match)) {
  2288.         /* ignore! return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s. Data = %s.', $match[0], htmlspecialchars(print_r($sBase, true)), print_r($dat, true)), E_USER_ERROR);*/
  2289.     }
  2290.  
  2291.     return $s;
  2292. }
  2293. function dir_read($dir, $ignore_ext = array(), $allow_ext = array(), $sort = null)
  2294. {
  2295.     if (is_null($ignore_ext)) $ignore_ext = array();
  2296.     if (is_null($allow_ext)) $allow_ext = array();
  2297.     foreach ($allow_ext as $k => $ext) {
  2298.         $allow_ext[$k] = str_replace('.', '', $ext);
  2299.     }
  2300.  
  2301.     $ret = array();
  2302.     if ($handle = opendir($dir)) {
  2303.         while (($file = readdir($handle)) !== false) {
  2304.             if ($file != '.' && $file != '..') {
  2305.                 $ignore = false;
  2306.                 foreach ($ignore_ext as $ext) {
  2307.                     if (file_ext_has($file, $ext)) {
  2308.                         $ignore = true;
  2309.                     }
  2310.                 }
  2311.                 if (is_array($allow_ext) && count($allow_ext) && !in_array(file_ext($file), $allow_ext)) {
  2312.                     $ignore = true;
  2313.                 }
  2314.                 if (!$ignore) {
  2315.                     $ret[] = array(
  2316.                         'file' => $dir.'/'.$file,
  2317.                         'time' => filemtime($dir.'/'.$file)
  2318.                     );
  2319.                 }
  2320.             }
  2321.         }
  2322.         closedir($handle);
  2323.     }
  2324.     if ('date_desc' == $sort) {
  2325.         $ret = array_sort_desc($ret, 'time');
  2326.     }
  2327.     return array_col($ret, 'file');
  2328. }
  2329. function array_col($arr, $col)
  2330. {
  2331.     $ret = array();
  2332.     foreach ($arr as $k => $row) {
  2333.         $ret[] = $row[$col];
  2334.     }
  2335.     return $ret;
  2336. }
  2337. function array_sort($arr, $col_key)
  2338. {
  2339.     if (is_array($col_key)) {
  2340.         foreach ($arr as $k => $v) {
  2341.             $arr[$k]['__array_sort'] = '';
  2342.             foreach ($col_key as $col) {
  2343.                 $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
  2344.             }
  2345.         }
  2346.         $col_key = '__array_sort';
  2347.     }
  2348.     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.'"]);'));
  2349.     if ('__array_sort' == $col_key) {
  2350.         foreach ($arr as $k => $v) {
  2351.             unset($arr[$k]['__array_sort']);
  2352.         }
  2353.     }
  2354.     return $arr;
  2355. }
  2356. function array_sort_desc($arr, $col_key)
  2357. {
  2358.     if (is_array($col_key)) {
  2359.         foreach ($arr as $k => $v) {
  2360.             $arr[$k]['__array_sort'] = '';
  2361.             foreach ($col_key as $col) {
  2362.                 $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
  2363.             }
  2364.         }
  2365.         $col_key = '__array_sort';
  2366.     }
  2367.     uasort($arr, create_function('$a,$b', 'return strnatcasecmp($b["'.$col_key.'"], $a["'.$col_key.'"]);'));
  2368.     if ('__array_sort' == $col_key) {
  2369.         foreach ($arr as $k => $v) {
  2370.             unset($arr[$k]['__array_sort']);
  2371.         }
  2372.     }
  2373.     return $arr;
  2374. }
  2375. function options($options, $selected = null, $ignore_type = false)
  2376. {
  2377.     $ret = '';
  2378.     foreach ($options as $k => $v) {
  2379.         //str_replace('"', '\"', $k)
  2380.         $ret .= '<option value="'.$k.'"';
  2381.         if ((is_array($selected) && in_array($k, $selected)) || (!is_array($selected) && $k == $selected && $selected !== '' && $selected !== null)) {
  2382.             if ($ignore_type) {
  2383.                 $ret .= ' selected="selected"';
  2384.             } else {
  2385.                 if (!(is_numeric($k) xor is_numeric($selected))) {
  2386.                     $ret .= ' selected="selected"';
  2387.                 }
  2388.             }
  2389.         }
  2390.         $ret .= '>'.$v.' </option>';
  2391.     }
  2392.     return $ret;
  2393. }
  2394. function sql_files()
  2395. {
  2396.     $files = dir_read('.', null, array('.sql'));
  2397.     $files2 = array();
  2398.     foreach ($files as $file) {
  2399.         $files2[md5($file)] = $file.sprintf(' (%s)', size(filesize($file)));
  2400.     }
  2401.     return $files2;
  2402. }
  2403. function sql_files_assoc()
  2404. {
  2405.     $files = dir_read('.', null, array('.sql'));
  2406.     $files2 = array();
  2407.     foreach ($files as $file) {
  2408.         $files2[md5($file)] = $file;
  2409.     }
  2410.     return $files2;
  2411. }
  2412. function file_ext($name)
  2413. {
  2414.     $ext = null;
  2415.     if (($pos = strrpos($name, '.')) !== false) {
  2416.         $len = strlen($name) - ($pos+1);
  2417.         $ext = substr($name, -$len);
  2418.         if (!preg_match('#^[a-z0-9]+$#i', $ext)) {
  2419.             return null;
  2420.         }
  2421.     }
  2422.     return $ext;
  2423. }
  2424. function checked($bool)
  2425. {
  2426.     if ($bool) return 'checked="checked"';
  2427. }
  2428. function radio_assoc($checked, $assoc, $input_name, $link = false)
  2429. {
  2430.     $ret = '<table cellspacing="0" cellpadding="0"><tr>';
  2431.     foreach ($assoc as $id => $name)
  2432.     {
  2433.         $params = array(
  2434.             'id' => $id,
  2435.             'name' => $name,
  2436.             'checked' => checked($checked == $id),
  2437.             'input_name' => $input_name
  2438.         );
  2439.         if ($link) {
  2440.             if (is_array($link)) {
  2441.                 $params['link'] = $link[$id];
  2442.             } else {
  2443.                 $params['link'] = sprintf($link, $id, $name);
  2444.             }
  2445.             $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);
  2446.         } else {
  2447.             $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);
  2448.         }
  2449.     }
  2450.     $ret .= '</tr></table>';
  2451.     return $ret;
  2452. }
  2453. function self($cut_query = false)
  2454. {
  2455.     $uri = $_SERVER['REQUEST_URI'];
  2456.     if ($cut_query) {
  2457.         $before = str_before($uri, '?');
  2458.         if ($before) {
  2459.             return $before;
  2460.         }
  2461.     }
  2462.     return $uri;
  2463. }
  2464. function url($script, $params = array())
  2465. {
  2466.     $query = '';
  2467.  
  2468.     /* remove from script url, actual params if exist */
  2469.     foreach ($params as $k => $v) {
  2470.         $exp = sprintf('#(\?|&)%s=[^&]*#i', $k);
  2471.         if (preg_match($exp, $script)) {
  2472.             $script = preg_replace($exp, '', $script);
  2473.         }
  2474.     }
  2475.  
  2476.     /* repair url like 'script.php&id=12&asd=133' */
  2477.     $exp = '#\?\w+=[^&]*#i';
  2478.     $exp2 = '#&(\w+=[^&]*)#i';
  2479.     if (!preg_match($exp, $script) && preg_match($exp2, $script)) {
  2480.         $script = preg_replace($exp2, '?$1', $script, 1);
  2481.     }
  2482.  
  2483.     foreach ($params as $k => $v) {
  2484.         if (!strlen($v)) continue;
  2485.         if ($query) { $query .= '&'; }
  2486.         else {
  2487.             if (strpos($script, '?') === false) {
  2488.                 $query .= '?';
  2489.             } else {
  2490.                 $query .= '&';
  2491.             }
  2492.         }
  2493.         if ('%s' != $v) {
  2494.             $v = urlencode($v);
  2495.         }
  2496.         $v = preg_replace('#%25(\w+)%25#i', '%$1%', $v); // %id_news% etc. used in listing
  2497.         $query .= sprintf('%s=%s', $k, $v);
  2498.     }
  2499.     return $script.$query;
  2500. }
  2501. function url_offset($offset, $params = array())
  2502. {
  2503.     $url = $_SERVER['REQUEST_URI'];
  2504.     if (preg_match('#&offset=\d+#', $url)) {
  2505.         $url = preg_replace('#&offset=\d+#', '&offset='.$offset, $url);
  2506.     } else {
  2507.         $url .= '&offset='.$offset;
  2508.     }
  2509.     return $url;
  2510. }
  2511. function str_wrap($s, $width, $break = ' ', $omit_tags = false)
  2512. {
  2513.     //$restart = array(' ', "\t", "\r", "\n");
  2514.     $restart = array();
  2515.     $cnt = 0;
  2516.     $ret = '';
  2517.     $open_tag = false;
  2518.     $inside_link = false;
  2519.     for ($i=0; $i<strlen($s); $i++)
  2520.     {
  2521.         $char = $s[$i];
  2522.         $nextchar = isset($s[$i+1]) ? $s[$i+1] : null;
  2523.         $nextchar2 = isset($s[$i+2]) ? $s[$i+2] : null;
  2524.  
  2525.         if ($omit_tags)
  2526.         {
  2527.             if ($char == '<') {
  2528.                 $open_tag = true;
  2529.                 if ('a' == $nextchar) {
  2530.                     $inside_link = true;
  2531.                 } else if ('/' == $nextchar && 'a' == $nextchar2) {
  2532.                     $inside_link = false;
  2533.                 }
  2534.             }
  2535.             if ($char == '>') {
  2536.                 $open_tag = false;
  2537.             }
  2538.             if ($open_tag) {
  2539.                 $ret .= $char;
  2540.                 continue;
  2541.             }
  2542.         }
  2543.  
  2544.         if (in_array($char, $restart)) {
  2545.             $cnt = 0;
  2546.         } else {
  2547.             $cnt++;
  2548.         }
  2549.         $ret .= $char;
  2550.         if ($cnt > $width) {
  2551.             if (!$inside_link) {
  2552.                 // Inside link, do not break it.
  2553.                 $ret .= $break;
  2554.                 $cnt = 0;
  2555.             }
  2556.         }
  2557.     }
  2558.     return $ret;
  2559. }
  2560. function time_micro()
  2561. {
  2562.     list($usec, $sec) = explode(" ", microtime());
  2563.     return ((float)$usec + (float)$sec);
  2564. }
  2565. function time_start()
  2566. {
  2567.     return time_micro();
  2568. }
  2569. function time_end($start)
  2570. {
  2571.     $end = time_micro();
  2572.     $end = round($end - $start, 3);
  2573.     $end = pad_zeros($end, 3);
  2574.     return $end;
  2575. }
  2576. function str_has($str, $needle, $ignore_case = false)
  2577. {
  2578.     if (is_array($needle)) {
  2579.         foreach ($needle as $n) {
  2580.             if (!str_has($str, $n, $ignore_case)) {
  2581.                 return false;
  2582.             }
  2583.         }
  2584.         return true;
  2585.     }
  2586.     if ($ignore_case) {
  2587.         $str = str_lower($str);
  2588.         $needle = str_lower($needle);
  2589.     }
  2590.     return strpos($str, $needle) !== false;
  2591. }
  2592. function str_has_any($str, $arr_needle, $ignore_case = false)
  2593. {
  2594.     if (is_string($arr_needle)) {
  2595.         $arr_needle = preg_replace('#\s+#', ' ', $arr_needle);
  2596.         $arr_needle = explode(' ', $arr_needle);
  2597.     }
  2598.     foreach ($arr_needle as $needle) {
  2599.         if (str_has($str, $needle, $ignore_case)) {
  2600.             return true;
  2601.         }
  2602.     }
  2603.     return false;
  2604. }
  2605. function str_before($str, $needle)
  2606. {
  2607.     $pos = strpos($str, $needle);
  2608.     if ($pos !== false) {
  2609.         $before = substr($str, 0, $pos);
  2610.         return strlen($before) ? $before : false;
  2611.     } else {
  2612.         return false;
  2613.     }
  2614. }
  2615. function pad_zeros($number, $zeros)
  2616. {
  2617.     if (str_has($number, '.')) {
  2618.         preg_match('#\.(\d+)$#', $number, $match);
  2619.         $number .= str_repeat('0', $zeros-strlen($match[1]));
  2620.         return $number;
  2621.     } else {
  2622.         return $number.'.'.str_repeat('0', $zeros);
  2623.     }
  2624. }
  2625. function charset_fix_invalid($s)
  2626. {
  2627.     $fix = '€â“„¢ž˜™”Ã';
  2628.     $s = str_replace(str_array($fix), '', $s);
  2629.     return $s;
  2630. }
  2631. function charset_is_invalid($s)
  2632. {
  2633.     $fix = '€â“„¢ž˜™”Ã';
  2634.     $fix = str_array($fix);
  2635.     foreach ($fix as $char) {
  2636.         if (str_has($s, $char)) {
  2637.             return true;
  2638.         }
  2639.     }
  2640.     return false;
  2641. }
  2642. function charset_fix($string)
  2643. {
  2644.     // UTF-8 && WIN-1250 => ISO-8859-2
  2645.     // todo: is checking required? redundant computing?
  2646.     if (charset_win_is($string)) {
  2647.         $string = charset_win_fix($string);
  2648.     }
  2649.     if (charset_utf_is($string)) {
  2650.         $string = charset_utf_fix($string);
  2651.     }
  2652.     return $string;
  2653. }
  2654. function charset_win_is($string)
  2655. {
  2656.     $win = '¹¥æÆêʳ£ñÑóÓœŒŸ¿¯';
  2657.     $iso = '±¡æÆêʳ£ñÑóÓ¶¦¼¬¿¯';
  2658.     for ($i=0; $i<strlen($win); $i++) {
  2659.         if ($win{$i} != $iso{$i}) {
  2660.             if (strstr($string, $win{$i}) !== false) {
  2661.                 return true;
  2662.             }
  2663.         }
  2664.     }
  2665.     return false;
  2666. }
  2667. function charset_win_fix($string)
  2668. {
  2669.     $win = '¹¥æÆêʳ£ñÑóÓœŒŸ¿¯';
  2670.     $iso = '±¡æÆêʳ£ñÑóÓ¶¦¼¬¿¯';
  2671.     $srh = array();
  2672.     $rpl = array();
  2673.     for ($i = 0; $i < strlen($win); $i++) {
  2674.         if ($win{$i} != $iso{$i}) {
  2675.             $srh[] = $win{$i};
  2676.             $rpl[] = $iso{$i};
  2677.         }
  2678.     }
  2679.     $string = str_replace($srh, $rpl, $string);
  2680.     return $string;
  2681. }
  2682. function charset_utf_is($string)
  2683. {
  2684.     $utf_iso = array(
  2685.        "\xc4\x85" => "\xb1",
  2686.        "\xc4\x84" => "\xa1",
  2687.        "\xc4\x87" => "\xe6",
  2688.        "\xc4\x86" => "\xc6",
  2689.        "\xc4\x99" => "\xea",
  2690.        "\xc4\x98" => "\xca",
  2691.        "\xc5\x82" => "\xb3",
  2692.        "\xc5\x81" => "\xa3",
  2693.        "\xc3\xb3" => "\xf3",
  2694.        "\xc3\x93" => "\xd3",
  2695.        "\xc5\x9b" => "\xb6",
  2696.        "\xc5\x9a" => "\xa6",
  2697.        "\xc5\xba" => "\xbc",
  2698.        "\xc5\xb9" => "\xac",
  2699.        "\xc5\xbc" => "\xbf",
  2700.        "\xc5\xbb" => "\xaf",
  2701.        "\xc5\x84" => "\xf1",
  2702.        "\xc5\x83" => "\xd1",
  2703.         // xmlhttprequest utf-8 encoding
  2704.        "%u0104" => "\xA1",
  2705.        "%u0106" => "\xC6",
  2706.        "%u0118" => "\xCA",
  2707.        "%u0141" => "\xA3",
  2708.        "%u0143" => "\xD1",
  2709.        "%u00D3" => "\xD3",
  2710.        "%u015A" => "\xA6",
  2711.        "%u0179" => "\xAC",
  2712.        "%u017B" => "\xAF",
  2713.        "%u0105" => "\xB1",
  2714.        "%u0107" => "\xE6",
  2715.        "%u0119" => "\xEA",
  2716.        "%u0142" => "\xB3",
  2717.        "%u0144" => "\xF1",
  2718.        "%u00D4" => "\xF3",
  2719.        "%u015B" => "\xB6",
  2720.        "%u017A" => "\xBC",
  2721.        "%u017C" => "\xBF"
  2722.     );
  2723.     foreach ($utf_iso as $k => $v) {
  2724.         if (strpos($string, $k) !== false) {
  2725.             return true;
  2726.         }
  2727.     }
  2728.     return false;
  2729. }
  2730. function charset_utf_fix($string)
  2731. {
  2732.     $utf_iso = array(
  2733.        "\xc4\x85" => "\xb1",
  2734.        "\xc4\x84" => "\xa1",
  2735.        "\xc4\x87" => "\xe6",
  2736.        "\xc4\x86" => "\xc6",
  2737.        "\xc4\x99" => "\xea",
  2738.        "\xc4\x98" => "\xca",
  2739.        "\xc5\x82" => "\xb3",
  2740.        "\xc5\x81" => "\xa3",
  2741.        "\xc3\xb3" => "\xf3",
  2742.        "\xc3\x93" => "\xd3",
  2743.        "\xc5\x9b" => "\xb6",
  2744.        "\xc5\x9a" => "\xa6",
  2745.        "\xc5\xba" => "\xbc",
  2746.        "\xc5\xb9" => "\xac",
  2747.        "\xc5\xbc" => "\xbf",
  2748.        "\xc5\xbb" => "\xaf",
  2749.        "\xc5\x84" => "\xf1",
  2750.        "\xc5\x83" => "\xd1",
  2751.         // xmlhttprequest uses different encoding
  2752.        "%u0104" => "\xA1",
  2753.        "%u0106" => "\xC6",
  2754.        "%u0118" => "\xCA",
  2755.        "%u0141" => "\xA3",
  2756.        "%u0143" => "\xD1",
  2757.        "%u00D3" => "\xD3",
  2758.        "%u015A" => "\xA6",
  2759.        "%u0179" => "\xAC",
  2760.        "%u017B" => "\xAF",
  2761.        "%u0105" => "\xB1",
  2762.        "%u0107" => "\xE6",
  2763.        "%u0119" => "\xEA",
  2764.        "%u0142" => "\xB3",
  2765.        "%u0144" => "\xF1",
  2766.        "%u00D4" => "\xF3",
  2767.        "%u015B" => "\xB6",
  2768.        "%u017A" => "\xBC",
  2769.        "%u017C" => "\xBF"
  2770.     );
  2771.     return str_replace(array_keys($utf_iso), array_values($utf_iso), $string);
  2772. }
  2773. function str_starts_with($str, $start, $ignore_case = false)
  2774. {
  2775.     if ($ignore_case) {
  2776.         $str = str_upper($str);
  2777.         $start = str_upper($start);
  2778.     }
  2779.     if (!strlen($str) && !strlen($start)) {
  2780.         return true;
  2781.     }
  2782.     if (!strlen($start)) {
  2783.         trigger_error('str_starts_with() failed, start arg cannot be empty', E_USER_ERROR);
  2784.     }
  2785.     if (strlen($start) > strlen($str)) {
  2786.         return false;
  2787.     }
  2788.     for ($i = 0; $i < strlen($start); $i++) {
  2789.         if ($start{$i} != $str{$i}) {
  2790.             return false;
  2791.         }
  2792.     }
  2793.     return true;
  2794. }
  2795. function str_ends_with($str, $end, $ignore_case = false)
  2796. {
  2797.     if ($ignore_case) {
  2798.         $str = str_upper($str);
  2799.         $end = str_upper($end);
  2800.     }
  2801.     if (!strlen($str) && !strlen($end)) {
  2802.         return true;
  2803.     }
  2804.     if (!strlen($end)) {
  2805.         trigger_error('str_ends_with() failed, end arg cannot be empty', E_USER_ERROR);
  2806.     }
  2807.     if (strlen($end) > strlen($str)) {
  2808.         return false;
  2809.     }
  2810.     return str_starts_with(strrev($str), strrev($end));
  2811.     return true;
  2812. }
  2813. function str_cut_start($str, $start)
  2814. {
  2815.     if (str_starts_with($str, $start)) {
  2816.         $str = substr($str, strlen($start));
  2817.     }
  2818.     return $str;
  2819. }
  2820. function str_cut_end($str, $end)
  2821. {
  2822.     if (str_ends_with($str, $end)) {
  2823.         $str = substr($str, 0, -strlen($end));
  2824.     }
  2825.     return $str;
  2826. }
  2827. function file_get($file)
  2828. {
  2829.     return file_get_contents($file);
  2830. }
  2831. function file_put($file, $s)
  2832. {
  2833.     $fp = fopen($file, 'wb') or trigger_error('fopen() failed: '.$file, E_USER_ERROR);
  2834.     if ($fp) {
  2835.         fwrite($fp, $s);
  2836.         fclose($fp);
  2837.     }
  2838. }
  2839. function file_date($file)
  2840. {
  2841.     return date('Y-m-d H:i:s', filemtime($file));
  2842. }
  2843. function dir_exists($dir)
  2844. {
  2845.     return file_exists($dir) && !is_file($dir);
  2846. }
  2847. function dir_delete_old_files($dir, $ext = array(), $sec)
  2848. {
  2849.     // NOT USED right now.
  2850.     // older than x seconds
  2851.     $files = dir_read($dir, null, $ext);
  2852.     $time = time() - $sec;
  2853.     foreach ($files as $file) {
  2854.         if (file_time($file) < $time) {
  2855.             unlink($file);
  2856.         }
  2857.     }
  2858. }
  2859. global $_error, $_error_style;
  2860. $_error = array();
  2861. $_error_style = '';
  2862.  
  2863. function error($msg = null)
  2864. {
  2865.     if (isset($msg) && func_num_args() > 1) {
  2866.         $args = func_get_args();
  2867.         $msg = call_user_func_array('sprintf', $args);
  2868.     }
  2869.     global $_error, $_error_style;
  2870.     if (isset($msg)) {
  2871.         $_error[] = $msg;
  2872.     }
  2873.     if (!count($_error)) {
  2874.         return null;
  2875.     }
  2876.     if (count($_error) == 1) {
  2877.         return sprintf('<div class="error" style="%s">%s</div>', $_error_style, $_error[0]);
  2878.     }
  2879.     $ret = '<div class="error" style="'.$_error_style.'">Following errors appeared:<ul>';
  2880.     foreach ($_error as $msg) {
  2881.         $ret .= sprintf('<li>%s</li>', $msg);
  2882.     }
  2883.     $ret .= '</ul></div>';
  2884.     return $ret;
  2885. }
  2886. function timestamp($time, $span = true)
  2887. {
  2888.     $time_base = $time;
  2889.     $time = substr($time, 0, 16);
  2890.     $time2 = substr($time, 0, 10);
  2891.     $today = date('Y-m-d');
  2892.     $yesterday = date('Y-m-d', time()-3600*24);
  2893.     if ($time2 == $today) {
  2894.         if (substr($time_base, -8) == '00:00:00') {
  2895.             $time = 'Today';
  2896.         } else {
  2897.             $time = 'Today'.substr($time, -6);
  2898.         }
  2899.     } else if ($time2 == $yesterday) {
  2900.         $time = 'Yesterday'.substr($time, -6);
  2901.     }
  2902.     return '<span style="white-space: nowrap;">'.$time.'</span>';
  2903. }
  2904. function str_lower($str)
  2905. {
  2906.     /* strtolower iso-8859-2 compatible */
  2907.     $lower = str_array(iso_chars_lower());
  2908.     $upper = str_array(iso_chars_upper());
  2909.     $str = str_replace($upper, $lower, $str);
  2910.     $str = strtolower($str);
  2911.     return $str;
  2912. }
  2913. function str_upper($str)
  2914. {
  2915.     /* strtoupper iso-8859-2 compatible */
  2916.     $lower = str_array(iso_chars_lower());
  2917.     $upper = str_array(iso_chars_upper());
  2918.     $str = str_replace($lower, $upper, $str);
  2919.     $str = strtoupper($str);
  2920.     return $str;
  2921. }
  2922. function str_array($str)
  2923. {
  2924.     $arr = array();
  2925.     for ($i = 0; $i < strlen($str); $i++) {
  2926.         $arr[$i] = $str{$i};
  2927.     }
  2928.     return $arr;
  2929. }
  2930. function iso_chars()
  2931. {
  2932.     return iso_chars_lower().iso_chars_upper();
  2933. }
  2934. function iso_chars_lower()
  2935. {
  2936.     return '±æê³ñ󶼿';
  2937. }
  2938. function iso_chars_upper()
  2939. {
  2940.     return '¡ÆÊ£ÑÓ¦¬¯';
  2941. }
  2942. function array_first_key($arr)
  2943. {
  2944.     $arr2 = $arr;
  2945.     reset($arr);
  2946.     list($key, $val) = each($arr);
  2947.     return $key;
  2948. }
  2949. function array_first($arr)
  2950. {
  2951.     return array_first_value($arr);
  2952. }
  2953. function array_first_value($arr)
  2954. {
  2955.     $arr2 = $arr;
  2956.     return array_shift($arr2);
  2957. }
  2958. function array_col_values($arr, $col)
  2959. {
  2960.     $ret = array();
  2961.     foreach ($arr as $k => $row) {
  2962.         $ret[] = $row[$col];
  2963.     }
  2964.     return $ret;
  2965. }
  2966. function array_col_values_unique($arr, $col)
  2967. {
  2968.     return array_unique(array_col_values($arr, $col));
  2969. }
  2970. function array_col_match($rows, $col, $pattern)
  2971. {
  2972.     if (!count($rows)) {
  2973.         trigger_error('array_col_match(): array is empty', E_USER_ERROR);
  2974.     }
  2975.     $ret = true;
  2976.     foreach ($rows as $row) {
  2977.         if (!preg_match($pattern, $row[$col])) {
  2978.             return false;
  2979.         }
  2980.     }
  2981.     return true;
  2982. }
  2983. function array_col_match_unique($rows, $col, $pattern)
  2984. {
  2985.     if (!array_col_match($rows, $col, $pattern)) {
  2986.         return false;
  2987.     }
  2988.     return count($rows) == count(array_col_values_unique($rows, $col));
  2989. }
  2990. function redirect($url)
  2991. {
  2992.     $url = url($url);
  2993.     header("Location: $url");
  2994.     exit;
  2995. }
  2996. function redirect_notify($url, $msg)
  2997. {
  2998.     if (strpos($msg, '<') === false) {
  2999.         $msg = sprintf('<b>%s</b>', $msg);
  3000.     }
  3001.     cookie_set('flash_notify', $msg);
  3002.     redirect($url);
  3003. }
  3004. function redirect_ok($url, $msg)
  3005. {
  3006.     if (strpos($msg, '<') === false) {
  3007.         $msg = sprintf('<b>%s</b>', $msg);
  3008.     }
  3009.     cookie_set('flash_ok', $msg);
  3010.     redirect($url);
  3011. }
  3012. function redirect_error($url, $msg)
  3013. {
  3014.     if (strpos($msg, '<') === false) {
  3015.         $msg = sprintf('<b>%s</b>', $msg);
  3016.     }
  3017.     cookie_set('flash_error', $msg);
  3018.     redirect($url);
  3019. }
  3020. function flash()
  3021. {
  3022.     static $is_style = false;
  3023.  
  3024.     $flash_error = cookie_get('flash_error');
  3025.     $flash_ok = cookie_get('flash_ok');
  3026.     $flash_notify = cookie_get('flash_notify');
  3027.  
  3028.     $flash_error = filter_allow_tags($flash_error, '<b><i><u><br><span>');
  3029.     $flash_ok = filter_allow_tags($flash_ok, '<b><i><u><br><span>');
  3030.     $flash_notify = filter_allow_tags($flash_notify, '<b><i><u><br><span>');
  3031.  
  3032.     if (!($flash_error || $flash_ok || $flash_notify)) {
  3033.         return false;
  3034.     }
  3035.  
  3036.     ob_start();
  3037.     ?>
  3038.  
  3039.     <?php if (!$is_style): ?>
  3040.         <style type="text/css">
  3041.         #flash { background: #ffffd7; padding: 0.3em; padding-bottom: 0.15em; border: #ddd 1px solid; margin-bottom: 1em; }
  3042.         #flash div { padding: 0em 0em; }
  3043.         #flash table { font-weight: normal; }
  3044.         #flash td { text-align: left; }
  3045.         </style>
  3046.     <?php endif; ?>
  3047.  
  3048.     <div id="flash" ondblclick="document.getElementById('flash').style.display='none';">
  3049.         <table width="100%" ondblclick="document.getElementById('flash').style.display='none';"><tr>
  3050.         <td style="line-height: 14px;"><?php echo  $flash_error ? $flash_error : ($flash_ok ? $flash_ok : $flash_notify); ?></td></tr></table>
  3051.     </div>
  3052.  
  3053.     <?php
  3054.     $cont = ob_get_contents();
  3055.     ob_end_clean();
  3056.  
  3057.     if ($flash_error) cookie_del('flash_error');
  3058.     else if ($flash_ok) cookie_del('flash_ok');
  3059.     else if ($flash_notify) cookie_del('flash_notify');
  3060.  
  3061.     $is_style = true;
  3062.  
  3063.     return $cont;
  3064. }
  3065. function filter($post, $filters)
  3066. {
  3067.     if (is_string($filters))
  3068.     {
  3069.         $filter = $filters;
  3070.         $func = 'filter_'.$filter;
  3071.         foreach ($post as $key => $val) {
  3072.             $post[$key] = call_user_func($func, $post[$key]);
  3073.         }
  3074.         return $post;
  3075.     }
  3076.     foreach ($filters as $key => $filter)
  3077.     {
  3078.         if (!array_key_exists($key, $post)) {
  3079.             return trigger_error(sprintf('filter() failed. Key missing = %s.', $key), E_USER_ERROR);
  3080.         }
  3081.         $func = 'filter_'.$filter;
  3082.         if (!function_exists($func)) {
  3083.             return trigger_error(sprintf('filter() failed. Filter missing = %s.', $func), E_USER_ERROR);
  3084.         }
  3085.         $post[$key] = call_user_func($func, $post[$key]);
  3086.     }
  3087.     return $post;
  3088. }
  3089. function filter_html($s)
  3090. {
  3091.     if (req_gpc_has($s)) {
  3092.         $s = html_tags_undo($s);
  3093.     }
  3094.     return html(trim($s));
  3095. }
  3096. function filter_allow_tags($s, $allow)
  3097. {
  3098.     if (req_gpc_has($s)) {
  3099.         $s = html_tags_undo($s);
  3100.     }
  3101.     return html_allow_tags($s, $allow);
  3102. }
  3103. function filter_allow_html($s)
  3104. {
  3105.     global $SafeHtml;
  3106.     if (!isset($SafeHtml)) {
  3107.         include_once 'inc/SafeHtml.php';
  3108.     }
  3109.     if (req_gpc_has($s)) {
  3110.         $s = html_tags_undo($s);
  3111.     }
  3112.     if (in_array(trim(strtolower($s)), array('<br>', '<p>&nbsp;</p>'))) {
  3113.         return '';
  3114.     }
  3115.     $SafeHtml->clear();
  3116.     $s = $SafeHtml->parse($s);
  3117.     return trim($s);
  3118. }
  3119. function filter_allow_html_script($s)
  3120. {
  3121.     if (in_array(trim(strtolower($s)), array('<br>', '<p>&nbsp;</p>'))) {
  3122.         return '';
  3123.     }
  3124.     if (req_gpc_has($s)) {
  3125.         $s = html_tags_undo($s);
  3126.     }
  3127.     return trim($s);
  3128. }
  3129. function filter_editor($s)
  3130. {
  3131.     return filter_allow_html($s);
  3132. }
  3133. function date_now()
  3134. {
  3135.     return date('Y-m-d H:i:s');
  3136. }
  3137. function guess_pk($rows)
  3138. {
  3139.     if (!count($rows)) {
  3140.         return false;
  3141.     }
  3142.     $patterns = array('#^\d+$#', '#^[^\s]+$#');
  3143.     $row = array_first($rows);
  3144.     foreach ($patterns as $pattern)
  3145.     {
  3146.         foreach ($row as $col => $v) {
  3147.             if ($v && preg_match($pattern, $v)) {
  3148.                 if (array_col_match_unique($rows, $col, $pattern)) {
  3149.                     return $col;
  3150.                 }
  3151.             }
  3152.         }
  3153.     }
  3154.     return false;
  3155. }
  3156. function layout_start($title='')
  3157. {
  3158.     global $page_charset;
  3159.     $flash = flash();
  3160.     ?>
  3161.  
  3162.     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3163.     <html>
  3164.     <head>
  3165.         <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
  3166.         <title><?php echo $title;?></title>
  3167.         <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
  3168.         <script>
  3169.         function $(id)
  3170.         {
  3171.             if (typeof id == 'string') return document.getElementById(id);
  3172.             return id;
  3173.         }
  3174.         </script>
  3175.     </head>
  3176.     <body>
  3177.  
  3178.     <?php layout(); ?>
  3179.  
  3180.     <?php if ($flash) { echo $flash; } ?>
  3181.  
  3182.     <?php
  3183. }
  3184. function layout_end()
  3185. {
  3186.     ?>
  3187.     <?php powered_by(); ?>
  3188.     </body>
  3189.     </html>
  3190.     <?php
  3191. }
  3192. function powered_by()
  3193. {
  3194.     ?>
  3195.         <script>
  3196.         function link_noreferer(link)
  3197.         {
  3198.             // Tested: Chrome, Firefox, Inetrnet Explorer, Opera.
  3199.             var w = window.open("about:blank", "_blank");
  3200.             w.document.open();
  3201.             w.document.write("<"+"!doctype html>");
  3202.             w.document.write("<"+"html><"+"head>");
  3203.             w.document.write("<"+"title>Secure redirection</title>");
  3204.             w.document.write("<"+"style>body { font: 11px Tahoma; }<"+"/style>");
  3205.             w.document.write("<"+"meta http-equiv=refresh content='10;url="+link+"'>");
  3206.             // Meta.setAttribute() doesn't work on firefox.
  3207.             // Firefox: needs document.write('<meta>')
  3208.             // IE: the firefox workaround doesn't work on ie, but we can use a normal redirection
  3209.             //      as IE is already not sending the referer because it does not do it when using
  3210.             //      open.window, besides the blank url in address bar works fine (about:blank).
  3211.             // Opera: firefox fix works.
  3212.             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>");
  3213.             w.document.write("<"+"/head><"+"body>");
  3214.             w.document.write("<"+"h1>Secure redirection<"+"/h1>");
  3215.             w.document.write("<"+"p>This is a secure redirection that hides the HTTP REFERER header - using javascript and meta refresh combination.");
  3216.             w.document.write("<br>The site you are being redirected will not know the location of the dbkiss script on your site.<"+"/p>");
  3217.             w.document.write("<"+"p>In 10 seconds you will be redirected to the following address: <"+"a href='javascript:void(0)' onclick='redirect()'>"+link+"<"+"/a><br>");
  3218.             w.document.write("Clicking the link is also secure, so if you do not wish to wait, then click it.<"+"/p>");
  3219.             w.document.write("<"+"/body><"+"/html>");
  3220.             w.document.close();
  3221.         }
  3222.         </script>
  3223.         <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://code.google.com/p/dbkiss/')">dbkiss</a></div>
  3224.     <?php
  3225. }
  3226.  
  3227. ?>
  3228. <?php if (get('import')): ?>
  3229.  
  3230.     <?php
  3231.  
  3232.     // ----------------------------------------------------------------
  3233.     // IMPORT
  3234.     // ----------------------------------------------------------------
  3235.  
  3236.     ?>
  3237.  
  3238.     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3239.     <html>
  3240.     <head>
  3241.         <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
  3242.         <title><?php echo $db_name_h1?$db_name_h1:$db_name;?> &gt; Import</title>
  3243.         <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
  3244.     </head>
  3245.     <body>
  3246.  
  3247.     <?php layout(); ?>
  3248.     <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>
  3249.     <?php conn_info(); ?>
  3250.  
  3251.     <?php $files = sql_files(); ?>
  3252.  
  3253.     <?php if (count($files)): ?>
  3254.         <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
  3255.         <table class="none" cellspacing="0" cellpadding="0">
  3256.         <tr>
  3257.             <td>SQL file:</th>
  3258.             <td><select name="sqlfile"><option value="" selected="selected"></option><?php echo options($files);?></select></td>
  3259.             <td><input type="checkbox" name="ignore_errors" id="ignore_errors" value="1"></td>
  3260.             <td><label for="ignore_errors">ignore errors</label></td>
  3261.             <td><input type="checkbox" name="transaction" id="transaction" value="1"></td>
  3262.             <td><label for="transaction">transaction</label></td>
  3263.             <td><input type="checkbox" name="force_myisam" id="force_myisam" value="1"></td>
  3264.             <td><label for="force_myisam">force myisam</label></td>
  3265.             <td><input type="text" size="5" name="query_start" value=""></td>
  3266.             <td>query start</td>
  3267.             <td><input type="submit" value="Import"></td>
  3268.         </tr>
  3269.         </table>
  3270.         </form>
  3271.         <br>
  3272.     <?php else: ?>
  3273.         No sql files found in current directory.
  3274.     <?php endif; ?>
  3275.  
  3276.     <?php powered_by(); ?>
  3277.  
  3278.     </body></html>
  3279.  
  3280. <?php exit; endif; ?>
  3281. <?php if ('editrow' == get('action')): ?>
  3282. <?php
  3283.     function dbkiss_filter_id($id)
  3284.     {
  3285.         # mysql allows table names of: `62-511`
  3286.         # also, columns might be numeric ex. `62`
  3287.         if (preg_match('#^[_a-z0-9][a-z0-9_\-]*$#i', $id)) {
  3288.             return $id;
  3289.         }
  3290.         return false;
  3291.     }
  3292.  
  3293.     $get = get(array(
  3294.         'table' => 'string',
  3295.         'pk' => 'string',
  3296.         'id' => 'string'
  3297.     ));
  3298.  
  3299.     $get['table'] = html_once($get['table']);
  3300.     $get['pk'] = html_once($get['pk']);
  3301.  
  3302.     $title_edit = sprintf('Edit row (%s=%s)', $get['pk'], $get['id']);
  3303.     $title = ' &gt; '.$get['table'].' &gt; '.$title_edit;
  3304.  
  3305.     if (!dbkiss_filter_id($get['table'])) {
  3306.         error('Invalid table name');
  3307.     }
  3308.     if (!dbkiss_filter_id($get['pk'])) {
  3309.         error('Invalid pk');
  3310.     }
  3311.  
  3312.     $row = false;
  3313.  
  3314.     if (!error())
  3315.     {
  3316.         $table_enq = quote_table($get['table']);
  3317.         $test = db_row("SELECT * FROM $table_enq");
  3318.         if ($test) {
  3319.             if (!array_key_exists($get['pk'], $test)) {
  3320.                 error('Invalid pk');
  3321.             }
  3322.         }
  3323.         if (!error())
  3324.         {
  3325.             $table_enq = quote_table($get['table']);
  3326.             $query = db_bind("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
  3327.             $query = db_limit($query, 0, 2);
  3328.             $rows = db_list($query);
  3329.             if (count($rows) > 1) {
  3330.                 error('Invalid pk: found more than one row with given id');
  3331.             } else if (count($rows) == 0) {
  3332.                 error('Row not found');
  3333.             } else {
  3334.                 $row = $rows[0];
  3335.                 $row_id = $row[$get['pk']];
  3336.             }
  3337.         }
  3338.     }
  3339.  
  3340.     if ($row) {
  3341.         $types = table_types2($get['table']);
  3342.     }
  3343.  
  3344.     $edit_actions_assoc = array(
  3345.         'update' => 'Update',
  3346.         'update_pk' => 'Overwrite pk',
  3347.         'insert' => 'Copy row (insert)',
  3348.         'delete' => 'Delete'
  3349.     );
  3350.  
  3351.     $edit_action = post('dbkiss_action');
  3352.  
  3353.     if ($_ENV['IS_GET'])
  3354.     {
  3355.         $edit_action = array_first_key($edit_actions_assoc);
  3356.         $post = $row;
  3357.     }
  3358.  
  3359.     if ($_ENV['IS_POST'])
  3360.     {
  3361.         if (!array_key_exists($edit_action, $edit_actions_assoc)) {
  3362.             $edit_action = '';
  3363.             error('Invalid action');
  3364.         }
  3365.  
  3366.         $post = array();
  3367.         foreach ($row as $k => $v) {
  3368.             if (array_key_exists($k, $_POST)) {
  3369.                 $val = (string) $_POST[$k];
  3370.                 if ('null' == $val) {
  3371.                     $val = null;
  3372.                 }
  3373.                 if ('int' == $types[$k]) {
  3374.                     if (!strlen($val)) {
  3375.                         $val = null;
  3376.                     }
  3377.                     if (!(preg_match('#^-?\d+$#', $val) || is_null($val))) {
  3378.                         error('%s: invalid value', $k);
  3379.                     }
  3380.                 }
  3381.                 if ('float' == $types[$k]) {
  3382.                     if (!strlen($val)) {
  3383.                         $val = null;
  3384.                     }
  3385.                     $val = str_replace(',', '.', $val);
  3386.                     if (!(is_numeric($val) || is_null($val))) {
  3387.                         error('%s: invalid value', $k);
  3388.                     }
  3389.                 }
  3390.                 if ('time' == $types[$k]) {
  3391.                     if (!strlen($val)) {
  3392.                         $val = null;
  3393.                     }
  3394.                     if ('now' == $val) {
  3395.                         $val = date_now();
  3396.                     }
  3397.                 }
  3398.                 $post[$k] = $val;
  3399.             } else {
  3400.                 error('Missing key: %s in POST', $k);
  3401.             }
  3402.         }
  3403.  
  3404.         if ('update' == $edit_action)
  3405.         {
  3406.             if ($post[$get['pk']] != $row[$get['pk']]) {
  3407.                 if (count($row) != 1) { // Case: more than 1 column
  3408.                     error('%s: cannot change pk on UPDATE', $get['pk']);
  3409.                 }
  3410.             }
  3411.         }
  3412.         if ('update_pk' == $edit_action)
  3413.         {
  3414.             if ($post[$get['pk']] == $row[$get['pk']]) {
  3415.                 error('%s: selected action Overwrite pk, but pk value has not changed', $get['pk']);
  3416.             }
  3417.         }
  3418.         if ('insert' == $edit_action)
  3419.         {
  3420.             if (strlen($post[$get['pk']])) {
  3421.                 $table_enq = quote_table($get['table']);
  3422.                 $test = db_row("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", array($post[$get['pk']]));
  3423.                 if ($test) {
  3424.                     error('%s: there is already a record with that id', $get['pk']);
  3425.                 }
  3426.             }
  3427.         }
  3428.  
  3429.         if (!error())
  3430.         {
  3431.             $post2 = $post;
  3432.             if ('update' == $edit_action)
  3433.             {
  3434.                 if (count($row) != 1) { // Case: more than 1 column
  3435.                     unset($post2[$get['pk']]);
  3436.                 }
  3437.                 db_update($get['table'], $post2, array($get['pk'] => $row_id));
  3438.                 if (db_error()) {
  3439.                     error('<font color="red"><b>DB error</b></font>: '.db_error());
  3440.                 } else {
  3441.                     if (count($row) == 1) { // Case: only 1 column
  3442.                         redirect_ok(url(self(), array('id'=>$post[$get['pk']])), 'Row updated');
  3443.                     } else {
  3444.                         redirect_ok(self(), 'Row updated');
  3445.                     }
  3446.                 }
  3447.             }
  3448.             if ('update_pk' == $edit_action)
  3449.             {
  3450.                 @db_update($get['table'], $post2, array($get['pk'] => $row_id));
  3451.                 if (db_error()) {
  3452.                     error('<font color="red"><b>DB error</b></font>: '.db_error());
  3453.                 } else {
  3454.                     $url = url(self(), array('id' => $post[$get['pk']]));
  3455.                     redirect_ok($url, 'Row updated (pk overwritten)');
  3456.                 }
  3457.             }
  3458.             if ('insert' == $edit_action)
  3459.             {
  3460.                 $new_id = false;
  3461.                 if (!strlen($post2[$get['pk']])) {
  3462.                     unset($post2[$get['pk']]);
  3463.                 } else {
  3464.                     $new_id = $post2[$get['pk']];
  3465.                 }
  3466.                 @db_insert($get['table'], $post2);
  3467.                 if (db_error()) {
  3468.                     error('<font color="red"><b>DB error</b></font>: '.db_error());
  3469.                 } else {
  3470.                     if (!$new_id) {
  3471.                         $new_id = db_insert_id($get['table'], $get['pk']);
  3472.                     }
  3473.                     $url = url(self(), array('id'=>$new_id));
  3474.                     $msg = sprintf('Row inserted (%s=%s)', $get['pk'], $new_id);
  3475.                     redirect_ok($url, $msg);
  3476.                 }
  3477.             }
  3478.             if ('delete' == $edit_action)
  3479.             {
  3480.                 $table_enq = quote_table($get['table']);
  3481.                 @db_exe("DELETE FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
  3482.                 if (db_error()) {
  3483.                     error('<font color="red"><b>DB error</b></font>: '.db_error());
  3484.                 } else {
  3485.                     redirect_ok(self(), 'Row deleted');
  3486.                 }
  3487.             }
  3488.         }
  3489.     }
  3490.  
  3491.     ?>
  3492. <?php layout_start($title_edit); ?>
  3493.     <h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span><?php echo $title;?></h1>
  3494.  
  3495.     <?php echo error();?>
  3496.  
  3497.     <?php if ($row): ?>
  3498.  
  3499.         <form action="<?php echo self();?>" method="post">
  3500.  
  3501.         <?php echo radio_assoc($edit_action, $edit_actions_assoc, 'dbkiss_action');?></td>
  3502.         <br>
  3503.  
  3504.         <table cellspacing="1" class="ls ls2">
  3505.         <?php foreach ($post as $k => $v): if (is_null($v)) { $v = 'null'; } $v = htmlspecialchars($v); ?>
  3506.             <tr>
  3507.                 <th><?php echo $k;?>:</th>
  3508.                 <td>
  3509.                     <?php if ('int' == $types[$k]): ?>
  3510.                         <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="11">
  3511.                     <?php elseif ('char' == $types[$k]): ?>
  3512.                         <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="50">
  3513.                     <?php elseif (in_array($types[$k], array('text', 'mediumtext', 'longtext')) || str_has($types[$k], 'blob')): ?>
  3514.                         <textarea name="<?php echo $k;?>" cols="80" rows="<?php echo $k=='notes'?10:10;?>"><?php echo html_once($v);?></textarea>
  3515.                     <?php else: ?>
  3516.                         <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="30">
  3517.                     <?php endif; ?>
  3518.                 </td>
  3519.                 <td valign="top"><?php echo $types[$k];?></td>
  3520.             </tr>
  3521.         <?php endforeach; ?>
  3522.         <tr>
  3523.             <td colspan="3" class="none">
  3524.                 <input type="submit" wait="1" block="1" class="button" value="Edit">
  3525.             </td>
  3526.         </tr>
  3527.         </table>
  3528.  
  3529.         </form>
  3530.  
  3531.     <?php endif; ?>
  3532.  
  3533.     <?php layout_end(); ?>
  3534.  
  3535. <?php exit; endif; ?>
  3536. <?php if (isset($_GET['execute_sql']) && $_GET['execute_sql']): ?>
  3537. <?php
  3538.  
  3539. function listing($base_query, $md5_get = false)
  3540. {
  3541.     global $db_driver, $db_link;
  3542.  
  3543.     $md5_i = false;
  3544.     if ($md5_get) {
  3545.         preg_match('#_(\d+)$#', $md5_get, $match);
  3546.         $md5_i = $match[1];
  3547.     }
  3548.  
  3549.     $base_query = trim($base_query);
  3550.     $base_query = str_cut_end($base_query, ';');
  3551.  
  3552.     $query = $base_query;
  3553.     $ret = array('msg'=>'', 'error'=>'', 'data_html'=>false);
  3554.     $limit = 25;
  3555.     $offset = get('offset','int');
  3556.     $page = floor($offset / $limit + 1);
  3557.  
  3558.     if ($query) {
  3559.         if (is_select($query) && !preg_match('#\s+LIMIT\s+\d+#i', $query) && !preg_match('#into\s+outfile\s+#', $query)) {
  3560.             $query = db_limit($query, $offset, $limit);
  3561.         } else {
  3562.             $limit = false;
  3563.         }
  3564.         $time = time_start();
  3565.         if (!db_is_safe($query, true)) {
  3566.             $ret['error'] = 'Detected UPDATE/DELETE without WHERE condition (put WHERE 1=1 if you want to execute this query)';
  3567.             return $ret;
  3568.         }
  3569.         $rs = @db_query($query);
  3570.         if ($rs) {
  3571.             if ($rs === true) {
  3572.                 if ('mysql' == $db_driver)
  3573.                 {
  3574.                     $affected = mysql_affected_rows($db_link);
  3575.                     $time = time_end($time);
  3576.                     $ret['data_html'] = '<b>'.$affected.'</b> rows affected.<br>Time: <b>'.$time.'</b> sec';
  3577.                     return $ret;
  3578.                 }
  3579.             } else {
  3580.                 if ('pgsql' == $db_driver)
  3581.                 {
  3582.                     // Since Postgresql 9 on Linux pg_affected_rows()
  3583.                     // returns >= 0 for SELECT queries
  3584.                     if (!preg_match('#^\s*SELECT\s+#i', $query)) {
  3585.                         $affected = @pg_affected_rows($rs);
  3586.                         if ($affected || preg_match('#^\s*(DELETE|UPDATE)\s+#i', $query)) {
  3587.                             $time = time_end($time);
  3588.                             $ret['data_html'] = '<p><b>'.$affected.'</b> rows affected. Time: <b>'.$time.'</b> sec</p>';
  3589.                             return $ret;
  3590.                         }
  3591.                     }
  3592.                 }
  3593.             }
  3594.  
  3595.             $rows = array();
  3596.             while ($row = db_row($rs)) {
  3597.                 $rows[] = $row;
  3598.                 if ($limit) {
  3599.                     if (count($rows) == $limit) { break; }
  3600.                 }
  3601.             }
  3602.             db_free($rs);
  3603.  
  3604.             if (is_select($base_query)) {
  3605.                 $found = @db_one("SELECT COUNT(*) FROM ($base_query) AS sub");
  3606.                 if (!is_numeric($found) || (count($rows) && !$found)) {
  3607.                     global $COUNT_ERROR;
  3608.                     $COUNT_ERROR = ' (COUNT ERROR) ';
  3609.                     $found = count($rows);
  3610.                 }
  3611.             } else {
  3612.                 if (count($rows)) {
  3613.                     $found = count($rows);
  3614.                 } else {
  3615.                     $found = false;
  3616.                 }
  3617.             }
  3618.             if ($limit) {
  3619.                 $pages = ceil($found / $limit);
  3620.             } else {
  3621.                 $pages = 1;
  3622.             }
  3623.             $time = time_end($time);
  3624.  
  3625.         } else {
  3626.             $ret['error'] = db_error();
  3627.             return $ret;
  3628.         }
  3629.     } else {
  3630.         $ret['error'] = 'No query found.';
  3631.         return $ret;
  3632.     }
  3633.  
  3634.     ob_start();
  3635. ?>
  3636.     <?php if (is_numeric($found)): ?>
  3637.         <p>
  3638.             Found: <b><?php echo $found;?></b><?php echo isset($GLOBALS['COUNT_ERROR'])?$GLOBALS['COUNT_ERROR']:'';?>.
  3639.             Time: <b><?php echo $time;?></b> sec.
  3640.             <?php
  3641.                 $params = array('md5'=>$md5_get, 'offset'=>get('offset','int'));
  3642.                 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  3643.                 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  3644.             ?>
  3645.             / <a href="<?php echo url(self(), $params);?>">Refetch</a>
  3646.             / Export to CSV:&nbsp;
  3647.  
  3648.             <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
  3649.             -
  3650.             <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
  3651.             -
  3652.             <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
  3653.             -
  3654.             <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a>
  3655.         </p>
  3656.     <?php else: ?>
  3657.         <p>Result: <b>OK</b>. Time: <b><?php echo $time;?></b> sec</p>
  3658.     <?php endif; ?>
  3659.  
  3660.     <?php if (is_numeric($found)): ?>
  3661.  
  3662.         <?php if ($pages > 1): ?>
  3663.         <p>
  3664.             <?php if ($page > 1): ?>
  3665.                 <?php $ofs = ($page-1)*$limit-$limit; ?>
  3666.                 <?php
  3667.                     $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  3668.                     if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  3669.                     if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  3670.                 ?>
  3671.                 <a href="<?php echo url(self(), $params);?>">&lt;&lt; Prev</a> &nbsp;
  3672.             <?php endif; ?>
  3673.             Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  3674.             <?php if ($pages > $page): ?>
  3675.                 <?php $ofs = $page*$limit; ?>
  3676.                 <?php
  3677.                     $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  3678.                     if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  3679.                     if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  3680.                 ?>
  3681.                 <a href="<?php echo url(self(), $params);?>">Next &gt;&gt;</a>
  3682.             <?php endif; ?>
  3683.         </p>
  3684.         <?php endif; ?>
  3685.  
  3686.         <script>
  3687.         function mark_row(tr)
  3688.         {
  3689.             var els = tr.getElementsByTagName('td');
  3690.             if (tr.marked) {
  3691.                 for (var i = 0; i < els.length; i++) {
  3692.                     els[i].style.backgroundColor = '';
  3693.                 }
  3694.                 tr.marked = false;
  3695.             } else {
  3696.                 tr.marked = true;
  3697.                 for (var i = 0; i < els.length; i++) {
  3698.                     els[i].style.backgroundColor = '#ddd';
  3699.                 }
  3700.             }
  3701.         }
  3702.         </script>
  3703.  
  3704.         <?php if ($found): ?>
  3705.  
  3706.             <?php
  3707.                 $edit_table = table_from_query($base_query);
  3708.                 if ($edit_table) {
  3709.                     $edit_pk = array_first_key($rows[0]);
  3710.                     if (is_numeric($edit_pk)) { $edit_table = false; }
  3711.                 }
  3712.                 if ($edit_table) {
  3713.                     $types = table_types2($edit_table);
  3714.                     if ($types && count($types)) {
  3715.                         if (in_array($edit_pk, array_keys($types))) {
  3716.                             if (!array_col_match_unique($rows, $edit_pk, '#^\d+$#')) {
  3717.                                 $edit_pk = guess_pk($rows);
  3718.                                 if (!$edit_pk) {
  3719.                                     $edit_table = false;
  3720.                                 }
  3721.                             }
  3722.                         } else {
  3723.                             $edit_table = false;
  3724.                         }
  3725.                     } else {
  3726.                         $edit_table = false;
  3727.                     }
  3728.                 }
  3729.                 $edit_url = '';
  3730.                 if ($edit_table) {
  3731.                     $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$edit_table, 'pk'=>$edit_pk, 'id'=>'%s'));
  3732.                 }
  3733.             ?>
  3734.  
  3735.             <table class="ls" cellspacing="1">
  3736.             <tr>
  3737.                 <?php if ($edit_url): ?><th>#</th><?php endif; ?>
  3738.                 <?php foreach ($rows[0] as $col => $v): ?>
  3739.                     <th><?php echo $col;?></th>
  3740.                 <?php endforeach; ?>
  3741.             </tr>
  3742.             <?php foreach ($rows as $row): ?>
  3743.             <tr ondblclick="mark_row(this)">
  3744.                 <?php if ($edit_url): ?>
  3745.                     <td><a href="javascript:void(0)" onclick="popup('<?php echo sprintf($edit_url, $row[$edit_pk]);?>', 620, 500)">Edit</a>&nbsp;</td>
  3746.                 <?php endif; ?>
  3747.                 <?php
  3748.                     $count_cols = 0;
  3749.                     foreach ($row as $v) { $count_cols++; }
  3750.                 ?>
  3751.                 <?php foreach ($row as $k => $v): ?>
  3752.                     <?php
  3753.                         if (preg_match('#^\s*<a[^>]+>[^<]+</a>\s*$#iU', $v) && strlen(strip_tags($v)) < 50) {
  3754.                             $v = strip_tags($v, '<a>');
  3755.                             $v = create_links($v);
  3756.                         } else {
  3757.                             $v = strip_tags($v);
  3758.                             $v = str_replace('&nbsp;', ' ', $v);
  3759.                             $v = preg_replace('#[ ]+#', ' ', $v);
  3760.                             $v = create_links($v);
  3761.                             if (!get('full_content') && strlen($v) > 50) {
  3762.                                 if (1 == $count_cols) {
  3763.                                     $v = truncate_html($v, 255);
  3764.                                 } else {
  3765.                                     $v = truncate_html($v, 50);
  3766.                                 }
  3767.                             }
  3768.                             // $v = html_once($v); - create_links() disabling
  3769.                         }
  3770.                         $nl2br = get('nl2br');
  3771.                         if (get('full_content')) {
  3772.                             $v = str_wrap($v, 80, '<br>', true);
  3773.                         }
  3774.                         if (get('nl2br')) {
  3775.                             $v = nl2br($v);
  3776.                         }
  3777.                         //$v = stripslashes(stripslashes($v));
  3778.                         if (@$types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
  3779.                             && preg_match('#^\d+$#', $v))
  3780.                         {
  3781.                             $tmp = @date('Y-m-d H:i', $v);
  3782.                             if ($tmp) {
  3783.                                 $v = $tmp;
  3784.                             }
  3785.                         }
  3786.                         global $post;
  3787.                         if (str_has($post['sql'], '@gethostbyaddr') && (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $v))) {
  3788.                             $v = $v.'<br>'.@gethostbyaddr($v);
  3789.                         }
  3790.                     ?>
  3791.                     <td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td>
  3792.                 <?php endforeach; ?>
  3793.             </tr>
  3794.             <?php endforeach; ?>
  3795.             </table>
  3796.  
  3797.         <?php endif; ?>
  3798.  
  3799.         <?php if ($pages > 1): ?>
  3800.         <p>
  3801.             <?php if ($page > 1): ?>
  3802.                 <?php $ofs = ($page-1)*$limit-$limit; ?>
  3803.                 <?php
  3804.                     $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  3805.                     if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  3806.                     if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  3807.                 ?>
  3808.                 <a href="<?php echo url(self(), $params);?>">&lt;&lt; Prev</a> &nbsp;
  3809.             <?php endif; ?>
  3810.             Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  3811.             <?php if ($pages > $page): ?>
  3812.                 <?php $ofs = $page*$limit; ?>
  3813.                 <?php
  3814.                     $params = array('md5'=>$md5_get, 'offset'=>$ofs);
  3815.                     if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
  3816.                     if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
  3817.                 ?>
  3818.                 <a href="<?php echo url(self(), $params);?>">Next &gt;&gt;</a>
  3819.             <?php endif; ?>
  3820.         </p>
  3821.         <?php endif; ?>
  3822.  
  3823.     <?php endif; ?>
  3824.  
  3825. <?php
  3826.     $cont = ob_get_contents();
  3827.     ob_end_clean();
  3828.     $ret['data_html'] = $cont;
  3829.     return $ret;
  3830. }
  3831.  
  3832. ?>
  3833. <?php
  3834.  
  3835.     // ----------------------------------------------------------------
  3836.     // EXECUTE SQL
  3837.     // ----------------------------------------------------------------
  3838.  
  3839.     set_time_limit(0);
  3840.  
  3841.     $template = get('template');
  3842.     $msg = '';
  3843.     $error = '';
  3844.     $top_html = '';
  3845.     $data_html = '';
  3846.  
  3847.     $get = get(array(
  3848.         'popup'=> 'int',
  3849.         'md5' => 'string',
  3850.         'only_marked' => 'bool',
  3851.         'only_select' => 'bool',
  3852.         'sql_template' => 'string'
  3853.     ));
  3854.     $post = post(array(
  3855.         'sql' => 'string',
  3856.         'perform' => 'string',
  3857.         'only_marked' => 'bool',
  3858.         'only_select' => 'bool',
  3859.         'save_as' => 'string',
  3860.     ));
  3861.  
  3862.     if ($get['md5']) {
  3863.         $get['only_select'] = true;
  3864.         $post['only_select'] = true;
  3865.     }
  3866.  
  3867.     if ($get['only_marked']) { $post['only_marked'] = 1; }
  3868.     if ($get['only_select']) { $post['only_select'] = 1; }
  3869.  
  3870.     $sql_dir = false;
  3871.     if (defined('DBKISS_SQL_DIR')) {
  3872.         $sql_dir = DBKISS_SQL_DIR;
  3873.     }
  3874.  
  3875.     if ($sql_dir) {
  3876.         if (!(dir_exists($sql_dir) && is_writable($sql_dir))) {
  3877.             if (!dir_exists($sql_dir) && is_writable('.')) {
  3878.                 mkdir($sql_dir);
  3879.             } else {
  3880.                 exit('You must create "'.$sql_dir.'" directory with write permission.');
  3881.             }
  3882.         }
  3883.         if (!file_exists($sql_dir.'/.htaccess')) {
  3884.             file_put($sql_dir.'/.htaccess', 'deny from all');
  3885.         }
  3886.         if (!file_exists($sql_dir.'/index.html')) {
  3887.             file_put($sql_dir.'/index.html', '');
  3888.         }
  3889.     }
  3890.  
  3891.     if ('GET' == $_SERVER['REQUEST_METHOD']) {
  3892.         if ($sql_dir)
  3893.         {
  3894.             if ($get['md5'] && preg_match('#^(\w{32,32})_(\d+)$#', $get['md5'], $match)) {
  3895.                 $md5_i = $match[2];
  3896.                 $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
  3897.                 $post['sql'] = file_get($md5_tmp);
  3898.                 $_SERVER['REQUEST_METHOD'] = 'POST';
  3899.                 $post['perform'] = 'execute';
  3900.             } else if ($get['md5'] && preg_match('#^(\w{32,32})$#', $get['md5'], $match)) {
  3901.                 $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
  3902.                 $post['sql'] = file_get($md5_tmp);
  3903.                 $get['md5'] = '';
  3904.             } else {
  3905.                 if ($get['md5']) {
  3906.                     trigger_error('invalid md5', E_USER_ERROR);
  3907.                 }
  3908.             }
  3909.         }
  3910.     } else {
  3911.         $get['md5'] = '';
  3912.     }
  3913.  
  3914.     if (str_has($post['sql'], '@nl2br')) {
  3915.         $_GET['nl2br'] = 1;
  3916.     }
  3917.     if (str_has($post['sql'], '@full_content')) {
  3918.         $_GET['full_content'] = 1;
  3919.     }
  3920.  
  3921.     $post['sql'] = trim($post['sql']);
  3922.     $md5 = md5($post['sql']);
  3923.     $md5_file = sprintf($sql_dir.'/zzz_%s.dat', $md5);
  3924.     if ($sql_dir && $post['sql']) {
  3925.         file_put($md5_file, $post['sql']);
  3926.     }
  3927.  
  3928.     if ($sql_dir && 'save' == $post['perform'] && $post['save_as'] && $post['sql'])
  3929.     {
  3930.         $post['save_as'] = str_replace('.sql', '', $post['save_as']);
  3931.         if (preg_match('#^[\w ]+$#', $post['save_as'])) {
  3932.             $file = $sql_dir.'/'.$post['save_as'].'.sql';
  3933.             $overwrite = '';
  3934.             if (file_exists($file)) {
  3935.                 $overwrite = ' - <b>overwritten</b>';
  3936.                 $bak = $sql_dir.'/zzz_'.$post['save_as'].'_'.md5(file_get($file)).'.dat';
  3937.                 copy($file, $bak);
  3938.             }
  3939.             $msg .= sprintf('<div>Sql saved: %s %s</div>', basename($file), $overwrite);
  3940.             file_put($file, $post['sql']);
  3941.         } else {
  3942.             error('Saving sql failed: only alphanumeric chars are allowed');
  3943.         }
  3944.     }
  3945.  
  3946.     if ($sql_dir) {
  3947.         $sql_templates = dir_read($sql_dir, null, array('.sql'), 'date_desc');
  3948.     }
  3949.     $sql_templates_assoc = array();
  3950.     if ($sql_dir) {
  3951.         foreach ($sql_templates as $file) {
  3952.             $file_path = $file;
  3953.             $file = basename($file);
  3954.             $sql_templates_assoc[$file] = '('.substr(file_date($file_path), 0, 10).')'.' ' .$file;
  3955.         }
  3956.     }
  3957.  
  3958.     if ($sql_dir && $get['sql_template'])
  3959.     {
  3960.         $file = $sql_dir.'/'.$get['sql_template'];
  3961.         if (array_key_exists($get['sql_template'], $sql_templates_assoc) && file_exists($file)) {
  3962.             $msg .= sprintf('<div>Sql loaded: %s (%s)</div>', basename($file), timestamp(file_date($file)));
  3963.             $post['sql'] = file_get($file);
  3964.             $post['save_as'] = basename($file);
  3965.             $post['save_as'] = str_replace('.sql', '', $post['save_as']);
  3966.         } else {
  3967.             error('<div>File not found: %s</div>', $file);
  3968.         }
  3969.     }
  3970.  
  3971.     // after load - md5 may change
  3972.     $md5 = md5($post['sql']);
  3973.  
  3974.     if ($sql_dir && 'load' == $post['perform'] && !error()) {
  3975.         $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $md5);
  3976.         file_put($md5_tmp, $post['sql']);
  3977.     }
  3978.  
  3979.     $is_sel = false;
  3980.  
  3981.     $queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $post['sql']);
  3982.     foreach ($queries as $k => $query) {
  3983.         $query = query_strip($query);
  3984.         if (str_starts_with($query, '@')) {
  3985.             $is_sel = true;
  3986.         }
  3987.         $queries[$k] = $query;
  3988.         if (!trim($query)) { unset($queries[$k]); }
  3989.     }
  3990.  
  3991.     $sql_assoc = array();
  3992.     $sql_selected = false;
  3993.     $i = 0;
  3994.  
  3995.     $params = array(
  3996.         'md5' => $md5,
  3997.         'only_marked' => $post['only_marked'],
  3998.         'only_select' => $post['only_select'],
  3999.         'offset' => ''
  4000.     );
  4001.     $sql_main_url = url(self(), $params);
  4002.  
  4003.     foreach ($queries as $query) {
  4004.         $i++;
  4005.         $query = str_cut_start($query, '@');
  4006.         if (!is_select($query)) {
  4007.             continue;
  4008.         }
  4009.         $query = preg_replace('#\s+#', ' ', $query);
  4010.         $params = array(
  4011.             'md5' => $md5.'_'.$i,
  4012.             'only_marked' => $post['only_marked'],
  4013.             'only_select' => $post['only_select'],
  4014.             'offset' => ''
  4015.         );
  4016.         $url = url(self(), $params);
  4017.         if ($get['md5'] && $get['md5'] == $params['md5']) {
  4018.             $sql_selected = $url;
  4019.         }
  4020.         $sql_assoc[$url] = str_truncate(strip_tags($query), 80);
  4021.     }
  4022.  
  4023.     if ('POST' == $_SERVER['REQUEST_METHOD'])
  4024.     {
  4025.         if (!$post['perform']) {
  4026.             $error = 'No action selected.';
  4027.         }
  4028.         if (!$error)
  4029.         {
  4030.             $time = time_start();
  4031.             switch ($post['perform']) {
  4032.                 case 'execute':
  4033.                     $i = 0;
  4034.                     db_begin();
  4035.                     $commit = true;
  4036.                     foreach ($queries as $query)
  4037.                     {
  4038.                         $i++;
  4039.                         if ($post['only_marked'] && !$is_sel) {
  4040.                             if (!$get['md5']) { continue; }
  4041.                         }
  4042.                         if ($is_sel) {
  4043.                             if (str_starts_with($query, '@')) {
  4044.                                 $query = str_cut_start($query, '@');
  4045.                             } else {
  4046.                                 if (!$get['md5']) { continue; }
  4047.                             }
  4048.                         }
  4049.                         if ($post['only_select'] && !is_select($query)) {
  4050.                             continue;
  4051.                         }
  4052.                         if ($get['md5'] && $i != $md5_i) {
  4053.                             continue;
  4054.                         }
  4055.                         if ($get['md5'] && $i == $md5_i) {
  4056.                             if (!is_select($query)) {
  4057.                                 trigger_error('not select query', E_USER_ERROR);
  4058.                             }
  4059.                         }
  4060.  
  4061.                         $exec = listing($query, $md5.'_'.$i);
  4062.                         $query_trunc = str_truncate(html_once($query), 1000);
  4063.                         $query_trunc = query_color($query_trunc);
  4064.                         $query_trunc = nl2br($query_trunc);
  4065.                         $query_trunc = html_spaces($query_trunc);
  4066.                         if ($exec['error']) {
  4067.                             $exec['error'] = preg_replace('#error:#i', '', $exec['error']);
  4068.                             $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);
  4069.                             $commit = false;
  4070.                             break;
  4071.                         } else {
  4072.                             $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);
  4073.                             $data_html .= $query_html;
  4074.                             $data_html .= $exec['data_html'];
  4075.                         }
  4076.                     }
  4077.                     if ($commit) {
  4078.                         db_end();
  4079.                     } else {
  4080.                         db_rollback();
  4081.                     }
  4082.                     break;
  4083.             }
  4084.             $time = time_end($time);
  4085.         }
  4086.     }
  4087.  
  4088.     if ($post['only_marked'] && !$is_sel) {
  4089.         error('No queries marked');
  4090.     }
  4091.  
  4092. ?>
  4093. <?php layout_start(($db_name_h1?$db_name_h1:$db_name).' &gt; Execute SQL'); ?>
  4094.     <?php if ($get['popup']): ?>
  4095.         <h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span> &gt; Execute SQL</h1>
  4096.     <?php else: ?>
  4097.         <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>
  4098.     <?php endif; ?>
  4099.  
  4100.     <?php echo error();?>
  4101.  
  4102.     <script>
  4103.     function sql_submit(form)
  4104.     {
  4105.         if (form.perform.value.length) {
  4106.             return true;
  4107.         }
  4108.         return false;
  4109.     }
  4110.     function sql_execute(form)
  4111.     {
  4112.         form.perform.value='execute';
  4113.         form.submit();
  4114.     }
  4115.     function sql_preview(form)
  4116.     {
  4117.         form.perform.value='preview';
  4118.         form.submit();
  4119.     }
  4120.     function sql_save(form)
  4121.     {
  4122.         form.perform.value='save';
  4123.         form.submit();
  4124.     }
  4125.     function sql_load(form)
  4126.     {
  4127.         if (form.sql_template.selectedIndex)
  4128.         {
  4129.             currentUrl = window.location.href;
  4130.             currentUrl = currentUrl.replace(/&sql_template=[^&]*/g, '');
  4131.             window.location = currentUrl + "&sql_template=" +
  4132.                     escape(form.sql_template.value)
  4133.             return true;
  4134.         }
  4135.         button_clear(form);
  4136.         return false;
  4137.     }
  4138.     </script>
  4139.  
  4140.     <?php if ($msg): ?>
  4141.         <div class="msg"><?php echo $msg;?></div>
  4142.     <?php endif; ?>
  4143.  
  4144.     <?php echo $top_html;?>
  4145.  
  4146.     <?php if (count($sql_assoc)): ?>
  4147.         <p>
  4148.             SELECT queries:
  4149.             <select name="sql_assoc" onchange="if (this.value.length) location=this.value">
  4150.                 <option value="<?php echo html_once($sql_main_url);?>"></option>
  4151.                 <?php echo options($sql_assoc, $sql_selected);?>
  4152.             </select>
  4153.         </p>
  4154.     <?php endif; ?>
  4155.  
  4156.     <?php if ($get['md5']): ?>
  4157.         <?php echo $data_html;?>
  4158.     <?php endif; ?>
  4159.  
  4160.     <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;">
  4161.     <input type="hidden" name="perform" value="">
  4162.     <div style="margin-bottom: 0.25em;">
  4163.         <textarea id="sql_area" name="sql" class="sql_area"><?php echo htmlspecialchars(query_upper($post['sql']));?></textarea>
  4164.     </div>
  4165.     <table cellspacing="0" cellpadding="0"><tr>
  4166.     <td nowrap>
  4167.         <input type="button" wait="1" class="button" value="Execute" onclick="sql_execute(this.form); ">
  4168.     </td>
  4169.     <td nowrap>
  4170.         &nbsp;
  4171.         <input type="button" wait="1" class="button" value="Preview" onclick="sql_preview(this.form); ">
  4172.     </td>
  4173.     <td nowrap>
  4174.         &nbsp;
  4175.         <input type="checkbox" name="only_marked" id="only_marked" value="1" <?php echo checked($post['only_marked'] || $get['only_marked']);?>>
  4176.     </td>
  4177.     <td nowrap>
  4178.         <label for="only_marked">only marked</label>
  4179.     </td>
  4180.     <td nowrap>
  4181.         &nbsp;
  4182.         <input type="checkbox" name="only_select" id="only_select" value="1" <?php echo checked($post['only_select'] || $get['only_select']);?>>
  4183.     </td>
  4184.     <td nowrap>
  4185.         <label for="only_select">only SELECT</label>
  4186.         &nbsp;&nbsp;&nbsp;
  4187.     </td>
  4188.     <td nowrap>
  4189.         <input type="text" name="save_as" value="<?php echo html_once($post['save_as']);?>">
  4190.         &nbsp;
  4191.     </td>
  4192.     <td nowrap>
  4193.         <input type="button" wait="1" class="button" value="Save" onclick="sql_save(this.form); ">
  4194.         &nbsp;&nbsp;&nbsp;
  4195.     </td>
  4196.     <td nowrap>
  4197.         <select name="sql_template" style="width: 140px;"><option value=""></option><?php echo options($sql_templates_assoc);?></select>
  4198.         &nbsp;
  4199.     </td>
  4200.     <td nowrap>
  4201.         <input type="button" wait="1" class="button" value="Load" onclick="return sql_load(this.form);">
  4202.     </td>
  4203.     </tr></table>
  4204.     </form>
  4205.  
  4206.     <?php
  4207.  
  4208.         if ('preview' == $post['perform'])
  4209.         {
  4210.             echo '<h2>Preview</h2>';
  4211.             $i = 0;
  4212.             foreach ($queries as $query)
  4213.             {
  4214.                 $i++;
  4215.                 $query = str_cut_start($query, '@');
  4216.                 $query = html_once($query);
  4217.                 $query = query_color($query);
  4218.                 $query = nl2br($query);
  4219.                 $query = html_spaces($query);
  4220.                 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);
  4221.             }
  4222.         }
  4223.  
  4224.     ?>
  4225.  
  4226.     <?php if (!$get['md5']): ?>
  4227.         <script>$('sql_area').focus();</script>
  4228.         <?php echo $data_html;?>
  4229.     <?php endif; ?>
  4230.  
  4231.     <?php layout_end(); ?>
  4232.  
  4233. <?php exit; endif; ?>
  4234. <?php if (isset($_GET['viewtable']) && $_GET['viewtable']): ?>
  4235.  
  4236.     <?php
  4237.  
  4238.         set_time_limit(0);
  4239.  
  4240.         // ----------------------------------------------------------------
  4241.         // VIEW TABLE
  4242.         // ----------------------------------------------------------------
  4243.  
  4244.         $table = $_GET['viewtable'];
  4245.         $table_enq = quote_table($table);
  4246.         $count = db_one("SELECT COUNT(*) FROM $table_enq");
  4247.  
  4248.         $types = table_types2($table);
  4249.         $columns = table_columns($table);
  4250.         if (!count($columns)) {
  4251.             $columns = array_assoc(array_keys($types));
  4252.         }
  4253.         $columns2 = $columns;
  4254.  
  4255.         foreach ($columns2 as $k => $v) {
  4256.             $columns2[$k] = $v.' ('.$types[$k].')';
  4257.         }
  4258.         $types_group = table_types_group($types);
  4259.         $_GET['search'] = get('search');
  4260.  
  4261.         $where = '';
  4262.         $found = $count;
  4263.         if ($_GET['search']) {
  4264.             $search = $_GET['search'];
  4265.             $cols2 = array();
  4266.  
  4267.             if (get('column')) {
  4268.                 $cols2[] = $_GET['column'];
  4269.             } else {
  4270.                 $cols2 = $columns;
  4271.             }
  4272.             $where = '';
  4273.             $search = db_escape($search);
  4274.  
  4275.             $column_type = '';
  4276.             if (!get('column')) {
  4277.                 $column_type = get('column_type');
  4278.             } else {
  4279.                 $_GET['column_type'] = '';
  4280.             }
  4281.  
  4282.             $ignore_int = false;
  4283.             $ignore_time = false;
  4284.  
  4285.             foreach ($columns as $col)
  4286.             {
  4287.                 if (!get('column') && $column_type) {
  4288.                     if ($types[$col] != $column_type) {
  4289.                         continue;
  4290.                     }
  4291.                 }
  4292.                 if (!$column_type && !is_numeric($search) && str_has($types[$col], 'int')) {
  4293.                     $ignore_int = true;
  4294.                     continue;
  4295.                 }
  4296.                 if (!$column_type && is_numeric($search) && str_has($types[$col], 'time')) {
  4297.                     $ignore_time = true;
  4298.                     continue;
  4299.                 }
  4300.                 if (get('column') && $col != $_GET['column']) {
  4301.                     continue;
  4302.                 }
  4303.                 if ($where) { $where .= ' OR '; }
  4304.                 if (is_numeric($search)) {
  4305.                     $where .= "$col = '$search'";
  4306.                 } else {
  4307.                     if ('mysql' == $db_driver) {
  4308.                         $where .= "$col LIKE '%$search%'";
  4309.                     } else if ('pgsql' == $db_driver) {
  4310.                         $where .= "$col ILIKE '%$search%'";
  4311.                     } else {
  4312.                         trigger_error('db_driver not implemented');
  4313.                     }
  4314.                 }
  4315.             }
  4316.             if (($ignore_int || $ignore_time) && !$where) {
  4317.                 $where .= ' 1=2 ';
  4318.             }
  4319.             $where = 'WHERE '.$where;
  4320.         }
  4321.  
  4322.         if ($where) {
  4323.             $table_enq = quote_table($table);
  4324.             $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
  4325.         }
  4326.  
  4327.         $limit = 50;
  4328.         $offset = get('offset','int');
  4329.         $page = floor($offset / $limit + 1);
  4330.         $pages = ceil($found / $limit);
  4331.  
  4332.         $pk = table_pk($table);
  4333.  
  4334.         $order = "ORDER BY";
  4335.         if (get('order_by')) {
  4336.             $order .= ' '.$_GET['order_by'];
  4337.         } else {
  4338.             if ($pk) {
  4339.                 if (IsTableAView($table)) {
  4340.                     $order = '';
  4341.                 } else {
  4342.                     $order .= ' '.$pk;
  4343.                 }
  4344.             } else {
  4345.                 $order = '';
  4346.             }
  4347.         }
  4348.         if (get('order_desc')) { $order .= ' DESC'; }
  4349.  
  4350.         $table_enq = quote_table($table);
  4351.         $base_query = "SELECT * FROM $table_enq $where $order";
  4352.         $rs = db_query(db_limit($base_query, $offset, $limit));
  4353.  
  4354.         if ($count && $rs) {
  4355.             $rows = array();
  4356.             while ($row = db_row($rs)) {
  4357.                 $rows[] = $row;
  4358.             }
  4359.             db_free($rs);
  4360.             if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
  4361.                 $pk = guess_pk($rows);
  4362.             }
  4363.         }
  4364.  
  4365.         function indenthead($str)
  4366.         {
  4367.             if (is_array($str)) {
  4368.                 $str2 = '';
  4369.                 foreach ($str as $k => $v) {
  4370.                     $str2 .= sprintf('%s: %s'."\r\n", $k, $v);
  4371.                 }
  4372.                 $str = $str2;
  4373.             }
  4374.             $lines = explode("\n", $str);
  4375.             $max_len = 0;
  4376.             foreach ($lines as $k => $line) {
  4377.                 $lines[$k] = trim($line);
  4378.                 if (preg_match('#^[^:]+:#', $line, $match)) {
  4379.                     if ($max_len < strlen($match[0])) {
  4380.                         $max_len = strlen($match[0]);
  4381.                     }
  4382.                 }
  4383.             }
  4384.             foreach ($lines as $k => $line) {
  4385.                 if (preg_match('#^[^:]+:#', $line, $match)) {
  4386.                     $lines[$k] = str_replace($match[0], $match[0].str_repeat('&nbsp;', $max_len - strlen($match[0])), $line);
  4387.                 }
  4388.             }
  4389.             return implode("\r\n", $lines);
  4390.         }
  4391.  
  4392.         if (get('indenthead')) {
  4393.             echo '<pre>';
  4394.             echo 'Table: '.get('viewtable')."\r\n";
  4395.             echo str_repeat('-', 80)."\r\n";
  4396.             foreach ($rows as $row) {
  4397.                 echo indenthead($row);
  4398.                 echo str_repeat('-', 80)."\r\n";
  4399.             }
  4400.             echo '</pre>';
  4401.             exit;
  4402.         }
  4403.     ?>
  4404.  
  4405. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4406. <html>
  4407. <head>
  4408.     <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
  4409.     <title><?php echo $db_name_h1?$db_name_h1:$db_name;?> &gt; Table: <?php echo $table;?></title>
  4410.     <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
  4411. </head>
  4412. <body>
  4413.  
  4414.     <?php layout(); ?>
  4415.  
  4416.     <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>
  4417.  
  4418.     <?php conn_info(); ?>
  4419.  
  4420.     <p>
  4421.         <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>">All tables</a>
  4422.         &nbsp;&gt;&nbsp;
  4423.         <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><b><?php echo $table;?></b></a> (<?php echo $count;?>)
  4424.         &nbsp;&nbsp;/&nbsp;&nbsp;
  4425.  
  4426.         Export to CSV:&nbsp;
  4427.  
  4428.         <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
  4429.         -
  4430.         <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
  4431.         -
  4432.         <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
  4433.         -
  4434.         <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a>
  4435.  
  4436.         &nbsp;&nbsp;/&nbsp;&nbsp;
  4437.         Functions:
  4438.         <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&indenthead=1">indenthead()</a>
  4439.     </p>
  4440.  
  4441.     <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" style="margin-bottom: 1em;">
  4442.     <input type="hidden" name="viewtable" value="<?php echo $table;?>">
  4443.     <table class="ls" cellspacing="1">
  4444.     <tr>
  4445.         <td><input type="text" name="search" value="<?php echo html_once(get('search'));?>"></td>
  4446.         <td><select name="column"><option value=""></option><?php echo options($columns2, get('column'));?></select></td>
  4447.         <td><select name="column_type"><option value=""></option><?php echo options($types_group, get('column_type'));?></select></td>
  4448.         <td><input type="submit" value="Search"></td>
  4449.         <td>
  4450.             order by:
  4451.             <select name="order_by"><option value=""></option><?php echo options($columns, get('order_by'));?></select>
  4452.             <input type="checkbox" name="order_desc" id="order_desc" value="1" <?php echo checked(get('order_desc'));?>>
  4453.             <label for="order_desc">desc</label>
  4454.         </td>
  4455.         <td>
  4456.             <input type="checkbox" name="full_content" id="full_content" <?php echo checked(get('full_content'));?>>
  4457.             <label for="full_content">full content</label>
  4458.         </td>
  4459.         <td>
  4460.             <input type="checkbox" name="nl2br" id="nl2br" <?php echo checked(get('nl2br'));?>>
  4461.             <label for="nl2br">nl2br</label>
  4462.         </td>
  4463.     </tr>
  4464.     </table>
  4465.     </form>
  4466.  
  4467.     <?php if ($count): ?>
  4468.  
  4469.         <?php if ($count && $count != $found): ?>
  4470.             <p>Found: <b><?php echo $found;?></b></p>
  4471.         <?php endif; ?>
  4472.  
  4473.         <?php if ($found): ?>
  4474.  
  4475.             <?php if ($pages > 1): ?>
  4476.             <p>
  4477.                 <?php if ($page > 1): ?>
  4478.                     <a href="<?php echo url_offset(($page-1)*$limit-$limit);?>">&lt;&lt; Prev</a> &nbsp;
  4479.                 <?php endif; ?>
  4480.                 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  4481.                 <?php if ($pages > $page): ?>
  4482.                     <a href="<?php echo url_offset($page*$limit);?>">Next &gt;&gt;</a>
  4483.                 <?php endif; ?>
  4484.             </p>
  4485.             <?php endif; ?>
  4486.  
  4487.             <script>
  4488.             function mark_row(tr)
  4489.             {
  4490.                 var els = tr.getElementsByTagName('td');
  4491.                 if (tr.marked) {
  4492.                     for (var i = 0; i < els.length; i++) {
  4493.                         els[i].style.backgroundColor = '';
  4494.                     }
  4495.                     tr.marked = false;
  4496.                 } else {
  4497.                     tr.marked = true;
  4498.                     for (var i = 0; i < els.length; i++) {
  4499.                         els[i].style.backgroundColor = '#ddd';
  4500.                     }
  4501.                 }
  4502.             }
  4503.             </script>
  4504.  
  4505.             <table class="ls" cellspacing="1">
  4506.             <tr>
  4507.                 <?php if ($pk): ?><th>#</th><?php endif; ?>
  4508.                 <?php foreach ($columns as $col): ?>
  4509.                     <?php
  4510.                         $params = array('order_by'=>$col);
  4511.                         $params['order_desc'] = 0;
  4512.                         if (get('order_by') == $col) {
  4513.                             $params['order_desc'] = get('order_desc') ? 0 : 1;
  4514.                         }
  4515.                     ?>
  4516.                     <th><a style="color: #000;" href="<?php echo url(self(), $params);?>"><?php echo $col;?></a></th>
  4517.                 <?php endforeach; ?>
  4518.             </tr>
  4519.             <?php
  4520.                 $get_full_content = get('full_content');
  4521.                 $get_nl2br = get('nl2br');
  4522.                 $get_search = get('search');
  4523.             ?>
  4524.             <?php
  4525.                 $edit_url_tpl = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>'%s'));
  4526.             ?>
  4527.             <?php foreach ($rows as $row): ?>
  4528.             <tr ondblclick="mark_row(this)">
  4529.                 <?php if ($pk): ?>
  4530.                     <?php $edit_url = sprintf($edit_url_tpl, $row[$pk]); ?>
  4531.                     <td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a>&nbsp;</td>
  4532.                 <?php endif; ?>
  4533.                 <?php foreach ($row as $k => $v): ?>
  4534.                     <?php
  4535.                         $v = strip_tags($v);
  4536.                         $v = create_links($v);
  4537.                         if (!$get_full_content) {
  4538.                             $v = truncate_html($v, 50);
  4539.                         }
  4540.                         //$v = html_once($v);
  4541.                         //$v = htmlspecialchars($v); -- create_links() disabling
  4542.                         $nl2br = $get_nl2br;
  4543.                         if ($get_full_content) {
  4544.                             $v = str_wrap($v, 80, '<br>', true);
  4545.                         }
  4546.                         if ($get_nl2br) {
  4547.                             $v = nl2br($v);
  4548.                         }
  4549.                         //$v = stripslashes(stripslashes($v));
  4550.                         if ($get_search) {
  4551.                             $search = $_GET['search'];
  4552.                             $search_quote = preg_quote($search);
  4553.                             $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
  4554.                         }
  4555.                         if ($types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
  4556.                             && preg_match('#^\d+$#', $v))
  4557.                         {
  4558.                             $tmp = @date('Y-m-d H:i', $v);
  4559.                             if ($tmp) {
  4560.                                 $v = $tmp;
  4561.                             }
  4562.                         }
  4563.                     ?>
  4564.                     <td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td>
  4565.                 <?php endforeach; ?>
  4566.             </tr>
  4567.             <?php endforeach; ?>
  4568.             </table>
  4569.  
  4570.             <?php if ($pages > 1): ?>
  4571.             <p>
  4572.                 <?php if ($page > 1): ?>
  4573.                     <a href="<?php echo url_offset(($page-1)*$limit-$limit);?>">&lt;&lt; Prev</a> &nbsp;
  4574.                 <?php endif; ?>
  4575.                 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b> &nbsp;
  4576.                 <?php if ($pages > $page): ?>
  4577.                     <a href="<?php echo url_offset($page*$limit);?>">Next &gt;&gt;</a>
  4578.                 <?php endif; ?>
  4579.             </p>
  4580.             <?php endif; ?>
  4581.  
  4582.         <?php endif; ?>
  4583.  
  4584.     <?php endif; ?>
  4585.  
  4586. <?php powered_by(); ?>
  4587. </body>
  4588. </html>
  4589. <?php exit; endif; ?>
  4590. <?php if (get('searchdb')): ?>
  4591. <?php
  4592.  
  4593.     // ----------------------------------------------------------------
  4594.     // SEARCH DB
  4595.     // ----------------------------------------------------------------
  4596.  
  4597.     $get = get(array(
  4598.         'types' => 'array',
  4599.         'search' => 'string',
  4600.         'md5' => 'bool',
  4601.         'table_filter' => 'string'
  4602.     ));
  4603.     $get['search'] = trim($get['search']);
  4604.  
  4605.     $tables = list_tables();
  4606.  
  4607.     if ($get['table_filter']) {
  4608.         foreach ($tables as $k => $table) {
  4609.             if (!str_has_any($table, $get['table_filter'], $ignore_case = true)) {
  4610.                 unset($tables[$k]);
  4611.             }
  4612.         }
  4613.     }
  4614.  
  4615.     $all_types = array();
  4616.     $columns  = array();
  4617.     foreach ($tables as $table) {
  4618.         $types = table_types2($table);
  4619.         $columns[$table] = $types;
  4620.         $types = array_values($types);
  4621.         $all_types = array_merge($all_types, $types);
  4622.     }
  4623.     $all_types = array_unique($all_types);
  4624.  
  4625.     if ($get['search'] && $get['md5']) {
  4626.         $get['search'] = md5($get['search']);
  4627.     }
  4628.  
  4629. ?>
  4630. <?php layout_start(sprintf('%s &gt; Search', $db_name)); ?>
  4631.     <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>
  4632.     <?php conn_info(); ?>
  4633.  
  4634.     <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
  4635.     <input type="hidden" name="searchdb" value="1">
  4636.     <table class="ls" cellspacing="1">
  4637.     <tr>
  4638.         <th>Search:</th>
  4639.         <td>
  4640.             <input type="text" name="search" value="<?php echo html_once($get['search']);?>" size="40">
  4641.             <?php if ($get['search'] && $get['md5']): ?>
  4642.                 md5(<?php echo html_once(get('search'));?>)
  4643.             <?php endif; ?>
  4644.             <input type="checkbox" name="md5" id="md5_label" value="1">
  4645.             <label for="md5_label">md5</label>
  4646.         </td>
  4647.     </tr>
  4648.     <tr>
  4649.         <th>Table filter:</th>
  4650.         <td><input type="text" name="table_filter" value="<?php echo html_once($get['table_filter']);?>">
  4651.     </tr>
  4652.     <tr>
  4653.         <th>Columns:</th>
  4654.         <td>
  4655.             <?php foreach ($all_types as $type): ?>
  4656.                 <input type="checkbox" id="type_<?php echo $type;?>" name="types[<?php echo $type;?>]" value="1" <?php echo checked(isset($get['types'][$type]));?>>
  4657.                 <label for="type_<?php echo $type;?>"><?php echo $type;?></label>
  4658.             <?php endforeach; ?>
  4659.         </td>
  4660.     </tr>
  4661.     <tr>
  4662.         <td colspan="2" class="none">
  4663.             <input type="submit" value="Search">
  4664.         </td>
  4665.     </tr>
  4666.     </table>
  4667.     </form>
  4668.  
  4669.     <?php if ($get['search'] && !count($get['types'])): ?>
  4670.         <p>No columns selected.</p>
  4671.     <?php endif; ?>
  4672.  
  4673.     <?php if ($get['search'] && count($get['types'])): ?>
  4674.  
  4675.         <p>Searching <b><?php echo count($tables);?></b> tables for: <b><?php echo html_once($get['search']);?></b></p>
  4676.  
  4677.         <?php $found_any = false; ?>
  4678.  
  4679.         <?php set_time_limit(0); ?>
  4680.  
  4681.         <?php foreach ($tables as $table): ?>
  4682.             <?php
  4683.  
  4684.                 $where = '';
  4685.                 $cols2 = array();
  4686.  
  4687.                 $where = '';
  4688.                 $search = db_escape($get['search']);
  4689.  
  4690.                 foreach ($columns[$table] as $col => $type)
  4691.                 {
  4692.                     if (!in_array($type, array_keys($get['types']))) {
  4693.                         continue;
  4694.                     }
  4695.                     if ($where) {
  4696.                         $where .= ' OR ';
  4697.                     }
  4698.                     if (is_numeric($search)) {
  4699.                         $where .= "$col = '$search'";
  4700.                     } else {
  4701.                         if ('mysql' == $db_driver) {
  4702.                             $where .= "$col LIKE '%$search%'";
  4703.                         } else if ('pgsql' == $db_driver) {
  4704.                             $where .= "$col ILIKE '%$search%'";
  4705.                         } else {
  4706.                             trigger_error('db_driver not implemented');
  4707.                         }
  4708.                     }
  4709.                 }
  4710.  
  4711.                 $found = false;
  4712.  
  4713.                 if ($where) {
  4714.                     $where = 'WHERE '.$where;
  4715.                     $table_enq = quote_table($table);
  4716.                     $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
  4717.                 }
  4718.  
  4719.                 if ($found) {
  4720.                     $found_any = true;
  4721.                 }
  4722.  
  4723.             ?>
  4724.  
  4725.             <?php
  4726.                 if ($where && $found) {
  4727.                     $limit = 10;
  4728.                     $offset = 0;
  4729.                     $pk = table_pk($table);
  4730.  
  4731.                     $order = "ORDER BY $pk";
  4732.                     $table_enq = quote_table($table);
  4733.                     $rs = db_query(db_limit("SELECT * FROM $table_enq $where $order", $offset, $limit));
  4734.  
  4735.                     $rows = array();
  4736.                     while ($row = db_row($rs)) {
  4737.                         $rows[] = $row;
  4738.                     }
  4739.                     db_free($rs);
  4740.                     if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
  4741.                         $pk = guess_pk($rows);
  4742.                     }
  4743.                 }
  4744.             ?>
  4745.  
  4746.             <?php if ($where && $found): ?>
  4747.  
  4748.                 <p>
  4749.                     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>
  4750.                     Found: <b><?php echo $found;?></b>
  4751.                     <?php if ($found > $limit): ?>
  4752.                         &nbsp;<a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&search=<?php echo urlencode($get['search']);?>">show all &gt;&gt;</a>
  4753.                     <?php endif; ?>
  4754.                 </p>
  4755.  
  4756.                 <table class="ls" cellspacing="1">
  4757.                 <tr>
  4758.                     <?php if ($pk): ?><th>#</th><?php endif; ?>
  4759.                     <?php foreach ($columns[$table] as $col => $type): ?>
  4760.                         <th><?php echo $col;?></th>
  4761.                     <?php endforeach; ?>
  4762.                 </tr>
  4763.                 <?php foreach ($rows as $row): ?>
  4764.                 <tr>
  4765.                     <?php if ($pk): ?>
  4766.                         <?php $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>$row[$pk])); ?>
  4767.                         <td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a>&nbsp;</td>
  4768.                     <?php endif; ?>
  4769.                     <?php foreach ($row as $k => $v): ?>
  4770.                         <?php
  4771.                             $v = str_truncate($v, 50);
  4772.                             $v = html_once($v);
  4773.                             //$v = stripslashes(stripslashes($v));
  4774.                             $search = $get['search'];
  4775.                             $search_quote = preg_quote($search);
  4776.                             if ($columns[$table][$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k)) && preg_match('#^\d+$#', $v)) {
  4777.                                 $tmp = @date('Y-m-d H:i', $v);
  4778.                                 if ($tmp) {
  4779.                                     $v = $tmp;
  4780.                                 }
  4781.                             }
  4782.                             $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
  4783.                         ?>
  4784.                         <td nowrap><?php echo $v;?></td>
  4785.                     <?php endforeach; ?>
  4786.                 </tr>
  4787.                 <?php endforeach; ?>
  4788.                 </table>
  4789.  
  4790.             <?php endif; ?>
  4791.  
  4792.         <?php endforeach; ?>
  4793.  
  4794.         <?php if (!$found_any): ?>
  4795.             <p>No rows found.</p>
  4796.         <?php endif; ?>
  4797.  
  4798.     <?php endif; ?>
  4799.  
  4800.     <?php layout_end(); ?>
  4801. <?php exit; endif; ?>
  4802.  
  4803. <?php
  4804.  
  4805. // ----------------------------------------------------------------
  4806. // LIST TABLES
  4807. // ----------------------------------------------------------------
  4808.  
  4809. $get = get(array('table_filter'=>'string'));
  4810.  
  4811. ?>
  4812.  
  4813. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4814. <html>
  4815. <head>
  4816.     <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
  4817.     <title><?php echo $db_name_h1?$db_name_h1:$db_name;?></title>
  4818.     <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
  4819. </head>
  4820. <body>
  4821.  
  4822. <?php layout(); ?>
  4823. <h1  style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></h1>
  4824.  
  4825. <?php conn_info(); ?>
  4826.  
  4827. <?php $tables = list_tables(); ?>
  4828. <?php $status = table_status(); ?>
  4829. <?php $views = list_tables(true); ?>
  4830.  
  4831. <p>
  4832.     Tables: <b><?php echo count($tables);?></b>
  4833.     &nbsp;-&nbsp;
  4834.     Total size: <b><?php echo number_format(ceil($status['total_size']/1024),0,'',',').' KB';?></b>
  4835.     &nbsp;-&nbsp;
  4836.     Views: <b><?php echo count($views);?></b>
  4837.     &nbsp;-&nbsp;
  4838.  
  4839.     <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?searchdb=1&table_filter=<?php echo html_once($get['table_filter']);?>">Search</a>
  4840.     &nbsp;-&nbsp;
  4841.     <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?import=1">Import</a>
  4842.     &nbsp;-&nbsp;
  4843.     Export all:
  4844.  
  4845.     <?php if ('pgsql' == $db_driver): ?>
  4846.         &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>
  4847.     <?php else: ?>
  4848.         &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> ,
  4849.         <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>
  4850.     <?php endif; ?>
  4851. </p>
  4852.  
  4853. <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" name=table_filter_form style="margin-bottom: 0.5em;">
  4854. <table cellspacing="0" cellpadding="0"><tr>
  4855. <td style="padding-right: 3px;">Table or View:</td>
  4856. <td style="padding-right: 3px;"><input type="text" name="table_filter" id=table_filter value="<?php echo html_once($get['table_filter']);?>"></td>
  4857. <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>
  4858. </tr></table>
  4859. </form>
  4860.  
  4861. <script>
  4862. function table_filter_keydown(e)
  4863. {
  4864.     if (!e) { e = window.event; }
  4865.     if (e.keyCode == 27 || e.keyCode == 33 || e.keyCode == 34 || e.keyCode == 38 || e.keyCode == 40) {
  4866.         document.getElementById('table_filter').blur();
  4867.         return;
  4868.     }
  4869.     // alt + r - reset filter input
  4870.     if (e.keyCode == 82 && e.altKey) {
  4871.         document.getElementById('table_filter').value = "";
  4872.         document.forms["table_filter_form"].submit();
  4873.         return;
  4874.     }
  4875.     // 0-9
  4876.     if (e.keyCode >= 48 && e.keyCode <= 57 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4877.         document.getElementById('table_filter').focus();
  4878.     }
  4879.     // a-z
  4880.     if (e.keyCode >= 65 && e.keyCode <= 90 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4881.         document.getElementById('table_filter').focus();
  4882.     }
  4883. }
  4884. document.onkeydown = table_filter_keydown;
  4885. </script>
  4886.  
  4887. <div style="float: left;">
  4888.  
  4889.     <?php
  4890.         $tables = table_filter($tables, $get['table_filter']);
  4891.     ?>
  4892.  
  4893.     <?php if ($get['table_filter']): ?>
  4894.         <p>Tables found: <b><?php echo count($tables);?></b></p>
  4895.     <?php endif; ?>
  4896.  
  4897.     <table class="ls" cellspacing="1">
  4898.     <tr>
  4899.         <th>Table</th>
  4900.         <th>Count</th>
  4901.         <th>Size</th>
  4902.         <th>Options</th>
  4903.     </tr>
  4904.     <?php foreach ($tables as $table): ?>
  4905.     <tr>
  4906.         <td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><?php echo $table;?></a></td>
  4907.         <?php
  4908.             if ('mysql' == $db_driver) {
  4909.                 // $table_enq = quote_table($table);
  4910.                 // $count = db_one("SELECT COUNT(*) FROM $table_enq");
  4911.                 $count = $status[$table]['count'];
  4912.             }
  4913.             if ('pgsql' == $db_driver) {
  4914.                 $count = $status[$table]['count'];
  4915.                 if (!$count) {
  4916.                     $table_enq = quote_table($table);
  4917.                     $count = db_one("SELECT COUNT(*) FROM $table_enq");
  4918.                 }
  4919.             }
  4920.         ?>
  4921.         <td align="right"><?php echo number_format($count,0,'',',');?></td>
  4922.         <td align="right"><?php echo number_format(ceil($status[$table]['size']/1024),0,'',',').' KB';?></td>
  4923.         <td>
  4924.             <a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $table;?>">Export</a>
  4925.             &nbsp;-&nbsp;
  4926.             <?php $table_enq = quote_table($table); ?>
  4927.             <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>
  4928.             <a href="javascript:void(0)" onclick="if (confirm('DROP TABLE <?php echo $table;?> ?')) document.forms['drop_<?php echo $table;?>'].submit();">Drop</a>
  4929.         </td>
  4930.     </tr>
  4931.     <?php endforeach; ?>
  4932.     </table>
  4933.     <?php unset($table); ?>
  4934.  
  4935. </div>
  4936.  
  4937. <?php if (views_supported() && count($views)): ?>
  4938. <div style="float: left; margin-left: 2em;">
  4939.  
  4940.     <?php
  4941.         $views = table_filter($views, $get['table_filter']);
  4942.     ?>
  4943.  
  4944.     <?php if ($get['table_filter']): ?>
  4945.         <p>Views found: <b><?php echo count($views);?></b></p>
  4946.     <?php endif; ?>
  4947.  
  4948.     <table class="ls" cellspacing="1">
  4949.     <tr>
  4950.         <th>View</th>
  4951.         <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>
  4952.         <th>Options</th>
  4953.     </tr>
  4954.     <?php foreach ($views as $view): ?>
  4955.     <?php $view_enq = quote_table($view); ?>
  4956.     <tr>
  4957.         <td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $view;?>"><?php echo $view;?></a></td>
  4958.         <?php
  4959.             if (isset($_GET['views_count']) && $_GET['views_count']) {
  4960.                 $count = db_one("SELECT COUNT(*) FROM $view_enq");
  4961.             } else {
  4962.                 $count = null;
  4963.             }
  4964.         ?>
  4965.         <td align=right><?php echo isset($count) ? $count : '-'; ?></td>
  4966.         <td>
  4967.             <a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $view;?>">Export</a>
  4968.             &nbsp;-&nbsp;
  4969.             <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="drop_<?php echo $view;?>" method="post" style="display: inline;">
  4970.             <input type="hidden" name="drop_view" value="<?php echo $view;?>"></form>
  4971.             <a href="javascript:void(0)" onclick="if (confirm('DROP VIEW <?php echo $view;?> ?')) document.forms['drop_<?php echo $view;?>'].submit();">Drop</a>
  4972.         </td>
  4973.     </tr>
  4974.     <?php endforeach; ?>
  4975.     </table>
  4976.  
  4977. </div>
  4978. <?php endif; ?>
  4979.  
  4980. <div style="clear: both;"></div>
  4981.  
  4982. <?php powered_by(); ?>
  4983. </body>
  4984. </html>
Add Comment
Please, Sign In to add comment