forked from arleincho/cis
/
dbkiss.php
4964 lines (4649 loc) · 135 KB
/
dbkiss.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
DBKiss 1.11 (2011-05-29)
Author: Cezary Tomczak [cagret@gmail.com]
Web site: http://www.gosu.pl/dbkiss/
License: BSD revised (free for any use)
*/
ob_start('ob_gzhandler');
// Some of the features in the SQL editor require creating 'dbkiss_sql' directory,
// where history of queries are kept and other data. If the script has permission
// it will create that directory automatically, otherwise you need to create that
// directory manually and make it writable. You can also set it to empty '' string,
// but some of the features in the sql editor will not work (templates, pagination)
if (!defined('DBKISS_SQL_DIR')) {
define('DBKISS_SQL_DIR', 'dbkiss_sql');
}
/*
An example configuration script that will automatically connect to localhost database.
This is useful on localhost if you don't want to see the "Connect" screen.
mysql_local.php:
---------------------------------------------------------------------
define('COOKIE_PREFIX', str_replace('.php', '', basename(__FILE__)).'_');
define('DBKISS_SQL_DIR', 'dbkiss_mysql');
$cookie = array(
'db_driver' => 'mysql',
'db_server' => 'localhost',
'db_name' => 'test',
'db_user' => 'root',
'db_pass' => 'toor',
'db_charset' => 'latin2',
'page_charset' => 'iso-8859-2',
'remember' => 1
);
foreach ($cookie as $k => $v) {
if ('db_pass' == $k) { $v = base64_encode($v); }
$k = COOKIE_PREFIX.$k;
if (!isset($_COOKIE[$k])) {
$_COOKIE[$k] = $v;
}
}
require './dbkiss.php';
---------------------------------------------------------------------
*/
/*
Changelog:
1.11
* Links in data output are now clickable. Clicking them does not reveal the location of your dbkiss script to external sites.
1.10
* Support for views in Postgresql (mysql had it already).
* Views are now displayed in a seperate listing, to the right of the tables on main page.
* 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 revealed.
1.09
* CSV export in sql editor and table view (feature sponsored by Patrick McGovern)
1.08
* date.timezone E_STRICT error fixed
1.07
* mysql tables with dash in the name generated errors, now all tables in mysql driver are
enquoted with backtick.
1.06
* postgresql fix
1.05
* export of all structure and data does take into account the table name filter on the main page,
so you can filter the tables that you want to export.
1.04
* exporting all structure/data didn't work (ob_gzhandler flush bug)
* cookies are now set using httponly option
* text editor complained about bad cr/lf in exported sql files
(mysql create table uses \n, so insert queries need to be seperated by \n and not \r\n)
1.03
* re-created array_walk_recursive for php4 compatibility
* removed stripping slashes from displayed content
* added favicon (using base64_encode to store the icon in php code, so it is still one-file database browser)
1.02
* works with short_open_tag disabled
* code optimizations/fixes
* postgresql error fix for large tables
1.01
* fix for mysql 3.23, which doesnt understand "LIMIT x OFFSET z"
1.00
* bug fixes
* minor feature enhancements
* this release is stable and can be used in production environment
0.61
* upper casing keywords in submitted sql is disabled (it also modified quoted values)
* sql error when displaying table with 0 rows
* could not connect to database that had upper case characters
*/
// todo: php error handler which cancels buffer output and exits on error
// todo: XSS and CSRF protection.
// todo: connect screen: [x] create database (if not exists) [charset]
// todo: connect screen: database (optional, if none provided will select the first database the user has access to)
// todo: mysqli driver (check if mysql extension is loaded, if not try to use mysqli)
// todo: support for the enum field type when editing row
// todo: search whole database form should appear also on main page
// todo: improve detecting primary keys when editing row (querying information_schema , for mysql > 4)
// 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
// todo: "Insert" on table view page
// todo: edit table structure
error_reporting(-1);
ini_set('display_errors', true);
if (!ini_get('date.timezone')) {
ini_set('date.timezone', 'Europe/Warsaw');
}
if (isset($_GET['dbkiss_favicon'])) {
$favicon = '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C///////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';
header('Content-type: image/vnd.microsoft.icon');
echo base64_decode($favicon);
exit();
}
if (!function_exists('array_walk_recursive'))
{
function array_walk_recursive(&$array, $func)
{
foreach ($array as $k => $v) {
if (is_array($v)) {
array_walk_recursive($array[$k], $func);
} else {
$func($array[$k], $k);
}
}
}
}
function create_links($text)
{
// Protocols: http, https, ftp, irc, svn
// Parse emails also?
$text = preg_replace('#([a-z]+://[a-zA-Z0-9\.\,\;\:\[\]\{\}\-\_\+\=\!\@\#\%\&\(\)\/\?\`\~]+)#e', 'create_links_eval("\\1")', $text);
// Excaptions:
// 1) cut last char if link ends with ":" or ";" or "." or "," - cause in 99% cases that char doesnt belong to the link
// (check if previous char was "=" then let it stay cause that could be some variable in a query, some kind of separator)
// (should we add also "-" ? But it is a valid char in links and very common, many links might end with it when creating from some title of an article?)
// 2) brackets, the link could be inside one of 3 types of brackets:
// [http://...] , {http://...}
// and most common: (http://some.com/) OR http://some.com(some description of the link)
// In these cases regular expression will catch: "http://some.com/)" AND "http://some.com(some"
// So when we catch some kind of bracket in the link we will cut it unless there is also a closing bracket in the link:
// We will not cut brackets in this link: http://en.wikipedia.org/wiki/Common_(entertainer) - wikipedia often uses brackets.
return $text;
}
function create_links_eval($link)
{
$orig_link = $link;
$cutted = "";
if (in_array($link[strlen($link)-1], array(":", ";", ".", ","))) {
$link = substr($link, 0, -1);
$cutted = $orig_link[strlen($orig_link)-1];
}
if (($pos = strpos($link, "(")) !== false) {
if (strpos($link, ")") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
} else if (($pos = strpos($link, ")")) !== false) {
if (strpos($link, "(") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
} else if (($pos = strpos($link, "[")) !== false) {
if (strpos($link, "]") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
} else if (($pos = strpos($link, "]")) !== false) {
if (strpos($link, "[") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
} else if (($pos = strpos($link, "{")) !== false) {
if (strpos($link, "}") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
} else if (($pos = strpos($link, "}")) !== false) {
if (strpos($link, "{") === false) {
$link = substr($link, 0, $pos);
$cutted = substr($orig_link, $pos);
}
}
return "<a title=\"$link\" style=\"color: #000; text-decoration: none; border-bottom: #000 1px dotted;\" href=\"javascript:;\" onclick=\"link_noreferer('$link')\">$link</a>$cutted";
}
function truncate_html($string, $length, $break_words = false, $end_str = '..')
{
// Does not break html tags whilte truncating, does not take into account chars inside tags: <b>a</b> = 1 char length.
// Break words is always TRUE - no breaking is not implemented.
// Limits: no handling of <script> tags.
$inside_tag = false;
$inside_amp = 0;
$finished = false; // finished but the loop is still running cause inside tag or amp.
$opened = 0;
$string_len = strlen($string);
$count = 0;
$ret = "";
for ($i = 0; $i < $string_len; $i++)
{
$char = $string[$i];
$nextchar = isset($string[$i+1]) ? $string[$i+1] : null;
if ('<' == $char && ('/' == $nextchar || ctype_alpha($nextchar))) {
if ('/' == $nextchar) {
$opened--;
} else {
$opened++;
}
$inside_tag = true;
}
if ('>' == $char) {
$inside_tag = false;
$ret .= $char;
continue;
}
if ($inside_tag) {
$ret .= $char;
continue;
}
if (!$finished)
{
if ('&' == $char) {
$inside_amp = 1;
$ret .= $char;
continue;
}
if (';' == $char && $inside_amp) {
$inside_amp = 0;
$count++;
$ret .= $char;
continue;
}
if ($inside_amp) {
$inside_amp++;
$ret .= $char;
if ('#' == $char || ctype_alnum($char)) {
if ($inside_amp > 7) {
$count += $inside_amp;
$inside_amp = 0;
}
} else {
$count += $inside_amp;
$inside_amp = 0;
}
continue;
}
}
$count++;
if (!$finished) {
$ret .= $char;
}
if ($count >= $length) {
if (!$inside_tag && !$inside_amp) {
if (!$finished) {
$ret .= $end_str;
$finished = true;
if (0 == $opened) {
break;
}
}
if (0 == $opened) {
break;
}
}
}
}
return $ret;
}
function table_filter($tables, $filter)
{
$filter = trim($filter);
if ($filter) {
foreach ($tables as $k => $table) {
if (!str_has_any($table, $filter, $ignore_case = true)) {
unset($tables[$k]);
}
}
}
return $tables;
}
function get($key, $type='string')
{
if (is_string($key)) {
$_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
settype($_GET[$key], $type);
if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
return $_GET[$key];
}
$vars = $key;
foreach ($vars as $key => $type) {
$_GET[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
if ('float' == $type) $_GET[$key] = str_replace(',','.',$_GET[$key]);
settype($_GET[$key], $type);
if ('string' == $type) $_GET[$key] = trim($_GET[$key]);
$vars[$key] = $_GET[$key];
}
return $vars;
}
function post($key, $type='string')
{
if (is_string($key)) {
$_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
settype($_POST[$key], $type);
if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
return $_POST[$key];
}
$vars = $key;
foreach ($vars as $key => $type) {
$_POST[$key] = isset($_POST[$key]) ? $_POST[$key] : null;
if ('float' == $type) $_POST[$key] = str_replace(',','.',$_POST[$key]);
settype($_POST[$key], $type);
if ('string' == $type) $_POST[$key] = trim($_POST[$key]);
$vars[$key] = $_POST[$key];
}
return $vars;
}
$_ENV['IS_GET'] = ('GET' == $_SERVER['REQUEST_METHOD']);
$_ENV['IS_POST'] = ('POST' == $_SERVER['REQUEST_METHOD']);
function req_gpc_has($str)
{
/* finds if value exists in GPC data, used in filter_() functions, to check whether use html_tags_undo() on the data */
foreach ($_GET as $k => $v) {
if ($str == $v) {
return true;
}
}
foreach ($_POST as $k => $v) {
if ($str == $v) {
return true;
}
}
foreach ($_COOKIE as $k => $v) {
if ($str == $v) {
return true;
}
}
return false;
}
if (ini_get('magic_quotes_gpc')) {
ini_set('magic_quotes_runtime', 0);
array_walk_recursive($_GET, 'db_magic_quotes_gpc');
array_walk_recursive($_POST, 'db_magic_quotes_gpc');
array_walk_recursive($_COOKIE, 'db_magic_quotes_gpc');
}
function db_magic_quotes_gpc(&$val)
{
$val = stripslashes($val);
}
$sql_font = 'font-size: 12px; font-family: courier new;';
$sql_area = $sql_font.' width: 708px; height: 182px; border: #ccc 1px solid; background: #f9f9f9; padding: 3px;';
if (!isset($db_name_style)) {
$db_name_style = '';
}
if (!isset($db_name_h1)) {
$db_name_h1 = '';
}
global $db_link, $db_name;
if (!defined('COOKIE_PREFIX')) {
define('COOKIE_PREFIX', 'dbkiss_');
}
define('COOKIE_WEEK', 604800); // 3600*24*7
define('COOKIE_SESS', 0);
function cookie_get($key)
{
$key = COOKIE_PREFIX.$key;
if (isset($_COOKIE[$key])) return $_COOKIE[$key];
return null;
}
function cookie_set($key, $val, $time = COOKIE_SESS)
{
$key = COOKIE_PREFIX.$key;
$expire = $time ? time() + $time : 0;
if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
setcookie($key, $val, $expire, '', '', false, true);
} else {
setcookie($key, $val, $expire);
}
$_COOKIE[$key] = $val;
}
function cookie_del($key)
{
$key = COOKIE_PREFIX.$key;
if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
setcookie($key, '', time()-3600*24, '', '', false, true);
} else {
setcookie($key, '', time()-3600*24);
}
unset($_COOKIE[$key]);
}
conn_modify('db_name');
conn_modify('db_charset');
conn_modify('page_charset');
function conn_modify($key)
{
if (array_key_exists($key, $_GET)) {
cookie_set($key, $_GET[$key], cookie_get('remember') ? COOKIE_WEEK : COOKIE_SESS);
if (isset($_GET['from']) && $_GET['from']) {
header('Location: '.$_GET['from']);
} else {
header('Location: '.$_SERVER['PHP_SELF']);
}
exit;
}
}
$db_driver = cookie_get('db_driver');
$db_server = cookie_get('db_server');
$db_name = cookie_get('db_name');
$db_user = cookie_get('db_user');
$db_pass = base64_decode(cookie_get('db_pass'));
$db_charset = cookie_get('db_charset');
$page_charset = cookie_get('page_charset');
$charset1 = array('latin1', 'latin2', 'utf8', 'cp1250');
$charset2 = array('iso-8859-1', 'iso-8859-2', 'utf-8', 'windows-1250');
$charset1[] = $db_charset;
$charset2[] = $page_charset;
$charset1 = charset_assoc($charset1);
$charset2 = charset_assoc($charset2);
$driver_arr = array('mysql', 'pgsql');
$driver_arr = array_assoc($driver_arr);
function array_assoc($a)
{
$ret = array();
foreach ($a as $v) {
$ret[$v] = $v;
}
return $ret;
}
function charset_assoc($arr)
{
sort($arr);
$ret = array();
foreach ($arr as $v) {
if (!$v) { continue; }
$v = strtolower($v);
$ret[$v] = $v;
}
return $ret;
}
if (isset($_GET['disconnect']) && $_GET['disconnect'])
{
cookie_del('db_pass');
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
if (!$db_pass || (!$db_driver || !$db_server || !$db_name || !$db_user))
{
if ('POST' == $_SERVER['REQUEST_METHOD'])
{
$db_driver = post('db_driver');
$db_server = post('db_server');
$db_name = post('db_name');
$db_user = post('db_user');
$db_pass = post('db_pass');
$db_charset = post('db_charset');
$page_charset = post('page_charset');
if ($db_driver && $db_server && $db_name && $db_user)
{
$db_test = true;
db_connect($db_server, $db_name, $db_user, $db_pass);
if (is_resource($db_link))
{
$time = post('remember') ? COOKIE_WEEK : COOKIE_SESS;
cookie_set('db_driver', $db_driver, $time);
cookie_set('db_server', $db_server, $time);
cookie_set('db_name', $db_name, $time);
cookie_set('db_user', $db_user, $time);
cookie_set('db_pass', base64_encode($db_pass), $time);
cookie_set('db_charset', $db_charset, $time);
cookie_set('page_charset', $page_charset, $time);
cookie_set('remember', post('remember'), $time);
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
}
}
else
{
$_POST['db_driver'] = $db_driver;
$_POST['db_server'] = $db_server ? $db_server : 'localhost';
$_POST['db_name'] = $db_name;
$_POST['db_user'] = $db_user;
$_POST['db_charset'] = $db_charset;
$_POST['page_charset'] = $page_charset;
$_POST['db_driver'] = $db_driver;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Connect</title>
<link rel="shortcut icon" href="<?php echo $_SERVER['PHP_SELF']; ?>?dbkiss_favicon=1">
</head>
<body>
<?php layout(); ?>
<h1>Connect</h1>
<?php if (isset($db_test) && is_string($db_test)): ?>
<div style="background: #ffffd7; padding: 0.5em; border: #ccc 1px solid; margin-bottom: 1em;">
<span style="color: red; font-weight: bold;">Error:</span>
<?php echo $db_test;?>
</div>
<?php endif; ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<table class="ls ls2" cellspacing="1">
<tr>
<th>Driver:</th>
<td><select name="db_driver"><?php echo options($driver_arr, post('db_driver'));?></select></td>
</tr>
<tr>
<th>Server:</th>
<td><input type="text" name="db_server" value="<?php echo post('db_server');?>"></td>
</tr>
<tr>
<th>Database:</th>
<td><input type="text" name="db_name" value="<?php echo post('db_name');?>"></td>
</tr>
<tr>
<th>User:</th>
<td><input type="text" name="db_user" value="<?php echo post('db_user');?>"></td>
</tr>
<tr>
<th>Password:</th>
<td><input type="password" name="db_pass" value=""></td>
</tr>
<tr>
<th>Db charset:</th>
<td><input type="text" name="db_charset" value="<?php echo post('db_charset');?>" size="10"> (optional)</td>
</tr>
<tr>
<th>Page charset:</th>
<td><input type="text" name="page_charset" value="<?php echo post('page_charset');?>" size="10"> (optional)</td>
</tr>
<tr>
<td colspan="2" class="none" style="padding: 0; background: none; padding-top: 0.3em;">
<table cellspacing="0" cellpadding="0"><tr><td>
<input type="checkbox" name="remember" id="remember" value="1" <?php echo checked(post('remember'));?>></td><td>
<label for="remember">remember me on this computer</label></td></tr></table>
</td>
</tr>
<tr>
<td class="none" colspan="2" style="padding-top: 0.4em;"><input type="submit" value="Connect"></td>
</tr>
</table>
</form>
<?php powered_by(); ?>
</body>
</html>
<?php
exit;
}
db_connect($db_server, $db_name, $db_user, $db_pass);
if ($db_charset && 'mysql' == $db_driver) {
db_exe("SET NAMES $db_charset");
}
if (isset($_GET['dump_all']) && 1 == $_GET['dump_all'])
{
dump_all($data = false);
}
if (isset($_GET['dump_all']) && 2 == $_GET['dump_all'])
{
dump_all($data = true);
}
if (isset($_GET['dump_table']) && $_GET['dump_table'])
{
dump_table($_GET['dump_table']);
}
if (isset($_GET['export']) && 'csv' == $_GET['export'])
{
export_csv(base64_decode($_GET['query']), $_GET['separator']);
}
if (isset($_POST['sqlfile']) && $_POST['sqlfile'])
{
$files = sql_files_assoc();
if (!isset($files[$_POST['sqlfile']])) {
exit('File not found. md5 = '.$_POST['sqlfile']);
}
$sqlfile = $files[$_POST['sqlfile']];
layout();
echo '<div>Importing: <b>'.$sqlfile.'</b> ('.size(filesize($sqlfile)).')</div>';
echo '<div>Database: <b>'.$db_name.'</b></div>';
flush();
import($sqlfile, post('ignore_errors'), post('transaction'), post('force_myisam'), post('query_start','int'));
exit;
}
if (isset($_POST['drop_table']) && $_POST['drop_table'])
{
$drop_table_enq = quote_table($_POST['drop_table']);
db_exe('DROP TABLE '.$drop_table_enq);
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
if (isset($_POST['drop_view']) && $_POST['drop_view'])
{
$drop_view_enq = quote_table($_POST['drop_view']);
db_exe('DROP VIEW '.$drop_view_enq);
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
function db_connect($db_server, $db_name, $db_user, $db_pass)
{
global $db_driver, $db_link, $db_test;
if (!extension_loaded($db_driver)) {
trigger_error($db_driver.' extension not loaded', E_USER_ERROR);
}
if ('mysql' == $db_driver)
{
$db_link = @mysql_connect($db_server, $db_user, $db_pass);
if (!is_resource($db_link)) {
if ($db_test) {
$db_test = 'mysql_connect() failed: '.db_error();
return;
} else {
cookie_del('db_pass');
cookie_del('db_name');
die('mysql_connect() failed: '.db_error());
}
}
if (!@mysql_select_db($db_name, $db_link)) {
$error = db_error();
db_close();
if ($db_test) {
$db_test = 'mysql_select_db() failed: '.$error;
return;
} else {
cookie_del('db_pass');
cookie_del('db_name');
die('mysql_select_db() failed: '.$error);
}
}
}
if ('pgsql' == $db_driver)
{
$conn = sprintf("host='%s' dbname='%s' user='%s' password='%s'", $db_server, $db_name, $db_user, $db_pass);
$db_link = @pg_connect($conn);
if (!is_resource($db_link)) {
if ($db_test) {
$db_test = 'pg_connect() failed: '.db_error();
return;
} else {
cookie_del('db_pass');
cookie_del('db_name');
die('pg_connect() failed: '.db_error());
}
}
}
register_shutdown_function('db_cleanup');
}
function db_cleanup()
{
db_close();
}
function db_close()
{
global $db_driver, $db_link;
if (is_resource($db_link)) {
if ('mysql' == $db_driver) {
mysql_close($db_link);
}
if ('pgsql' == $db_driver) {
pg_close($db_link);
}
}
}
function db_query($query, $dat = false)
{
global $db_driver, $db_link;
$query = db_bind($query, $dat);
if (!db_is_safe($query)) {
return false;
}
if ('mysql' == $db_driver)
{
$rs = mysql_query($query, $db_link);
return $rs;
}
if ('pgsql' == $db_driver)
{
$rs = pg_query($db_link, $query);
return $rs;
}
}
function db_is_safe($q, $ret = false)
{
// currently only checks UPDATE's/DELETE's if WHERE condition is not missing
$upd = 'update';
$del = 'delete';
$q = ltrim($q);
if (strtolower(substr($q, 0, strlen($upd))) == $upd
|| strtolower(substr($q, 0, strlen($del))) == $del) {
if (!preg_match('#\swhere\s#i', $q)) {
if ($ret) {
return false;
} else {
trigger_error(sprintf('db_is_safe() failed. Detected UPDATE/DELETE without WHERE condition. Query: %s.', $q), E_USER_ERROR);
return false;
}
}
}
return true;
}
function db_exe($query, $dat = false)
{
$rs = db_query($query, $dat);
db_free($rs);
}
function db_one($query, $dat = false)
{
$row = db_row_num($query, $dat);
if ($row) {
return $row[0];
} else {
return false;
}
}
function db_row($query, $dat = false)
{
global $db_driver, $db_link;
if ('mysql' == $db_driver)
{
if (is_resource($query)) {
$rs = $query;
return mysql_fetch_assoc($rs);
} else {
$query = db_limit($query, 0, 1);
$rs = db_query($query, $dat);
$row = mysql_fetch_assoc($rs);
db_free($rs);
if ($row) {
return $row;
}
}
return false;
}
if ('pgsql' == $db_driver)
{
if (is_resource($query) || is_object($query)) {
$rs = $query;
return pg_fetch_assoc($rs);
} else {
$query = db_limit($query, 0, 1);
$rs = db_query($query, $dat);
$row = pg_fetch_assoc($rs);
db_free($rs);
if ($row) {
return $row;
}
}
return false;
}
}
function db_row_num($query, $dat = false)
{
global $db_driver, $db_link;
if ('mysql' == $db_driver)
{
if (is_resource($query)) {
$rs = $query;
return mysql_fetch_row($rs);
} else {
$rs = db_query($query, $dat);
if (!$rs) {
/*
echo '<pre>';
print_r($rs);
echo "\r\n";
print_r($query);
echo "\r\n";
print_r($dat);
exit;
*/
}
$row = mysql_fetch_row($rs);
db_free($rs);
if ($row) {
return $row;
}
return false;
}
}
if ('pgsql' == $db_driver)
{
if (is_resource($query) || is_object($query)) {
$rs = $query;
return pg_fetch_row($rs);
} else {
$rs = db_query($query, $dat);
$row = pg_fetch_row($rs);
db_free($rs);
if ($row) {
return $row;
}
return false;
}
}
}
function db_list($query)
{
global $db_driver, $db_link;
$rs = db_query($query);
$ret = array();
if ('mysql' == $db_driver) {
while ($row = mysql_fetch_assoc($rs)) {
$ret[] = $row;
}
}
if ('pgsql' == $db_driver) {
while ($row = pg_fetch_assoc($rs)) {
$ret[] = $row;
}
}
db_free($rs);
return $ret;
}
function db_assoc($query)
{
global $db_driver, $db_link;
$rs = db_query($query);
$rows = array();
$num = db_row_num($rs);
if (!is_array($num)) {
return array();
}
if (!array_key_exists(0, $num)) {
return array();
}
if (1 == count($num)) {
$rows[] = $num[0];
while ($num = db_row_num($rs)) {
$rows[] = $num[0];
}
return $rows;
}
if ('mysql' == $db_driver)
{
mysql_data_seek($rs, 0);
}
if ('pgsql' == $db_driver)
{
pg_result_seek($rs, 0);
}
$row = db_row($rs);
if (!is_array($row)) {
return array();
}
if (count($num) < 2) {
trigger_error(sprintf('db_assoc() failed. Two fields required. Query: %s.', $query), E_USER_ERROR);
}
if (count($num) > 2 && count($row) <= 2) {
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);
}
foreach ($row as $k => $v) {
$first_key = $k;
break;
}
if (count($row) > 2) {
$rows[$row[$first_key]] = $row;
while ($row = db_row($rs)) {
$rows[$row[$first_key]] = $row;
}
} else {
$rows[$num[0]] = $num[1];
while ($num = db_row_num($rs)) {
$rows[$num[0]] = $num[1];
}
}
db_free($rs);
return $rows;
}
function db_limit($query, $offset, $limit)
{
global $db_driver;
$offset = (int) $offset;
$limit = (int) $limit;
$query = trim($query);
if (str_ends_with($query, ';')) {
$query = str_cut_end($query, ';');
}
$query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s+OFFSET\s+\d+\s*$#i', '$1', $query);
$query = preg_replace('#^([\s\S]+)LIMIT\s+\d+\s*,\s*\d+\s*$#i', '$1', $query);
if ('mysql' == $db_driver) {
// mysql 3.23 doesn't understand "LIMIT x OFFSET z"
return $query." LIMIT $offset, $limit";
} else {
return $query." LIMIT $limit OFFSET $offset";
}
}
function db_escape($value)
{
global $db_driver, $db_link;
if ('mysql' == $db_driver) {
return mysql_real_escape_string($value, $db_link);
}
if ('pgsql' == $db_driver) {
return pg_escape_string($value);
}
}
function db_quote($s)
{
switch (true) {
case is_null($s): return 'NULL';
case is_int($s): return $s;
case is_float($s): return $s;
case is_bool($s): return (int) $s;
case is_string($s): return "'" . db_escape($s) . "'";
case is_object($s): return $s->getValue();
default:
trigger_error(sprintf("db_quote() failed. Invalid data type: '%s'.", gettype($s)), E_USER_ERROR);
return false;
}
}
function db_strlen_cmp($a, $b)
{
if (strlen($a) == strlen($b)) {
return 0;
}
return strlen($a) > strlen($b) ? -1 : 1;
}
function db_bind($q, $dat)
{
if (false === $dat) {
return $q;
}
if (!is_array($dat)) {
//return trigger_error('db_bind() failed. Second argument expects to be an array.', E_USER_ERROR);
$dat = array($dat);
}
$qBase = $q;
// special case: LIKE '%asd%', need to ignore that
$q_search = array("'%", "%'");
$q_replace = array("'\$", "\$'");
$q = str_replace($q_search, $q_replace, $q);
preg_match_all('#%\w+#', $q, $match);
if ($match) {
$match = $match[0];
}