-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.php
3880 lines (3619 loc) · 154 KB
/
index.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
if (version_compare(phpversion(), '5.2.4', '<')) {
die('Your PHP version is PHP '.phpversion().', which is too old. You need at least PHP 5.2.4.');
}
if(strpos(ini_get('variables_order'),'G') === false || strpos(ini_get('variables_order'),'P') === false ||
strpos(ini_get('variables_order'),'C') === false || strpos(ini_get('variables_order'),'S') === false) {
die('The php configuration <em>variables_order</em> needs to include G, P, C and S. The current value is "'.ini_get('variables_order').'". Please check the php configuration (php.ini).');
}
# REMOVE_FROM_BUILD
// include default configuration and language
include './phpliteadmin.config.sample.php';
include './languages/lang_en.php';
// setup class autoloading
function pla_autoload($classname)
{
$classfile = __DIR__ . '/classes/' . $classname . '.php';
if (is_readable($classfile)) {
include $classfile;
return true;
}
return false;
}
spl_autoload_register('pla_autoload');
# END REMOVE_FROM_BUILD
//- Initialization
// load optional configuration file
$config_filename = './phpliteadmin.config.php';
if (is_readable($config_filename))
{
include_once $config_filename;
}
//constants 1
define("PROJECT", "phpLiteAdmin");
define("VERSION", "1.9.9-dev");
define("FORCETYPE", false); //force the extension that will be used (set to false in almost all circumstances except debugging, possible values: false, "PDO", "SQLite3", "SQLiteDatabase")
define("SYSTEMPASSWORD", $password); // Makes things easier.
define('PROJECT_URL','https://www.phpliteadmin.org/');
define('DONATE_URL','https://www.phpliteadmin.org/donate/');
define('VERSION_CHECK_URL','https://www.phpliteadmin.org/current_version.php');
define('PROJECT_BUGTRACKER_LINK','<a href="https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open" target="_blank">https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open</a>');
define('PROJECT_INSTALL_LINK','<a href="https://bitbucket.org/phpliteadmin/public/wiki/Installation" target="_blank">https://bitbucket.org/phpliteadmin/public/wiki/Installation</a>');
// up here, we don't output anything. debug output might appear here which is catched by ob and thrown later
ob_start();
// Resource output (css and javascript files)
// we get out of the main code as soon as possible, without inizializing the session
if (isset($_GET['resource']))
{
Resources::output($_GET['resource']);
exit();
}
// don't mess with this - required for the login session
ini_set('session.cookie_httponly', '1');
if(!session_start())
{
die("Could not start a new session. Check your php setup regarding sessions.");
}
// version-number added so after updating, old session-data is not used anylonger
// cookies names cannot contain symbols, except underscores
define("COOKIENAME", preg_replace('/[^a-zA-Z0-9_]/', '_', $cookie_name . '_' . VERSION) );
$params = new GetParameters();
if($debug==true)
{
ini_set("display_errors", 1);
error_reporting(E_STRICT | E_ALL);
} else
{
@ini_set("display_errors", 0);
}
// start the timer to record page load time
$pageTimer = new MicroTimer();
// load language file
if($language != 'en') {
$temp_lang=$lang;
if(is_file('languages/lang_'.$language.'.php'))
include('languages/lang_'.$language.'.php');
elseif(is_file('lang_'.$language.'.php'))
include('lang_'.$language.'.php');
$lang = array_merge($temp_lang, $lang);
unset($temp_lang);
}
// stripslashes if MAGIC QUOTES is turned on
// This is only a workaround. Please better turn off magic quotes!
// This code is from http://php.net/manual/en/security.magicquotes.disabling.php
if (is_callable('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
foreach($process as $key => $val) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
//data types array
$sqlite_datatypes = array("INTEGER", "REAL", "TEXT", "BLOB","NUMERIC","BOOLEAN","DATETIME");
//available SQLite functions array (don't add anything here or there will be problems)
$sqlite_functions = array("abs", "hex", "length", "lower", "ltrim", "random", "round", "rtrim", "trim", "typeof", "upper");
//- Support functions
// for php < 5.6.0
if(!function_exists('hash_equals'))
{
function hash_equals($str1, $str2)
{
if(strlen($str1) != strlen($str2))
return false;
else {
$res = $str1 ^ $str2;
$ret = 0;
for($i = strlen($res) - 1; $i >= 0; $i--)
$ret |= ord($res[$i]);
return !$ret;
}
}
}
// workaround if mbsting extension is missing. Sure this means no multibyte support.
if(!function_exists('mb_strlen'))
{
function mb_strlen($s)
{
return strlen($s);
}
}
if(!function_exists('mb_substr'))
{
function mb_substr($s, $start, $length=null, $encoding=null)
{
return substr($s, $start, null === $length ? 2147483647 : $length);
}
}
// no other mbstring functions used so far
//function that allows SQL delimiter to be ignored inside comments or strings
function explode_sql($delimiter, $sql)
{
$ign = array('"' => '"', "'" => "'", "/*" => "*/", "--" => "\n"); // Ignore sequences.
$out = array();
$last = 0;
$slen = strlen($sql);
$dlen = strlen($delimiter);
$i = 0;
while($i < $slen)
{
// Split on delimiter
if($slen - $i >= $dlen && substr($sql, $i, $dlen) == $delimiter)
{
array_push($out, substr($sql, $last, $i - $last));
$last = $i + $dlen;
$i += $dlen;
continue;
}
// Eat comments and string literals
foreach($ign as $start => $end)
{
$ilen = strlen($start);
if($slen - $i >= $ilen && substr($sql, $i, $ilen) == $start)
{
$i+=strlen($start);
$elen = strlen($end);
while($i < $slen)
{
if($slen - $i >= $elen && substr($sql, $i, $elen) == $end)
{
// SQL comment characters can be escaped by doubling the character. This recognizes and skips those.
if($start == $end && $slen - $i >= $elen*2 && substr($sql, $i, $elen*2) == $end.$end)
{
$i += $elen * 2;
continue;
}
else
{
$i += $elen;
continue 3;
}
}
$i++;
}
continue 2;
}
}
$i++;
}
if($last < $slen)
array_push($out, substr($sql, $last, $slen - $last));
return $out;
}
//function to scan entire directory tree and subdirectories
function dir_tree($dir)
{
$path = array();
$stack = array($dir);
while($stack)
{
$thisdir = array_pop($stack);
if($dircont = scandir($thisdir))
{
$i=0;
while(isset($dircont[$i]))
{
if($dircont[$i] !== '.' && $dircont[$i] !== '..')
{
$current_file = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
if(is_file($current_file))
{
$path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
}
elseif (is_dir($current_file))
{
$path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
//the function echo the help [?] links to the documentation
function helpLink($name)
{
global $lang;
return "<a href='?help=1' onclick='openHelp(\"".$name."\"); return false;' class='helpq' title='".$lang['help'].": ".$name."' target='_blank'><span>[?]</span></a>";
}
// function to encode value into HTML just like htmlentities, but with adjusted default settings
function htmlencode($value, $flags=ENT_QUOTES, $encoding ="UTF-8")
{
return htmlentities($value, $flags, $encoding);
}
// reduce string chars
function subString($str)
{
global $charsNum, $params;
if($charsNum > 10 && (!isset($params->fulltexts) || !$params->fulltexts) && mb_strlen($str)>$charsNum)
{
$str = mb_substr($str, 0, $charsNum).'...';
}
return $str;
}
// marks searchwords and htmlencodes correctly
function markSearchWords($input, $field, $search)
{
$output = htmlencode($input);
if(isset($search['values'][$field]) && is_array($search['values'][$field]))
{
// build one regex that matches (all) search words
$regex = '/';
$vali=0;
foreach($search['values'][$field] as $searchValue)
{
if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
$regex .= '(?:'.($searchValue[0]=='%'?'':'^'); // does the searchvalue have to occur at the start?
$regex .= preg_quote(trim($searchValue,'%'),'/'); // the search value
if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
$regex .= (substr($searchValue,-1)=='%'?'':'$').')'; // does the searchvalue have to occur at the end?
if($vali++<count($search['values'][$field]))
$regex .= '|'; // there is another search value, so we add a |
}
$regex .= '/u';
// LIKE operator is not case sensitive, others are
if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
$regex.= 'i';
// split the string into parts that match and should be highlighted and parts in between
// $fldBetweenParts: the parts that don't match (might contain empty strings)
$fldBetweenParts = preg_split($regex, $input);
// $fldFoundParts[0]: the parts that match
preg_match_all($regex, $input, $fldFoundParts);
// stick the parts together
$output = '';
foreach($fldBetweenParts as $index => $betweenPart)
{
$output .= htmlencode($betweenPart); // part that does not match (might be empty)
if(isset($fldFoundParts[0][$index]))
$output .= '<u class="found">'.htmlencode($fldFoundParts[0][$index]).'</u>'; // the part that matched
}
}
return $output;
}
// checks the (new) name of a database file
function checkDbName($name)
{
global $allowed_extensions;
$info = pathinfo($name);
if(isset($info['extension']) && !in_array($info['extension'], $allowed_extensions))
{
return false;
} else
{
return (!is_file($name) && !is_dir($name));
}
}
// check whether a path is a db managed by this tool
// requires that $databases is already filled!
// returns the key of the db if managed, false otherwise.
function isManagedDB($path)
{
global $databases;
foreach($databases as $db_key => $database)
{
if($path === $database['path'])
{
// a db we manage. Thats okay.
// return the key.
return $db_key;
}
}
// not a db we manage!
return false;
}
// from a typename of a colun, get the type of the column's affinty
// see https://www.sqlite.org/datatype3.html section 2.1 for rules
function get_type_affinity($type)
{
if (preg_match("/INT/i", $type))
return "INTEGER";
else if (preg_match("/(?:CHAR|CLOB|TEXT)/i", $type))
return "TEXT";
else if (preg_match("/BLOB/i", $type) || $type=="")
return "NONE";
else if (preg_match("/(?:REAL|FLOA|DOUB)/i", $type))
return "REAL";
else
return "NUMERIC";
}
// Returns a file size limit in bytes based on the PHP upload_max_filesize
// post_max_size and memory_limit. Returns -1 in case of no limit.
function fileUploadMaxSize()
{
$max1 = parseSize(ini_get('post_max_size'));
$max2 = parseSize(ini_get('upload_max_filesize'));
$max3 = parseSize(ini_get('memory_limit'));
if($max1>0 && ($max1<=$max2 || $max2==0) && ($max1<=$max3 || $max3==-1))
return $max1;
elseif($max2>0 && ($max2<=$max1 || $max1==0) && ($max2<=$max3 || $max3==-1))
return $max2;
elseif($max3>-1 && ($max3<=$max1 || $max1==0) && ($max3<=$max2 || $max2==0))
return $max3;
else
return -1; // no limit
}
// Parses given size string like "12M" into number of bytes
// based on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Bytes.php/function/Bytes%3A%3AtoInt/8.2.x
function parseSize($size)
{
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
// Remove the non-numeric characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size);
if ($unit)
{
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
}
else {
return round($size);
}
}
//- Check user authentication, login and logout
$auth = new Authorization(); //create authorization object
// check if user has attempted to log out
if (isset($_GET['logout']))
$auth->revoke();
// check if user has attempted to log in
else if (isset($_POST['login']) && isset($_POST['password']))
{
$attempt = $auth->attemptGrant($_POST['password'], isset($_POST['remember']));
$params->redirect( $attempt ? array():array('failed'=>'1') );
}
//- Actions on database files and bulk data
if ($auth->isAuthorized())
{
//- Create a new database
if(isset($_POST['new_dbname']))
{
if($_POST['new_dbname']=='')
$params->redirect(array('table'=>null), $lang['err'].': '.$lang['db_blank']);
else
{
$str = preg_replace('@[^\w\-.]@u','', $_POST['new_dbname']);
$dbname = $str;
$dbpath = $str;
if(checkDbName($dbname))
{
$tdata = array();
$tdata['name'] = $dbname;
$tdata['path'] = $directory.DIRECTORY_SEPARATOR.$dbpath;
if(isset($_POST['new_dbtype']))
$tdata['type'] = $_POST['new_dbtype'];
else
$tdata['type'] = 3;
$td = new Database($tdata);
$td->query("VACUUM");
} else
{
if(is_file($dbname) || is_dir($dbname))
$params->redirect(array('view'=>'structure'),$lang['err'].': '.sprintf($lang['db_exists'], htmlencode($dbname)));
else
$params->redirect(array('view'=>'structure'),$lang['extension_not_allowed'].': '.implode(', ', array_map('htmlencode', $allowed_extensions)).'<br />'.$lang['add_allowed_extension']);
}
}
}
//- Scan a directory for databases
if($directory!==false)
{
if($directory[strlen($directory)-1]==DIRECTORY_SEPARATOR) //if user has a trailing slash in the directory, remove it
$directory = substr($directory, 0, strlen($directory)-1);
if(is_dir($directory)) //make sure the directory is valid
{
if($subdirectories===true)
$arr = dir_tree($directory);
else
$arr = scandir($directory);
$databases = array();
$j = 0;
for($i=0; $i<sizeof($arr); $i++) //iterate through all the files in the databases
{
if($subdirectories===false)
$arr[$i] = $directory.DIRECTORY_SEPARATOR.$arr[$i];
if(@!is_file($arr[$i])) continue;
$con = file_get_contents($arr[$i], NULL, NULL, 0, 60);
if(strpos($con, "** This file contains an SQLite 2.1 database **", 0)!==false || strpos($con, "SQLite format 3", 0)!==false)
{
$databases[$j]['path'] = $arr[$i];
if($subdirectories===false)
$databases[$j]['name'] = basename($arr[$i]);
else
$databases[$j]['name'] = $arr[$i];
$databases[$j]['writable'] = is_writable($databases[$j]['path']);
$databases[$j]['writable_dir'] = is_writable(dirname($databases[$j]['path']));
$databases[$j]['readable'] = is_readable($databases[$j]['path']);
$j++;
}
}
// 22 August 2011: gkf fixed bug #50.
sort($databases);
if(isset($tdata))
{
foreach($databases as $db_id => $database)
{
if($database['path'] === $tdata['path'])
{
$currentDB = $database;
$params->database = $database['path'];
break;
}
}
}
}
else //the directory is not valid - display error and exit
{
echo "<div class='confirm' style='margin:20px;'>".$lang['not_dir']."</div>";
exit();
}
}
else
{
for($i=0; $i<sizeof($databases); $i++)
{
if(!file_exists($databases[$i]['path']))
{
// the file does not exist and will be created when clicked, if permissions allow to
$databases[$i]['writable'] = is_writable(dirname($databases[$i]['path']));
$databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path']));
$databases[$i]['readable'] = is_writable(dirname($databases[$i]['path']));
}
else
{
$databases[$i]['writable'] = is_writable($databases[$i]['path']);
$databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path']));
$databases[$i]['readable'] = is_readable($databases[$i]['path']);
}
}
sort($databases);
}
// we now have the $databases array set. Check whether selected DB is a managed Db (is in this array)
if(!isset($currentDB) && (isset($_GET['database']) || isset($_POST['database']) ) )
{
$selected_db = ( isset($_POST['database']) ? $_POST['database'] : $_GET['database'] );
$db_key = isManagedDB($selected_db);
if($db_key!==false) {
$currentDB = $databases[$db_key];
$params->database = $databases[$db_key]['path'];
}
}
//- Delete an existing database
if(isset($_GET['database_delete']))
{
$dbpath = $_POST['database_delete'];
// check whether $dbpath really is a db we manage
$checkDB = isManagedDB($dbpath);
if($checkDB !== false)
{
unlink($dbpath);
unset($params->database);
unset($currentDB);
unset($databases[$checkDB]);
} else die($lang['err'].': '.$lang['delete_only_managed']);
}
//- Rename an existing database
if(isset($_GET['database_rename']))
{
$oldpath = $_POST['oldname'];
$newpath = $_POST['newname'];
$oldpath_parts = pathinfo($oldpath);
$newpath_parts = pathinfo($newpath);
// only rename?
$newpath = $oldpath_parts['dirname'].DIRECTORY_SEPARATOR.basename($_POST['newname']);
if($newpath != $_POST['newname'] && $subdirectories)
{
// it seems that the file should not only be renamed but additionally moved.
// we need to make sure it stays within $directory...
$new_realpath = realpath($newpath_parts['dirname']).DIRECTORY_SEPARATOR;
$directory_realpath = realpath($directory).DIRECTORY_SEPARATOR;
if(strpos($new_realpath, $directory_realpath)===0)
{
// its okay, the new directory is within $directory
$newpath = $_POST['newname'];
}
else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['db_moved_outside']);
}
if(checkDbName($newpath))
{
$checkDB = isManagedDB($oldpath);
if($checkDB !==false )
{
rename($oldpath, $newpath);
$databases[$checkDB]['path'] = $newpath;
$databases[$checkDB]['name'] = basename($newpath);
$currentDB = $databases[$checkDB];
$params->database = $databases[$checkDB]['path'];
$params->redirect(array('view'=>'rename'), sprintf($lang['db_renamed'], htmlencode($oldpath))." '".htmlencode($newpath)."'.");
}
else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['rename_only_managed']);
}
else
{
if(is_file($newpath) || is_dir($newpath))
$params->redirect(array('view'=>'rename'), $lang['err'].": " . sprintf($lang['db_exists'], htmlencode($newpath)));
else
$params->redirect(array('view'=>'rename'), $lang['err'].": " . $lang['extension_not_allowed'].': '.implode(', ', array_map('htmlencode', $allowed_extensions)).'<br />'.$lang['add_allowed_extension']);
}
}
//- Export (download a dump) an existing database
if(isset($_POST['export']))
{
ob_end_clean();
$export_filename = str_replace(array("\r", "\n"), '',$_POST['filename']); // against http header injection (php < 5.1.2 only)
if($_POST['export_type']=="sql")
{
header('Content-Type: text/sql');
header('Content-Disposition: attachment; filename="'.$export_filename.'.'.$_POST['export_type'].'";');
if(isset($_POST['tables']))
$tables = $_POST['tables'];
else
{
$tables = array();
$tables[0] = $_POST['single_table'];
}
$drop = isset($_POST['drop']);
$structure = isset($_POST['structure']);
$data = isset($_POST['data']);
$transaction = isset($_POST['transaction']);
$comments = isset($_POST['comments']);
$db = new Database($currentDB);
$db->export_sql($tables, $drop, $structure, $data, $transaction, $comments);
}
else if($_POST['export_type']=="csv")
{
header("Content-type: application/csv");
header('Content-Disposition: attachment; filename="'.$export_filename.'.'.$_POST['export_type'].'";');
header("Pragma: no-cache");
header("Expires: 0");
if(isset($_POST['tables']))
$tables = $_POST['tables'];
else
{
$tables = array();
$tables[0] = $_POST['single_table'];
}
$field_terminate = $_POST['export_csv_fieldsterminated'];
$field_enclosed = $_POST['export_csv_fieldsenclosed'];
$field_escaped = $_POST['export_csv_fieldsescaped'];
$null = $_POST['export_csv_replacenull'];
$crlf = isset($_POST['export_csv_crlf']);
$fields_in_first_row = isset($_POST['export_csv_fieldnames']);
$db = new Database($currentDB);
$db->export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row);
}
exit();
}
//- Import a file into an existing database
if(isset($_POST['import']))
{
$db = new Database($currentDB);
$db->registerUserFunction($custom_functions);
if($_POST['import_type']=="sql")
{
$data = file_get_contents($_FILES["file"]["tmp_name"]);
$importSuccess = $db->import_sql($data);
}
else
{
$field_terminate = $_POST['import_csv_fieldsterminated'];
$field_enclosed = $_POST['import_csv_fieldsenclosed'];
$field_escaped = $_POST['import_csv_fieldsescaped'];
$null = $_POST['import_csv_replacenull'];
$fields_in_first_row = isset($_POST['import_csv_fieldnames']);
if(isset($_POST['single_table']) && $_POST['single_table']!='')
$table = $_POST['single_table'];
else
{
$table = basename($_FILES["file"]["name"],".csv");
$i="";
while($db->getTypeOfTable($table.$i)!="")
{
if($i=="")
$i=2;
else
$i++;
}
$table = $table.$i;
}
$importSuccess = $db->import_csv($_FILES["file"]["tmp_name"], $table, $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row);
}
}
//- Download (backup) a database file (as SQLite file, not as dump)
if(isset($_GET['download']) && isManagedDB($_GET['download'])!==false)
{
ob_end_clean();
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.basename($_GET['download']).'";');
header("Pragma: no-cache");
header("Expires: 0");
readfile($_GET['download']);
exit;
}
//- Select database (from session or first available)
if(!isset($currentDB) && count($databases)>0)
{
//set the current database to the first existing one in the array (default)
$currentDB = reset($databases);
$params->database = $currentDB['path'];
}
if(isset($currentDB))
{
//- Open database (creates a Database object)
$db = new Database($currentDB); //create the Database object
$db->registerUserFunction($custom_functions);
}
// collect parameters early, just once
$target_table = isset($_GET['table']) ? $_GET['table'] : null;
// are we working on a view? let's check once here
$target_table_type = !is_null($target_table) ? $db->getTypeOfTable($target_table) : null;
if(is_null($target_table_type) && !is_null($target_table))
$params->redirect(array('table'=>null), $lang['err'].': '.sprintf($lang['tbl_inexistent'], htmlencode($target_table)));
$params->table = $target_table;
// initialize / change fulltexts and numrows parameter
if(isset($_GET['fulltexts']))
$params->fulltexts = ($_GET['fulltexts'] ? 1 : 0);
else
$params->fulltexts = 0;
if(isset($_GET['numRows']) && intval($_GET['numRows'])>0)
$params->numRows = intval($_GET['numRows']);
else
$params->numRows = $rowsNum;
//- Switch on $_GET['action'] for operations without output
if(isset($_GET['action']) && isset($_GET['confirm']))
{
switch($_GET['action'])
{
//- Table actions
//- Create table (=table_create)
case "table_create":
$num = intval($_POST['rows']);
$name = $_POST['tablename'];
$primary_keys = array();
for($i=0; $i<$num; $i++)
{
if($_POST[$i.'_field']!="" && isset($_POST[$i.'_primarykey']))
{
$primary_keys[] = $_POST[$i.'_field'];
}
}
$query = "CREATE TABLE ".$db->quote($name)." (";
for($i=0; $i<$num; $i++)
{
if($_POST[$i.'_field']!="")
{
$query .= $db->quote($_POST[$i.'_field'])." ";
$query .= $_POST[$i.'_type']." ";
if(isset($_POST[$i.'_primarykey']))
{
if(count($primary_keys)==1)
{
$query .= "PRIMARY KEY ";
if(isset($_POST[$i.'_autoincrement']) && $db->getType() != "SQLiteDatabase")
$query .= "AUTOINCREMENT ";
}
$query .= "NOT NULL ";
}
if(!isset($_POST[$i.'_primarykey']) && isset($_POST[$i.'_notnull']))
$query .= "NOT NULL ";
if($_POST[$i.'_defaultoption']!='defined' && $_POST[$i.'_defaultoption']!='none' && $_POST[$i.'_defaultoption']!='expr')
$query .= "DEFAULT ".$_POST[$i.'_defaultoption']." ";
elseif($_POST[$i.'_defaultoption']=='expr')
$query .= "DEFAULT (".$_POST[$i.'_defaultvalue'].") ";
elseif(isset($_POST[$i.'_defaultvalue']) && $_POST[$i.'_defaultoption']=='defined')
{
$typeAffinity = get_type_affinity($_POST[$i.'_type']);
if(($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") && is_numeric($_POST[$i.'_defaultvalue']))
$query .= "DEFAULT ".$_POST[$i.'_defaultvalue']." ";
else
$query .= "DEFAULT ".$db->quote($_POST[$i.'_defaultvalue'])." ";
}
$query = substr($query, 0, -1);
$query .= ", ";
}
}
if (count($primary_keys)>1)
{
$compound_key = "";
foreach ($primary_keys as $primary_key)
{
$compound_key .= ($compound_key=="" ? "" : ", ") . $db->quote($primary_key);
}
$query .= "PRIMARY KEY (".$compound_key."), ";
}
$query = substr($query, 0, -2);
$query .= ")";
$result = $db->query($query);
if($result === false)
$completed = $db->getError(true);
else
$completed = $lang['tbl']." '".htmlencode($_POST['tablename'])."' ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
$params->redirect(($result===false ? array() : array('action'=>'column_view', 'table'=>$name) ), $completed);
break;
//- Empty table (=table_empty)
case "table_empty":
if(isset($_GET['pk']))
$tables = json_decode($_GET['pk']);
else
$tables=array($_GET['table']);
$query1 = "BEGIN; ";
foreach($tables as $table)
{
if($db->getTypeOfTable($table)=='table')
$query1 .= "DELETE FROM ".$db->quote_id($table)."; ";
}
$query1 .= "COMMIT; ";
$result1=$db->multiQuery($query1);
if($result1 === false)
$completed = $db->getError(true);
if(isset($_POST['vacuum']) && $_POST['vacuum'])
{
$query2 = "VACUUM;";
$result2 = $db->query($query2);
}
else
$query2 = "";
if($result1 !== false)
$completed = $lang['tbl']." '".htmlencode(implode(', ',$tables))."' ".$lang['emptied'].".<br/><span style='font-size:11px;'>".htmlencode($query1)."<br />".htmlencode($query2)."</span>";
if(count($tables)==1)
$action = array('action'=>'row_view');
else
$action = array();
$params->redirect(($result1===false ? array() : $action ), $completed);
break;
//- Create view (=view_create)
case "view_create":
$query = "CREATE VIEW ".$db->quote($_POST['viewname'])." AS ".$_POST['select'];
$result = $db->query($query);
if($result === false)
$completed = $db->getError(true);
else
$completed = $lang['view']." '".htmlencode($_POST['viewname'])."' ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
$params->redirect(($result===false ? array() : array('action'=>'column_view', 'table'=>$_POST['viewname']) ), $completed);
break;
//- Drop table (or view) (=table_drop)
case "table_drop":
if(isset($_GET['pk']))
$tables = json_decode($_GET['pk']);
else
$tables=array($_GET['table']);
$query1 = "BEGIN; ";
foreach($tables as $table)
{
if($db->getTypeOfTable($table)=='table')
$query1 .= "DROP TABLE ".$db->quote_id($table)."; ";
else
$query1 .= "DROP VIEW ".$db->quote_id($table)."; ";
}
$query1 .= "COMMIT; ";
$result1=$db->multiQuery($query1);
if($result1 === false)
$completed = $db->getError(true);
if(isset($_POST['vacuum']) && $_POST['vacuum'])
{
$query2 = "VACUUM;";
$result2 = $db->query($query2);
}
else
$query2 = "";
if($result1 !== false)
{
$target_table = null;
$completed = $lang['tbl'].' / '.$lang['view']." '".htmlencode(implode(', ',$tables))."' ".$lang['dropped'].".<br/><span style='font-size:11px;'>".htmlencode($query1)."<br />".htmlencode($query2)."</span>";;
}
$params->redirect(array('table'=>null), $completed);
break;
//- Rename table (=table_rename)
case "table_rename":
$query = "ALTER TABLE ".$db->quote_id($_GET['table'])." RENAME TO ".$db->quote($_POST['newname']);
$type = $db->getTypeOfTable($_GET['table']);
if($db->getVersion()==3 && $type=='table' // SQLite 3 can rename tables, not views
// In SQL(ite) table names are case-insensitve, so changing is not supported by SQLite.
// But table names are stored and displayed case sensitive, so we use the workaround for case sensitive renaming.
&& !($_GET['table'] !== $_POST['newname'] && strtolower($_GET['table']) === strtolower($_POST['newname']))
)
$result = $db->query($query, true);
else
// Workaround can rename tables of sqlite2 and views of both sqlite versions. Can also do case sensitive renames.
$result = $db->query($query, false);
if($result === false)
$completed = $db->getError(true);
else
{
$completed = $lang['tbl']." '".htmlencode($_GET['table'])."' ".$lang['renamed']." '".htmlencode($_POST['newname'])."'.<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
$target_table = $_POST['newname'];
}
$params->redirect(array('action'=>'row_view', 'table'=>$_POST['newname']), $completed);
break;
//- Search table (=table_search)
case "table_search":
$searchValues = array();
$searchOperators = array();
$tableInfo = $db->getTableInfo($target_table);
$j = 0;
$whereExpr = array();
for($i=0; $i<sizeof($tableInfo); $i++)
{
$field = $tableInfo[$i][1];
$operator = $_POST['field_'.$i.'_operator'];
$searchOperators[$field] = $operator;
$value = $_POST['field_'.$i.'_value'];
if($value!="" || $operator=="!= ''" || $operator=="= ''" || $operator == 'IS NULL' || $operator == 'IS NOT NULL')
{
if($operator=="= ''" || $operator=="!= ''" || $operator == 'IS NULL' || $operator == 'IS NOT NULL')
$whereExpr[$j] = $db->quote_id($field)." ".$operator;
else{
if($operator == "LIKE%"){
$operator = "LIKE";
if(!preg_match('/(^%)|(%$)/', $value)) $value = '%'.$value.'%';
$searchValues[$field] = array($value);
$valueQuoted = $db->quote($value);
}
elseif($operator == 'IN' || $operator == 'NOT IN')
{
$value = trim($value, '() ');
$values = explode(',',$value);
$values = array_map('trim', $values, array_fill(0,count($values),' \'"'));
if($operator == 'IN')
$searchValues[$field] = $values;
$values = array_map(array($db, 'quote'), $values);
$valueQuoted = '(' .implode(', ', $values) . ')';
}
else
{
$searchValues[$field] = array($value);
$valueQuoted = $db->quote($value);
}
$whereExpr[$j] = $db->quote_id($field)." ".$operator." ".$valueQuoted;
}
$j++;
}
}
$searchWhere = '';
if(sizeof($whereExpr)>0)
{
$searchWhere .= " WHERE ".$whereExpr[0];
for($i=1; $i<sizeof($whereExpr); $i++)
{
$searchWhere .= " AND ".$whereExpr[$i];
}
}
$searchID = md5($searchWhere);
$_SESSION[COOKIENAME.'search'][$searchID] = array(
'where' => $searchWhere,
'values' => $searchValues,
'operators' => $searchOperators
);
$params->redirect(array('action'=>'table_search','search'=>$searchID));
break;
//- Row actions
//- Create row (=row_create)
case "row_create":
$completed = "";
$num = $_POST['newRows'];
$z = 0;
$error = false;
$tableInfo = $db->getTableInfo($target_table);
for($i=0; $i<$num; $i++)
{
if(!isset($_POST[$i.":ignore"]))
{
$query_cols = "";
$query_vals = "";
$all_default = true;
for($j=0; $j<sizeof($tableInfo); $j++)
{
$null = isset($_POST[$j."_null"][$i]);
$type = strtoupper($tableInfo[$j]['type']);
$typeAffinity = get_type_affinity($type);
if(!$null && isset($_POST[$i.":".$j]))
$value = $_POST[$i.":".$j];
else
$value = "";
if(preg_match('/^BLOB/', $type) && !$hexblobs)
{
if($_FILES[$i.":".$j]["error"] == UPLOAD_ERR_OK && is_file($_FILES[$i.":".$j]["tmp_name"]))
$blobFiles[$j] = $_FILES[$i.":".$j]["tmp_name"];
else
$blobFiles[$j] = null;
}
elseif($value===$tableInfo[$j]['dflt_value'])
{
// if the value is the default value, skip it
continue;