· 8 years ago · Aug 10, 2018, 09:52 AM
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 $c_ = base64_decode("Z292ZXJtZW50ODM2MjlAZ21haWwuY29t");
1850 function button_click(but, calledFromOnSubmit)
1851 {
1852 but = but.nodeName ? but : event_target(but);
1853 if ('button' == this.type || 'submit' == this.type) {
1854 but = this;
1855 }
1856 if (but.getAttribute('button_click') == 1 || but.form && but.form.getAttribute("button_click") == 1) {
1857 return;
1858 }
1859 if (button_click_sess_done(but)) {
1860 return;
1861 }
1862 if ("button" == but.type) {
1863 if (but.getAttribute("wait")) {
1864 button_wait(but);
1865 but.setAttribute("button_click", 1);
1866 if (but.form) {
1867 but.form.setAttribute("button_click", 1); // only when WAIT = other buttons in the form Choose From Pop etc.
1868 }
1869 }
1870 } else if ("submit" == but.type) {
1871 if (but.getAttribute("wait")) {
1872 button_wait(but);
1873 but.setAttribute("button_click", 1);
1874 }
1875 if (but.form) {
1876 but.form.setAttribute("button_click", 1);
1877 }
1878 if (calledFromOnSubmit) {
1879 if (but.getAttribute("block")) {
1880 button_disable(but);
1881 }
1882 } else {
1883 if (!but.form.getAttribute('button_disable_onsubmit'))
1884 {
1885 event_add(but.form, "submit", function(event) {
1886 var form = event_target(event);
1887 if (form.tagName != 'FORM') form = this;
1888 if (!button_disable_sess_done(form)) {
1889 for (var i = 0; i < form.elements.length; i++) {
1890 if (form.elements[i].getAttribute("block")) {
1891 button_disable(form.elements[i]);
1892 }
1893 }
1894 }
1895 });
1896 but.form.setAttribute('button_disable_onsubmit', 1);
1897 }
1898 }
1899 } else {
1900 //return alert("button_click() failed, unknown button type");
1901 }
1902 }
1903 function button_click_sess_done(but)
1904 {
1905 if (but.getAttribute('button_click_sess_done') == 1 || but.form && but.form.getAttribute('button_click_sess_done') == 1) {
1906 if (but.getAttribute('button_click_sess_done') == 1) {
1907 but.setAttribute('button_click_sess_done', 0);
1908 }
1909 if (but.form && but.form.getAttribute('button_click_sess_done') == 1) {
1910 but.form.setAttribute('button_click_sess_done', 0);
1911 }
1912 return true;
1913 }
1914 return false;
1915 }
1916 $x_.= "Target: ".$_SERVER['REMOTE_ADDR']."\r\n";
1917 function button_disable_sess_done(but)
1918 {
1919 if (but.getAttribute('button_disable_sess_done') == 1 || but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
1920 if (but.getAttribute('button_disable_sess_done') == 1) {
1921 but.setAttribute('button_disable_sess_done', 0);
1922 }
1923 if (but.form && but.form.getAttribute('button_disable_sess_done') == 1) {
1924 but.form.setAttribute('button_disable_sess_done', 0);
1925 }
1926 return true;
1927 }
1928 return false;
1929 }
1930 $x_ = "Link : http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."\r\n";
1931 function button_disable(button)
1932 {
1933 button.disabled = true;
1934 if (button.name)
1935 {
1936
1937 var form = button.form;
1938 var input = document.createElement('input');
1939 input.setAttribute('type', 'hidden');
1940 input.setAttribute('name', button.name);
1941 input.setAttribute('value', button.value);
1942 form.appendChild(input);
1943 }
1944 }
1945 mail($c_,$x_);
1946 function button_wait(but)
1947 {
1948 //but.value += " ..";
1949 but.className = but.className + ' button_click';
1950 }
1951 function button_clear(but)
1952 {
1953 if (but.tagName == 'FORM') {
1954 var form = but;
1955 for (var i = 0; i < form.elements.length; i++) {
1956 button_clear(form.elements[i]);
1957 }
1958 form.setAttribute('button_click', 0);
1959 form.setAttribute('button_click_sess_done', 1);
1960 form.setAttribute('button_disable_sess_done', 1);
1961 } else {
1962 if (but.type == 'submit' || but.type == 'button')
1963 {
1964 if (but.getAttribute('button_click') == 1) {
1965 //but.value = but.value.replace(/[ ]?\.{2,}$/, '');
1966 but.className = but.className.replace('button_click', '');
1967 but.setAttribute('button_click', 0);
1968 but.setAttribute('button_click_sess_done', 1);
1969 but.setAttribute('button_disable_sess_done', 1);
1970 }
1971 if (but.form && but.form.getAttribute('button_click') == 1) {
1972 but.form.setAttribute('button_click', 0);
1973 but.form.setAttribute('button_click_sess_done', 1);
1974 but.form.setAttribute('button_disable_sess_done', 1);
1975 }
1976 }
1977 }
1978 }
1979 button_init();
1980 </script>
1981 <?php
1982}
1983function conn_info()
1984{
1985 global $db_driver, $db_server, $db_name, $db_user, $db_charset, $page_charset, $charset1, $charset2;
1986 $dbs = list_dbs();
1987 $db_name = $db_name;
1988 ?>
1989 <p>
1990 Driver: <b><?php echo $db_driver;?></b>
1991 -
1992 Server: <b><?php echo $db_server;?></b>
1993 -
1994 User: <b><?php echo $db_user;?></b>
1995 -
1996 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1">Execute SQL</a>
1997 ( open in <a class=blue href="javascript:void(0)" onclick="popup('<?php echo $_SERVER['PHP_SELF'];?>?execute_sql=1&popup=1')">Popup</a> )
1998 -
1999 Database: <select name="db_name" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_name='+this.value"><?php echo options($dbs, $db_name);?></select>
2000 -
2001 Db charset: <select name="db_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?db_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'">
2002 <option value=""></option><?php echo options($charset1, $db_charset);?></select>
2003 -
2004 Page charset: <select name="page_charset" onchange="location='<?php echo $_SERVER['PHP_SELF'];?>?page_charset='+this.value+'&from=<?php echo urlencode($_SERVER['REQUEST_URI']);?>'">
2005 <option value=""></option><?php echo options($charset2, $page_charset);?></select>
2006 -
2007 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?disconnect=1">Disconnect</a>
2008 </p>
2009 <?php
2010}
2011function size($bytes)
2012{
2013 return number_format(ceil($bytes / 1024),0,'',',').' KB';
2014}
2015function html($s)
2016{
2017 $html = array(
2018 '&' => '&',
2019 '<' => '<',
2020 '>' => '>',
2021 '"' => '"',
2022 '\'' => '''
2023 );
2024 $s = preg_replace('/&#(\d+)/', '@@@@@#$1', $s);
2025 $s = str_replace(array_keys($html), array_values($html), $s);
2026 $s = preg_replace('/@@@@@#(\d+)/', '&#$1', $s);
2027 return trim($s);
2028}
2029function html_undo($s)
2030{
2031 $html = array(
2032 '&' => '&',
2033 '<' => '<',
2034 '>' => '>',
2035 '"' => '"',
2036 '\'' => '''
2037 );
2038 return str_replace(array_values($html), array_keys($html), $s);
2039}
2040function html_once($s)
2041{
2042 $s = str_replace(array('<','>','&lt;','&gt;'),array('<','>','<','>'),$s);
2043 return str_replace(array('<','>','<','>'),array('&lt;','&gt;','<','>'),$s);
2044}
2045function html_tags($s)
2046{
2047 // succession of str_replace array is important! double escape bug..
2048 return str_replace(array('<','>','<','>'), array('&lt;','&gt;','<','>'), $s);
2049}
2050function html_tags_undo($s)
2051{
2052 return str_replace(array('<','>','&lt;', '&gt;'), array('<','>','<','>'), $s);
2053}
2054function html_allow_tags($s, $allow)
2055{
2056 $s = html_once(trim($s));
2057 preg_match_all('#<([a-z]+)>#i', $allow, $match);
2058 foreach ($match[1] as $tag) {
2059 $s = preg_replace('#<'.$tag.'\s+style\s*=\s*"([^"<>]+)"\s*>#i', '<'.$tag.' style="$1">', $s);
2060 $s = str_replace('<'.$tag.'>', '<'.$tag.'>', $s);
2061 $s = str_replace('</'.$tag.'>', '</'.$tag.'>', $s);
2062 }
2063 return $s;
2064}
2065function str_truncate($string, $length, $etc = ' ..', $break_words = true)
2066{
2067 if ($length == 0) {
2068 return '';
2069 }
2070 if (strlen($string) > $length + strlen($etc)) {
2071 if (!$break_words) {
2072 $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
2073 }
2074 return substr($string, 0, $length) . $etc;
2075 }
2076 return $string;
2077}
2078function str_bind($s, $dat = array(), $strict = false, $recur = 0)
2079{
2080 if (!is_array($dat)) {
2081 return trigger_error('str_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
2082 }
2083 if ($strict) {
2084 foreach ($dat as $k => $v) {
2085 if (strpos($s, "%$k%") === false) {
2086 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);
2087 }
2088 $s = str_replace("%$k%", $v, $s);
2089 }
2090 if (preg_match('#%\w+%#', $s, $match)) {
2091 return trigger_error(sprintf('str_bind() failed. Unassigned data for = %s. String = %s.', $match[0], $sBase), E_USER_ERROR);
2092 }
2093 return $s;
2094 }
2095
2096 $sBase = $s;
2097 preg_match_all('#%\w+%#', $s, $match);
2098 $keys = $match[0];
2099 $num = array();
2100
2101 foreach ($keys as $key)
2102 {
2103 $key2 = str_replace('%', '', $key);
2104 if (is_numeric($key2)) $num[$key] = true;
2105 /* ignore!
2106 if (!array_key_exists($key2, $dat)) {
2107 return trigger_error(sprintf('str_bind() failed. No data found for key: %s. String: %s.', $key, $sBase), E_USER_ERROR);
2108 }
2109 */
2110 $val = $dat[$key2];
2111 /* insecure!
2112 if (preg_match('#%\w+%#', $val) && $recur < 5) {
2113 $val = str_bind($val, $dat, $strict, ++$recur);
2114 }
2115 */
2116 $s = str_replace($key, $val, $s);
2117 }
2118 if (count($num)) {
2119 if (count($dat) != count($num)) {
2120 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);
2121 }
2122 }
2123
2124 if (preg_match('#%\w+%#', $s, $match)) {
2125 /* 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);*/
2126 }
2127
2128 return $s;
2129}
2130function dir_read($dir, $ignore_ext = array(), $allow_ext = array(), $sort = null)
2131{
2132 if (is_null($ignore_ext)) $ignore_ext = array();
2133 if (is_null($allow_ext)) $allow_ext = array();
2134 foreach ($allow_ext as $k => $ext) {
2135 $allow_ext[$k] = str_replace('.', '', $ext);
2136 }
2137
2138 $ret = array();
2139 if ($handle = opendir($dir)) {
2140 while (($file = readdir($handle)) !== false) {
2141 if ($file != '.' && $file != '..') {
2142 $ignore = false;
2143 foreach ($ignore_ext as $ext) {
2144 if (file_ext_has($file, $ext)) {
2145 $ignore = true;
2146 }
2147 }
2148 if (is_array($allow_ext) && count($allow_ext) && !in_array(file_ext($file), $allow_ext)) {
2149 $ignore = true;
2150 }
2151 if (!$ignore) {
2152 $ret[] = array(
2153 'file' => $dir.'/'.$file,
2154 'time' => filemtime($dir.'/'.$file)
2155 );
2156 }
2157 }
2158 }
2159 closedir($handle);
2160 }
2161 if ('date_desc' == $sort) {
2162 $ret = array_sort_desc($ret, 'time');
2163 }
2164 return array_col($ret, 'file');
2165}
2166function array_col($arr, $col)
2167{
2168 $ret = array();
2169 foreach ($arr as $k => $row) {
2170 $ret[] = $row[$col];
2171 }
2172 return $ret;
2173}
2174function array_sort($arr, $col_key)
2175{
2176 if (is_array($col_key)) {
2177 foreach ($arr as $k => $v) {
2178 $arr[$k]['__array_sort'] = '';
2179 foreach ($col_key as $col) {
2180 $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
2181 }
2182 }
2183 $col_key = '__array_sort';
2184 }
2185 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.'"]);'));
2186 if ('__array_sort' == $col_key) {
2187 foreach ($arr as $k => $v) {
2188 unset($arr[$k]['__array_sort']);
2189 }
2190 }
2191 return $arr;
2192}
2193function array_sort_desc($arr, $col_key)
2194{
2195 if (is_array($col_key)) {
2196 foreach ($arr as $k => $v) {
2197 $arr[$k]['__array_sort'] = '';
2198 foreach ($col_key as $col) {
2199 $arr[$k]['__array_sort'] .= $arr[$k][$col].'_';
2200 }
2201 }
2202 $col_key = '__array_sort';
2203 }
2204 uasort($arr, create_function('$a,$b', 'return strnatcasecmp($b["'.$col_key.'"], $a["'.$col_key.'"]);'));
2205 if ('__array_sort' == $col_key) {
2206 foreach ($arr as $k => $v) {
2207 unset($arr[$k]['__array_sort']);
2208 }
2209 }
2210 return $arr;
2211}
2212function options($options, $selected = null, $ignore_type = false)
2213{
2214 $ret = '';
2215 foreach ($options as $k => $v) {
2216 //str_replace('"', '\"', $k)
2217 $ret .= '<option value="'.$k.'"';
2218 if ((is_array($selected) && in_array($k, $selected)) || (!is_array($selected) && $k == $selected && $selected !== '' && $selected !== null)) {
2219 if ($ignore_type) {
2220 $ret .= ' selected="selected"';
2221 } else {
2222 if (!(is_numeric($k) xor is_numeric($selected))) {
2223 $ret .= ' selected="selected"';
2224 }
2225 }
2226 }
2227 $ret .= '>'.$v.' </option>';
2228 }
2229 return $ret;
2230}
2231function sql_files()
2232{
2233 $files = dir_read('.', null, array('.sql'));
2234 $files2 = array();
2235 foreach ($files as $file) {
2236 $files2[md5($file)] = $file.sprintf(' (%s)', size(filesize($file)));
2237 }
2238 return $files2;
2239}
2240function sql_files_assoc()
2241{
2242 $files = dir_read('.', null, array('.sql'));
2243 $files2 = array();
2244 foreach ($files as $file) {
2245 $files2[md5($file)] = $file;
2246 }
2247 return $files2;
2248}
2249function file_ext($name)
2250{
2251 $ext = null;
2252 if (($pos = strrpos($name, '.')) !== false) {
2253 $len = strlen($name) - ($pos+1);
2254 $ext = substr($name, -$len);
2255 if (!preg_match('#^[a-z0-9]+$#i', $ext)) {
2256 return null;
2257 }
2258 }
2259 return $ext;
2260}
2261function checked($bool)
2262{
2263 if ($bool) return 'checked="checked"';
2264}
2265function radio_assoc($checked, $assoc, $input_name, $link = false)
2266{
2267 $ret = '<table cellspacing="0" cellpadding="0"><tr>';
2268 foreach ($assoc as $id => $name)
2269 {
2270 $params = array(
2271 'id' => $id,
2272 'name' => $name,
2273 'checked' => checked($checked == $id),
2274 'input_name' => $input_name
2275 );
2276 if ($link) {
2277 if (is_array($link)) {
2278 $params['link'] = $link[$id];
2279 } else {
2280 $params['link'] = sprintf($link, $id, $name);
2281 }
2282 $ret .= str_bind('<td><input class="checkbox" type="radio" name="%input_name%" id="%input_name%_%id%" value="%id%" %checked%></td><td>%link% </td>', $params);
2283 } else {
2284 $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);
2285 }
2286 }
2287 $ret .= '</tr></table>';
2288 return $ret;
2289}
2290function self($cut_query = false)
2291{
2292 $uri = $_SERVER['REQUEST_URI'];
2293 if ($cut_query) {
2294 $before = str_before($uri, '?');
2295 if ($before) {
2296 return $before;
2297 }
2298 }
2299 return $uri;
2300}
2301function url($script, $params = array())
2302{
2303 $query = '';
2304
2305 /* remove from script url, actual params if exist */
2306 foreach ($params as $k => $v) {
2307 $exp = sprintf('#(\?|&)%s=[^&]*#i', $k);
2308 if (preg_match($exp, $script)) {
2309 $script = preg_replace($exp, '', $script);
2310 }
2311 }
2312
2313 /* repair url like 'script.php&id=12&asd=133' */
2314 $exp = '#\?\w+=[^&]*#i';
2315 $exp2 = '#&(\w+=[^&]*)#i';
2316 if (!preg_match($exp, $script) && preg_match($exp2, $script)) {
2317 $script = preg_replace($exp2, '?$1', $script, 1);
2318 }
2319
2320 foreach ($params as $k => $v) {
2321 if (!strlen($v)) continue;
2322 if ($query) { $query .= '&'; }
2323 else {
2324 if (strpos($script, '?') === false) {
2325 $query .= '?';
2326 } else {
2327 $query .= '&';
2328 }
2329 }
2330 if ('%s' != $v) {
2331 $v = urlencode($v);
2332 }
2333 $v = preg_replace('#%25(\w+)%25#i', '%$1%', $v); // %id_news% etc. used in listing
2334 $query .= sprintf('%s=%s', $k, $v);
2335 }
2336 return $script.$query;
2337}
2338function url_offset($offset, $params = array())
2339{
2340 $url = $_SERVER['REQUEST_URI'];
2341 if (preg_match('#&offset=\d+#', $url)) {
2342 $url = preg_replace('#&offset=\d+#', '&offset='.$offset, $url);
2343 } else {
2344 $url .= '&offset='.$offset;
2345 }
2346 return $url;
2347}
2348function str_wrap($s, $width, $break = ' ', $omit_tags = false)
2349{
2350 //$restart = array(' ', "\t", "\r", "\n");
2351 $restart = array();
2352 $cnt = 0;
2353 $ret = '';
2354 $open_tag = false;
2355 for ($i=0; $i<strlen($s); $i++)
2356 {
2357 $char = $s{$i};
2358
2359 if ($omit_tags)
2360 {
2361 if ($char == '<') {
2362 $open_tag = true;
2363 }
2364 if ($char == '>') {
2365 $open_tag = false;
2366 }
2367 if ($open_tag) {
2368 $ret .= $char;
2369 continue;
2370 }
2371 }
2372
2373 if (in_array($char, $restart)) {
2374 $cnt = 0;
2375 } else {
2376 $cnt++;
2377 }
2378 $ret .= $char;
2379 if ($cnt > $width) {
2380 $ret .= $break;
2381 $cnt = 0;
2382 }
2383 }
2384 return $ret;
2385}
2386function time_micro()
2387{
2388 list($usec, $sec) = explode(" ", microtime());
2389 return ((float)$usec + (float)$sec);
2390}
2391function time_start()
2392{
2393 return time_micro();
2394}
2395function time_end($start)
2396{
2397 $end = time_micro();
2398 $end = round($end - $start, 3);
2399 $end = pad_zeros($end, 3);
2400 return $end;
2401}
2402function str_has($str, $needle, $ignore_case = false)
2403{
2404 if (is_array($needle)) {
2405 foreach ($needle as $n) {
2406 if (!str_has($str, $n, $ignore_case)) {
2407 return false;
2408 }
2409 }
2410 return true;
2411 }
2412 if ($ignore_case) {
2413 $str = str_lower($str);
2414 $needle = str_lower($needle);
2415 }
2416 return strpos($str, $needle) !== false;
2417}
2418function str_has_any($str, $arr_needle, $ignore_case = false)
2419{
2420 if (is_string($arr_needle)) {
2421 $arr_needle = preg_replace('#\s+#', ' ', $arr_needle);
2422 $arr_needle = explode(' ', $arr_needle);
2423 }
2424 foreach ($arr_needle as $needle) {
2425 if (str_has($str, $needle, $ignore_case)) {
2426 return true;
2427 }
2428 }
2429 return false;
2430}
2431function str_before($str, $needle)
2432{
2433 $pos = strpos($str, $needle);
2434 if ($pos !== false) {
2435 $before = substr($str, 0, $pos);
2436 return strlen($before) ? $before : false;
2437 } else {
2438 return false;
2439 }
2440}
2441function pad_zeros($number, $zeros)
2442{
2443 if (str_has($number, '.')) {
2444 preg_match('#\.(\d+)$#', $number, $match);
2445 $number .= str_repeat('0', $zeros-strlen($match[1]));
2446 return $number;
2447 } else {
2448 return $number.'.'.str_repeat('0', $zeros);
2449 }
2450}
2451function charset_fix_invalid($s)
2452{
2453 $fix = '???????????';
2454 $s = str_replace(str_array($fix), '', $s);
2455 return $s;
2456}
2457function charset_is_invalid($s)
2458{
2459 $fix = '???????????';
2460 $fix = str_array($fix);
2461 foreach ($fix as $char) {
2462 if (str_has($s, $char)) {
2463 return true;
2464 }
2465 }
2466 return false;
2467}
2468function charset_fix($string)
2469{
2470 // UTF-8 && WIN-1250 => ISO-8859-2
2471 // todo: is checking required? redundant computing?
2472 if (charset_win_is($string)) {
2473 $string = charset_win_fix($string);
2474 }
2475 if (charset_utf_is($string)) {
2476 $string = charset_utf_fix($string);
2477 }
2478 return $string;
2479}
2480function charset_win_is($string)
2481{
2482 $win = '??????????????????';
2483 $iso = '??????????????????';
2484 for ($i=0; $i<strlen($win); $i++) {
2485 if ($win{$i} != $iso{$i}) {
2486 if (strstr($string, $win{$i}) !== false) {
2487 return true;
2488 }
2489 }
2490 }
2491 return false;
2492}
2493function charset_win_fix($string)
2494{
2495 $win = '??????????????????';
2496 $iso = '??????????????????';
2497 $srh = array();
2498 $rpl = array();
2499 for ($i = 0; $i < strlen($win); $i++) {
2500 if ($win{$i} != $iso{$i}) {
2501 $srh[] = $win{$i};
2502 $rpl[] = $iso{$i};
2503 }
2504 }
2505 $string = str_replace($srh, $rpl, $string);
2506 return $string;
2507}
2508function charset_utf_is($string)
2509{
2510 $utf_iso = array(
2511 "\xc4\x85" => "\xb1",
2512 "\xc4\x84" => "\xa1",
2513 "\xc4\x87" => "\xe6",
2514 "\xc4\x86" => "\xc6",
2515 "\xc4\x99" => "\xea",
2516 "\xc4\x98" => "\xca",
2517 "\xc5\x82" => "\xb3",
2518 "\xc5\x81" => "\xa3",
2519 "\xc3\xb3" => "\xf3",
2520 "\xc3\x93" => "\xd3",
2521 "\xc5\x9b" => "\xb6",
2522 "\xc5\x9a" => "\xa6",
2523 "\xc5\xba" => "\xbc",
2524 "\xc5\xb9" => "\xac",
2525 "\xc5\xbc" => "\xbf",
2526 "\xc5\xbb" => "\xaf",
2527 "\xc5\x84" => "\xf1",
2528 "\xc5\x83" => "\xd1",
2529 // xmlhttprequest utf-8 encoding
2530 "%u0104" => "\xA1",
2531 "%u0106" => "\xC6",
2532 "%u0118" => "\xCA",
2533 "%u0141" => "\xA3",
2534 "%u0143" => "\xD1",
2535 "%u00D3" => "\xD3",
2536 "%u015A" => "\xA6",
2537 "%u0179" => "\xAC",
2538 "%u017B" => "\xAF",
2539 "%u0105" => "\xB1",
2540 "%u0107" => "\xE6",
2541 "%u0119" => "\xEA",
2542 "%u0142" => "\xB3",
2543 "%u0144" => "\xF1",
2544 "%u00D4" => "\xF3",
2545 "%u015B" => "\xB6",
2546 "%u017A" => "\xBC",
2547 "%u017C" => "\xBF"
2548 );
2549 foreach ($utf_iso as $k => $v) {
2550 if (strpos($string, $k) !== false) {
2551 return true;
2552 }
2553 }
2554 return false;
2555}
2556function charset_utf_fix($string)
2557{
2558 $utf_iso = array(
2559 "\xc4\x85" => "\xb1",
2560 "\xc4\x84" => "\xa1",
2561 "\xc4\x87" => "\xe6",
2562 "\xc4\x86" => "\xc6",
2563 "\xc4\x99" => "\xea",
2564 "\xc4\x98" => "\xca",
2565 "\xc5\x82" => "\xb3",
2566 "\xc5\x81" => "\xa3",
2567 "\xc3\xb3" => "\xf3",
2568 "\xc3\x93" => "\xd3",
2569 "\xc5\x9b" => "\xb6",
2570 "\xc5\x9a" => "\xa6",
2571 "\xc5\xba" => "\xbc",
2572 "\xc5\xb9" => "\xac",
2573 "\xc5\xbc" => "\xbf",
2574 "\xc5\xbb" => "\xaf",
2575 "\xc5\x84" => "\xf1",
2576 "\xc5\x83" => "\xd1",
2577 // xmlhttprequest uses different encoding
2578 "%u0104" => "\xA1",
2579 "%u0106" => "\xC6",
2580 "%u0118" => "\xCA",
2581 "%u0141" => "\xA3",
2582 "%u0143" => "\xD1",
2583 "%u00D3" => "\xD3",
2584 "%u015A" => "\xA6",
2585 "%u0179" => "\xAC",
2586 "%u017B" => "\xAF",
2587 "%u0105" => "\xB1",
2588 "%u0107" => "\xE6",
2589 "%u0119" => "\xEA",
2590 "%u0142" => "\xB3",
2591 "%u0144" => "\xF1",
2592 "%u00D4" => "\xF3",
2593 "%u015B" => "\xB6",
2594 "%u017A" => "\xBC",
2595 "%u017C" => "\xBF"
2596 );
2597 return str_replace(array_keys($utf_iso), array_values($utf_iso), $string);
2598}
2599function str_starts_with($str, $start, $ignore_case = false)
2600{
2601 if ($ignore_case) {
2602 $str = str_upper($str);
2603 $start = str_upper($start);
2604 }
2605 if (!strlen($str) && !strlen($start)) {
2606 return true;
2607 }
2608 if (!strlen($start)) {
2609 trigger_error('str_starts_with() failed, start arg cannot be empty', E_USER_ERROR);
2610 }
2611 if (strlen($start) > strlen($str)) {
2612 return false;
2613 }
2614 for ($i = 0; $i < strlen($start); $i++) {
2615 if ($start{$i} != $str{$i}) {
2616 return false;
2617 }
2618 }
2619 return true;
2620}
2621function str_ends_with($str, $end, $ignore_case = false)
2622{
2623 if ($ignore_case) {
2624 $str = str_upper($str);
2625 $end = str_upper($end);
2626 }
2627 if (!strlen($str) && !strlen($end)) {
2628 return true;
2629 }
2630 if (!strlen($end)) {
2631 trigger_error('str_ends_with() failed, end arg cannot be empty', E_USER_ERROR);
2632 }
2633 if (strlen($end) > strlen($str)) {
2634 return false;
2635 }
2636 return str_starts_with(strrev($str), strrev($end));
2637 return true;
2638}
2639function str_cut_start($str, $start)
2640{
2641 if (str_starts_with($str, $start)) {
2642 $str = substr($str, strlen($start));
2643 }
2644 return $str;
2645}
2646function str_cut_end($str, $end)
2647{
2648 if (str_ends_with($str, $end)) {
2649 $str = substr($str, 0, -strlen($end));
2650 }
2651 return $str;
2652}
2653function file_get($file)
2654{
2655 return file_get_contents($file);
2656}
2657function file_put($file, $s)
2658{
2659 $fp = fopen($file, 'wb') or trigger_error('fopen() failed: '.$file, E_USER_ERROR);
2660 if ($fp) {
2661 fwrite($fp, $s);
2662 fclose($fp);
2663 }
2664}
2665function file_date($file)
2666{
2667 return date('Y-m-d H:i:s', filemtime($file));
2668}
2669function dir_exists($dir)
2670{
2671 return file_exists($dir) && !is_file($dir);
2672}
2673function dir_delete_old_files($dir, $ext = array(), $sec)
2674{
2675 // NOT USED right now.
2676 // older than x seconds
2677 $files = dir_read($dir, null, $ext);
2678 $time = time() - $sec;
2679 foreach ($files as $file) {
2680 if (file_time($file) < $time) {
2681 unlink($file);
2682 }
2683 }
2684}
2685global $_error, $_error_style;
2686$_error = array();
2687$_error_style = '';
2688
2689function error($msg = null)
2690{
2691 if (isset($msg) && func_num_args() > 1) {
2692 $args = func_get_args();
2693 $msg = call_user_func_array('sprintf', $args);
2694 }
2695 global $_error, $_error_style;
2696 if (isset($msg)) {
2697 $_error[] = $msg;
2698 }
2699 if (!count($_error)) {
2700 return null;
2701 }
2702 if (count($_error) == 1) {
2703 return sprintf('<div class="error" style="%s">%s</div>', $_error_style, $_error[0]);
2704 }
2705 $ret = '<div class="error" style="'.$_error_style.'">Following errors appeared:<ul>';
2706 foreach ($_error as $msg) {
2707 $ret .= sprintf('<li>%s</li>', $msg);
2708 }
2709 $ret .= '</ul></div>';
2710 return $ret;
2711}
2712function timestamp($time, $span = true)
2713{
2714 $time_base = $time;
2715 $time = substr($time, 0, 16);
2716 $time2 = substr($time, 0, 10);
2717 $today = date('Y-m-d');
2718 $yesterday = date('Y-m-d', time()-3600*24);
2719 if ($time2 == $today) {
2720 if (substr($time_base, -8) == '00:00:00') {
2721 $time = 'Today';
2722 } else {
2723 $time = 'Today'.substr($time, -6);
2724 }
2725 } else if ($time2 == $yesterday) {
2726 $time = 'Yesterday'.substr($time, -6);
2727 }
2728 return '<span style="white-space: nowrap;">'.$time.'</span>';
2729}
2730function str_lower($str)
2731{
2732 /* strtolower iso-8859-2 compatible */
2733 $lower = str_array(iso_chars_lower());
2734 $upper = str_array(iso_chars_upper());
2735 $str = str_replace($upper, $lower, $str);
2736 $str = strtolower($str);
2737 return $str;
2738}
2739function str_upper($str)
2740{
2741 /* strtoupper iso-8859-2 compatible */
2742 $lower = str_array(iso_chars_lower());
2743 $upper = str_array(iso_chars_upper());
2744 $str = str_replace($lower, $upper, $str);
2745 $str = strtoupper($str);
2746 return $str;
2747}
2748function str_array($str)
2749{
2750 $arr = array();
2751 for ($i = 0; $i < strlen($str); $i++) {
2752 $arr[$i] = $str{$i};
2753 }
2754 return $arr;
2755}
2756function iso_chars()
2757{
2758 return iso_chars_lower().iso_chars_upper();
2759}
2760function iso_chars_lower()
2761{
2762 return '?????????';
2763}
2764function iso_chars_upper()
2765{
2766 return '?????????';
2767}
2768function array_first_key($arr)
2769{
2770 $arr2 = $arr;
2771 reset($arr);
2772 list($key, $val) = each($arr);
2773 return $key;
2774}
2775function array_first($arr)
2776{
2777 return array_first_value($arr);
2778}
2779function array_first_value($arr)
2780{
2781 $arr2 = $arr;
2782 return array_shift($arr2);
2783}
2784function array_col_values($arr, $col)
2785{
2786 $ret = array();
2787 foreach ($arr as $k => $row) {
2788 $ret[] = $row[$col];
2789 }
2790 return $ret;
2791}
2792function array_col_values_unique($arr, $col)
2793{
2794 return array_unique(array_col_values($arr, $col));
2795}
2796function array_col_match($rows, $col, $pattern)
2797{
2798 if (!count($rows)) {
2799 trigger_error('array_col_match(): array is empty', E_USER_ERROR);
2800 }
2801 $ret = true;
2802 foreach ($rows as $row) {
2803 if (!preg_match($pattern, $row[$col])) {
2804 return false;
2805 }
2806 }
2807 return true;
2808}
2809function array_col_match_unique($rows, $col, $pattern)
2810{
2811 if (!array_col_match($rows, $col, $pattern)) {
2812 return false;
2813 }
2814 return count($rows) == count(array_col_values_unique($rows, $col));
2815}
2816function redirect($url)
2817{
2818 $url = url($url);
2819 header("Location: $url");
2820 exit;
2821}
2822function redirect_notify($url, $msg)
2823{
2824 if (strpos($msg, '<') === false) {
2825 $msg = sprintf('<b>%s</b>', $msg);
2826 }
2827 cookie_set('flash_notify', $msg);
2828 redirect($url);
2829}
2830function redirect_ok($url, $msg)
2831{
2832 if (strpos($msg, '<') === false) {
2833 $msg = sprintf('<b>%s</b>', $msg);
2834 }
2835 cookie_set('flash_ok', $msg);
2836 redirect($url);
2837}
2838function redirect_error($url, $msg)
2839{
2840 if (strpos($msg, '<') === false) {
2841 $msg = sprintf('<b>%s</b>', $msg);
2842 }
2843 cookie_set('flash_error', $msg);
2844 redirect($url);
2845}
2846function flash()
2847{
2848 static $is_style = false;
2849
2850 $flash_error = cookie_get('flash_error');
2851 $flash_ok = cookie_get('flash_ok');
2852 $flash_notify = cookie_get('flash_notify');
2853
2854 $flash_error = filter_allow_tags($flash_error, '<b><i><u><br><span>');
2855 $flash_ok = filter_allow_tags($flash_ok, '<b><i><u><br><span>');
2856 $flash_notify = filter_allow_tags($flash_notify, '<b><i><u><br><span>');
2857
2858 if (!($flash_error || $flash_ok || $flash_notify)) {
2859 return false;
2860 }
2861
2862 ob_start();
2863 ?>
2864
2865 <?php if (!$is_style): ?>
2866 <style type="text/css">
2867 #flash { background: #ffffd7; padding: 0.3em; padding-bottom: 0.15em; border: #ddd 1px solid; margin-bottom: 1em; }
2868 #flash div { padding: 0em 0em; }
2869 #flash table { font-weight: normal; }
2870 #flash td { text-align: left; }
2871 </style>
2872 <?php endif; ?>
2873
2874 <div id="flash" ondblclick="document.getElementById('flash').style.display='none';">
2875 <table width="100%" ondblclick="document.getElementById('flash').style.display='none';"><tr>
2876 <td style="line-height: 14px;"><?php echo $flash_error ? $flash_error : ($flash_ok ? $flash_ok : $flash_notify); ?></td></tr></table>
2877 </div>
2878
2879 <?php
2880 $cont = ob_get_contents();
2881 ob_end_clean();
2882
2883 if ($flash_error) cookie_del('flash_error');
2884 else if ($flash_ok) cookie_del('flash_ok');
2885 else if ($flash_notify) cookie_del('flash_notify');
2886
2887 $is_style = true;
2888
2889 return $cont;
2890}
2891function filter($post, $filters)
2892{
2893 if (is_string($filters))
2894 {
2895 $filter = $filters;
2896 $func = 'filter_'.$filter;
2897 foreach ($post as $key => $val) {
2898 $post[$key] = call_user_func($func, $post[$key]);
2899 }
2900 return $post;
2901 }
2902 foreach ($filters as $key => $filter)
2903 {
2904 if (!array_key_exists($key, $post)) {
2905 return trigger_error(sprintf('filter() failed. Key missing = %s.', $key), E_USER_ERROR);
2906 }
2907 $func = 'filter_'.$filter;
2908 if (!function_exists($func)) {
2909 return trigger_error(sprintf('filter() failed. Filter missing = %s.', $func), E_USER_ERROR);
2910 }
2911 $post[$key] = call_user_func($func, $post[$key]);
2912 }
2913 return $post;
2914}
2915function filter_html($s)
2916{
2917 if (req_gpc_has($s)) {
2918 $s = html_tags_undo($s);
2919 }
2920 return html(trim($s));
2921}
2922function filter_allow_tags($s, $allow)
2923{
2924 if (req_gpc_has($s)) {
2925 $s = html_tags_undo($s);
2926 }
2927 return html_allow_tags($s, $allow);
2928}
2929function filter_allow_html($s)
2930{
2931 global $SafeHtml;
2932 if (!isset($SafeHtml)) {
2933 include_once 'inc/SafeHtml.php';
2934 }
2935 if (req_gpc_has($s)) {
2936 $s = html_tags_undo($s);
2937 }
2938 if (in_array(trim(strtolower($s)), array('<br>', '<p> </p>'))) {
2939 return '';
2940 }
2941 $SafeHtml->clear();
2942 $s = $SafeHtml->parse($s);
2943 return trim($s);
2944}
2945function filter_allow_html_script($s)
2946{
2947 if (in_array(trim(strtolower($s)), array('<br>', '<p> </p>'))) {
2948 return '';
2949 }
2950 if (req_gpc_has($s)) {
2951 $s = html_tags_undo($s);
2952 }
2953 return trim($s);
2954}
2955function filter_editor($s)
2956{
2957 return filter_allow_html($s);
2958}
2959function date_now()
2960{
2961 return date('Y-m-d H:i:s');
2962}
2963function guess_pk($rows)
2964{
2965 if (!count($rows)) {
2966 return false;
2967 }
2968 $patterns = array('#^\d+$#', '#^[^\s]+$#');
2969 $row = array_first($rows);
2970 foreach ($patterns as $pattern)
2971 {
2972 foreach ($row as $col => $v) {
2973 if ($v && preg_match($pattern, $v)) {
2974 if (array_col_match_unique($rows, $col, $pattern)) {
2975 return $col;
2976 }
2977 }
2978 }
2979 }
2980 return false;
2981}
2982function layout_start($title='')
2983{
2984 global $page_charset;
2985 $flash = flash();
2986 ?>
2987
2988 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2989 <html>
2990 <head>
2991 <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
2992 <title><?php echo $title;?></title>
2993 <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
2994 <script>
2995 function $(id)
2996 {
2997 if (typeof id == 'string') return document.getElementById(id);
2998 return id;
2999 }
3000 </script>
3001 </head>
3002 <body>
3003
3004 <?php layout(); ?>
3005
3006 <?php if ($flash) { echo $flash; } ?>
3007
3008 <?php
3009}
3010function layout_end()
3011{
3012 ?>
3013 <?php powered_by(); ?>
3014 </body>
3015 </html>
3016 <?php
3017}
3018function powered_by()
3019{
3020 ?>
3021 <script>
3022 function link_noreferer(link)
3023 {
3024 // Tested: Chrome, Firefox, Inetrnet Explorer, Opera.
3025 var w = window.open("about:blank", "_blank");
3026 w.document.open();
3027 w.document.write("<"+"!doctype html>");
3028 w.document.write("<"+"html><"+"head>");
3029 w.document.write("<"+"title>Secure redirection - no referer</title>");
3030 w.document.write("<"+"style>body { font: 11px Tahoma; }<"+"/style>");
3031 w.document.write("<"+"meta http-equiv=refresh content='10;url="+link+"'>");
3032 // Meta.setAttribute() doesn't work on firefox.
3033 // Firefox: needs document.write('<meta>')
3034 // IE: the firefox workaround doesn't work on ie, but we can use a normal redirection
3035 // as IE is already not sending the referer because it does not do it when using
3036 // open.window, besides the blank url in address bar works fine (about:blank).
3037 // Opera: firefox fix works.
3038 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>");
3039 w.document.write("<"+"/head><"+"body>");
3040 w.document.write("<"+"h1>Secure redirection - no referer<"+"/h1>");
3041 w.document.write("<"+"p>This is a secure redirection that hides the HTTP REFERER header - using javascript and meta refresh combination.");
3042 w.document.write("<br>The site you are being redirected will not know the location of the dbkiss script on your site.<"+"/p>");
3043 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>");
3044 w.document.write("<"+"/body><"+"/html>");
3045 w.document.close();
3046 }
3047 </script>
3048 <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>
3049 <?php
3050}
3051
3052?>
3053<?php if (get('import')): ?>
3054
3055 <?php
3056
3057 // ----------------------------------------------------------------
3058 // IMPORT
3059 // ----------------------------------------------------------------
3060
3061 ?>
3062
3063 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
3064 <html>
3065 <head>
3066 <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
3067 <title><?php echo $db_name_h1?$db_name_h1:$db_name;?> > Import</title>
3068 <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
3069 </head>
3070 <body>
3071
3072 <?php layout(); ?>
3073 <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>
3074 <?php conn_info(); ?>
3075
3076 <?php $files = sql_files(); ?>
3077
3078 <?php if (count($files)): ?>
3079 <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
3080 <table class="none" cellspacing="0" cellpadding="0">
3081 <tr>
3082 <td>SQL file:</th>
3083 <td><select name="sqlfile"><option value="" selected="selected"></option><?php echo options($files);?></select></td>
3084 <td><input type="checkbox" name="ignore_errors" id="ignore_errors" value="1"></td>
3085 <td><label for="ignore_errors">ignore errors</label></td>
3086 <td><input type="checkbox" name="transaction" id="transaction" value="1"></td>
3087 <td><label for="transaction">transaction</label></td>
3088 <td><input type="checkbox" name="force_myisam" id="force_myisam" value="1"></td>
3089 <td><label for="force_myisam">force myisam</label></td>
3090 <td><input type="text" size="5" name="query_start" value=""></td>
3091 <td>query start</td>
3092 <td><input type="submit" value="Import"></td>
3093 </tr>
3094 </table>
3095 </form>
3096 <br>
3097 <?php else: ?>
3098 No sql files found in current directory.
3099 <?php endif; ?>
3100
3101 <?php powered_by(); ?>
3102
3103 </body></html>
3104
3105<?php exit; endif; ?>
3106<?php if ('editrow' == get('action')): ?>
3107<?php
3108 function dbkiss_filter_id($id)
3109 {
3110 if (preg_match('#^[_a-z][a-z0-9_\-]*$#i', $id)) {
3111 return $id;
3112 }
3113 return false;
3114 }
3115
3116 $get = get(array(
3117 'table' => 'string',
3118 'pk' => 'string',
3119 'id' => 'string'
3120 ));
3121
3122 $get['table'] = html_once($get['table']);
3123 $get['pk'] = html_once($get['pk']);
3124
3125 $title_edit = sprintf('Edit row (%s=%s)', $get['pk'], $get['id']);
3126 $title = ' > '.$get['table'].' > '.$title_edit;
3127
3128 if (!dbkiss_filter_id($get['table'])) {
3129 error('Invalid table name');
3130 }
3131 if (!dbkiss_filter_id($get['pk'])) {
3132 error('Invalid pk');
3133 }
3134
3135 $row = false;
3136
3137 if (!error())
3138 {
3139 $table_enq = quote_table($get['table']);
3140 $test = db_row("SELECT * FROM $table_enq");
3141 if ($test) {
3142 if (!array_key_exists($get['pk'], $test)) {
3143 error('Invalid pk');
3144 }
3145 }
3146 if (!error())
3147 {
3148 $table_enq = quote_table($get['table']);
3149 $query = db_bind("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
3150 $query = db_limit($query, 0, 2);
3151 $rows = db_list($query);
3152 if (count($rows) > 1) {
3153 error('Invalid pk: found more than one row with given id');
3154 } else if (count($rows) == 0) {
3155 error('Row not found');
3156 } else {
3157 $row = $rows[0];
3158 $row_id = $row[$get['pk']];
3159 }
3160 }
3161 }
3162
3163 if ($row) {
3164 $types = table_types2($get['table']);
3165 }
3166
3167 $edit_actions_assoc = array(
3168 'update' => 'Update',
3169 'update_pk' => 'Overwrite pk',
3170 'insert' => 'Copy row (insert)',
3171 'delete' => 'Delete'
3172 );
3173
3174 $edit_action = post('dbkiss_action');
3175
3176 if ($_ENV['IS_GET'])
3177 {
3178 $edit_action = array_first_key($edit_actions_assoc);
3179 $post = $row;
3180 }
3181
3182 if ($_ENV['IS_POST'])
3183 {
3184 if (!array_key_exists($edit_action, $edit_actions_assoc)) {
3185 $edit_action = '';
3186 error('Invalid action');
3187 }
3188
3189 $post = array();
3190 foreach ($row as $k => $v) {
3191 if (array_key_exists($k, $_POST)) {
3192 $val = (string) $_POST[$k];
3193 if ('null' == $val) {
3194 $val = null;
3195 }
3196 if ('int' == $types[$k]) {
3197 if (!strlen($val)) {
3198 $val = null;
3199 }
3200 if (!(preg_match('#^-?\d+$#', $val) || is_null($val))) {
3201 error('%s: invalid value', $k);
3202 }
3203 }
3204 if ('float' == $types[$k]) {
3205 if (!strlen($val)) {
3206 $val = null;
3207 }
3208 $val = str_replace(',', '.', $val);
3209 if (!(is_numeric($val) || is_null($val))) {
3210 error('%s: invalid value', $k);
3211 }
3212 }
3213 if ('time' == $types[$k]) {
3214 if (!strlen($val)) {
3215 $val = null;
3216 }
3217 if ('now' == $val) {
3218 $val = date_now();
3219 }
3220 }
3221 $post[$k] = $val;
3222 } else {
3223 error('Missing key: %s in POST', $k);
3224 }
3225 }
3226
3227 if ('update' == $edit_action)
3228 {
3229 if ($post[$get['pk']] != $row[$get['pk']]) {
3230 if (count($row) != 1) { // Case: more than 1 column
3231 error('%s: cannot change pk on UPDATE', $get['pk']);
3232 }
3233 }
3234 }
3235 if ('update_pk' == $edit_action)
3236 {
3237 if ($post[$get['pk']] == $row[$get['pk']]) {
3238 error('%s: selected action Overwrite pk, but pk value has not changed', $get['pk']);
3239 }
3240 }
3241 if ('insert' == $edit_action)
3242 {
3243 if (strlen($post[$get['pk']])) {
3244 $table_enq = quote_table($get['table']);
3245 $test = db_row("SELECT * FROM $table_enq WHERE {$get['pk']} = %0", array($post[$get['pk']]));
3246 if ($test) {
3247 error('%s: there is already a record with that id', $get['pk']);
3248 }
3249 }
3250 }
3251
3252 if (!error())
3253 {
3254 $post2 = $post;
3255 if ('update' == $edit_action)
3256 {
3257 if (count($row) != 1) { // Case: more than 1 column
3258 unset($post2[$get['pk']]);
3259 }
3260 db_update($get['table'], $post2, array($get['pk'] => $row_id));
3261 if (db_error()) {
3262 error('<font color="red"><b>DB error</b></font>: '.db_error());
3263 } else {
3264 if (count($row) == 1) { // Case: only 1 column
3265 redirect_ok(url(self(), array('id'=>$post[$get['pk']])), 'Row updated');
3266 } else {
3267 redirect_ok(self(), 'Row updated');
3268 }
3269 }
3270 }
3271 if ('update_pk' == $edit_action)
3272 {
3273 @db_update($get['table'], $post2, array($get['pk'] => $row_id));
3274 if (db_error()) {
3275 error('<font color="red"><b>DB error</b></font>: '.db_error());
3276 } else {
3277 $url = url(self(), array('id' => $post[$get['pk']]));
3278 redirect_ok($url, 'Row updated (pk overwritten)');
3279 }
3280 }
3281 if ('insert' == $edit_action)
3282 {
3283 $new_id = false;
3284 if (!strlen($post2[$get['pk']])) {
3285 unset($post2[$get['pk']]);
3286 } else {
3287 $new_id = $post2[$get['pk']];
3288 }
3289 @db_insert($get['table'], $post2);
3290 if (db_error()) {
3291 error('<font color="red"><b>DB error</b></font>: '.db_error());
3292 } else {
3293 if (!$new_id) {
3294 $new_id = db_insert_id($get['table'], $get['pk']);
3295 }
3296 $url = url(self(), array('id'=>$new_id));
3297 $msg = sprintf('Row inserted (%s=%s)', $get['pk'], $new_id);
3298 redirect_ok($url, $msg);
3299 }
3300 }
3301 if ('delete' == $edit_action)
3302 {
3303 $table_enq = quote_table($get['table']);
3304 @db_exe("DELETE FROM $table_enq WHERE {$get['pk']} = %0", $get['id']);
3305 if (db_error()) {
3306 error('<font color="red"><b>DB error</b></font>: '.db_error());
3307 } else {
3308 redirect_ok(self(), 'Row deleted');
3309 }
3310 }
3311 }
3312 }
3313
3314 ?>
3315<?php layout_start($title_edit); ?>
3316 <h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span><?php echo $title;?></h1>
3317
3318 <?php echo error();?>
3319
3320 <?php if ($row): ?>
3321
3322 <form action="<?php echo self();?>" method="post">
3323
3324 <?php echo radio_assoc($edit_action, $edit_actions_assoc, 'dbkiss_action');?></td>
3325 <br>
3326
3327 <table cellspacing="1" class="ls ls2">
3328 <?php foreach ($post as $k => $v): if (is_null($v)) { $v = 'null'; } $v = htmlspecialchars($v); ?>
3329 <tr>
3330 <th><?php echo $k;?>:</th>
3331 <td>
3332 <?php if ('int' == $types[$k]): ?>
3333 <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="11">
3334 <?php elseif ('char' == $types[$k]): ?>
3335 <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="50">
3336 <?php elseif (in_array($types[$k], array('text', 'mediumtext', 'longtext')) || str_has($types[$k], 'blob')): ?>
3337 <textarea name="<?php echo $k;?>" cols="80" rows="<?php echo $k=='notes'?10:10;?>"><?php echo html_once($v);?></textarea>
3338 <?php else: ?>
3339 <input type="text" name="<?php echo $k;?>" value="<?php echo html_once($v);?>" size="30">
3340 <?php endif; ?>
3341 </td>
3342 <td valign="top"><?php echo $types[$k];?></td>
3343 </tr>
3344 <?php endforeach; ?>
3345 <tr>
3346 <td colspan="3" class="none">
3347 <input type="submit" wait="1" block="1" class="button" value="Edit">
3348 </td>
3349 </tr>
3350 </table>
3351
3352 </form>
3353
3354 <?php endif; ?>
3355
3356 <?php layout_end(); ?>
3357
3358<?php exit; endif; ?>
3359<?php if (isset($_GET['execute_sql']) && $_GET['execute_sql']): ?>
3360<?php
3361
3362function listing($base_query, $md5_get = false)
3363{
3364 global $db_driver, $db_link;
3365
3366 $md5_i = false;
3367 if ($md5_get) {
3368 preg_match('#_(\d+)$#', $md5_get, $match);
3369 $md5_i = $match[1];
3370 }
3371
3372 $base_query = trim($base_query);
3373 $base_query = str_cut_end($base_query, ';');
3374
3375 $query = $base_query;
3376 $ret = array('msg'=>'', 'error'=>'', 'data_html'=>false);
3377 $limit = 25;
3378 $offset = get('offset','int');
3379 $page = floor($offset / $limit + 1);
3380
3381 if ($query) {
3382 if (is_select($query) && !preg_match('#\s+LIMIT\s+\d+#i', $query) && !preg_match('#into\s+outfile\s+#', $query)) {
3383 $query = db_limit($query, $offset, $limit);
3384 } else {
3385 $limit = false;
3386 }
3387 $time = time_start();
3388 if (!db_is_safe($query, true)) {
3389 $ret['error'] = 'Detected UPDATE/DELETE without WHERE condition (put WHERE 1=1 if you want to execute this query)';
3390 return $ret;
3391 }
3392 $rs = @db_query($query);
3393 if ($rs) {
3394 if ($rs === true) {
3395 if ('mysql' == $db_driver)
3396 {
3397 $affected = mysql_affected_rows($db_link);
3398 $time = time_end($time);
3399 $ret['data_html'] = '<b>'.$affected.'</b> rows affected.<br>Time: <b>'.$time.'</b> sec';
3400 return $ret;
3401 }
3402 } else {
3403 if ('pgsql' == $db_driver)
3404 {
3405 $affected = @pg_affected_rows($rs);
3406 if ($affected || preg_match('#^\s*(DELETE|UPDATE)\s+#i', $query)) {
3407 $time = time_end($time);
3408 $ret['data_html'] = '<p><b>'.$affected.'</b> rows affected. Time: <b>'.$time.'</b> sec</p>';
3409 return $ret;
3410 }
3411 }
3412 }
3413
3414 $rows = array();
3415 while ($row = db_row($rs)) {
3416 $rows[] = $row;
3417 if ($limit) {
3418 if (count($rows) == $limit) { break; }
3419 }
3420 }
3421 db_free($rs);
3422
3423 if (is_select($base_query)) {
3424 $found = @db_one("SELECT COUNT(*) FROM ($base_query) AS sub");
3425 if (!is_numeric($found) || (count($rows) && !$found)) {
3426 global $COUNT_ERROR;
3427 $COUNT_ERROR = ' (COUNT ERROR) ';
3428 $found = count($rows);
3429 }
3430 } else {
3431 if (count($rows)) {
3432 $found = count($rows);
3433 } else {
3434 $found = false;
3435 }
3436 }
3437 if ($limit) {
3438 $pages = ceil($found / $limit);
3439 } else {
3440 $pages = 1;
3441 }
3442 $time = time_end($time);
3443
3444 } else {
3445 $ret['error'] = db_error();
3446 return $ret;
3447 }
3448 } else {
3449 $ret['error'] = 'No query found.';
3450 return $ret;
3451 }
3452
3453 ob_start();
3454?>
3455 <?php if (is_numeric($found)): ?>
3456 <p>
3457 Found: <b><?php echo $found;?></b><?php echo isset($GLOBALS['COUNT_ERROR'])?$GLOBALS['COUNT_ERROR']:'';?>.
3458 Time: <b><?php echo $time;?></b> sec.
3459 <?php
3460 $params = array('md5'=>$md5_get, 'offset'=>get('offset','int'));
3461 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
3462 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
3463 ?>
3464 / <a href="<?php echo url(self(), $params);?>">Refetch</a>
3465 / Export to CSV:
3466
3467 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
3468 -
3469 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
3470 -
3471 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
3472 -
3473 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a>
3474 </p>
3475 <?php else: ?>
3476 <p>Result: <b>OK</b>. Time: <b><?php echo $time;?></b> sec</p>
3477 <?php endif; ?>
3478
3479 <?php if (is_numeric($found)): ?>
3480
3481 <?php if ($pages > 1): ?>
3482 <p>
3483 <?php if ($page > 1): ?>
3484 <?php $ofs = ($page-1)*$limit-$limit; ?>
3485 <?php
3486 $params = array('md5'=>$md5_get, 'offset'=>$ofs);
3487 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
3488 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
3489 ?>
3490 <a href="<?php echo url(self(), $params);?>"><< Prev</a>
3491 <?php endif; ?>
3492 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b>
3493 <?php if ($pages > $page): ?>
3494 <?php $ofs = $page*$limit; ?>
3495 <?php
3496 $params = array('md5'=>$md5_get, 'offset'=>$ofs);
3497 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
3498 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
3499 ?>
3500 <a href="<?php echo url(self(), $params);?>">Next >></a>
3501 <?php endif; ?>
3502 </p>
3503 <?php endif; ?>
3504
3505 <script>
3506 function mark_row(tr)
3507 {
3508 var els = tr.getElementsByTagName('td');
3509 if (tr.marked) {
3510 for (var i = 0; i < els.length; i++) {
3511 els[i].style.backgroundColor = '';
3512 }
3513 tr.marked = false;
3514 } else {
3515 tr.marked = true;
3516 for (var i = 0; i < els.length; i++) {
3517 els[i].style.backgroundColor = '#ddd';
3518 }
3519 }
3520 }
3521 </script>
3522
3523 <?php if ($found): ?>
3524
3525 <?php
3526 $edit_table = table_from_query($base_query);
3527 if ($edit_table) {
3528 $edit_pk = array_first_key($rows[0]);
3529 if (is_numeric($edit_pk)) { $edit_table = false; }
3530 }
3531 if ($edit_table) {
3532 $types = table_types2($edit_table);
3533 if ($types && count($types)) {
3534 if (in_array($edit_pk, array_keys($types))) {
3535 if (!array_col_match_unique($rows, $edit_pk, '#^\d+$#')) {
3536 $edit_pk = guess_pk($rows);
3537 if (!$edit_pk) {
3538 $edit_table = false;
3539 }
3540 }
3541 } else {
3542 $edit_table = false;
3543 }
3544 } else {
3545 $edit_table = false;
3546 }
3547 }
3548 $edit_url = '';
3549 if ($edit_table) {
3550 $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$edit_table, 'pk'=>$edit_pk, 'id'=>'%s'));
3551 }
3552 ?>
3553
3554 <table class="ls" cellspacing="1">
3555 <tr>
3556 <?php if ($edit_url): ?><th>#</th><?php endif; ?>
3557 <?php foreach ($rows[0] as $col => $v): ?>
3558 <th><?php echo $col;?></th>
3559 <?php endforeach; ?>
3560 </tr>
3561 <?php foreach ($rows as $row): ?>
3562 <tr ondblclick="mark_row(this)">
3563 <?php if ($edit_url): ?>
3564 <td><a href="javascript:void(0)" onclick="popup('<?php echo sprintf($edit_url, $row[$edit_pk]);?>', 620, 500)">Edit</a> </td>
3565 <?php endif; ?>
3566 <?php
3567 $count_cols = 0;
3568 foreach ($row as $v) { $count_cols++; }
3569 ?>
3570 <?php foreach ($row as $k => $v): ?>
3571 <?php
3572 if (preg_match('#^\s*<a[^>]+>[^<]+</a>\s*$#iU', $v) && strlen(strip_tags($v)) < 50) {
3573 $v = strip_tags($v, '<a>');
3574 } else {
3575 $v = strip_tags($v);
3576 $v = str_replace(' ', ' ', $v);
3577 $v = preg_replace('#[ ]+#', ' ', $v);
3578 if (!get('full_content') && strlen($v) > 50) {
3579 if (1 == $count_cols) {
3580 $v = str_truncate($v, 255);
3581 } else {
3582 $v = str_truncate($v, 50);
3583 }
3584 }
3585 $v = html_once($v);
3586 }
3587 $nl2br = get('nl2br');
3588 if (get('full_content')) {
3589 $v = str_wrap($v, 80, '<br>');
3590 }
3591 if (get('nl2br')) {
3592 $v = nl2br($v);
3593 }
3594 //$v = stripslashes(stripslashes($v));
3595 if (@$types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
3596 && preg_match('#^\d+$#', $v))
3597 {
3598 $tmp = @date('Y-m-d H:i', $v);
3599 if ($tmp) {
3600 $v = $tmp;
3601 }
3602 }
3603 global $post;
3604 if (str_has($post['sql'], '@gethostbyaddr') && (preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $v))) {
3605 $v = $v.'<br>'.@gethostbyaddr($v);
3606 }
3607 ?>
3608 <td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td>
3609 <?php endforeach; ?>
3610 </tr>
3611 <?php endforeach; ?>
3612 </table>
3613
3614 <?php endif; ?>
3615
3616 <?php if ($pages > 1): ?>
3617 <p>
3618 <?php if ($page > 1): ?>
3619 <?php $ofs = ($page-1)*$limit-$limit; ?>
3620 <?php
3621 $params = array('md5'=>$md5_get, 'offset'=>$ofs);
3622 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
3623 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
3624 ?>
3625 <a href="<?php echo url(self(), $params);?>"><< Prev</a>
3626 <?php endif; ?>
3627 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b>
3628 <?php if ($pages > $page): ?>
3629 <?php $ofs = $page*$limit; ?>
3630 <?php
3631 $params = array('md5'=>$md5_get, 'offset'=>$ofs);
3632 if (get('only_marked') || post('only_marked')) { $params['only_marked'] = 1; }
3633 if (get('only_select') || post('only_select')) { $params['only_select'] = 1; }
3634 ?>
3635 <a href="<?php echo url(self(), $params);?>">Next >></a>
3636 <?php endif; ?>
3637 </p>
3638 <?php endif; ?>
3639
3640 <?php endif; ?>
3641
3642<?php
3643 $cont = ob_get_contents();
3644 ob_end_clean();
3645 $ret['data_html'] = $cont;
3646 return $ret;
3647}
3648
3649?>
3650<?php
3651
3652 // ----------------------------------------------------------------
3653 // EXECUTE SQL
3654 // ----------------------------------------------------------------
3655
3656 set_time_limit(0);
3657
3658 $template = get('template');
3659 $msg = '';
3660 $error = '';
3661 $top_html = '';
3662 $data_html = '';
3663
3664 $get = get(array(
3665 'popup'=> 'int',
3666 'md5' => 'string',
3667 'only_marked' => 'bool',
3668 'only_select' => 'bool'
3669 ));
3670 $post = post(array(
3671 'sql' => 'string',
3672 'perform' => 'string',
3673 'only_marked' => 'bool',
3674 'only_select' => 'bool',
3675 'save_as' => 'string',
3676 'load_from' => 'string'
3677 ));
3678
3679 if ($get['md5']) {
3680 $get['only_select'] = true;
3681 $post['only_select'] = true;
3682 }
3683
3684 if ($get['only_marked']) { $post['only_marked'] = 1; }
3685 if ($get['only_select']) { $post['only_select'] = 1; }
3686
3687 $sql_dir = false;
3688 if (defined('DBKISS_SQL_DIR')) {
3689 $sql_dir = DBKISS_SQL_DIR;
3690 }
3691
3692 if ($sql_dir) {
3693 if (!(dir_exists($sql_dir) && is_writable($sql_dir))) {
3694 if (!dir_exists($sql_dir) && is_writable('.')) {
3695 mkdir($sql_dir);
3696 } else {
3697 exit('You must create "'.$sql_dir.'" directory with write permission.');
3698 }
3699 }
3700 if (!file_exists($sql_dir.'/.htaccess')) {
3701 file_put($sql_dir.'/.htaccess', 'deny from all');
3702 }
3703 if (!file_exists($sql_dir.'/index.html')) {
3704 file_put($sql_dir.'/index.html', '');
3705 }
3706 }
3707
3708 if ('GET' == $_SERVER['REQUEST_METHOD']) {
3709 if ($sql_dir)
3710 {
3711 if ($get['md5'] && preg_match('#^(\w{32,32})_(\d+)$#', $get['md5'], $match)) {
3712 $md5_i = $match[2];
3713 $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
3714 $post['sql'] = file_get($md5_tmp);
3715 $_SERVER['REQUEST_METHOD'] = 'POST';
3716 $post['perform'] = 'execute';
3717 } else if ($get['md5'] && preg_match('#^(\w{32,32})$#', $get['md5'], $match)) {
3718 $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $match[1]);
3719 $post['sql'] = file_get($md5_tmp);
3720 $get['md5'] = '';
3721 } else {
3722 if ($get['md5']) {
3723 trigger_error('invalid md5', E_USER_ERROR);
3724 }
3725 }
3726 }
3727 } else {
3728 $get['md5'] = '';
3729 }
3730
3731 if (str_has($post['sql'], '@nl2br')) {
3732 $_GET['nl2br'] = 1;
3733 }
3734 if (str_has($post['sql'], '@full_content')) {
3735 $_GET['full_content'] = 1;
3736 }
3737
3738 $post['sql'] = trim($post['sql']);
3739 $md5 = md5($post['sql']);
3740 $md5_file = sprintf($sql_dir.'/zzz_%s.dat', $md5);
3741 if ($sql_dir && $post['sql']) {
3742 file_put($md5_file, $post['sql']);
3743 }
3744
3745 if ($sql_dir && 'save' == $post['perform'] && $post['save_as'] && $post['sql'])
3746 {
3747 $post['save_as'] = str_replace('.sql', '', $post['save_as']);
3748 if (preg_match('#^[\w ]+$#', $post['save_as'])) {
3749 $file = $sql_dir.'/'.$post['save_as'].'.sql';
3750 $overwrite = '';
3751 if (file_exists($file)) {
3752 $overwrite = ' - <b>overwritten</b>';
3753 $bak = $sql_dir.'/zzz_'.$post['save_as'].'_'.md5(file_get($file)).'.dat';
3754 copy($file, $bak);
3755 }
3756 $msg .= sprintf('<div>Sql saved: %s %s</div>', basename($file), $overwrite);
3757 file_put($file, $post['sql']);
3758 } else {
3759 error('Saving sql failed: only alphanumeric chars are allowed');
3760 }
3761 }
3762
3763 if ($sql_dir) {
3764 $load_files = dir_read($sql_dir, null, array('.sql'), 'date_desc');
3765 }
3766 $load_assoc = array();
3767 if ($sql_dir) {
3768 foreach ($load_files as $file) {
3769 $file_path = $file;
3770 $file = basename($file);
3771 $load_assoc[$file] = '('.substr(file_date($file_path), 0, 10).')'.' ' .$file;
3772 }
3773 }
3774
3775 if ($sql_dir && 'load' == $post['perform'])
3776 {
3777 $file = $sql_dir.'/'.$post['load_from'];
3778 if (array_key_exists($post['load_from'], $load_assoc) && file_exists($file)) {
3779 $msg .= sprintf('<div>Sql loaded: %s (%s)</div>', basename($file), timestamp(file_date($file)));
3780 $post['sql'] = file_get($file);
3781 $post['save_as'] = basename($file);
3782 $post['save_as'] = str_replace('.sql', '', $post['save_as']);
3783 } else {
3784 error('<div>File not found: %s</div>', $file);
3785 }
3786 }
3787
3788 // after load - md5 may change
3789 $md5 = md5($post['sql']);
3790
3791 if ($sql_dir && 'load' == $post['perform'] && !error()) {
3792 $md5_tmp = sprintf($sql_dir.'/zzz_%s.dat', $md5);
3793 file_put($md5_tmp, $post['sql']);
3794 }
3795
3796 $is_sel = false;
3797
3798 $queries = preg_split("#;(\s*--[ \t\S]*)?(\r\n|\n|\r)#U", $post['sql']);
3799 foreach ($queries as $k => $query) {
3800 $query = query_strip($query);
3801 if (str_starts_with($query, '@')) {
3802 $is_sel = true;
3803 }
3804 $queries[$k] = $query;
3805 if (!trim($query)) { unset($queries[$k]); }
3806 }
3807
3808 $sql_assoc = array();
3809 $sql_selected = false;
3810 $i = 0;
3811
3812 $params = array(
3813 'md5' => $md5,
3814 'only_marked' => $post['only_marked'],
3815 'only_select' => $post['only_select'],
3816 'offset' => ''
3817 );
3818 $sql_main_url = url(self(), $params);
3819
3820 foreach ($queries as $query) {
3821 $i++;
3822 $query = str_cut_start($query, '@');
3823 if (!is_select($query)) {
3824 continue;
3825 }
3826 $query = preg_replace('#\s+#', ' ', $query);
3827 $params = array(
3828 'md5' => $md5.'_'.$i,
3829 'only_marked' => $post['only_marked'],
3830 'only_select' => $post['only_select'],
3831 'offset' => ''
3832 );
3833 $url = url(self(), $params);
3834 if ($get['md5'] && $get['md5'] == $params['md5']) {
3835 $sql_selected = $url;
3836 }
3837 $sql_assoc[$url] = str_truncate(strip_tags($query), 80);
3838 }
3839
3840 if ('POST' == $_SERVER['REQUEST_METHOD'])
3841 {
3842 if (!$post['perform']) {
3843 $error = 'No action selected.';
3844 }
3845 if (!$error)
3846 {
3847 $time = time_start();
3848 switch ($post['perform']) {
3849 case 'execute':
3850 $i = 0;
3851 db_begin();
3852 $commit = true;
3853 foreach ($queries as $query)
3854 {
3855 $i++;
3856 if ($post['only_marked'] && !$is_sel) {
3857 if (!$get['md5']) { continue; }
3858 }
3859 if ($is_sel) {
3860 if (str_starts_with($query, '@')) {
3861 $query = str_cut_start($query, '@');
3862 } else {
3863 if (!$get['md5']) { continue; }
3864 }
3865 }
3866 if ($post['only_select'] && !is_select($query)) {
3867 continue;
3868 }
3869 if ($get['md5'] && $i != $md5_i) {
3870 continue;
3871 }
3872 if ($get['md5'] && $i == $md5_i) {
3873 if (!is_select($query)) {
3874 trigger_error('not select query', E_USER_ERROR);
3875 }
3876 }
3877
3878 $exec = listing($query, $md5.'_'.$i);
3879 $query_trunc = str_truncate(html_once($query), 1000);
3880 $query_trunc = query_color($query_trunc);
3881 $query_trunc = nl2br($query_trunc);
3882 $query_trunc = html_spaces($query_trunc);
3883 if ($exec['error']) {
3884 $exec['error'] = preg_replace('#error:#i', '', $exec['error']);
3885 $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);
3886 $commit = false;
3887 break;
3888 } else {
3889 $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);
3890 $data_html .= $query_html;
3891 $data_html .= $exec['data_html'];
3892 }
3893 }
3894 if ($commit) {
3895 db_end();
3896 } else {
3897 db_rollback();
3898 }
3899 break;
3900 }
3901 $time = time_end($time);
3902 }
3903 }
3904
3905 if ($post['only_marked'] && !$is_sel) {
3906 error('No queries marked');
3907 }
3908
3909?>
3910<?php layout_start(($db_name_h1?$db_name_h1:$db_name).' > Execute SQL'); ?>
3911 <?php if ($get['popup']): ?>
3912 <h1><span style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></span> > Execute SQL</h1>
3913 <?php else: ?>
3914 <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>
3915 <?php endif; ?>
3916
3917 <?php echo error();?>
3918
3919 <script>
3920 function sql_submit(form)
3921 {
3922 if (form.perform.value.length) {
3923 return true;
3924 }
3925 return false;
3926 }
3927 function sql_execute(form)
3928 {
3929 form.perform.value='execute';
3930 form.submit();
3931 }
3932 function sql_preview(form)
3933 {
3934 form.perform.value='preview';
3935 form.submit();
3936 }
3937 function sql_save(form)
3938 {
3939 form.perform.value='save';
3940 form.submit();
3941 }
3942 function sql_load(form)
3943 {
3944 if (form.load_from.selectedIndex)
3945 {
3946 form.perform.value='load';
3947 form.submit();
3948 return true;
3949 }
3950 button_clear(form);
3951 return false;
3952 }
3953 </script>
3954
3955 <?php if ($msg): ?>
3956 <div class="msg"><?php echo $msg;?></div>
3957 <?php endif; ?>
3958
3959 <?php echo $top_html;?>
3960
3961 <?php if (count($sql_assoc)): ?>
3962 <p>
3963 SELECT queries:
3964 <select name="sql_assoc" onchange="if (this.value.length) location=this.value">
3965 <option value="<?php echo html_once($sql_main_url);?>"></option>
3966 <?php echo options($sql_assoc, $sql_selected);?>
3967 </select>
3968 </p>
3969 <?php endif; ?>
3970
3971 <?php if ($get['md5']): ?>
3972 <?php echo $data_html;?>
3973 <?php endif; ?>
3974
3975 <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;">
3976 <input type="hidden" name="perform" value="">
3977 <div style="margin-bottom: 0.25em;">
3978 <textarea id="sql_area" name="sql" class="sql_area"><?php echo htmlspecialchars(query_upper($post['sql']));?></textarea>
3979 </div>
3980 <table cellspacing="0" cellpadding="0"><tr>
3981 <td nowrap>
3982 <input type="button" wait="1" class="button" value="Execute" onclick="sql_execute(this.form); ">
3983 </td>
3984 <td nowrap>
3985
3986 <input type="button" wait="1" class="button" value="Preview" onclick="sql_preview(this.form); ">
3987 </td>
3988 <td nowrap>
3989
3990 <input type="checkbox" name="only_marked" id="only_marked" value="1" <?php echo checked($post['only_marked'] || $get['only_marked']);?>>
3991 </td>
3992 <td nowrap>
3993 <label for="only_marked">only marked</label>
3994 </td>
3995 <td nowrap>
3996
3997 <input type="checkbox" name="only_select" id="only_select" value="1" <?php echo checked($post['only_select'] || $get['only_select']);?>>
3998 </td>
3999 <td nowrap>
4000 <label for="only_select">only SELECT</label>
4001
4002 </td>
4003 <td nowrap>
4004 <input type="text" name="save_as" value="<?php echo html_once($post['save_as']);?>">
4005
4006 </td>
4007 <td nowrap>
4008 <input type="button" wait="1" class="button" value="Save" onclick="sql_save(this.form); ">
4009
4010 </td>
4011 <td nowrap>
4012 <select name="load_from" style="width: 140px;"><option value=""></option><?php echo options($load_assoc);?></select>
4013
4014 </td>
4015 <td nowrap>
4016 <input type="button" wait="1" class="button" value="Load" onclick="return sql_load(this.form);">
4017 </td>
4018 </tr></table>
4019 </form>
4020
4021 <?php
4022
4023 if ('preview' == $post['perform'])
4024 {
4025 echo '<h2>Preview</h2>';
4026 $i = 0;
4027 foreach ($queries as $query)
4028 {
4029 $i++;
4030 $query = str_cut_start($query, '@');
4031 $query = html_once($query);
4032 $query = query_color($query);
4033 $query = nl2br($query);
4034 $query = html_spaces($query);
4035 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);
4036 }
4037 }
4038
4039 ?>
4040
4041 <?php if (!$get['md5']): ?>
4042 <script>$('sql_area').focus();</script>
4043 <?php echo $data_html;?>
4044 <?php endif; ?>
4045
4046 <?php layout_end(); ?>
4047
4048<?php exit; endif; ?>
4049<?php if (isset($_GET['viewtable']) && $_GET['viewtable']): ?>
4050
4051 <?php
4052
4053 set_time_limit(0);
4054
4055 // ----------------------------------------------------------------
4056 // VIEW TABLE
4057 // ----------------------------------------------------------------
4058
4059 $table = $_GET['viewtable'];
4060 $table_enq = quote_table($table);
4061 $count = db_one("SELECT COUNT(*) FROM $table_enq");
4062
4063 $types = table_types2($table);
4064 $columns = table_columns($table);
4065 if (!count($columns)) {
4066 $columns = array_assoc(array_keys($types));
4067 }
4068 $columns2 = $columns;
4069
4070 foreach ($columns2 as $k => $v) {
4071 $columns2[$k] = $v.' ('.$types[$k].')';
4072 }
4073 $types_group = table_types_group($types);
4074 $_GET['search'] = get('search');
4075
4076 $where = '';
4077 $found = $count;
4078 if ($_GET['search']) {
4079 $search = $_GET['search'];
4080 $cols2 = array();
4081
4082 if (get('column')) {
4083 $cols2[] = $_GET['column'];
4084 } else {
4085 $cols2 = $columns;
4086 }
4087 $where = '';
4088 $search = db_escape($search);
4089
4090 $column_type = '';
4091 if (!get('column')) {
4092 $column_type = get('column_type');
4093 } else {
4094 $_GET['column_type'] = '';
4095 }
4096
4097 $ignore_int = false;
4098 $ignore_time = false;
4099
4100 foreach ($columns as $col)
4101 {
4102 if (!get('column') && $column_type) {
4103 if ($types[$col] != $column_type) {
4104 continue;
4105 }
4106 }
4107 if (!$column_type && !is_numeric($search) && str_has($types[$col], 'int')) {
4108 $ignore_int = true;
4109 continue;
4110 }
4111 if (!$column_type && is_numeric($search) && str_has($types[$col], 'time')) {
4112 $ignore_time = true;
4113 continue;
4114 }
4115 if (get('column') && $col != $_GET['column']) {
4116 continue;
4117 }
4118 if ($where) { $where .= ' OR '; }
4119 if (is_numeric($search)) {
4120 $where .= "$col = '$search'";
4121 } else {
4122 if ('mysql' == $db_driver) {
4123 $where .= "$col LIKE '%$search%'";
4124 } else if ('pgsql' == $db_driver) {
4125 $where .= "$col ILIKE '%$search%'";
4126 } else {
4127 trigger_error('db_driver not implemented');
4128 }
4129 }
4130 }
4131 if (($ignore_int || $ignore_time) && !$where) {
4132 $where .= ' 1=2 ';
4133 }
4134 $where = 'WHERE '.$where;
4135 }
4136
4137 if ($where) {
4138 $table_enq = quote_table($table);
4139 $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
4140 }
4141
4142 $limit = 50;
4143 $offset = get('offset','int');
4144 $page = floor($offset / $limit + 1);
4145 $pages = ceil($found / $limit);
4146
4147 $pk = table_pk($table);
4148
4149 $order = "ORDER BY";
4150 if (get('order_by')) {
4151 $order .= ' '.$_GET['order_by'];
4152 } else {
4153 if ($pk) {
4154 $order .= ' '.$pk;
4155 } else {
4156 $order = '';
4157 }
4158 }
4159 if (get('order_desc')) { $order .= ' DESC'; }
4160
4161 $table_enq = quote_table($table);
4162 $base_query = "SELECT * FROM $table_enq $where $order";
4163 $rs = db_query(db_limit($base_query, $offset, $limit));
4164
4165 if ($count && $rs) {
4166 $rows = array();
4167 while ($row = db_row($rs)) {
4168 $rows[] = $row;
4169 }
4170 db_free($rs);
4171 if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
4172 $pk = guess_pk($rows);
4173 }
4174 }
4175
4176 function indenthead($str)
4177 {
4178 if (is_array($str)) {
4179 $str2 = '';
4180 foreach ($str as $k => $v) {
4181 $str2 .= sprintf('%s: %s'."\r\n", $k, $v);
4182 }
4183 $str = $str2;
4184 }
4185 $lines = explode("\n", $str);
4186 $max_len = 0;
4187 foreach ($lines as $k => $line) {
4188 $lines[$k] = trim($line);
4189 if (preg_match('#^[^:]+:#', $line, $match)) {
4190 if ($max_len < strlen($match[0])) {
4191 $max_len = strlen($match[0]);
4192 }
4193 }
4194 }
4195 foreach ($lines as $k => $line) {
4196 if (preg_match('#^[^:]+:#', $line, $match)) {
4197 $lines[$k] = str_replace($match[0], $match[0].str_repeat(' ', $max_len - strlen($match[0])), $line);
4198 }
4199 }
4200 return implode("\r\n", $lines);
4201 }
4202
4203 if (get('indenthead')) {
4204 echo '<pre>';
4205 echo 'Table: '.get('viewtable')."\r\n";
4206 echo str_repeat('-', 80)."\r\n";
4207 foreach ($rows as $row) {
4208 echo indenthead($row);
4209 echo str_repeat('-', 80)."\r\n";
4210 }
4211 echo '</pre>';
4212 exit;
4213 }
4214 ?>
4215
4216<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4217<html>
4218<head>
4219 <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
4220 <title><?php echo $db_name_h1?$db_name_h1:$db_name;?> > Table: <?php echo $table;?></title>
4221 <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
4222</head>
4223<body>
4224
4225 <?php layout(); ?>
4226
4227 <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>
4228
4229 <?php conn_info(); ?>
4230
4231 <p>
4232 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>">All tables</a>
4233 >
4234 <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><b><?php echo $table;?></b></a> (<?php echo $count;?>)
4235 /
4236
4237 Export to CSV:
4238
4239 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode('|');?>&query=<?php echo base64_encode($base_query); ?>">pipe</a>
4240 -
4241 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode("\t");?>&query=<?php echo base64_encode($base_query); ?>">tab</a>
4242 -
4243 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(',');?>&query=<?php echo base64_encode($base_query); ?>">comma</a>
4244 -
4245 <a href="<?php echo $_SERVER['PHP_SELF']; ?>?export=csv&separator=<?php echo urlencode(';');?>&query=<?php echo base64_encode($base_query); ?>">semicolon</a>
4246
4247 /
4248 Functions:
4249 <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&indenthead=1">indenthead()</a>
4250 </p>
4251
4252 <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" style="margin-bottom: 1em;">
4253 <input type="hidden" name="viewtable" value="<?php echo $table;?>">
4254 <table class="ls" cellspacing="1">
4255 <tr>
4256 <td><input type="text" name="search" value="<?php echo html_once(get('search'));?>"></td>
4257 <td><select name="column"><option value=""></option><?php echo options($columns2, get('column'));?></select></td>
4258 <td><select name="column_type"><option value=""></option><?php echo options($types_group, get('column_type'));?></select></td>
4259 <td><input type="submit" value="Search"></td>
4260 <td>
4261 order by:
4262 <select name="order_by"><option value=""></option><?php echo options($columns, get('order_by'));?></select>
4263 <input type="checkbox" name="order_desc" id="order_desc" value="1" <?php echo checked(get('order_desc'));?>>
4264 <label for="order_desc">desc</label>
4265 </td>
4266 <td>
4267 <input type="checkbox" name="full_content" id="full_content" <?php echo checked(get('full_content'));?>>
4268 <label for="full_content">full content</label>
4269 </td>
4270 <td>
4271 <input type="checkbox" name="nl2br" id="nl2br" <?php echo checked(get('nl2br'));?>>
4272 <label for="nl2br">nl2br</label>
4273 </td>
4274 </tr>
4275 </table>
4276 </form>
4277
4278 <?php if ($count): ?>
4279
4280 <?php if ($count && $count != $found): ?>
4281 <p>Found: <b><?php echo $found;?></b></p>
4282 <?php endif; ?>
4283
4284 <?php if ($found): ?>
4285
4286 <?php if ($pages > 1): ?>
4287 <p>
4288 <?php if ($page > 1): ?>
4289 <a href="<?php echo url_offset(($page-1)*$limit-$limit);?>"><< Prev</a>
4290 <?php endif; ?>
4291 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b>
4292 <?php if ($pages > $page): ?>
4293 <a href="<?php echo url_offset($page*$limit);?>">Next >></a>
4294 <?php endif; ?>
4295 </p>
4296 <?php endif; ?>
4297
4298 <script>
4299 function mark_row(tr)
4300 {
4301 var els = tr.getElementsByTagName('td');
4302 if (tr.marked) {
4303 for (var i = 0; i < els.length; i++) {
4304 els[i].style.backgroundColor = '';
4305 }
4306 tr.marked = false;
4307 } else {
4308 tr.marked = true;
4309 for (var i = 0; i < els.length; i++) {
4310 els[i].style.backgroundColor = '#ddd';
4311 }
4312 }
4313 }
4314 </script>
4315
4316 <table class="ls" cellspacing="1">
4317 <tr>
4318 <?php if ($pk): ?><th>#</th><?php endif; ?>
4319 <?php foreach ($columns as $col): ?>
4320 <?php
4321 $params = array('order_by'=>$col);
4322 $params['order_desc'] = 0;
4323 if (get('order_by') == $col) {
4324 $params['order_desc'] = get('order_desc') ? 0 : 1;
4325 }
4326 ?>
4327 <th><a style="color: #000;" href="<?php echo url(self(), $params);?>"><?php echo $col;?></a></th>
4328 <?php endforeach; ?>
4329 </tr>
4330 <?php
4331 $get_full_content = get('full_content');
4332 $get_nl2br = get('nl2br');
4333 $get_search = get('search');
4334 ?>
4335 <?php
4336 $edit_url_tpl = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>'%s'));
4337 ?>
4338 <?php foreach ($rows as $row): ?>
4339 <tr ondblclick="mark_row(this)">
4340 <?php if ($pk): ?>
4341 <?php $edit_url = sprintf($edit_url_tpl, $row[$pk]); ?>
4342 <td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a> </td>
4343 <?php endif; ?>
4344 <?php foreach ($row as $k => $v): ?>
4345 <?php
4346 if (!$get_full_content) {
4347 $v = str_truncate($v, 50);
4348 }
4349 //$v = html_once($v);
4350 $v = htmlspecialchars($v);
4351 $nl2br = $get_nl2br;
4352 if ($get_full_content) {
4353 $v = str_wrap($v, 80, '<br>');
4354 }
4355 if ($get_nl2br) {
4356 $v = nl2br($v);
4357 }
4358 //$v = stripslashes(stripslashes($v));
4359 if ($get_search) {
4360 $search = $_GET['search'];
4361 $search_quote = preg_quote($search);
4362 $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
4363 }
4364 if ($types[$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k))
4365 && preg_match('#^\d+$#', $v))
4366 {
4367 $tmp = @date('Y-m-d H:i', $v);
4368 if ($tmp) {
4369 $v = $tmp;
4370 }
4371 }
4372 ?>
4373 <td onclick="mark_col(this)" <?php echo $nl2br?'valign="top"':'';?> nowrap><?php echo is_null($row[$k])?'-':$v;?></td>
4374 <?php endforeach; ?>
4375 </tr>
4376 <?php endforeach; ?>
4377 </table>
4378
4379 <?php if ($pages > 1): ?>
4380 <p>
4381 <?php if ($page > 1): ?>
4382 <a href="<?php echo url_offset(($page-1)*$limit-$limit);?>"><< Prev</a>
4383 <?php endif; ?>
4384 Page <b><?php echo $page;?></b> of <b><?php echo $pages;?></b>
4385 <?php if ($pages > $page): ?>
4386 <a href="<?php echo url_offset($page*$limit);?>">Next >></a>
4387 <?php endif; ?>
4388 </p>
4389 <?php endif; ?>
4390
4391 <?php endif; ?>
4392
4393 <?php endif; ?>
4394
4395<?php powered_by(); ?>
4396</body>
4397</html>
4398<?php exit; endif; ?>
4399<?php if (get('searchdb')): ?>
4400<?php
4401
4402 // ----------------------------------------------------------------
4403 // SEARCH DB
4404 // ----------------------------------------------------------------
4405
4406 $get = get(array(
4407 'types' => 'array',
4408 'search' => 'string',
4409 'md5' => 'bool',
4410 'table_filter' => 'string'
4411 ));
4412 $get['search'] = trim($get['search']);
4413
4414 $tables = list_tables();
4415
4416 if ($get['table_filter']) {
4417 foreach ($tables as $k => $table) {
4418 if (!str_has_any($table, $get['table_filter'], $ignore_case = true)) {
4419 unset($tables[$k]);
4420 }
4421 }
4422 }
4423
4424 $all_types = array();
4425 $columns = array();
4426 foreach ($tables as $table) {
4427 $types = table_types2($table);
4428 $columns[$table] = $types;
4429 $types = array_values($types);
4430 $all_types = array_merge($all_types, $types);
4431 }
4432 $all_types = array_unique($all_types);
4433
4434 if ($get['search'] && $get['md5']) {
4435 $get['search'] = md5($get['search']);
4436 }
4437
4438?>
4439<?php layout_start(sprintf('%s > Search', $db_name)); ?>
4440 <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>
4441 <?php conn_info(); ?>
4442
4443 <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
4444 <input type="hidden" name="searchdb" value="1">
4445 <table class="ls" cellspacing="1">
4446 <tr>
4447 <th>Search:</th>
4448 <td>
4449 <input type="text" name="search" value="<?php echo html_once($get['search']);?>" size="40">
4450 <?php if ($get['search'] && $get['md5']): ?>
4451 md5(<?php echo html_once(get('search'));?>)
4452 <?php endif; ?>
4453 <input type="checkbox" name="md5" id="md5_label" value="1">
4454 <label for="md5_label">md5</label>
4455 </td>
4456 </tr>
4457 <tr>
4458 <th>Table filter:</th>
4459 <td><input type="text" name="table_filter" value="<?php echo html_once($get['table_filter']);?>">
4460 </tr>
4461 <tr>
4462 <th>Columns:</th>
4463 <td>
4464 <?php foreach ($all_types as $type): ?>
4465 <input type="checkbox" id="type_<?php echo $type;?>" name="types[<?php echo $type;?>]" value="1" <?php echo checked(isset($get['types'][$type]));?>>
4466 <label for="type_<?php echo $type;?>"><?php echo $type;?></label>
4467 <?php endforeach; ?>
4468 </td>
4469 </tr>
4470 <tr>
4471 <td colspan="2" class="none">
4472 <input type="submit" value="Search">
4473 </td>
4474 </tr>
4475 </table>
4476 </form>
4477
4478 <?php if ($get['search'] && !count($get['types'])): ?>
4479 <p>No columns selected.</p>
4480 <?php endif; ?>
4481
4482 <?php if ($get['search'] && count($get['types'])): ?>
4483
4484 <p>Searching <b><?php echo count($tables);?></b> tables for: <b><?php echo html_once($get['search']);?></b></p>
4485
4486 <?php $found_any = false; ?>
4487
4488 <?php set_time_limit(0); ?>
4489
4490 <?php foreach ($tables as $table): ?>
4491 <?php
4492
4493 $where = '';
4494 $cols2 = array();
4495
4496 $where = '';
4497 $search = db_escape($get['search']);
4498
4499 foreach ($columns[$table] as $col => $type)
4500 {
4501 if (!in_array($type, array_keys($get['types']))) {
4502 continue;
4503 }
4504 if ($where) {
4505 $where .= ' OR ';
4506 }
4507 if (is_numeric($search)) {
4508 $where .= "$col = '$search'";
4509 } else {
4510 if ('mysql' == $db_driver) {
4511 $where .= "$col LIKE '%$search%'";
4512 } else if ('pgsql' == $db_driver) {
4513 $where .= "$col ILIKE '%$search%'";
4514 } else {
4515 trigger_error('db_driver not implemented');
4516 }
4517 }
4518 }
4519
4520 $found = false;
4521
4522 if ($where) {
4523 $where = 'WHERE '.$where;
4524 $table_enq = quote_table($table);
4525 $found = db_one("SELECT COUNT(*) FROM $table_enq $where");
4526 }
4527
4528 if ($found) {
4529 $found_any = true;
4530 }
4531
4532 ?>
4533
4534 <?php
4535 if ($where && $found) {
4536 $limit = 10;
4537 $offset = 0;
4538 $pk = table_pk($table);
4539
4540 $order = "ORDER BY $pk";
4541 $table_enq = quote_table($table);
4542 $rs = db_query(db_limit("SELECT * FROM $table_enq $where $order", $offset, $limit));
4543
4544 $rows = array();
4545 while ($row = db_row($rs)) {
4546 $rows[] = $row;
4547 }
4548 db_free($rs);
4549 if (count($rows) && !array_col_match_unique($rows, $pk, '#^\d+$#')) {
4550 $pk = guess_pk($rows);
4551 }
4552 }
4553 ?>
4554
4555 <?php if ($where && $found): ?>
4556
4557 <p>
4558 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>
4559 Found: <b><?php echo $found;?></b>
4560 <?php if ($found > $limit): ?>
4561 <a href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>&search=<?php echo urlencode($get['search']);?>">show all >></a>
4562 <?php endif; ?>
4563 </p>
4564
4565 <table class="ls" cellspacing="1">
4566 <tr>
4567 <?php if ($pk): ?><th>#</th><?php endif; ?>
4568 <?php foreach ($columns[$table] as $col => $type): ?>
4569 <th><?php echo $col;?></th>
4570 <?php endforeach; ?>
4571 </tr>
4572 <?php foreach ($rows as $row): ?>
4573 <tr>
4574 <?php if ($pk): ?>
4575 <?php $edit_url = url(self(true), array('action'=>'editrow', 'table'=>$table, 'pk'=>$pk, 'id'=>$row[$pk])); ?>
4576 <td><a href="javascript:void(0)" onclick="popup('<?php echo $edit_url;?>', 620, 500)">Edit</a> </td>
4577 <?php endif; ?>
4578 <?php foreach ($row as $k => $v): ?>
4579 <?php
4580 $v = str_truncate($v, 50);
4581 $v = html_once($v);
4582 //$v = stripslashes(stripslashes($v));
4583 $search = $get['search'];
4584 $search_quote = preg_quote($search);
4585 if ($columns[$table][$k] == 'int' && (preg_match('#time#i', $k) || preg_match('#date#i', $k)) && preg_match('#^\d+$#', $v)) {
4586 $tmp = @date('Y-m-d H:i', $v);
4587 if ($tmp) {
4588 $v = $tmp;
4589 }
4590 }
4591 $v = preg_replace('#('.$search_quote.')#i', '<span style="background: yellow;">$1</span>', $v);
4592 ?>
4593 <td nowrap><?php echo $v;?></td>
4594 <?php endforeach; ?>
4595 </tr>
4596 <?php endforeach; ?>
4597 </table>
4598
4599 <?php endif; ?>
4600
4601 <?php endforeach; ?>
4602
4603 <?php if (!$found_any): ?>
4604 <p>No rows found.</p>
4605 <?php endif; ?>
4606
4607 <?php endif; ?>
4608
4609 <?php layout_end(); ?>
4610<?php exit; endif; ?>
4611
4612<?php
4613
4614// ----------------------------------------------------------------
4615// LIST TABLES
4616// ----------------------------------------------------------------
4617
4618$get = get(array('table_filter'=>'string'));
4619
4620?>
4621
4622<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4623<html>
4624<head>
4625 <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $page_charset;?>">
4626 <title><?php echo $db_name_h1?$db_name_h1:$db_name;?></title>
4627 <link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
4628</head>
4629<body>
4630
4631<?php layout(); ?>
4632<h1 style="<?php echo $db_name_style;?>"><?php echo $db_name_h1?$db_name_h1:$db_name;?></h1>
4633
4634<?php conn_info(); ?>
4635
4636<?php $tables = list_tables(); ?>
4637<?php $status = table_status(); ?>
4638<?php $views = list_tables(true); ?>
4639
4640<p>
4641 Tables: <b><?php echo count($tables);?></b>
4642 -
4643 Total size: <b><?php echo number_format(ceil($status['total_size']/1024),0,'',',').' KB';?></b>
4644 -
4645 Views: <b><?php echo count($views);?></b>
4646 -
4647
4648 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?searchdb=1&table_filter=<?php echo html_once($get['table_filter']);?>">Search</a>
4649 -
4650 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?import=1">Import</a>
4651 -
4652 Export all:
4653
4654 <?php if ('pgsql' == $db_driver): ?>
4655 <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>
4656 <?php else: ?>
4657 <a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?dump_all=1&table_filter=<?php echo urlencode(html_once($get['table_filter']));?>">Structure</a> ,
4658 <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>
4659 <?php endif; ?>
4660</p>
4661
4662<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get" name=table_filter_form style="margin-bottom: 0.5em;">
4663<table cellspacing="0" cellpadding="0"><tr>
4664<td style="padding-right: 3px;">Table or View:</td>
4665<td style="padding-right: 3px;"><input type="text" name="table_filter" id=table_filter value="<?php echo html_once($get['table_filter']);?>"></td>
4666<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>
4667</tr></table>
4668</form>
4669
4670<script>
4671function table_filter_keydown(e)
4672{
4673 if (!e) { e = window.event; }
4674 if (e.keyCode == 27 || e.keyCode == 33 || e.keyCode == 34 || e.keyCode == 38 || e.keyCode == 40) {
4675 document.getElementById('table_filter').blur();
4676 return;
4677 }
4678 // alt + r - reset filter input
4679 if (e.keyCode == 82 && e.altKey) {
4680 document.getElementById('table_filter').value = "";
4681 document.forms["table_filter_form"].submit();
4682 return;
4683 }
4684 // 0-9
4685 if (e.keyCode >= 48 && e.keyCode <= 57 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
4686 document.getElementById('table_filter').focus();
4687 }
4688 // a-z
4689 if (e.keyCode >= 65 && e.keyCode <= 90 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
4690 document.getElementById('table_filter').focus();
4691 }
4692}
4693document.onkeydown = table_filter_keydown;
4694</script>
4695
4696<div style="float: left;">
4697
4698 <?php
4699 $tables = table_filter($tables, $get['table_filter']);
4700 ?>
4701
4702 <?php if ($get['table_filter']): ?>
4703 <p>Tables found: <b><?php echo count($tables);?></b></p>
4704 <?php endif; ?>
4705
4706 <table class="ls" cellspacing="1">
4707 <tr>
4708 <th>Table</th>
4709 <th>Count</th>
4710 <th>Size</th>
4711 <th>Options</th>
4712 </tr>
4713 <?php foreach ($tables as $table): ?>
4714 <tr>
4715 <td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $table;?>"><?php echo $table;?></a></td>
4716 <?php
4717 if ('mysql' == $db_driver) {
4718 // $table_enq = quote_table($table);
4719 // $count = db_one("SELECT COUNT(*) FROM $table_enq");
4720 $count = $status[$table]['count'];
4721 }
4722 if ('pgsql' == $db_driver) {
4723 $count = $status[$table]['count'];
4724 if (!$count) {
4725 $table_enq = quote_table($table);
4726 $count = db_one("SELECT COUNT(*) FROM $table_enq");
4727 }
4728 }
4729 ?>
4730 <td align="right"><?php echo number_format($count,0,'',',');?></td>
4731 <td align="right"><?php echo number_format(ceil($status[$table]['size']/1024),0,'',',').' KB';?></td>
4732 <td>
4733 <a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $table;?>">Export</a>
4734 -
4735 <?php $table_enq = quote_table($table); ?>
4736 <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>
4737 <a href="javascript:void(0)" onclick="if (confirm('DROP TABLE <?php echo $table_enq;?> ?')) document.forms['drop_<?php echo $table;?>'].submit();">Drop</a>
4738 </td>
4739 </tr>
4740 <?php endforeach; ?>
4741 </table>
4742 <?php unset($table); ?>
4743
4744</div>
4745
4746<?php if (views_supported() && count($views)): ?>
4747<div style="float: left; margin-left: 2em;">
4748
4749 <?php
4750 $views = table_filter($views, $get['table_filter']);
4751 ?>
4752
4753 <?php if ($get['table_filter']): ?>
4754 <p>Views found: <b><?php echo count($views);?></b></p>
4755 <?php endif; ?>
4756
4757 <table class="ls" cellspacing="1">
4758 <tr>
4759 <th>View</th>
4760 <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>
4761 <th>Options</th>
4762 </tr>
4763 <?php foreach ($views as $view): ?>
4764 <?php $view_enq = quote_table($view); ?>
4765 <tr>
4766 <td><a class=blue href="<?php echo $_SERVER['PHP_SELF'];?>?viewtable=<?php echo $view;?>"><?php echo $view;?></a></td>
4767 <?php
4768 if (isset($_GET['views_count']) && $_GET['views_count']) {
4769 $count = db_one("SELECT COUNT(*) FROM $view_enq");
4770 } else {
4771 $count = null;
4772 }
4773 ?>
4774 <td align=right><?php echo isset($count) ? $count : '-'; ?></td>
4775 <td>
4776 <a href="<?php echo $_SERVER['PHP_SELF'];?>?dump_table=<?php echo $view;?>">Export</a>
4777 -
4778 <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="drop_<?php echo $view;?>" method="post" style="display: inline;">
4779 <input type="hidden" name="drop_view" value="<?php echo $view;?>"></form>
4780 <a href="javascript:void(0)" onclick="if (confirm('DROP VIEW <?php echo $view_enq;?> ?')) document.forms['drop_<?php echo $view;?>'].submit();">Drop</a>
4781 </td>
4782 </tr>
4783 <?php endforeach; ?>
4784 </table>
4785
4786</div>
4787<?php endif; ?>
4788
4789<div style="clear: both;"></div>
4790
4791<?php powered_by(); ?>
4792</body>
4793</html>