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