-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsqlicity.php
5488 lines (4254 loc) · 175 KB
/
sqlicity.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
/*
Welcome to Sqlicity,
"SQL Simplicity"
copyright 2008-2011, by Chris Rogus
http://www.sqlicity.com/
build 2011111102
**********************
COPYRIGHT NOTICE:
**********************
2-clause BSD license:
Copyright 2011 Chris Rogus. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY CHRIS ROGUS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRIS ROGUS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Chris Rogus.
In short, most importantly, you ABSOLUTELY AGREE, by using this software,
that you will be fully responsible for ANY damages
that occur from its use. I am _suggesting_ this software
for the purposes I have described herein of MySQL database management,
But I make NO guarantees as to its usability or suitability
for ANY function or to its being error-free and safe on data.
There are plenty of companies who charge you a lot of money
to give you guarantees like that. If it's that important to you
(and for some people it really is, and I understand that fully)
go find them and pay through the nose.
Or pay me to test & develop that degree of certainty with Sqlicity.
**********************
FIRST TIME:
**********************
To configure Sqlicity for your database,
simply jump past the "KILL BAD PHP" code block
just below these comments, and change the "CONNECTION INFORMATION"
which has the lock-down (login) user/pass and the
database login (user/pass/server) and available db array
**********************
IMPORTANT:
**********************
The intention behind Sqlicity is for it to be used
only to aid in the development and debugging of
web applications that do more specialized management
of the data in the databases, knowing what the data represents
(e.g. content management systems, e-commerce sites)
Thus, I have deliberately designed Sqlicity to be so simple
that it is meant ONLY for people who
ALREADY KNOW WHAT THEY ARE DOING!!
Meaning, it is IMPERATIVE that you already moreorless
know your way through raw MySQL commands!!!!!
Sqlicity provides absolutely minimal interpretation of
the data, and relies on the user's understanding of
the way that MySQL respresents information.
** To my mind, Sqlicity is just a slightly
more sophisiticated version of the command line client!
If you need every feature under the sun, fully supporting
every version of MySQL going back to version 3.0 or something,
use PhpMyAdmin. I made Sqlicity because I dislike PhpMyAdmin's interface
and installation, but it does do more stuff than Sqlicity and it always will.
(I have no intention of fighting a features war with them,
my goal is and will remain to minimize features to the bare essentials.)
**********************
WARNING:
**********************
Sqlicity works great as it is, I use it for everything I do,
so it's already been tested quite a bit, in production environments.
However, I have my suspicions that errors could pop up
if you use strings for primary key values that include certain characters:
specifically, "s or 's or ,s (double-quotes, single-quotes and commas)
And these same chars or any html might also break things
if used in column/field names, or table or db names.
(Column values are html safe, of course, and well tested.)
I have prepared for all of these cases, but they are not extensively tested.
Thus, while I do not expect such errors to happen, they might.
You use this software acknowledging these risks.
Furthermore, there might be more, unanticipated risks
and you accept responsibilty for those dangers as well.
**** AGAIN, I AM NOT LIABLE FOR LOSS OR DAMAGE TO YOUR DATA!!!! ****
**********************
KNOWN ISSUES:
**********************
1) NO support for spatial column types. This is not likely to change.
2) Currently, only primary keys or entire row values
are used to identify individual rows -- isolating the non-null uniques
is not a currently supported method of identification, and might never be.
3) the SET clause of LOAD DATA INFILE (mysql 5.0.3+) is NOT simulated in sqlicity!
at best it would only ever offer very limited functionality,
it is highly unlikely that I will ever even attempt that simulation but just in case:
"Lines ignored by an IGNORE clause are not processed for the column/variable list or SET clause."
4) You need a pretty big screen resolution to see sqlicity
properly all the time (I use a 17" flat panel at 1280x1024)
I _DO_ want to make versions of sqlicity for cellphones/PDAs/etc
but that's long, long term. So, eventually, someday, maybe,
you'll find a link to open sqlicity in your micro-browser
and I will have come up with some creative way to navigate
a db effectively with extremely limited screen space.
5) Lots of columns in a table will stretch the page... a LOT.
It's on my list, I'm just working on a more creative way to
display such information -- I've got good ideas, just you wait...
6) ENUMs and SETs are not handled specially yet. They will be.
7) System variable display/editing is not yet implemented. It's coming.
8) User management is not yet implemented. It's coming.
9) MySQL 5.0 features: VIEWs, TRIGGERs and STORED PROCEDURES/FUNCTIONS
are not handled at all yet. Thus, Sqlicity will display Views
as regular tables (which will cause errors if you try to alter them, etc)
and will completely ignore Triggers, and stored procedues/etc
10) Export & import file compression is not yet implemented
Furthermore, the import/export could certainly use more testing of extreme special cases
11) Currently, there is no way to upload binary data for BLOBs
This will change in the future, once I implement it.
Relatedly, BLOBs will be... awkwardly displayed in data lists
(i.e. SELECTs and Data Views will show the binary data as text)
12) Localization is FAAAAARRRRR from complete -- many more strings need
to be added to the localization hash array, as I work with them, I replace them (sometimes...)
13) I do not use the $mysql_server variable (database link id) in calling ANY of the mysql_query()s
I consider to be acceptable since I don't expect anyone adding their own db code in the middle of this
(perhaps at the beginning as with db+cookie authentication systems), but I might change that eventually anyway.
CHRIS: FIXME FIX ME -- doesn't work when you specify a headerlist!!!
(problem is $display_columns_defaults not matched to headerlist)
DELIMITER !!!!
SHOW PROCEDURE STATUS
SHOW FUNCTION STATUS
SHOW CREATE PROCEDURE MY_PROC
export file -- compress export gz/bz2/etc & also with SQL export!
import file -- allow compressed even with LOAD DATA
edit data -- upload file for blob columns
edit data -- enums/sets should be dropdown/multi
mysql5
sysvars
users
select row/col display invert
data view scrolling for rows/cols
**** There are some other issues I have come across but not yet taken the time to isolate,
that are related only to selecting the data to be displayed on the data rows page
where certain where queries will actually crash the system.
I have never found this issue to be a show stopper for me and I've always been too busy
actually working on projects to fiddle much more with SQLicity to fix it.
So, if you come across this and can isolate it and submit a fix, I'll be most grateful.
Similarly with any other issues you encounter. By all means, play!
**********************
Table of Contents:
**********************
** line ~ 300 ** ACTION PREPARATION BLOCKS ** handle the core workload
1) "KILL BAD PHP" -- sanitize the environment against magic_quotes_gpc and register_globals
* 2) "CONNECTION INFORMATION" -- DEFINE USER CONFIGURATION: db login, etc
3) "LOCKDOWN DATA" -- manages the Sqlicity lock-down feature
4) "INITIALIZE PAGE" -- connect to the db, etc
5) "MYSQL COMMANDS" -- takes action on the db, based on your choices in Sqlicity
6) "CURRENT VIEW" -- barely more than a big switch(), picks page to display
** line ~ 1000 ** DATABASE STRUCTURE PAGES
1) MASSIVE ERROR CONTENT -- content_massive_error()
2) DB MUTLI TABLE CONTENT -- content_db_multi_table()
3) CREATE TABLE CONTENT -- content_create_table()
4) TABLE CONTENT -- content_table()
5) FIELDS CONTENT -- content_fields()
** line ~ 1200 ** IMPORT/EXPORT PAGES
1) EXPORT STRUCTURE CONTENT -- content_export_structure()
2) EXPORT DATA CONTENT -- content_export_data
3) DO EXPORT DATA CONTENT -- content_do_export_data
4) IMPORT DATA CONTENT -- content_import_data
5) DO IMPORT DATA CONTENT -- content_do_import_data
6) DO EXPORT DB SQL CONTENT -- content_do_db_sql_export
** line ~ 2100 ** MYSQL SYSTEM INFORMATION PAGES
1) SELECT CONTENT -- content_select()
2) PROCESSLIST CONTENT -- content_processlist()
3) USERLIST CONTENT -- content_userlist()
4) EDIT USER CONTENT -- content_edit_user()
5) SYSTEM VARS CONTENT -- content_system_vars()
** line ~ 2400 ** DATA MANAGEMENT PAGES
1) DATA CONTENT -- content_data()
2) EDIT ROW CONTENT -- content_edit_row()
** line ~ 3000 ** DISPLAYED HTML CONTENT
1) Javascript for sending sqlicity commands controlling the db
2) "Header" chunk -- db and table listing
3) "Footer" chunk -- pure sql input and copyright
**********************
Making Changes:
**********************
Remember, Sqlicity is designed to be barely more
than a visual (textual -- NOT graphical!) interface
to execute SQL statements directly on the db,
(i.e. only in a 1:1 interface:SQL relationship)
don't expect more than that and don't waste time
trying to add it -- that's not the goal here.
Feel free to contact me and recommend your changes
if you think you've got something really worth contributing,
(that is NOT an invitation to request features, ONLY
to suggests changes that you have already made and would
like added to the publicly available version of Sqlicity)
although it is my personal opinion that not much more is needed
in a barebones SQL db management tool than what Sqlicity has.
(Plus what's in my to-do/bugs list above, of course.)
However, if you have corporate business needs for enhancements/extensions
to Sqlicity, please, do contact me and I will gladly assist you
in developing such extras, for the appropriate price.
Furthermore, since this is NOT "free software" it is possible
to develop such extras as private add-ons instead of sharing
them with the public as is officially required with GPL software.
(such as the GPL'd PhpMyAdmin...)
**********************
**********************
Enjoy Sqlicity!
**********************
**********************
*/
/*************************************************************************************
======================================================================================
ACTION PREPARATION BLOCKS
Configure the environment, connect to the db,
execute commands, pick the view, etc -- initialize the page
======================================================================================
*************************************************************************************/
// default is 5 minutes -- 0 is NO timeout
set_time_limit(300);
/******************************************
KILL BAD PHP
For security, cleanliness and proper functioning
we need to kill some "features" of PHP:
magic_quotes_gpc and register_globals
******************************************/
// fix register_globals
// http://www.php.net/manual/en/security.globals.php
if (ini_get('register_globals'))
foreach ($_REQUEST as $key => $value)
{ unset($GLOBALS[$key]); }
// make sure db results are not escaped
set_magic_quotes_runtime(0);
// fix magic_quotes_gpc
// http://www.php.net/manual/en/security.magicquotes.php
if (get_magic_quotes_gpc())
{
// http://www.php.net/manual/en/security.magicquotes.disabling.php
function stripslashes_deep ($value)
{ return (!is_array($value) ? stripslashes($value) : array_map('stripslashes_deep', $value)); }
// I only use POST on this page, so that's all I fix
$_POST = stripslashes_deep($_POST);
}
// THESE ARE VERY BASIC INITIALIZATION VARS
// BUT THEY MUST COME _AFTER_ THE FIXING OF register_globals
// AND _BEFORE_ EVERYTHING ELSE!
// init vars to handle database errors
$small_error = $massive_error = '';
// this is optional, for visual effect only
$datetime_format = 'r';
// mark the beginning of page load
$start_timestamp = date($datetime_format);
/******************************************
LOCALIZATION LANGUAGE OPTIONS
Define the text strings for output
i.e. interface messages to the user
******************************************/
$output_text = array(
'sqlicity_failed_login' => 'This area is restricted.',
'cannot_open_db' => 'Cannot open the SQL database: ',
'no_db_available' => 'No mysql database available to connect to!',
'command_query_failed' => 'failed',
'command_query_action' => array(
'table_empty' => 'Empty table',
'table_drop' => 'Drop table',
'table_create' => 'Create table',
'table_rename' => 'Rename table',
'alter_table' => 'Alter table',
'table_add_col' => 'Add column',
'table_del_col' => 'Delete column',
'table_chg_col' => 'Change column',
'table_copy' => 'Copy table with LIKE',
'table_copy2' => 'Copy table with SELECT LIMIT 0',
'db_tables_drop' => 'Drop multiple tables',
'db_tables_empty' => 'Empty multiple tables',
'kill_process' => 'Kill process',
'data_row_delete' => 'Delete row',
'data_row_save_EDIT' => 'Edit row',
'data_row_save_ADD' => 'Add row',
'pure_sql_ONE' => 'Your pure SQL command',
'pure_sql' => 'Your multi-query SQL command',
'upload_pure_sql' => 'Your uploaded SQL commands',
),
'row_added_number' => '<b>Row{#ROW_ADDED_NUMBER} added.</b> Add another row or hit cancel to return to the data view.',
'select_failed' => 'Select failed: ',
'executed_pure_sql' => 'Executed pure SQL command',
'executed_multi_sql' => 'Executed multi-query SQL command',
'executed_upload_sql' => 'Executed uploaded SQL commands',
'rows_affected' => 'rows affected.',
'no_submitted_command' => 'No SQL commands were submitted for execution.',
'upload_executed_sql' => '## UPLOADED SQL ##',
'unknown_sqlicity_command' => 'Unknown Sqlicity command.<br />Try again or go to the <a href="http://www.sqlicity.com">Sqlicity website</a> and report this error.',
'upload_file_unreadable' => 'COULD NOT OPEN FILE FOR READ: ',
'upload_file_error' => 'Upload error: ',
'began_command_exec' => 'Began MySQL command execution at',
'ended_command_exec' => 'and ended at',
'show_tables_failed' => 'Show tables failed: ',
'NAME' => 'HTML_TEXT',
);
/******************************************
INITIALIZE PAGE
Make the connection to the MySQL DB,
select current db, table, view, etc
******************************************/
// list the user names which are ok to login to this page
$limitedUserList = array(); // empty means anyone can login
//$limitedUserList = array('root'); // just list them as strings
// hold current username and password
$sqlicity_username = $_SERVER['PHP_AUTH_USER'];
$sqlicity_password = $_SERVER['PHP_AUTH_PW'];
// define the server to connect to
$mysql_server_name = 'localhost';
// will be included if present, otherwise ignored -- see sample below
@include 'sqlicity_connect.php';
/*
optionally, can set sqlicity to always connect
as a specific user and to specific dbs
SAMPLE sqlicity_connect.php:
$sqlicity_username = 'alogin';
$sqlicity_password = 'apass';
$mysql_dbs = array(
'db1',
'db2',
'db3',
);
*/
// flag if we should ignore the POST db list
$resetDBs = FALSE;
// send them the box to demand a log in
// http://www.php.net/manual/en/features.http-auth.php
function show_auth_box ()
{
global $output_text;
header('WWW-Authenticate: Basic realm="Sqlicity"');
header('HTTP/1.0 401 Unauthorized');
echo $output_text['sqlicity_failed_login'];
exit;
}
// see if user just attempted to sign out
if ($_POST['logout_submitted'] == $sqlicity_username) { show_auth_box(); }
// see if no user given
if ($sqlicity_username == '') { show_auth_box(); }
// see if this user is even allowed to login on this page
if (count($limitedUserList) && !in_array($sqlicity_username, $limitedUserList)) { show_auth_box(); }
// try to connect to the server using these given logins
$mysql_server = @mysql_connect($mysql_server_name, $sqlicity_username, $sqlicity_password);
// verify the db connection (login details) worked
if (!$mysql_server) { show_auth_box(); }
// if they just signed back in after signing out, reload the db list
if ($_POST['logout_submitted']) { $resetDBs = TRUE; }
// get all the available dbs -- if they aren't hardcoded already, find them
// since this is kinda slow, we try to carry this in the viewstate form
if (is_array($mysql_dbs)) {} // got specified ones, just use those
elseif (!$resetDBs && is_array($_POST['mysql_dbs'])) { $mysql_dbs = $_POST['mysql_dbs']; }
else
{
// get all the known databases to start
$mysql_dbs = array();
$db_res = mysql_query("SHOW DATABASES");
while ($newdb = mysql_fetch_assoc($db_res))
{
// then narrow it down to ones we can connect to
if (mysql_select_db($newdb['Database'], $mysql_server))
{ $mysql_dbs[] = $newdb['Database']; }
}
}
// make sure we found at least one db to connect to at all!
if (count($mysql_dbs) > 0)
{
// if no db is selected, pick the first one on the list
$cur_mysql_db = $_POST['cur_mysql_db'];
if (!$cur_mysql_db || $resetDBs) { $cur_mysql_db = $mysql_dbs[0]; }
// open the current db
if (!$massive_error &&
!(mysql_select_db($cur_mysql_db, $mysql_server)))
$massive_error = $output_text['cannot_open_db'].htmlutf($cur_mysql_db);
}
else // in case we somehow have no dbs available right now
{ $massive_error = $output_text['no_db_available']; }
// describes current view
$current_view = $_POST['current_view'];
$cur_mysql_table = $_POST['cur_mysql_table'];
$show_puresql = $_POST['show_puresql'];
// default puresql to on.
if (!isset($show_puresql)) { $show_puresql = 1; }
// get MySQL version as a helper fact, and split out just the numbers
$mysql_version_string = mysql_result(mysql_query("SELECT VERSION()"), 0);
preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)(\-.*)?/', $mysql_version_string, $mysql_version);
$mysql_version_numbers = array($mysql_version[1],$mysql_version[2],$mysql_version[3]);
// checks a minimum mysql version for some action
function check_mysql_version_min ($big=0,$med=0,$sml=0)
{
global $mysql_version_numbers;
// first check easy ones -- big and middle versions
return (($mysql_version_numbers[0]>$big)
|| (($mysql_version_numbers[0]==$big) && (($mysql_version_numbers[1]>$med)
// then just the small version
|| ($mysql_version_numbers[1]==$med && $mysql_version_numbers[2]>=$sml))));
}
// use utf8 instead of simple latin1
// http://malevolent.com/weblog/archive/2007/03/12/unicode-utf8-php-mysql/
// http://www.richnetapps.com/php-mysql-speak-unicode/
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
function htmlutf ($v) { return htmlentities($v, ENT_QUOTES | ENT_IGNORE, "UTF-8"); }
/******************************************
MYSQL COMMANDS
Handle mysql commands sent from sqlicity
******************************************/
$mysql_command = $_POST['mysql_command'];
$executed_sql = ''; // empty this for security, appending, etc
// timestamp start/end for query times
$mysql_query_start = 0;
$mysql_query_end = 0;
// We need to use some ASCII codes, PHP does not have escape sequences for these chars
// there are no OS's running PHP that have diff ASCII tables are there?...
// NOTE: you have to be very careful with str_replace!
// if a later value is a subset of an earlier value, it will be replaced again!
// therefore, since we later str_replace by these keys,
// the escape char key MUST come before the others,
// or they will all get doubled backslashes!
$mysql_escaped_chars = array(
"\\" => "\\", // backslash
'0' => chr(0), // "\0", // ASCII 0 (NUL)
"'" => "'", // single quote
'"' => '"', // double quote
'n' => "\n", // newline/linefeed
'r' => "\r", // carriage return
'Z' => chr(26), // "\Z", // control-Z, EOF in Windows
'b' => chr(8), // "\b", // backspace
't' => "\t", // tab
// these two are special: the backslash stays... VERY UNCOOL
'%' => '\%', // percent sign
'_' => '\_', // underscore
);
// shortcut vars, rather than repeatedly calculating these
$mysql_escaped_chars_values = array_values($mysql_escaped_chars);
$mysql_escaped_chars_keys = array_map(create_function('$c', 'return "\\\\".$c;' ), array_keys($mysql_escaped_chars));
// proper addslashes/mysql_real_escape_string replacement
function add_mysql_slashes ($string)
{
global $mysql_escaped_chars_values, $mysql_escaped_chars_keys;
return ($string !== NULL ? str_replace($mysql_escaped_chars_values, $mysql_escaped_chars_keys, $string) : $string);
}
// same, but now with = then single quotes around non-null values and IS NULL for nulls
function add_mysql_slashes_where ($string)
{
global $mysql_escaped_chars_values, $mysql_escaped_chars_keys;
return ($string !== NULL ? "='".str_replace($mysql_escaped_chars_values, $mysql_escaped_chars_keys, $string)."'" : ' IS NULL');
}
// clean off the semicolon and whitespace
function clean_semiwhite ($s)
{
// do a regex trim, while also removing the semi colon
// NOTE: for some reason I _must_ use the /s modifier with .*
// as opposed to no modifer and [\S\s]*
// -- for some inexplicable reason, this doesn't catch vertical tabs (ascii 11)!!
preg_match('/^\s*(\S.*?)\s*\;?$/s',$s,$s1);
return $s1[1];
}
// used w/ nextSQLstatement for pure_sql (as opposed to upload)
function sqlicity_empty_read_func ($a, $b) { return NULL; }
// get the next SQL query in a [possibly compressed] file
// get the file read function -- for compressed files, etc
function nextSQLstatement ($readfunc, $sqlfile, &$leftoversql)
{
// define the open/close char pairs for strings/identifiers
$closers = array(
'`' => '`',
'\'' => '\'',
'"' => '"',
);
// track FSM state
$state = 1; // current FSM state
$closechar = NULL; // the char to close this string
$escaped = FALSE; // in case of escaped chars inside strings
$statement = ''; // holds the next statement we find
// loop over all the lines of the file
// until we hit a semicolon, or EOF
// first use the leftovers from the last statement, if present
while ($sqltext = (!$leftoversql ? $readfunc($sqlfile, 1024) : $leftoversql))
{
// we've included the leftovers, don't need them anymore
$leftoversql = '';
// loop through all the chars in the next line of text we pull
$maxlen = strlen($sqltext);
for ($i=0; $i<$maxlen; $i++)
{
// and process each char according to current state
$char = $sqltext{$i};
// check for comments, this is a temporary state change
// NEW comments only happen OUTSIDE matching quotes and NOT in comments!
// (i.e. NOT in states 2 or 3, which leaves only 1)
if ($char == '#' && $state == 1) { $state = 3; }
// first of all, we store every single char onto the current statement
$statement .= $char;
// now check if we end a statement, go in/out of matching/etc
switch($state)
{
case 1: // OUTside matching string&block quotes/etc
// hit a semicolon outside matches, means we finished a statement
if ($char == ';')
{
// save the leftovers to start the next statement
$leftoversql = substr($sqltext, $i+1);
// return the statement without the semicolon and whitespace
return clean_semiwhite($statement);
}
// hit a string/identifier opener char (a key in $closers), means we entered matching quotes/etc
elseif (($closechar = $closers[$char]) !== NULL) { $state = 2; }
break;
case 2: // INside matching STRING quotes/etc
// we completely ignore escaped chars, whatever they may be
// EXCEPT identifier quotes have no escape chars:
// http://dev.mysql.com/doc/mysql/en/legal-names.html
// doubled identifier quotes are handled just fine as-is
if ($escaped) { $escaped = FALSE; } // the current character was escaped, i.e. completely ignored
else // unescaped chars we check for string closers and the escape char
{
// once inside string matching quotes/etc, we only look for the closer char to get back outside
if ($closechar == $char) { $state = 1; }
// except... the char might be escaped... -- but not inside an identifier!
elseif ($char == "\\" && $closechar!='`') { $escaped = TRUE; }
}
break;
case 3: // finishing the line after a comment
// everything until the newline is a comment and cannot split statements
// afterwards, return to being outside matching quotes/etc
if ($char == "\n" || $char == "\r") { $state = 1; }
break;
}}
} // end loop over all the lines in the file
// FSM finished, means we hit EOF
// assumedly the statement is finished now...
// return the statement without the semicolon and whitespace
$leftoversql = NULL; // NULL leftover marks EOF
return clean_semiwhite($statement);
}
// execute all the statements in the uploaded file
// also works with pure_sql by giving $leftoversql the $cmd_data
function execute_file_sql ($readfunc, $sqlfile, $leftoversql='')
{
global $executed_sql, $mysql_command;
// get the data from the file
$command_count = 0;
while ($leftoversql !== NULL)
{
// get the next statement to be executed
$executed_sql = nextSQLstatement($readfunc, $sqlfile, $leftoversql);
// empty statements, after semi colon removed, should be ignored
// if the statement is there and fails, we stop processing the file
if ($executed_sql)
{
// track the number of executed commands
$command_count++;
if (!do_mysql_query($mysql_command)) { break; }
}
}
// tell how many commands were executed
return $command_count;
}
// runs a query, sets some vars, gives error, etc
function do_mysql_query ($actionname)
{
global $executed_sql, $small_error, $output_text,
$mysql_query_start, $mysql_query_end;
// did the query work or not? assume yes
$worked = TRUE;
// mark start time
$mysql_query_start = time();
// run the query, check for errors
if (!mysql_query($executed_sql))
{
$small_error = $output_text['command_query_action'][$actionname].' '
.$output_text['command_query_failed'].":</b><br />\n<i>"
.htmlutf($executed_sql)."</i><br />\n<b>".mysql_error();
$worked = FALSE;
}
// mark end time
$mysql_query_end = time();
// so we know quickly if this query worked or not
return $worked;
}
// handle changes to the database
if (!$massive_error && $mysql_command)
{
// do this for all commands,
// even ones which don't use data
$cmd_data = $_POST['mysql_command_data'];
// empty current table
if ($mysql_command == 'table_empty')
{
$executed_sql = "TRUNCATE TABLE `$cur_mysql_table`";
do_mysql_query($mysql_command);
}
// drop current table
elseif ($mysql_command == 'table_drop')
{
$executed_sql = "DROP TABLE `$cur_mysql_table`";
if (do_mysql_query($mysql_command))
{ $cur_mysql_table = ''; } // it was just deleted, don't use it anymore
}
// create a new table
elseif ($mysql_command == 'table_create')
{
$create_table_sql = $executed_sql = $cmd_data;
if (do_mysql_query($mysql_command))
{
// get the name of the table
// and switch to use that new table as the current
// FIXME FIX ME -- verify that even in later (than 3.23) MySQL vers, there must be at least one col!
$cur_mysql_table = array();
preg_match('/\s*CREATE(\s+TEMPORARY)?\s+TABLE(\s+IF NOT EXISTS)?\s+`?(.*?)`?\s+\(/is', $cmd_data, $cur_mysql_table);
$cur_mysql_table = $cur_mysql_table[3];
// and go to its default table view
$current_view = '';
}
}
// rename current table
elseif ($mysql_command == 'table_rename')
{
$executed_sql = "RENAME TABLE `$cur_mysql_table` TO `$cmd_data`";
if (do_mysql_query($mysql_command))
{ $cur_mysql_table = $cmd_data; } // it was just renamed, use new name
}
// alter the current table
elseif ($mysql_command == 'alter_table')
{
$executed_sql = "ALTER TABLE `$cur_mysql_table` $cmd_data";
do_mysql_query($mysql_command);
}
// add a column to current table
elseif ($mysql_command == 'table_add_col')
{
$executed_sql = "ALTER TABLE `$cur_mysql_table` ADD COLUMN $cmd_data";
do_mysql_query($mysql_command);
}
// remove a column from current table
elseif ($mysql_command == 'table_del_col')
{
$executed_sql = "ALTER TABLE `$cur_mysql_table` DROP COLUMN `$cmd_data`";
do_mysql_query($mysql_command);
}
// change a column
elseif ($mysql_command == 'table_chg_col')
{
$executed_sql = "ALTER TABLE `$cur_mysql_table` CHANGE COLUMN $cmd_data";
do_mysql_query($mysql_command);
}
// copy a table with LIKE
elseif ($mysql_command == 'table_copy')
{
$executed_sql = "CREATE TABLE `$cmd_data` LIKE `$cur_mysql_table`";
if (do_mysql_query($mysql_command))
{ $cur_mysql_table = $cmd_data; } // switch to the new table
}
// copy a table with SELECT LIMIT 0
elseif ($mysql_command == 'table_copy2')
{
$executed_sql = "CREATE TABLE `$cmd_data` SELECT * FROM `$cur_mysql_table` LIMIT 0";
if (do_mysql_query($mysql_command))
{ $cur_mysql_table = $cmd_data; } // switch to the new table
}
// drop multiple tables
elseif ($mysql_command == 'db_tables_drop')
{
$executed_sql = "DROP TABLE IF EXISTS $cmd_data";
do_mysql_query($mysql_command);
}
// empty multiple tables
elseif ($mysql_command == 'db_tables_empty')
{
$executed_sql = "TRUNCATE TABLE $cmd_data";
do_mysql_query($mysql_command);
}
// kill a process
elseif ($mysql_command == 'kill_process')
{
$executed_sql = "KILL $cmd_data";
do_mysql_query($mysql_command);
}
// remove a row from current table
elseif ($mysql_command == 'data_row_delete')
{
$executed_sql = "DELETE FROM `$cur_mysql_table` WHERE $cmd_data LIMIT 1";
do_mysql_query($mysql_command);
}
// save a single row -- can be update or insert
elseif ($mysql_command == 'data_row_save')
{
// returns actual column values, for array_map
// FIXME FIX ME -- does NOT yet handle binary data (file uploads)!
function actual_values ($col, $val)
{
// switch on the escape type
switch ($val[1])
{
case 1: // escaped data
return "`$col`".
// php 4.3.0 is req for MRES()
// so, for compatibility, we use mine
add_mysql_slashes_where($val[0]);
break;
case 2: // unescaped data
return "`$col`=$val[0]";
break;
case 3: // NULL
return "`$col`=NULL";
break;
}
// if no valid escape type is given,
// the implode will happen anyway, on empty data
// and this will cause an error in the SQL!!!
}
// these are used to build the executed_sql
// so clear these first, to be safe
$edit_row_key_identity = '';
$edit_row_data = array();
// this eval will create:
// $edit_row_key_identity -- WHERE clause for pri key
// $edit_row_data[col_name][0] -- column value
// $edit_row_data[col_name][1] -- escape type
eval($cmd_data);
// get the actual values to use in the SQL
$row_data_new = implode(', ', array_map('actual_values',
array_keys($edit_row_data), array_values($edit_row_data)));
// this is an UPDATE if identity exists, otherwise INSERT
if ($edit_row_key_identity)
{
$executed_sql = "UPDATE `$cur_mysql_table` SET $row_data_new WHERE $edit_row_key_identity LIMIT 1";
if (do_mysql_query($mysql_command.'_EDIT'))
{ $current_view = 'data'; } // go back to data view
}
else // new row -- INSERT it
{
$executed_sql = "INSERT INTO `$cur_mysql_table` SET $row_data_new";
// leave in row edit view, in case adding more
if (do_mysql_query($mysql_command.'_ADD'))
{
$idnumber = mysql_insert_id();
$small_error .= str_replace('{#ROW_ADDED_NUMBER}',
($idnumber ? ' #'.$idnumber : ''), $output_text['row_added_number']);
}
}
}
// execute pure SQL code
elseif ($mysql_command == 'pure_sql')
{
// first split into multiple statements, if that is the case
// "multiple" statements means at least one semicolon -- even if no query after it!
$leftoversql = $cmd_data;
$statement = nextSQLstatement('sqlicity_empty_read_func',NULL,$leftoversql);
// if it's just one command, we allow for special cases
// "just one command" means no leftovers here
if ($leftoversql === NULL)
{
// shortcut, and to do single queries on the semi-colon-less statement
$executed_sql = $statement;
// handle special displays for certain commands
preg_match('/^\s*\(?([a-z]+)\s+\S.*$/Dis', $executed_sql, $top_command);
$top_command = strtoupper($top_command[1]);
// unfortunately, a pure sql table rename does wreak havoc on sqlicity
// so we need to handle it specially here
if ($top_command == 'RENAME')
{ $cur_mysql_table = NULL; } // shortcut, to dodge figuring out the new name
// display SELECT or SHOW results on the appropriate page
if ($top_command == 'SELECT' || $top_command == 'SHOW')
{
$current_view = 'select_data';
$cur_mysql_table = NULL; // needed to show select data
// include what we just executed as select sql, for the select page
$select_sql = $cmd_data;