/
phpliteadmin.php
3320 lines (3184 loc) · 114 KB
/
phpliteadmin.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
//
// Project: phpLiteAdmin (http://phpliteadmin.googlecode.com)
// Version: 1.8.8
// Summary: PHP-based admin tool to manage SQLite2 and SQLite3 databases on the web
// Last updated: 10/19/11
// Developers:
// Dane Iracleous (daneiracleous@gmail.com)
// Ian Aldrighetti (ian.aldrighetti@gmail.com)
// George Flanagin & Digital Gaslight, Inc (george@digitalgaslight.com)
//
//
// Copyright (C) 2011 phpLiteAdmin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////////
//please report any bugs you encounter to http://code.google.com/p/phpliteadmin/issues/list
//password to gain access (change this to something more secure than 'admin')
$password = "admin";
//directory relative to this file to search for SQLite databases (if false, manually list databases below)
$directory = ".";
//whether or not (true or false) to scan the subdirectories of the above directory infinitely deep
$subdirectories = false;
//if the above $directory variable is set to false, you must specify the databases manually in an array as the next variable
//if any of the databases do not exist as they are referenced by their path, they will be created automatically if possible
$databases = array
(
array
(
"path"=> "database1.sqlite",
"name"=> "Database 1"
),
array
(
"path"=> "database2.sqlite",
"name"=> "Database 2"
)
);
// What should the name of the cookie be which contains the current password?
// Changing this allows multiple phpLiteAdmin installs to work under the same domain.
$cookie_name = 'pla3412';
//end of the variables you may need to edit
session_start(); //don't mess with this - required for the login session
date_default_timezone_set(date_default_timezone_get()); //needed to fix STRICT warnings about timezone issues
//toggle error reporting
ini_set("display_errors", 1);
error_reporting(E_STRICT | E_ALL);
$startTimeTot = microtime(true); //start the timer to record page load time
//the salt and password encrypting is probably unnecessary protection but is done just for the sake of being very secure
//create a random salt for this session if a cookie doesn't already exist for it
if(!isset($_SESSION[$cookie_name.'_salt']) && !isset($_COOKIE[$cookie_name.'_salt']))
{
$n = rand(10e16, 10e20);
$_SESSION[$cookie_name.'_salt'] = base_convert($n, 10, 36);
}
else if(!isset($_SESSION[$cookie_name.'_salt']) && isset($_COOKIE[$cookie_name.'_salt'])) //session doesn't exist, but cookie does so grab it
{
$_SESSION[$cookie_name.'_salt'] = $_COOKIE[$cookie_name.'_salt'];
}
//build the basename of this file for later reference
$info = pathinfo($_SERVER['PHP_SELF']);
$thisName = $info['basename'];
//constants
define("PROJECT", "phpLiteAdmin");
define("VERSION", "1.8.8");
define("PAGE", $thisName);
define("COOKIENAME", $cookie_name);
define("SYSTEMPASSWORD", $password); // Makes things easier.
define("SYSTEMPASSWORDENCRYPTED", md5($password."_".$_SESSION[$cookie_name.'_salt'])); //extra security - salted and encrypted password used for checking
define("FORCETYPE", false); //force the extension that will be used (set to false in almost all circumstances except debugging)
//data types array
$types = array("INTEGER", "REAL", "TEXT", "BLOB");
define("DATATYPES", serialize($types));
//available SQLite functions array
$functions = array("abs", "date", "datetime", "hex", "julianday", "length", "lower", "ltrim", "random", "round", "rtrim", "soundex", "time", "trim", "typeof", "upper");
define("FUNCTIONS", serialize($functions));
//function to scan entire directory tree and subdirectories
function dir_tree($dir)
{
$path = '';
$stack[] = $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}/{$dircont[$i]}";
if(is_file($current_file))
{
$path[] = "{$thisdir}/{$dircont[$i]}";
}
elseif (is_dir($current_file))
{
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
//if the user wants to scan a directory for databases, do so
if($directory!==false)
{
if($directory[strlen($directory)-1]=="/") //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
{
$file = pathinfo($arr[$i]);
if(isset($file['extension']))
{
$ext = strtolower($file['extension']);
if($ext=="sqlite" || $ext=="db" || $ext=="sqlite3" || $ext=="db3") //make sure the file is a valid SQLite database by checking its extension
{
if($subdirectories===true)
$databases[$j]['path'] = $arr[$i];
else
$databases[$j]['path'] = $directory."/".$arr[$i];
$databases[$j]['name'] = $arr[$i];
// 22 August 2011: gkf fixed bug 49.
$perms = 0;
$perms += is_readable($databases[$j]['path']) ? 4 : 0;
$perms += is_writeable($databases[$j]['path']) ? 2 : 0;
switch($perms)
{
case 6: $perms = "[rw] "; break;
case 4: $perms = "[r ] "; break;
case 2: $perms = "[ w] "; break; // God forbid, but it might happen.
default: $perms = "[ ] "; break;
}
$databases[$j]['perms'] = $perms;
$j++;
}
}
}
// 22 August 2011: gkf fixed bug #50.
sort($databases);
}
else //the directory is not valid - display error and exit
{
echo "<div class='confirm' style='margin:20px;'>";
echo "The directory you specified to scan for databases does not exist or is not a directory.";
echo "</div>";
exit();
}
}
// 22 August 2011: gkf added this function to support display of
// default values in the form used to INSERT new data.
function deQuoteSQL($s)
{
return trim(trim($s), "'");
}
//
// Authorization class
// Maintains user's logged-in state and security of application
//
class Authorization
{
public function grant($remember)
{
if($remember) //user wants to be remembered, so set a cookie
{
$expire = time()+60*60*24*30; //set expiration to 1 month from now
setcookie(COOKIENAME, SYSTEMPASSWORD, $expire);
setcookie(COOKIENAME."_salt", $_SESSION[COOKIENAME.'_salt'], $expire);
}
else
{
//user does not want to be remembered, so destroy any potential cookies
setcookie(COOKIENAME, "", time()-86400);
setcookie(COOKIENAME."_salt", "", time()-86400);
unset($_COOKIE[COOKIENAME]);
unset($_COOKIE[COOKIENAME.'_salt']);
}
$_SESSION[COOKIENAME.'password'] = SYSTEMPASSWORDENCRYPTED;
}
public function revoke()
{
//destroy everything - cookies and session vars
setcookie(COOKIENAME, "", time()-86400);
setcookie(COOKIENAME."_salt", "", time()-86400);
unset($_COOKIE[COOKIENAME]);
unset($_COOKIE[COOKIENAME.'_salt']);
session_unset();
session_destroy();
}
public function isAuthorized()
{
// Is this just session long? (What!?? -DI)
if((isset($_SESSION[COOKIENAME.'password']) && $_SESSION[COOKIENAME.'password'] == SYSTEMPASSWORDENCRYPTED) || (isset($_COOKIE[COOKIENAME]) && isset($_COOKIE[COOKIENAME.'_salt']) && md5($_COOKIE[COOKIENAME]."_".$_COOKIE[COOKIENAME.'_salt']) == SYSTEMPASSWORDENCRYPTED))
return true;
else
{
return false;
}
}
}
//
// Database class
// Generic database abstraction class to manage interaction with database without worrying about SQLite vs. PHP versions
//
class Database
{
protected $db; //reference to the DB object
protected $type; //the extension for PHP that handles SQLite
protected $data;
protected $lastResult;
public function __construct($data)
{
$this->data = $data;
try
{
if(file_exists($this->data["path"]) && !is_writable($this->data["path"])) //make sure the actual database file is writable
{
echo "<div class='confirm' style='margin:20px;'>";
echo "The database, '".$this->data["path"]."', is not writable. The application is unusable until you make it writable.";
echo "<form action='".PAGE."' method='post'/>";
echo "<input type='submit' value='Log Out' name='logout' class='btn'/>";
echo "</form>";
echo "</div><br/>";
exit();
}
if(!file_exists($this->data["path"]) && !is_writable(dirname($this->data["path"]))) //make sure the containing directory is writable if the database does not exist
{
echo "<div class='confirm' style='margin:20px;'>";
echo "The database, '".$this->data["path"]."', does not exist and cannot be created because the containing directory, '".dirname($this->data["path"])."', is not writable. The application is unusable until you make it writable.";
echo "<form action='".PAGE."' method='post'/>";
echo "<input type='submit' value='Log Out' name='logout' class='btn'/>";
echo "</form>";
echo "</div><br/>";
exit();
}
$ver = $this->getVersion();
switch(true)
{
case (FORCETYPE=="PDO" || ((FORCETYPE==false || $ver!=-1) && class_exists("PDO") && ($ver==-1 || $ver==3))):
$this->db = new PDO("sqlite:".$this->data['path']);
if($this->db!=NULL)
{
$this->type = "PDO";
break;
}
case (FORCETYPE=="SQLite3" || ((FORCETYPE==false || $ver!=-1) && class_exists("SQLite3") && ($ver==-1 || $ver==3))):
$this->db = new SQLite3($this->data['path']);
if($this->db!=NULL)
{
$this->type = "SQLite3";
break;
}
case (FORCETYPE=="SQLiteDatabase" || ((FORCETYPE==false || $ver!=-1) && class_exists("SQLiteDatabase") && ($ver==-1 || $ver==2))):
$this->db = new SQLiteDatabase($this->data['path']);
if($this->db!=NULL)
{
$this->type = "SQLiteDatabase";
break;
}
default:
$this->showError();
exit();
}
}
catch(Exception $e)
{
$this->showError();
exit();
}
}
public function showError()
{
$classPDO = class_exists("PDO");
$classSQLite3 = class_exists("SQLite3");
$classSQLiteDatabase = class_exists("SQLiteDatabase");
if($classPDO)
$strPDO = "installed";
else
$strPDO = "not installed";
if($classSQLite3)
$strSQLite3 = "installed";
else
$strSQLite3 = "not installed";
if($classSQLiteDatabase)
$strSQLiteDatabase = "installed";
else
$strSQLiteDatabase = "not installed";
echo "<div class='confirm' style='margin:20px;'>";
echo "There was a problem setting up your database, ".$this->getPath().". An attempt will be made to find out what's going on so you can fix the problem more easily.<br/><br/>";
echo "<i>Checking supported SQLite PHP extensions...<br/><br/>";
echo "<b>PDO</b>: ".$strPDO."<br/>";
echo "<b>SQLite3</b>: ".$strSQLite3."<br/>";
echo "<b>SQLiteDatabase</b>: ".$strSQLiteDatabase."<br/><br/>...done.</i><br/><br/>";
if(!$classPDO && !$classSQLite3 && !$classSQLiteDatabase)
echo "It appears that none of the supported SQLite library extensions are available in your installation of PHP. You may not use ".PROJECT." until you install at least one of them.";
else
{
if(!$classPDO && !$classSQLite3 && $this->getVersion()==3)
echo "It appears that your database is of SQLite version 3 but your installation of PHP does not contain the necessary extensions to handle this version. To fix the problem, either delete the database and allow ".PROJECT." to create it automatically or recreate it manually as SQLite version 2.";
else if(!$classSQLiteDatabase && $this->getVersion()==2)
echo "It appears that your database is of SQLite version 2 but your installation of PHP does not contain the necessary extensions to handle this version. To fix the problem, either delete the database and allow ".PROJECT." to create it automatically or recreate it manually as SQLite version 3.";
else
echo "The problem cannot be diagnosed properly. Please email me at daneiracleous@gmail.com with your database as an attachment and the contents of this error message. It may be that your database is simply not a valid SQLite database, but this is not certain.";
}
echo "</div><br/>";
}
public function __destruct()
{
if($this->db)
$this->close();
}
//get the exact PHP extension being used for SQLite
public function getType()
{
return $this->type;
}
//get the name of the database
public function getName()
{
return $this->data["name"];
}
//get the filename of the database
public function getPath()
{
return $this->data["path"];
}
//get the version of the database
public function getVersion()
{
if(file_exists($this->data['path'])) //make sure file exists before getting its contents
{
$content = strtolower(file_get_contents($this->data['path'], NULL, NULL, 0, 40)); //get the first 40 characters of the database file
$p = strpos($content, "** this file contains an sqlite 2"); //this text is at the beginning of every SQLite2 database
if($p!==false) //the text is found - this is version 2
return 2;
else
return 3;
}
else //return -1 to indicate that it does not exist and needs to be created
{
return -1;
}
}
//get the size of the database
public function getSize()
{
return round(filesize($this->data["path"])*0.0009765625, 1)." Kb";
}
//get the last modified time of database
public function getDate()
{
return date("g:ia \o\\n F j, Y", filemtime($this->data["path"]));
}
//get number of affected rows from last query
public function getAffectedRows()
{
if($this->type=="PDO")
return $this->lastResult->rowCount();
else if($this->type=="SQLite3")
return $this->db->changes();
else if($this->type=="SQLiteDatabase")
return $this->db->changes();
}
public function close()
{
if($this->type=="PDO")
$this->db = NULL;
else if($this->type=="SQLite3")
$this->db->close();
else if($this->type=="SQLiteDatabase")
$this->db = NULL;
}
public function beginTransaction()
{
$this->query("BEGIN");
}
public function commitTransaction()
{
$this->query("COMMIT");
}
public function rollbackTransaction()
{
$this->query("ROLLBACK");
}
//generic query wrapper
public function query($query, $ignoreAlterCase=false)
{
if(strtolower(substr(ltrim($query),0,5))=='alter' && $ignoreAlterCase==false) //this query is an ALTER query - call the necessary function
{
$queryparts = preg_split("/[\s]+/", $query, 4, PREG_SPLIT_NO_EMPTY);
$tablename = $queryparts[2];
$alterdefs = $queryparts[3];
//echo $query;
$result = $this->alterTable($tablename, $alterdefs);
}
else //this query is normal - proceed as normal
$result = $this->db->query($query);
if(!$result)
return NULL;
$this->lastResult = $result;
return $result;
}
//wrapper for an INSERT and returns the ID of the inserted row
public function insert($query)
{
$result = $this->query($query);
if($this->type=="PDO")
return $this->db->lastInsertId();
else if($this->type=="SQLite3")
return $this->db->lastInsertRowID();
else if($this->type=="SQLiteDatabase")
return $this->db->lastInsertRowid();
}
//returns an array for SELECT
public function select($query, $mode="both")
{
$result = $this->query($query);
if(!$result) //make sure the result is valid
return NULL;
if($this->type=="PDO")
{
if($mode=="assoc")
$mode = PDO::FETCH_ASSOC;
else if($mode=="num")
$mode = PDO::FETCH_NUM;
else
$mode = PDO::FETCH_BOTH;
return $result->fetch($mode);
}
else if($this->type=="SQLite3")
{
if($mode=="assoc")
$mode = SQLITE3_ASSOC;
else if($mode=="num")
$mode = SQLITE3_NUM;
else
$mode = SQLITE3_BOTH;
return $result->fetchArray($mode);
}
else if($this->type=="SQLiteDatabase")
{
if($mode=="assoc")
$mode = SQLITE_ASSOC;
else if($mode=="num")
$mode = SQLITE_NUM;
else
$mode = SQLITE_BOTH;
return $result->fetch($mode);
}
}
//returns an array of arrays after doing a SELECT
public function selectArray($query, $mode="both")
{
$result = $this->query($query);
if(!$result) //make sure the result is valid
return NULL;
if($this->type=="PDO")
{
if($mode=="assoc")
$mode = PDO::FETCH_ASSOC;
else if($mode=="num")
$mode = PDO::FETCH_NUM;
else
$mode = PDO::FETCH_BOTH;
return $result->fetchAll($mode);
}
else if($this->type=="SQLite3")
{
if($mode=="assoc")
$mode = SQLITE3_ASSOC;
else if($mode=="num")
$mode = SQLITE3_NUM;
else
$mode = SQLITE3_BOTH;
$arr = array();
$i = 0;
while($res = $result->fetchArray($mode))
{
$arr[$i] = $res;
$i++;
}
return $arr;
}
else if($this->type=="SQLiteDatabase")
{
if($mode=="assoc")
$mode = SQLITE_ASSOC;
else if($mode=="num")
$mode = SQLITE_NUM;
else
$mode = SQLITE_BOTH;
return $result->fetchAll($mode);
}
}
//function that is called for an alter table statement in a query
//code borrowed with permission from http://code.jenseng.com/db/
public function alterTable($table, $alterdefs)
{
if($alterdefs != '')
{
$tempQuery = "SELECT sql,name,type FROM sqlite_master WHERE tbl_name = '".$table."' ORDER BY type DESC";
$result = $this->query($tempQuery);
$resultArr = $this->selectArray($tempQuery);
if(sizeof($resultArr)>0)
{
$row = $this->select($tempQuery); //table sql
$tmpname = 't'.time();
$origsql = trim(preg_replace("/[\s]+/", " ", str_replace(",", ", ",preg_replace("/[\(]/", "( ", $row['sql'], 1))));
$createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'", $tmpname, $origsql, 1)), 6);
$createindexsql = array();
$i = 0;
$defs = preg_split("/[,]+/",$alterdefs, -1, PREG_SPLIT_NO_EMPTY);
$prevword = $table;
$oldcols = preg_split("/[,]+/", substr(trim($createtemptableSQL), strpos(trim($createtemptableSQL), '(')+1), -1, PREG_SPLIT_NO_EMPTY);
$newcols = array();
for($i=0; $i<sizeof($oldcols); $i++)
{
$colparts = preg_split("/[\s]+/", $oldcols[$i], -1, PREG_SPLIT_NO_EMPTY);
$oldcols[$i] = $colparts[0];
$newcols[$colparts[0]] = $colparts[0];
}
$newcolumns = '';
$oldcolumns = '';
reset($newcols);
while(list($key, $val) = each($newcols))
{
$newcolumns .= ($newcolumns?', ':'').$val;
$oldcolumns .= ($oldcolumns?', ':'').$key;
}
$copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
$dropoldsql = 'DROP TABLE '.$table;
$createtesttableSQL = $createtemptableSQL;
foreach($defs as $def)
{
$defparts = preg_split("/[\s]+/", $def,-1, PREG_SPLIT_NO_EMPTY);
$action = strtolower($defparts[0]);
switch($action)
{
case 'add':
if(sizeof($defparts) <= 2)
return false;
$createtesttableSQL = substr($createtesttableSQL, 0, strlen($createtesttableSQL)-1).',';
for($i=1;$i<sizeof($defparts);$i++)
$createtesttableSQL.=' '.$defparts[$i];
$createtesttableSQL.=')';
break;
case 'change':
if(sizeof($defparts) <= 3)
{
return false;
}
if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' '))
{
if($newcols[$defparts[1]] != $defparts[1])
return false;
$newcols[$defparts[1]] = $defparts[2];
$nextcommapos = strpos($createtesttableSQL,',',$severpos);
$insertval = '';
for($i=2;$i<sizeof($defparts);$i++)
$insertval.=' '.$defparts[$i];
if($nextcommapos)
$createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
else
$createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
}
else
return false;
break;
case 'drop':
if(sizeof($defparts) < 2)
return false;
if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' '))
{
$nextcommapos = strpos($createtesttableSQL,',',$severpos);
if($nextcommapos)
$createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
else
$createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
unset($newcols[$defparts[1]]);
}
else
return false;
break;
default:
return false;
}
$prevword = $defparts[sizeof($defparts)-1];
}
//this block of code generates a test table simply to verify that the columns specifed are valid in an sql statement
//this ensures that no reserved words are used as columns, for example
$tempResult = $this->query($createtesttableSQL);
if(!$tempResult)
return false;
$droptempsql = 'DROP TABLE '.$tmpname;
$tempResult = $this->query($droptempsql);
//end block
$createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'", $table, $createtesttableSQL, 1)), 17);
$newcolumns = '';
$oldcolumns = '';
reset($newcols);
while(list($key,$val) = each($newcols))
{
$newcolumns .= ($newcolumns?', ':'').$val;
$oldcolumns .= ($oldcolumns?', ':'').$key;
}
$copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
$this->query($createtemptableSQL); //create temp table
$this->query($copytotempsql); //copy to table
$this->query($dropoldsql); //drop old table
$this->query($createnewtableSQL); //recreate original table
$this->query($copytonewsql); //copy back to original table
$this->query($droptempsql); //drop temp table
}
else
{
return false;
}
return true;
}
}
//multiple query execution
public function multiQuery($query)
{
if($this->type=="PDO")
{
$success = $this->db->exec($query, $error);
}
else if($this->type=="SQLite3")
{
$success = $this->db->exec($query, $error);
}
else
{
$success = $this->db->queryExec($query, $error);
}
if(!$success)
{
return "Error in query: '".$error."'";
}
else
{
return true;
}
}
//get number of rows in table
public function numRows($table)
{
$result = $this->select("SELECT Count(*) FROM ".$table);
return $result[0];
}
//correctly escape a string to be injected into an SQL query
public function quote($value)
{
if($this->type=="PDO")
{
return $this->db->quote($value);
}
else if($this->type=="SQLite3")
{
return $this->db->escapeString($value);
}
else
{
return "'".$value."'";
}
}
//correctly format a string value from a table before showing it
public function formatString($value)
{
return htmlspecialchars(stripslashes($value));
}
//import
public function import($query)
{
return $this->multiQuery($query);
}
//export
public function export($tables, $drop, $structure, $data, $transaction, $comments)
{
if($comments)
{
echo "----\r\n";
echo "-- phpLiteAdmin database dump (http://phpliteadmin.googlecode.com)\r\n";
echo "-- phpLiteAdmin version: ".VERSION."\r\n";
echo "-- Exported on ".date('M jS, Y, h:i:sA')."\r\n";
echo "-- Database file: ".$this->getPath()."\r\n";
echo "----\r\n";
}
$query = "SELECT * FROM sqlite_master WHERE type='table' OR type='index' ORDER BY type DESC";
$result = $this->selectArray($query);
//iterate through each table
for($i=0; $i<sizeof($result); $i++)
{
$valid = false;
for($j=0; $j<sizeof($tables); $j++)
{
if($result[$i]['tbl_name']==$tables[$j])
$valid = true;
}
if($valid)
{
if($drop)
{
if($comments)
{
echo "\r\n----\r\n";
if($result[$i]['type']=="table")
echo "-- Drop table for ".$result[$i]['tbl_name']."\r\n";
else
echo "-- Drop index for ".$result[$i]['name']."\r\n";
echo "----\r\n";
}
if($result[$i]['type']=="table")
echo "DROP TABLE '".$result[$i]['tbl_name']."';\r\n";
else
echo "DROP INDEX '".$result[$i]['name']."';\r\n";
}
if($structure)
{
if($comments)
{
echo "\r\n----\r\n";
if($result[$i]['type']=="table")
echo "-- Table structure for ".$result[$i]['tbl_name']."\r\n";
else
echo "-- Structure for index ".$result[$i]['name']." on table ".$result[$i]['tbl_name']."\r\n";
echo "----\r\n";
}
echo $result[$i]['sql'].";\r\n";
}
if($data && $result[$i]['type']=="table")
{
$query = "SELECT * FROM ".$result[$i]['tbl_name'];
$arr = $this->selectArray($query, "assoc");
if($comments)
{
echo "\r\n----\r\n";
echo "-- Data dump for ".$result[$i]['tbl_name'].", a total of ".sizeof($arr)." rows\r\n";
echo "----\r\n";
}
$query = "PRAGMA table_info('".$result[$i]['tbl_name']."')";
$temp = $this->selectArray($query);
$cols = array();
$vals = array();
for($z=0; $z<sizeof($temp); $z++)
$cols[$z] = $temp[$z][1];
for($z=0; $z<sizeof($arr); $z++)
{
for($y=0; $y<sizeof($cols); $y++)
{
if(!isset($vals[$z]))
$vals[$z] = array();
$vals[$z][$cols[$y]] = $this->quote($arr[$z][$cols[$y]]);
}
}
if($transaction)
echo "BEGIN TRANSACTION;\r\n";
for($j=0; $j<sizeof($vals); $j++)
echo "INSERT INTO ".$result[$i]['tbl_name']." (".implode(",", $cols).") VALUES (".implode(",", $vals[$j]).");\r\n";
if($transaction)
echo "COMMIT;\r\n";
}
}
}
}
}
$auth = new Authorization(); //create authorization object
if(isset($_POST['logout'])) //user has attempted to log out
$auth->revoke();
else if(isset($_POST['login']) || isset($_POST['proc_login'])) //user has attempted to log in
{
$_POST['login'] = true;
if($_POST['password']==SYSTEMPASSWORD) //make sure passwords match before granting authorization
{
if(isset($_POST['remember']))
$auth->grant(true);
else
$auth->grant(false);
}
}
//user is downloading the exported database file
if(isset($_POST['export']))
{
header('Content-Type: text/sql');
header('Content-Disposition: attachment; filename="'.$_POST['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($databases[$_SESSION[COOKIENAME.'currentDB']]);
echo $db->export($tables, $drop, $structure, $data, $transaction, $comments);
exit();
}
//user is importing a file
if(isset($_POST['import']))
{
$data = file_get_contents($_FILES["file"]["tmp_name"]);
$db = new Database($databases[$_SESSION[COOKIENAME.'currentDB']]);
$importSuccess = $db->import($data);
}
// here begins the HTML.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
<title><?php echo PROJECT ?></title>
<?php
if(!file_exists("phpliteadmin.css")) //only use the inline stylesheet if an external one does not exist
{
?>
<!-- begin the customizable stylesheet/theme -->
<style type="text/css">
/* overall styles for entire page */
body
{
margin: 0px;
padding: 0px;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
color: #000000;
background-color: #e0ebf6;
}
/* general styles for hyperlink */
a
{
color: #03F;
text-decoration: none;
cursor :pointer;
}
hr
{
height: 1px;
border: 0;
color: #bbb;
background-color: #bbb;
width: 100%;
}
a:hover
{
color: #06F;
}
/* logo text containing name of project */
h1
{
margin: 0px;
padding: 5px;
font-size: 24px;
background-color: #f3cece;
text-align: center;
margin-bottom: 10px;
color: #000;
border-top-left-radius:5px;
border-top-right-radius:5px;
-moz-border-radius-topleft:5px;
-moz-border-radius-topright:5px;
}
/* version text within the logo */
h1 #version
{
color: #000000;
font-size: 16px;
}
/* logo text within logo */
h1 #logo
{
color:#000;
}
/* general header for various views */
h2
{
margin:0px;
padding:0px;
font-size:14px;
margin-bottom:20px;
}
/* input buttons and areas for entering text */
input, select, textarea
{
font-family:Arial, Helvetica, sans-serif;
background-color:#eaeaea;
color:#03F;
border-color:#03F;
border-style:solid;
border-width:1px;
margin:5px;
border-radius:5px;
-moz-border-radius:5px;
padding:3px;
}
/* just input buttons */
input.btn
{
cursor:pointer;
}
input.btn:hover
{
background-color:#ccc;
}
/* general styles for hyperlink */
fieldset
{
padding:15px;
border-color:#03F;