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