PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/phpliteadmin.php

https://bitbucket.org/nicolus/delation
PHP | 4793 lines | 4597 code | 80 blank | 116 comment | 226 complexity | 3e15b00a35eb38a2d93fff5b6fa297ae MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. //
  3. // Project: phpLiteAdmin (http://phpliteadmin.googlecode.com)
  4. // Version: 1.9.3
  5. // Summary: PHP-based admin tool to manage SQLite2 and SQLite3 databases on the web
  6. // Last updated: 2012-11-02
  7. // Developers:
  8. // Dane Iracleous (daneiracleous@gmail.com)
  9. // Ian Aldrighetti (ian.aldrighetti@gmail.com)
  10. // George Flanagin & Digital Gaslight, Inc (george@digitalgaslight.com)
  11. // Christopher Kramer (crazy4chrissi@gmail.com)
  12. //
  13. //
  14. // Copyright (C) 2012 phpLiteAdmin
  15. //
  16. // This program is free software: you can redistribute it and/or modify
  17. // it under the terms of the GNU General Public License as published by
  18. // the Free Software Foundation, either version 3 of the License, or
  19. // (at your option) any later version.
  20. //
  21. // This program is distributed in the hope that it will be useful,
  22. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. // GNU General Public License for more details.
  25. //
  26. // You should have received a copy of the GNU General Public License
  27. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. //
  29. ///////////////////////////////////////////////////////////////////////////
  30. //please report any bugs you encounter to http://code.google.com/p/phpliteadmin/issues/list
  31. //BEGIN USER-DEFINED VARIABLES
  32. //////////////////////////////
  33. //password to gain access
  34. $password = "admin";
  35. //directory relative to this file to search for databases (if false, manually list databases in the $databases variable)
  36. $directory = false;
  37. //whether or not to scan the subdirectories of the above directory infinitely deep
  38. $subdirectories = false;
  39. //if the above $directory variable is set to false, you must specify the databases manually in an array as the next variable
  40. //if any of the databases do not exist as they are referenced by their path, they will be created automatically
  41. $databases = array
  42. (
  43. array
  44. (
  45. "path"=> "db/db.sqlite",
  46. "name"=> "Database 1"
  47. ),
  48. );
  49. //a list of custom functions that can be applied to columns in the databases
  50. //make sure to define every function below if it is not a core PHP function
  51. $custom_functions = array('md5', 'md5rev', 'sha1', 'sha1rev', 'time', 'mydate', 'strtotime', 'myreplace');
  52. //define all the non-core custom functions
  53. function md5rev($value)
  54. {
  55. return strrev(md5($value));
  56. }
  57. function sha1rev($value)
  58. {
  59. return strrev(sha1($value));
  60. }
  61. function mydate($value)
  62. {
  63. return date("g:ia n/j/y", intval($value));
  64. }
  65. function myreplace($value)
  66. {
  67. return ereg_replace("[^A-Za-z0-9]", "", strval($value));
  68. }
  69. //changing the following variable allows multiple phpLiteAdmin installs to work under the same domain.
  70. $cookie_name = 'pla3412';
  71. //whether or not to put the app in debug mode where errors are outputted
  72. $debug = false;
  73. ////////////////////////////
  74. //END USER-DEFINED VARIABLES
  75. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  76. //there is no reason for the average user to edit anything below this comment
  77. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  78. session_start(); //don't mess with this - required for the login session
  79. date_default_timezone_set(date_default_timezone_get()); //needed to fix STRICT warnings about timezone issues
  80. if($debug==true)
  81. {
  82. ini_set("display_errors", 1);
  83. error_reporting(E_STRICT | E_ALL);
  84. }
  85. $startTimeTot = microtime(true); //start the timer to record page load time
  86. //the salt and password encrypting is probably unnecessary protection but is done just for the sake of being very secure
  87. //create a random salt for this session if a cookie doesn't already exist for it
  88. if(!isset($_SESSION[$cookie_name.'_salt']) && !isset($_COOKIE[$cookie_name.'_salt']))
  89. {
  90. $n = rand(10e16, 10e20);
  91. $_SESSION[$cookie_name.'_salt'] = base_convert($n, 10, 36);
  92. }
  93. else if(!isset($_SESSION[$cookie_name.'_salt']) && isset($_COOKIE[$cookie_name.'_salt'])) //session doesn't exist, but cookie does so grab it
  94. {
  95. $_SESSION[$cookie_name.'_salt'] = $_COOKIE[$cookie_name.'_salt'];
  96. }
  97. //build the basename of this file for later reference
  98. $info = pathinfo($_SERVER['PHP_SELF']);
  99. $thisName = $info['basename'];
  100. //constants
  101. define("PROJECT", "phpLiteAdmin");
  102. define("VERSION", "1.9.3");
  103. define("PAGE", $thisName);
  104. define("COOKIENAME", $cookie_name);
  105. define("SYSTEMPASSWORD", $password); // Makes things easier.
  106. define("SYSTEMPASSWORDENCRYPTED", md5($password."_".$_SESSION[$cookie_name.'_salt'])); //extra security - salted and encrypted password used for checking
  107. define("FORCETYPE", false); //force the extension that will be used (set to false in almost all circumstances except debugging)
  108. //data types array
  109. $types = array("INTEGER", "REAL", "TEXT", "BLOB");
  110. define("DATATYPES", serialize($types));
  111. //available SQLite functions array (don't add anything here or there will be problems)
  112. $functions = array("abs", "hex", "length", "lower", "ltrim", "random", "round", "rtrim", "trim", "typeof", "upper");
  113. define("FUNCTIONS", serialize($functions));
  114. define("CUSTOM_FUNCTIONS", serialize($custom_functions));
  115. //function that allows SQL delimiter to be ignored inside comments or strings
  116. function explode_sql($delimiter, $sql)
  117. {
  118. $ign = array('"' => '"', "'" => "'", "/*" => "*/", "--" => "\n"); // Ignore sequences.
  119. $out = array();
  120. $last = 0;
  121. $slen = strlen($sql);
  122. $dlen = strlen($delimiter);
  123. $i = 0;
  124. while($i < $slen)
  125. {
  126. // Split on delimiter
  127. if($slen - $i >= $dlen && substr($sql, $i, $dlen) == $delimiter)
  128. {
  129. array_push($out, substr($sql, $last, $i - $last));
  130. $last = $i + $dlen;
  131. $i += $dlen;
  132. continue;
  133. }
  134. // Eat comments and string literals
  135. foreach($ign as $start => $end)
  136. {
  137. $ilen = strlen($start);
  138. if($slen - $i >= $ilen && substr($sql, $i, $ilen) == $start)
  139. {
  140. $i+=strlen($start);
  141. $elen = strlen($end);
  142. while($i < $slen)
  143. {
  144. if($slen - $i >= $elen && substr($sql, $i, $elen) == $end)
  145. {
  146. // SQL comment characters can be escaped by doubling the character. This recognizes and skips those.
  147. if($start == $end && $slen - $i >= $elen*2 && substr($sql, $i, $elen*2) == $end.$end)
  148. {
  149. $i += $elen * 2;
  150. continue;
  151. }
  152. else
  153. {
  154. $i += $elen;
  155. continue 3;
  156. }
  157. }
  158. $i++;
  159. }
  160. continue 2;
  161. }
  162. }
  163. $i++;
  164. }
  165. if($last < $slen)
  166. array_push($out, substr($sql, $last, $slen - $last));
  167. return $out;
  168. }
  169. //function to scan entire directory tree and subdirectories
  170. function dir_tree($dir)
  171. {
  172. $path = '';
  173. $stack[] = $dir;
  174. while($stack)
  175. {
  176. $thisdir = array_pop($stack);
  177. if($dircont = scandir($thisdir))
  178. {
  179. $i=0;
  180. while(isset($dircont[$i]))
  181. {
  182. if($dircont[$i] !== '.' && $dircont[$i] !== '..')
  183. {
  184. $current_file = "{$thisdir}/{$dircont[$i]}";
  185. if(is_file($current_file))
  186. {
  187. $path[] = "{$thisdir}/{$dircont[$i]}";
  188. }
  189. elseif (is_dir($current_file))
  190. {
  191. $path[] = "{$thisdir}/{$dircont[$i]}";
  192. $stack[] = $current_file;
  193. }
  194. }
  195. $i++;
  196. }
  197. }
  198. }
  199. return $path;
  200. }
  201. //the function echo the help [?] links to the documentation
  202. function helpLink($name)
  203. {
  204. return "<a href='javascript:void' onclick='openHelp(\"".$name."\");' class='helpq' title='Help: ".$name."'>[?]</a>";
  205. }
  206. // function to encode value into HTML just like htmlentities, but with adjusted default settings
  207. function htmlencode($value, $flags=ENT_QUOTES, $encoding ="UTF-8")
  208. {
  209. return htmlentities($value, $flags, $encoding);
  210. }
  211. // 22 August 2011: gkf added this function to support display of
  212. // default values in the form used to INSERT new data.
  213. function deQuoteSQL($s)
  214. {
  215. return trim(trim($s), "'");
  216. }
  217. //
  218. // Authorization class
  219. // Maintains user's logged-in state and security of application
  220. //
  221. class Authorization
  222. {
  223. public function grant($remember)
  224. {
  225. if($remember) //user wants to be remembered, so set a cookie
  226. {
  227. $expire = time()+60*60*24*30; //set expiration to 1 month from now
  228. setcookie(COOKIENAME, SYSTEMPASSWORD, $expire);
  229. setcookie(COOKIENAME."_salt", $_SESSION[COOKIENAME.'_salt'], $expire);
  230. }
  231. else
  232. {
  233. //user does not want to be remembered, so destroy any potential cookies
  234. setcookie(COOKIENAME, "", time()-86400);
  235. setcookie(COOKIENAME."_salt", "", time()-86400);
  236. unset($_COOKIE[COOKIENAME]);
  237. unset($_COOKIE[COOKIENAME.'_salt']);
  238. }
  239. $_SESSION[COOKIENAME.'password'] = SYSTEMPASSWORDENCRYPTED;
  240. }
  241. public function revoke()
  242. {
  243. //destroy everything - cookies and session vars
  244. setcookie(COOKIENAME, "", time()-86400);
  245. setcookie(COOKIENAME."_salt", "", time()-86400);
  246. unset($_COOKIE[COOKIENAME]);
  247. unset($_COOKIE[COOKIENAME.'_salt']);
  248. session_unset();
  249. session_destroy();
  250. }
  251. public function isAuthorized()
  252. {
  253. // Is this just session long? (What!?? -DI)
  254. if((isset($_SESSION[COOKIENAME.'password']) && $_SESSION[COOKIENAME.'password'] == SYSTEMPASSWORDENCRYPTED) || (isset($_COOKIE[COOKIENAME]) && isset($_COOKIE[COOKIENAME.'_salt']) && md5($_COOKIE[COOKIENAME]."_".$_COOKIE[COOKIENAME.'_salt']) == SYSTEMPASSWORDENCRYPTED))
  255. return true;
  256. else
  257. {
  258. return false;
  259. }
  260. }
  261. }
  262. //
  263. // Database class
  264. // Generic database abstraction class to manage interaction with database without worrying about SQLite vs. PHP versions
  265. //
  266. class Database
  267. {
  268. protected $db; //reference to the DB object
  269. protected $type; //the extension for PHP that handles SQLite
  270. protected $data;
  271. protected $lastResult;
  272. protected $fns;
  273. public function __construct($data)
  274. {
  275. $this->data = $data;
  276. $this->fns = array();
  277. try
  278. {
  279. 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
  280. {
  281. echo "<div class='confirm' style='margin:20px;'>";
  282. echo "The database, '".htmlencode($this->data["path"])."', does not exist and cannot be created because the containing directory, '".htmlencode(dirname($this->data["path"]))."', is not writable. The application is unusable until you make it writable.";
  283. echo "<form action='".PAGE."' method='post'>";
  284. echo "<input type='submit' value='Log Out' name='logout' class='btn'/>";
  285. echo "</form>";
  286. echo "</div><br/>";
  287. exit();
  288. }
  289. $ver = $this->getVersion();
  290. switch(true)
  291. {
  292. case (FORCETYPE=="PDO" || ((FORCETYPE==false || $ver!=-1) && class_exists("PDO") && ($ver==-1 || $ver==3))):
  293. $this->db = new PDO("sqlite:".$this->data['path']);
  294. if($this->db!=NULL)
  295. {
  296. $this->type = "PDO";
  297. $cfns = unserialize(CUSTOM_FUNCTIONS);
  298. for($i=0; $i<sizeof($cfns); $i++)
  299. {
  300. $this->db->sqliteCreateFunction($cfns[$i], $cfns[$i], 1);
  301. $this->addUserFunction($cfns[$i]);
  302. }
  303. break;
  304. }
  305. case (FORCETYPE=="SQLite3" || ((FORCETYPE==false || $ver!=-1) && class_exists("SQLite3") && ($ver==-1 || $ver==3))):
  306. $this->db = new SQLite3($this->data['path']);
  307. if($this->db!=NULL)
  308. {
  309. $cfns = unserialize(CUSTOM_FUNCTIONS);
  310. for($i=0; $i<sizeof($cfns); $i++)
  311. {
  312. $this->db->createFunction($cfns[$i], $cfns[$i], 1);
  313. $this->addUserFunction($cfns[$i]);
  314. }
  315. $this->type = "SQLite3";
  316. break;
  317. }
  318. case (FORCETYPE=="SQLiteDatabase" || ((FORCETYPE==false || $ver!=-1) && class_exists("SQLiteDatabase") && ($ver==-1 || $ver==2))):
  319. $this->db = new SQLiteDatabase($this->data['path']);
  320. if($this->db!=NULL)
  321. {
  322. $cfns = unserialize(CUSTOM_FUNCTIONS);
  323. for($i=0; $i<sizeof($cfns); $i++)
  324. {
  325. $this->db->createFunction($cfns[$i], $cfns[$i], 1);
  326. $this->addUserFunction($cfns[$i]);
  327. }
  328. $this->type = "SQLiteDatabase";
  329. break;
  330. }
  331. default:
  332. $this->showError();
  333. exit();
  334. }
  335. }
  336. catch(Exception $e)
  337. {
  338. $this->showError();
  339. exit();
  340. }
  341. }
  342. public function getUserFunctions()
  343. {
  344. return $this->fns;
  345. }
  346. public function addUserFunction($name)
  347. {
  348. array_push($this->fns, $name);
  349. }
  350. public function getError()
  351. {
  352. if($this->type=="PDO")
  353. {
  354. $e = $this->db->errorInfo();
  355. return $e[2];
  356. }
  357. else if($this->type=="SQLite3")
  358. {
  359. return $this->db->lastErrorMsg();
  360. }
  361. else
  362. {
  363. return sqlite_error_string($this->db->lastError());
  364. }
  365. }
  366. public function showError()
  367. {
  368. $classPDO = class_exists("PDO");
  369. $classSQLite3 = class_exists("SQLite3");
  370. $classSQLiteDatabase = class_exists("SQLiteDatabase");
  371. if($classPDO)
  372. $strPDO = "installed";
  373. else
  374. $strPDO = "not installed";
  375. if($classSQLite3)
  376. $strSQLite3 = "installed";
  377. else
  378. $strSQLite3 = "not installed";
  379. if($classSQLiteDatabase)
  380. $strSQLiteDatabase = "installed";
  381. else
  382. $strSQLiteDatabase = "not installed";
  383. echo "<div class='confirm' style='margin:20px;'>";
  384. 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/>";
  385. echo "<i>Checking supported SQLite PHP extensions...<br/><br/>";
  386. echo "<b>PDO</b>: ".$strPDO."<br/>";
  387. echo "<b>SQLite3</b>: ".$strSQLite3."<br/>";
  388. echo "<b>SQLiteDatabase</b>: ".$strSQLiteDatabase."<br/><br/>...done.</i><br/><br/>";
  389. if(!$classPDO && !$classSQLite3 && !$classSQLiteDatabase)
  390. 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.";
  391. else
  392. {
  393. if(!$classPDO && !$classSQLite3 && $this->getVersion()==3)
  394. 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.";
  395. else if(!$classSQLiteDatabase && $this->getVersion()==2)
  396. 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.";
  397. else
  398. echo "The problem cannot be diagnosed properly. Please file an issue report at http://phpliteadmin.googlecode.com.";
  399. }
  400. echo "</div><br/>";
  401. }
  402. public function __destruct()
  403. {
  404. if($this->db)
  405. $this->close();
  406. }
  407. //get the exact PHP extension being used for SQLite
  408. public function getType()
  409. {
  410. return $this->type;
  411. }
  412. //get the name of the database
  413. public function getName()
  414. {
  415. return $this->data["name"];
  416. }
  417. //get the filename of the database
  418. public function getPath()
  419. {
  420. return $this->data["path"];
  421. }
  422. //get the version of the database
  423. public function getVersion()
  424. {
  425. if(file_exists($this->data['path'])) //make sure file exists before getting its contents
  426. {
  427. $content = strtolower(file_get_contents($this->data['path'], NULL, NULL, 0, 40)); //get the first 40 characters of the database file
  428. $p = strpos($content, "** this file contains an sqlite 2"); //this text is at the beginning of every SQLite2 database
  429. if($p!==false) //the text is found - this is version 2
  430. return 2;
  431. else
  432. return 3;
  433. }
  434. else //return -1 to indicate that it does not exist and needs to be created
  435. {
  436. return -1;
  437. }
  438. }
  439. //get the size of the database
  440. public function getSize()
  441. {
  442. return round(filesize($this->data["path"])*0.0009765625, 1)." KB";
  443. }
  444. //get the last modified time of database
  445. public function getDate()
  446. {
  447. return date("g:ia \o\\n F j, Y", filemtime($this->data["path"]));
  448. }
  449. //get number of affected rows from last query
  450. public function getAffectedRows()
  451. {
  452. if($this->type=="PDO")
  453. return $this->lastResult->rowCount();
  454. else if($this->type=="SQLite3")
  455. return $this->db->changes();
  456. else if($this->type=="SQLiteDatabase")
  457. return $this->db->changes();
  458. }
  459. public function close()
  460. {
  461. if($this->type=="PDO")
  462. $this->db = NULL;
  463. else if($this->type=="SQLite3")
  464. $this->db->close();
  465. else if($this->type=="SQLiteDatabase")
  466. $this->db = NULL;
  467. }
  468. public function beginTransaction()
  469. {
  470. $this->query("BEGIN");
  471. }
  472. public function commitTransaction()
  473. {
  474. $this->query("COMMIT");
  475. }
  476. public function rollbackTransaction()
  477. {
  478. $this->query("ROLLBACK");
  479. }
  480. //generic query wrapper
  481. public function query($query, $ignoreAlterCase=false)
  482. {
  483. global $debug;
  484. if(strtolower(substr(ltrim($query),0,5))=='alter' && $ignoreAlterCase==false) //this query is an ALTER query - call the necessary function
  485. {
  486. preg_match("/^\s*ALTER\s+TABLE\s+\"((?:[^\"]|\"\")+)\"\s+(.*)$/i",$query,$matches);
  487. if(!isset($matches[1]) || !isset($matches[2]))
  488. {
  489. if($debug) echo "<span title='".htmlencode($query)."' onclick='this.innerHTML=\"".htmlencode(str_replace('"','\"',$query))."\"' style='cursor:pointer'>SQL?</span><br />";
  490. return false;
  491. }
  492. $tablename = str_replace('""','"',$matches[1]);
  493. $alterdefs = $matches[2];
  494. if($debug) echo "ALTER TABLE QUERY=(".htmlencode($query)."), tablename=($tablename), alterdefs=($alterdefs)<hr>";
  495. $result = $this->alterTable($tablename, $alterdefs);
  496. }
  497. else //this query is normal - proceed as normal
  498. {
  499. $result = $this->db->query($query);
  500. if($debug) echo "<span title='".htmlencode($query)."' onclick='this.innerHTML=\"".htmlencode(str_replace('"','\"',$query))."\"' style='cursor:pointer'>SQL?</span><br />";
  501. }
  502. if(!$result)
  503. return false;
  504. $this->lastResult = $result;
  505. return $result;
  506. }
  507. //wrapper for an INSERT and returns the ID of the inserted row
  508. public function insert($query)
  509. {
  510. $result = $this->query($query);
  511. if($this->type=="PDO")
  512. return $this->db->lastInsertId();
  513. else if($this->type=="SQLite3")
  514. return $this->db->lastInsertRowID();
  515. else if($this->type=="SQLiteDatabase")
  516. return $this->db->lastInsertRowid();
  517. }
  518. //returns an array for SELECT
  519. public function select($query, $mode="both")
  520. {
  521. $result = $this->query($query);
  522. if(!$result) //make sure the result is valid
  523. return NULL;
  524. if($this->type=="PDO")
  525. {
  526. if($mode=="assoc")
  527. $mode = PDO::FETCH_ASSOC;
  528. else if($mode=="num")
  529. $mode = PDO::FETCH_NUM;
  530. else
  531. $mode = PDO::FETCH_BOTH;
  532. return $result->fetch($mode);
  533. }
  534. else if($this->type=="SQLite3")
  535. {
  536. if($mode=="assoc")
  537. $mode = SQLITE3_ASSOC;
  538. else if($mode=="num")
  539. $mode = SQLITE3_NUM;
  540. else
  541. $mode = SQLITE3_BOTH;
  542. return $result->fetchArray($mode);
  543. }
  544. else if($this->type=="SQLiteDatabase")
  545. {
  546. if($mode=="assoc")
  547. $mode = SQLITE_ASSOC;
  548. else if($mode=="num")
  549. $mode = SQLITE_NUM;
  550. else
  551. $mode = SQLITE_BOTH;
  552. return $result->fetch($mode);
  553. }
  554. }
  555. //returns an array of arrays after doing a SELECT
  556. public function selectArray($query, $mode="both")
  557. {
  558. $result = $this->query($query);
  559. if(!$result) //make sure the result is valid
  560. return NULL;
  561. if($this->type=="PDO")
  562. {
  563. if($mode=="assoc")
  564. $mode = PDO::FETCH_ASSOC;
  565. else if($mode=="num")
  566. $mode = PDO::FETCH_NUM;
  567. else
  568. $mode = PDO::FETCH_BOTH;
  569. return $result->fetchAll($mode);
  570. }
  571. else if($this->type=="SQLite3")
  572. {
  573. if($mode=="assoc")
  574. $mode = SQLITE3_ASSOC;
  575. else if($mode=="num")
  576. $mode = SQLITE3_NUM;
  577. else
  578. $mode = SQLITE3_BOTH;
  579. $arr = array();
  580. $i = 0;
  581. while($res = $result->fetchArray($mode))
  582. {
  583. $arr[$i] = $res;
  584. $i++;
  585. }
  586. return $arr;
  587. }
  588. else if($this->type=="SQLiteDatabase")
  589. {
  590. if($mode=="assoc")
  591. $mode = SQLITE_ASSOC;
  592. else if($mode=="num")
  593. $mode = SQLITE_NUM;
  594. else
  595. $mode = SQLITE_BOTH;
  596. return $result->fetchAll($mode);
  597. }
  598. }
  599. // SQlite supports multiple ways of surrounding names in quotes:
  600. // single-quotes, double-quotes, backticks, square brackets.
  601. // As sqlite does not keep this strict, we also need to be flexible here.
  602. // This function generates a regex that matches any of the possibilities.
  603. private function sqlite_surroundings_preg($name,$preg_quote=true,$notAllowedIfNone="'\"")
  604. {
  605. if($name=="*" || $name=="+")
  606. {
  607. $nameSingle = "(?:[^']|'')".$name;
  608. $nameDouble = "(?:[^\"]|\"\")".$name;
  609. $nameBacktick = "(?:[^`]|``)".$name;
  610. $nameSquare = "(?:[^\]]|\]\])".$name;
  611. $nameNo = "[^".$notAllowedIfNone."]".$name;
  612. }
  613. else
  614. {
  615. if($preg_quote) $name = preg_quote($name,"/");
  616. $nameSingle = str_replace("'","''",$name);
  617. $nameDouble = str_replace('"','""',$name);
  618. $nameBacktick = str_replace('`','``',$name);
  619. $nameSquare = str_replace(']',']]',$name);
  620. $nameNo = $name;
  621. }
  622. $preg = "(?:'".$nameSingle."'|". // single-quote surrounded or not in quotes (correct SQL for values/new names)
  623. $nameNo."|". // not surrounded (correct SQL if not containing reserved words, spaces or some special chars)
  624. "\"".$nameDouble."\"|". // double-quote surrounded (correct SQL for identifiers)
  625. "`".$nameBacktick."`|". // backtick surrounded (MySQL-Style)
  626. "\[".$nameSquare."\])"; // square-bracket surrounded (MS Access/SQL server-Style)
  627. return $preg;
  628. }
  629. // function that is called for an alter table statement in a query
  630. // code borrowed with permission from http://code.jenseng.com/db/
  631. // this has been completely debugged / rewritten by Christopher Kramer
  632. public function alterTable($table, $alterdefs)
  633. {
  634. global $debug;
  635. if($debug) echo "ALTER TABLE: table=($table), alterdefs=($alterdefs)<hr>";
  636. if($alterdefs != '')
  637. {
  638. $recreateQueries = array();
  639. $tempQuery = "SELECT sql,name,type FROM sqlite_master WHERE tbl_name = ".$this->quote($table)." ORDER BY type DESC";
  640. $result = $this->query($tempQuery);
  641. $resultArr = $this->selectArray($tempQuery);
  642. if($this->type=="PDO")
  643. $result->closeCursor();
  644. if(sizeof($resultArr)<1)
  645. return false;
  646. for($i=0; $i<sizeof($resultArr); $i++)
  647. {
  648. $row = $resultArr[$i];
  649. if($row['type'] != 'table')
  650. {
  651. // store the CREATE statements of triggers and indexes to recreate them later
  652. $recreateQueries[] = $row['sql']."; ";
  653. if($debug) echo "recreate=(".$row['sql'].";)<hr />";
  654. }
  655. else
  656. {
  657. // ALTER the table
  658. $tmpname = 't'.time();
  659. $origsql = $row['sql'];
  660. $createtemptableSQL = "CREATE TEMPORARY TABLE ".$this->quote($tmpname)." ".
  661. preg_replace("/^\s*CREATE\s+TABLE\s+".$this->sqlite_surroundings_preg($table)."\s*(\(.*)$/i", '$1', $origsql, 1);
  662. if($debug) echo "createtemptableSQL=($createtemptableSQL)<hr>";
  663. $createindexsql = array();
  664. preg_match_all("/(?:DROP|ADD|CHANGE|RENAME TO)\s+(?:\"(?:[^\"]|\"\")+\"|'(?:[^']|'')+')((?:[^,')]|'[^']*')+)?/i",$alterdefs,$matches);
  665. $defs = $matches[0];
  666. $get_oldcols_query = "PRAGMA table_info(".$this->quote_id($table).")";
  667. $result_oldcols = $this->selectArray($get_oldcols_query);
  668. $newcols = array();
  669. $coltypes = array();
  670. foreach($result_oldcols as $column_info)
  671. {
  672. $newcols[$column_info['name']] = $column_info['name'];
  673. $coltypes[$column_info['name']] = $column_info['type'];
  674. }
  675. $newcolumns = '';
  676. $oldcolumns = '';
  677. reset($newcols);
  678. while(list($key, $val) = each($newcols))
  679. {
  680. $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val);
  681. $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key);
  682. }
  683. $copytotempsql = 'INSERT INTO '.$this->quote_id($tmpname).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($table);
  684. $dropoldsql = 'DROP TABLE '.$this->quote_id($table);
  685. $createtesttableSQL = $createtemptableSQL;
  686. if(count($defs)<1)
  687. {
  688. if($debug) echo "ERROR: defs&lt;1<hr />";
  689. return false;
  690. }
  691. foreach($defs as $def)
  692. {
  693. if($debug) echo "def=$def<hr />";
  694. $parse_def = preg_match("/^(DROP|ADD|CHANGE|RENAME TO)\s+(?:\"((?:[^\"]|\"\")+)\"|'((?:[^']|'')+)')((?:\s+'((?:[^']|'')+)')?\s+(TEXT|INTEGER|BLOB|REAL).*)?\s*$/i",$def,$matches);
  695. if($parse_def===false)
  696. {
  697. if($debug) echo "ERROR: !parse_def<hr />";
  698. return false;
  699. }
  700. if(!isset($matches[1]))
  701. {
  702. if($debug) echo "ERROR: !isset(matches[1])<hr />";
  703. return false;
  704. }
  705. $action = strtolower($matches[1]);
  706. if($action == 'add' || $action == 'rename to')
  707. $column = str_replace("''","'",$matches[3]); // enclosed in ''
  708. else
  709. $column = str_replace('""','"',$matches[2]); // enclosed in ""
  710. $column_escaped = str_replace("'","''",$column);
  711. if($debug) echo "action=($action), column=($column), column_escaped=($column_escaped)<hr />";
  712. /* we build a regex that devides the CREATE TABLE statement parts:
  713. Part example Group Explanation
  714. 1. CREATE TABLE t... ( $1
  715. 2. 'col1' ..., 'col2' ..., 'colN' ..., $3 (with col1-colN being columns that are not changed and listed before the col to change)
  716. 3. 'colX' ..., - (with colX being the column to change/drop)
  717. 4. 'colX+1' ..., ..., 'colK') $5 (with colX+1-colK being columns after the column to change/drop)
  718. */
  719. $preg_create_table = "\s*(CREATE\s+TEMPORARY\s+TABLE\s+'?".preg_quote($tmpname,"/")."'?\s*\()"; // This is group $1 (keep unchanged)
  720. $preg_column_definiton = "\s*".$this->sqlite_surroundings_preg("+",false," '\"\[`")."(?:\s+".$this->sqlite_surroundings_preg("*",false,"'\",`\[) ").")+"; // catches a complete column definition, even if it is
  721. // 'column' TEXT NOT NULL DEFAULT 'we have a comma, here and a double ''quote!'
  722. if($debug) echo "preg_column_definition=(".$preg_column_definiton.")<hr />";
  723. $preg_columns_before = // columns before the one changed/dropped (keep)
  724. "(?:".
  725. "(". // group $2. Keep this one unchanged!
  726. "(?:".
  727. "$preg_column_definiton,\s*". // column definition + comma
  728. ")*". // there might be any number of such columns here
  729. $preg_column_definiton. // last column definition
  730. ")". // end of group $2
  731. ",\s*" // the last comma of the last column before the column to change. Do not keep it!
  732. .")?"; // there might be no columns before
  733. if($debug) echo "preg_columns_before=(".$preg_columns_before.")<hr />";
  734. $preg_columns_after = "(,\s*([^)]+))?"; // the columns after the column to drop. This is group $3 (drop) or $4(change) (keep!)
  735. // we could remove the comma using $6 instead of $5, but then we might have no comma at all.
  736. // Keeping it leaves a problem if we drop the first column, so we fix that case in another regex.
  737. $table_new = $table;
  738. switch($action)
  739. {
  740. case 'add':
  741. if(!isset($matches[4]))
  742. {
  743. return false;
  744. }
  745. $new_col_definition = "'$column_escaped' ".$matches[4];
  746. $preg_pattern_add = "/^".$preg_create_table."(.*)\\)\s*$/";
  747. // append the column definiton in the CREATE TABLE statement
  748. $newSQL = preg_replace($preg_pattern_add, '$1$2, ', $createtesttableSQL).$new_col_definition.')';
  749. if($debug)
  750. {
  751. echo $createtesttableSQL."<hr>";
  752. echo $newSQL."<hr>";
  753. echo $preg_pattern_add."<hr>";
  754. }
  755. if($newSQL==$createtesttableSQL) // pattern did not match, so column removal did not succed
  756. return false;
  757. $createtesttableSQL = $newSQL;
  758. break;
  759. case 'change':
  760. if(!isset($matches[5]) || !isset($matches[6]))
  761. {
  762. return false;
  763. }
  764. $new_col_name = $matches[5];
  765. $new_col_type = $matches[6];
  766. $new_col_definition = "'$new_col_name' $new_col_type";
  767. $preg_column_to_change = "\s*".$this->sqlite_surroundings_preg($column)."(?:\s+".preg_quote($coltypes[$column]).")?(\s+(?:".$this->sqlite_surroundings_preg("*",false,",'\")`\[").")+)?";
  768. // replace this part (we want to change this column)
  769. // group $3 contains the column constraints (keep!). the name & data type is replaced.
  770. $preg_pattern_change = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_change.$preg_columns_after."\s*\\)\s*$/";
  771. // replace the column definiton in the CREATE TABLE statement
  772. $newSQL = preg_replace($preg_pattern_change, '$1$2,'.strtr($new_col_definition, array('\\' => '\\\\', '$' => '\$')).'$3$4)', $createtesttableSQL);
  773. // remove comma at the beginning if the first column is changed
  774. // probably somebody is able to put this into the first regex (using lookahead probably).
  775. $newSQL = preg_replace("/^\s*(CREATE\s+TEMPORARY\s+TABLE\s+'".preg_quote($tmpname,"/")."'\s+\(),\s*/",'$1',$newSQL);
  776. if($debug)
  777. {
  778. echo "preg_column_to_change=(".$preg_column_to_change.")<hr />";
  779. echo $createtesttableSQL."<hr />";
  780. echo $newSQL."<hr />";
  781. echo $preg_pattern_change."<hr />";
  782. }
  783. if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed
  784. return false;
  785. $createtesttableSQL = $newSQL;
  786. $newcols[$column] = str_replace("''","'",$new_col_name);
  787. break;
  788. case 'drop':
  789. $preg_column_to_drop = "\s*".$this->sqlite_surroundings_preg($column)."\s+(?:".$this->sqlite_surroundings_preg("*",false,",')\"\[`").")+"; // delete this part (we want to drop this column)
  790. $preg_pattern_drop = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_drop.$preg_columns_after."\s*\\)\s*$/";
  791. // remove the column out of the CREATE TABLE statement
  792. $newSQL = preg_replace($preg_pattern_drop, '$1$2$3)', $createtesttableSQL);
  793. // remove comma at the beginning if the first column is removed
  794. // probably somebody is able to put this into the first regex (using lookahead probably).
  795. $newSQL = preg_replace("/^\s*(CREATE\s+TEMPORARY\s+TABLE\s+'".preg_quote($tmpname,"/")."'\s+\(),\s*/",'$1',$newSQL);
  796. if($debug)
  797. {
  798. echo $createtesttableSQL."<hr>";
  799. echo $newSQL."<hr>";
  800. echo $preg_pattern_drop."<hr>";
  801. }
  802. if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed
  803. return false;
  804. $createtesttableSQL = $newSQL;
  805. unset($newcols[$column]);
  806. break;
  807. case 'rename to':
  808. // don't change column definition at all
  809. $newSQL = $createtesttableSQL;
  810. // only change the name of the table
  811. $table_new = $column;
  812. break;
  813. default:
  814. if($default) echo 'ERROR: unknown alter operation!<hr />';
  815. return false;
  816. }
  817. }
  818. $droptempsql = 'DROP TABLE '.$this->quote_id($tmpname);
  819. $createnewtableSQL = "CREATE TABLE ".$this->quote($table_new)." ".preg_replace("/^\s*CREATE\s+TEMPORARY\s+TABLE\s+'?".str_replace("'","''",preg_quote($tmpname,"/"))."'?\s+(.*)$/i", '$1', $createtesttableSQL, 1);
  820. $newcolumns = '';
  821. $oldcolumns = '';
  822. reset($newcols);
  823. while(list($key,$val) = each($newcols))
  824. {
  825. $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val);
  826. $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key);
  827. }
  828. $copytonewsql = 'INSERT INTO '.$this->quote_id($table_new).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($tmpname);
  829. }
  830. }
  831. $alter_transaction = 'BEGIN; ';
  832. $alter_transaction .= $createtemptableSQL.'; '; //create temp table
  833. $alter_transaction .= $copytotempsql.'; '; //copy to table
  834. $alter_transaction .= $dropoldsql.'; '; //drop old table
  835. $alter_transaction .= $createnewtableSQL.'; '; //recreate original table
  836. $alter_transaction .= $copytonewsql.'; '; //copy back to original table
  837. $alter_transaction .= $droptempsql.'; '; //drop temp table
  838. $preg_index="/^\s*(CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*ON\s+)(".$this->sqlite_surroundings_preg($table).")(\s*\((?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*\)\s*;)\s*$/i";
  839. for($i=0; $i<sizeof($recreateQueries); $i++)
  840. {
  841. // recreate triggers / indexes
  842. if($table == $table_new)
  843. {
  844. // we had no RENAME TO, so we can recreate indexes/triggers just like the original ones
  845. $alter_transaction .= $recreateQueries[$i];
  846. } else
  847. {
  848. // we had a RENAME TO, so we need to exchange the table-name in the CREATE-SQL of triggers & indexes
  849. // first let's try if it's an index...
  850. $recreate_queryIndex = preg_replace($preg_index, '$1'.$this->quote_id(strtr($table_new, array('\\' => '\\\\', '$' => '\$'))).'$3 ', $recreateQueries[$i]);
  851. if($recreate_queryIndex!=$recreateQueries[$i] && $recreate_queryIndex != NULL)
  852. {
  853. // the CREATE INDEX regex did match
  854. $alter_transaction .= $recreate_queryIndex;
  855. } else
  856. {
  857. // the CREATE INDEX regex did not match, so we try if it's a CREATE TRIGGER
  858. $recreate_queryTrigger = $recreateQueries[$i];
  859. // TODO: IMPLEMENT
  860. $alter_transaction .= $recreate_queryTrigger;
  861. }
  862. }
  863. }
  864. $alter_transaction .= 'COMMIT;';
  865. if($debug) echo $alter_transaction;
  866. return $this->multiQuery($alter_transaction);
  867. }
  868. }
  869. //multiple query execution
  870. public function multiQuery($query)
  871. {
  872. $error = "Unknown error.";
  873. if($this->type=="PDO")
  874. {
  875. $success = $this->db->exec($query);
  876. if(!$success) $error = implode(" - ", $this->db->errorInfo());
  877. }
  878. else if($this->type=="SQLite3")
  879. {
  880. $success = $this->db->exec($query);
  881. if(!$success) $error = $this->db->lastErrorMsg();
  882. }
  883. else
  884. {
  885. $success = $this->db->queryExec($query, $error);
  886. }
  887. if(!$success)
  888. {
  889. return "Error in query: '".htmlencode($error)."'";
  890. }
  891. else
  892. {
  893. return true;
  894. }
  895. }
  896. //get number of rows in table
  897. public function numRows($table)
  898. {
  899. $result = $this->select("SELECT Count(*) FROM ".$this->quote_id($table));
  900. return $result[0];
  901. }
  902. //correctly escape a string to be injected into an SQL query
  903. public function quote($value)
  904. {
  905. if($this->type=="PDO")
  906. {
  907. // PDO quote() escapes and adds quotes
  908. return $this->db->quote($value);
  909. }
  910. else if($this->type=="SQLite3")
  911. {
  912. return "'".$this->db->escapeString($value)."'";
  913. }
  914. else
  915. {
  916. return "'".sqlite_escape_string($value)."'";
  917. }
  918. }
  919. //correctly escape an identifier (column / table / trigger / index name) to be injected into an SQL query
  920. public function quote_id($value)
  921. {
  922. // double-quotes need to be escaped by doubling them
  923. $value = str_replace('"','""',$value);
  924. return '"'.$value.'"';
  925. }
  926. //import sql
  927. public function import_sql($query)
  928. {
  929. return $this->multiQuery($query);
  930. }
  931. //import csv
  932. public function import_csv($filename, $table, $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row)
  933. {
  934. // CSV import implemented by Christopher Kramer - http://www.christosoft.de
  935. $csv_handle = fopen($filename,'r');
  936. $csv_insert = "BEGIN;\n";
  937. $csv_number_of_rows = 0;
  938. // PHP requires enclosure defined, but has no problem if it was not used
  939. if($field_enclosed=="") $field_enclosed='"';
  940. // PHP requires escaper defined
  941. if($field_escaped=="") $field_escaped='\\';
  942. while(!feof($csv_handle))
  943. {
  944. $csv_data = fgetcsv($csv_handle, 0, $field_terminate, $field_enclosed, $field_escaped);
  945. if($csv_data[0] != NULL || count($csv_data)>1)
  946. {
  947. $csv_number_of_rows++;
  948. if($fields_in_first_row && $csv_number_of_rows==1) continue;
  949. $csv_col_number = count($csv_data);
  950. $csv_insert .= "INSERT INTO ".$this->quote_id($table)." VALUES (";
  951. foreach($csv_data as $csv_col => $csv_cell)
  952. {
  953. if($csv_cell == $null) $csv_insert .= "NULL";
  954. else
  955. {
  956. $csv_insert.= $this->quote($csv_cell);
  957. }
  958. if($csv_col == $csv_col_number-2 && $csv_data[$csv_col+1]=='')
  959. {
  960. // the CSV row ends with the separator (like old phpliteadmin exported)
  961. break;
  962. }
  963. if($csv_col < $csv_col_number-1) $csv_insert .= ",";
  964. }
  965. $csv_insert .= ");\n";
  966. if($csv_number_of_rows > 5000)
  967. {
  968. $csv_insert .= "COMMIT;\nBEGIN;\n";
  969. $csv_number_of_rows = 0;
  970. }
  971. }
  972. }
  973. $csv_insert .= "COMMIT;";
  974. fclose($csv_handle);
  975. return $this->multiQuery($csv_insert);
  976. }
  977. //export csv
  978. public function export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row)
  979. {
  980. $field_enclosed = stripslashes($field_enclosed);
  981. $query = "SELECT * FROM sqlite_master WHERE type='table' or type='view' ORDER BY type DESC";
  982. $result = $this->selectArray($query);
  983. for($i=0; $i<sizeof($result); $i++)
  984. {
  985. $valid = false;
  986. for($j=0; $j<sizeof($tables); $j++)
  987. {
  988. if($result[$i]['tbl_name']==$tables[$j])
  989. $valid = true;
  990. }
  991. if($valid)
  992. {
  993. $query = "PRAGMA table_info(".$this->quote_id($result[$i]['tbl_name']).")";
  994. $temp = $this->selectArray($query);
  995. $cols = array();
  996. for($z=0; $z<sizeof($temp); $z++)
  997. $cols[$z] = $temp[$z][1];
  998. if($fields_in_first_row)
  999. {
  1000. for($z=0; $z<sizeof($cols); $z++)
  1001. {
  1002. echo $field_enclosed.$cols[$z].$field_enclosed;
  1003. // do not terminate the last column!
  1004. if($z < sizeof($cols)-1)
  1005. echo $field_terminate;
  1006. }
  1007. echo "\r\n";
  1008. }
  1009. $query = "SELECT * FROM ".$this->quote_id($result[$i]['tbl_name']);
  1010. $arr = $this->selectArray($query, "assoc");
  1011. for($z=0; $z<sizeof($arr); $z++)
  1012. {
  1013. for($y=0; $y<sizeof($cols); $y++)
  1014. {
  1015. $cell = $arr[$z][$cols[$y]];
  1016. if($crlf)
  1017. {
  1018. $cell = str_replace("\n","", $cell);
  1019. $cell = str_replace("\r","", $cell);
  1020. }
  1021. $cell = str_replace($field_terminate,$field_escaped.$field_terminate,$cell);
  1022. $cell = str_replace($field_enclosed,$field_escaped.$field_enclosed,$cell);
  1023. // do not enclose NULLs
  1024. if($cell == NULL)
  1025. echo $null;
  1026. else
  1027. echo $field_enclosed.$cell.$field_enclosed;
  1028. // do not terminate the last column!
  1029. if($y < sizeof($cols)-1)
  1030. echo $field_terminate;
  1031. }
  1032. if($z<sizeof($arr)-1)
  1033. echo "\r\n";
  1034. }
  1035. if($i<sizeof($result)-1)
  1036. echo "\r\n";
  1037. }
  1038. }
  1039. }
  1040. //export sql
  1041. public function export_sql($tables, $drop, $structure, $data, $transaction, $comments)
  1042. {
  1043. if($comments)
  1044. {
  1045. echo "----\r\n";
  1046. echo "-- phpLiteAdmin database dump (http://phpliteadmin.googlecode.com)\r\n";
  1047. echo "-- phpLiteAdmin version: ".VERSION."\r\n";
  1048. echo "-- Exported on ".date('M jS, Y, h:i:sA')."\r\n";
  1049. echo "-- Database file: ".$this->getPath()."\r\n";
  1050. echo "----\r\n";
  1051. }
  1052. $query = "SELECT * FROM sqlite_master WHERE type='table' OR type='index' OR type='view' OR type='trigger' ORDER BY type='trigger', type='index', type='view', type='table'";
  1053. $result = $this->selectArray($query);
  1054. if($transaction)
  1055. echo "BEGIN TRANSACTION;\r\n";
  1056. //iterate through each table
  1057. for($i=0; $i<sizeof($result); $i++)
  1058. {
  1059. $valid = false;
  1060. for($j=0; $j<sizeof($tables); $j++)
  1061. {
  1062. if($result[$i]['tbl_name']==$tables[$j])
  1063. $valid = true;
  1064. }
  1065. if($valid)
  1066. {
  1067. if($drop)
  1068. {
  1069. if($comments)
  1070. {
  1071. echo "\r\n----\r\n";
  1072. echo "-- Drop ".$result[$i]['type']." for ".$result[$i]['name']."\r\n";
  1073. echo "----\r\n";
  1074. }
  1075. echo "DROP ".strtoupper($result[$i]['type'])." ".$this->quote_id($result[$i]['name']).";\r\n";
  1076. }
  1077. if($structure)
  1078. {
  1079. if($comments)
  1080. {
  1081. echo "\r\n----\r\n";
  1082. if($result[$i]['type']=="table" || $result[$i]['type']=="view")
  1083. echo "-- ".ucfirst($result[$i]['type'])." structure for ".$result[$i]['tbl_name']."\r\n";
  1084. else // index or trigger
  1085. echo "-- Structure for ".$result[$i]['type']." ".$result[$i]['name']." on table ".$result[$i]['tbl_name']."\r\n";
  1086. echo "----\r\n";
  1087. }
  1088. echo $result[$i]['sql'].";\r\n";
  1089. }
  1090. if($data && $result[$i]['type']=="table")
  1091. {
  1092. $query = "SELECT * FROM ".$this->quote_id($result[$i]['tbl_name']);
  1093. $arr = $this->selectArray($query, "assoc");
  1094. if($comments)
  1095. {
  1096. echo "\r\n----\r\n";
  1097. echo "-- Data dump for ".$result[$i]['tbl_name'].", a total of ".sizeof($arr)." rows\r\n";
  1098. echo "----\r\n";
  1099. }
  1100. $query = "PRAGMA table_info(".$this->quote_id($result[$i]['tbl_name']).")";
  1101. $temp = $this->selectArray($query);
  1102. $cols = array();
  1103. $cols_quoted = array();
  1104. $vals = array();
  1105. for($z=0; $z<sizeof($temp); $z++)
  1106. {
  1107. $cols[$z] = $temp[$z][1];
  1108. $cols_quoted[$z] = $this->quote_id($temp[$z][1]);
  1109. }
  1110. for($z=0; $z<sizeof($arr); $z++)
  1111. {
  1112. for($y=0; $y<sizeof($cols); $y++)
  1113. {
  1114. if(!isset($vals[$z]))
  1115. $vals[$z] = array();
  1116. if($arr[$z][$cols[$y]] === NULL)
  1117. $vals[$z][$cols[$y]] = 'NULL';
  1118. else
  1119. $vals[$z][$cols[$y]] = $this->quote($arr[$z][$cols[$y]]);
  1120. }
  1121. }
  1122. for($j=0; $j<sizeof($vals); $j++)
  1123. echo "INSERT INTO ".$this->quote_id($result[$i]['tbl_name'])." (".implode(",", $cols_quoted).") VALUES (".implode(",", $vals[$j]).");\r\n";
  1124. }
  1125. }
  1126. }
  1127. if($transaction)
  1128. echo "COMMIT;\r\n";
  1129. }
  1130. }
  1131. $auth = new Authorization(); //create authorization object
  1132. if(isset($_POST['logout'])) //user has attempted to log out
  1133. $auth->revoke();
  1134. else if(isset($_POST['login']) || isset($_POST['proc_login'])) //user has attempted to log in
  1135. {
  1136. $_POST['login'] = true;
  1137. if($_POST['password']==SYSTEMPASSWORD) //make sure passwords match before granting authorization
  1138. {
  1139. if(isset($_POST['remember']))
  1140. $auth->grant(true);
  1141. else
  1142. $auth->grant(false);
  1143. }
  1144. }
  1145. if($auth->isAuthorized())
  1146. {
  1147. //user is deleting a database
  1148. if(isset($_GET['database_delete']))
  1149. {
  1150. $dbpath = $_POST['database_delete'];
  1151. unlink($dbpath);
  1152. unset($_SESSION[COOKIENAME.'currentDB']);
  1153. }
  1154. //user is renaming a database
  1155. if(isset($_GET['database_rename']))
  1156. {
  1157. $oldpath = $_POST['oldname'];
  1158. $newpath = $_POST['newname'];
  1159. if(!file_exists($newpath))
  1160. {
  1161. copy($oldpath, $newpath);
  1162. unlink($oldpath);
  1163. $justrenamed = true;
  1164. }
  1165. else
  1166. {
  1167. $dbexists = true;
  1168. }
  1169. }
  1170. //user is creating a new Database
  1171. if(isset($_POST['new_dbname']) && $auth->isAuthorized())
  1172. {
  1173. $str = preg_replace('@[^\w-.]@','', $_POST['new_dbname']);
  1174. $dbname = $str;
  1175. $dbpath = $str;
  1176. $info = pathinfo($dbpath);
  1177. $tdata = array();
  1178. $tdata['name'] = $dbname;
  1179. $tdata['path'] = $directory."/".$dbpath;
  1180. $td = new Database($tdata);
  1181. $td->query("VACUUM");
  1182. }
  1183. //if the user wants to scan a directory for databases, do so
  1184. if($directory!==false)
  1185. {
  1186. if($directory[strlen($directory)-1]=="/") //if user has a trailing slash in the directory, remove it
  1187. $directory = substr($directory, 0, strlen($directory)-1);
  1188. if(is_dir($directory)) //make sure the directory is valid
  1189. {
  1190. if($subdirectories===true)
  1191. $arr = dir_tree($directory);
  1192. else
  1193. $arr = scandir($directory);
  1194. $databases = array();
  1195. $j = 0;
  1196. for($i=0; $i<sizeof($arr); $i++) //iterate through all the files in the databases
  1197. {
  1198. if($subdirectories===false)
  1199. $arr[$i] = $directory."/".$arr[$i];
  1200. if(!is_file($arr[$i])) continue;
  1201. $con = file_get_contents($arr[$i], NULL, NULL, 0, 60);
  1202. if(strpos($con, "** This file contains an SQLite 2.1 database **", 0)!==false || strpos($con, "SQLite format 3", 0)!==false)
  1203. {
  1204. $databases[$j]['path'] = $arr[$i];
  1205. if($subdirectories===false)
  1206. $databases[$j]['name'] = basename($arr[$i]);
  1207. else
  1208. $databases[$j]['name'] = $arr[$i];
  1209. // 22 August 2011: gkf fixed bug 49.
  1210. $perms = 0;
  1211. $perms += is_readable($databases[$j]['path']) ? 4 : 0;
  1212. $perms += is_writeable($databases[$j]['path']) ? 2 : 0;
  1213. switch($perms)
  1214. {
  1215. case 6: $perms = "[rw] "; break;
  1216. case 4: $perms = "[r ] "; break;
  1217. case 2: $perms = "[ w] "; break; // God forbid, but it might happen.
  1218. default: $perms = "[ ] "; break;
  1219. }
  1220. $databases[$j]['perms'] = $perms;
  1221. $j++;
  1222. }
  1223. }
  1224. // 22 August 2011: gkf fixed bug #50.
  1225. sort($databases);
  1226. if(isset($tdata))
  1227. {
  1228. foreach($databases as $db_id => $database)
  1229. {
  1230. if($database['path'] == $tdata)
  1231. {
  1232. $_SESSION[COOKIENAME.'currentDB'] = $database;
  1233. break;
  1234. }
  1235. }
  1236. }
  1237. if(isset($justrenamed))
  1238. {
  1239. foreach($databases as $db_id => $database)
  1240. {
  1241. if($database['path'] == $newpath)
  1242. {
  1243. $_SESSION[COOKIENAME.'currentDB'] = $database;
  1244. break;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. else //the directory is not valid - display error and exit
  1250. {
  1251. echo "<div class='confirm' style='margin:20px;'>";
  1252. echo "The directory you specified to scan for databases does not exist or is not a directory.";
  1253. echo "</div>";
  1254. exit();
  1255. }
  1256. }
  1257. else
  1258. {
  1259. for($i=0; $i<sizeof($databases); $i++)
  1260. {
  1261. if(!file_exists($databases[$i]['path']))
  1262. continue; //skip if file not found ! - probably a warning can be displayed - later
  1263. $perms = 0;
  1264. $perms += is_readable($databases[$i]['path']) ? 4 : 0;
  1265. $perms += is_writeable($databases[$i]['path']) ? 2 : 0;
  1266. switch($perms)
  1267. {
  1268. case 6: $perms = "[rw] "; break;
  1269. case 4: $perms = "[r ] "; break;
  1270. case 2: $perms = "[ w] "; break; // God forbid, but it might happen.
  1271. default: $perms = "[ ] "; break;
  1272. }
  1273. $databases[$i]['perms'] = $perms;
  1274. }
  1275. sort($databases);
  1276. }
  1277. //user is downloading the exported database file
  1278. if(isset($_POST['export']))
  1279. {
  1280. if($_POST['export_type']=="sql")
  1281. {
  1282. header('Content-Type: text/sql');
  1283. header('Content-Disposition: attachment; filename="'.$_POST['filename'].'.'.$_POST['export_type'].'";');
  1284. if(isset($_POST['tables']))
  1285. $tables = $_POST['tables'];
  1286. else
  1287. {
  1288. $tables = array();
  1289. $tables[0] = $_POST['single_table'];
  1290. }
  1291. $drop = isset($_POST['drop']);
  1292. $structure = isset($_POST['structure']);
  1293. $data = isset($_POST['data']);
  1294. $transaction = isset($_POST['transaction']);
  1295. $comments = isset($_POST['comments']);
  1296. $db = new Database($_SESSION[COOKIENAME.'currentDB']);
  1297. echo $db->export_sql($tables, $drop, $structure, $data, $transaction, $comments);
  1298. }
  1299. else if($_POST['export_type']=="csv")
  1300. {
  1301. header("Content-type: application/csv");
  1302. header('Content-Disposition: attachment; filename="'.$_POST['filename'].'.'.$_POST['export_type'].'";');
  1303. header("Pragma: no-cache");
  1304. header("Expires: 0");
  1305. if(isset($_POST['tables']))
  1306. $tables = $_POST['tables'];
  1307. else
  1308. {
  1309. $tables = array();
  1310. $tables[0] = $_POST['single_table'];
  1311. }
  1312. $field_terminate = $_POST['export_csv_fieldsterminated'];
  1313. $field_enclosed = $_POST['export_csv_fieldsenclosed'];
  1314. $field_escaped = $_POST['export_csv_fieldsescaped'];
  1315. $null = $_POST['export_csv_replacenull'];
  1316. $crlf = isset($_POST['export_csv_crlf']);
  1317. $fields_in_first_row = isset($_POST['export_csv_fieldnames']);
  1318. $db = new Database($_SESSION[COOKIENAME.'currentDB']);
  1319. echo $db->export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row);
  1320. }
  1321. exit();
  1322. }
  1323. //user is importing a file
  1324. if(isset($_POST['import']))
  1325. {
  1326. $db = new Database($_SESSION[COOKIENAME.'currentDB']);
  1327. if($_POST['import_type']=="sql")
  1328. {
  1329. $data = file_get_contents($_FILES["file"]["tmp_name"]);
  1330. $importSuccess = $db->import_sql($data);
  1331. }
  1332. else
  1333. {
  1334. $field_terminate = $_POST['import_csv_fieldsterminated'];
  1335. $field_enclosed = $_POST['import_csv_fieldsenclosed'];
  1336. $field_escaped = $_POST['import_csv_fieldsescaped'];
  1337. $null = $_POST['import_csv_replacenull'];
  1338. $fields_in_first_row = isset($_POST['import_csv_fieldnames']);
  1339. $importSuccess = $db->import_csv($_FILES["file"]["tmp_name"], $_POST['single_table'], $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row);
  1340. }
  1341. }
  1342. }
  1343. header('Content-Type: text/html; charset=utf-8');
  1344. // here begins the HTML.
  1345. ?>
  1346. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  1347. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  1348. <head>
  1349. <!-- Copyright <?php echo date("Y"); ?> phpLiteAdmin (http://phpliteadmin.googlecode.com) -->
  1350. <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
  1351. <title><?php echo PROJECT ?></title>
  1352. <?php
  1353. if(!file_exists("phpliteadmin.css")) //only use the inline stylesheet if an external one does not exist
  1354. {
  1355. ?>
  1356. <!-- begin the customizable stylesheet/theme -->
  1357. <style type="text/css">
  1358. /* overall styles for entire page */
  1359. body
  1360. {
  1361. margin: 0px;
  1362. padding: 0px;
  1363. font-family: Arial, Helvetica, sans-serif;
  1364. font-size: 14px;
  1365. color: #000000;
  1366. background-color: #e0ebf6;
  1367. }
  1368. /* general styles for hyperlink */
  1369. a
  1370. {
  1371. color: #03F;
  1372. text-decoration: none;
  1373. cursor :pointer;
  1374. }
  1375. a:hover
  1376. {
  1377. color: #06F;
  1378. }
  1379. hr
  1380. {
  1381. height: 1px;
  1382. borde

Large files files are truncated, but you can click here to view the full file