From b4ba50fbe285a1ad60fb39fe34e9915d90e993df Mon Sep 17 00:00:00 2001 From: schucan Date: Sun, 19 May 2024 23:09:54 +0200 Subject: [PATCH 1/2] Update index.php: removing Microtimer for this to work in PHP 8.2 --- index.php | 3776 +++++++++++++++++++++++++---------------------------- 1 file changed, 1802 insertions(+), 1974 deletions(-) diff --git a/index.php b/index.php index 6837650..f90ddb7 100644 --- a/index.php +++ b/index.php @@ -1,13 +1,7 @@ variables_order needs to include G, P, C and S. The current value is "'.ini_get('variables_order').'". Please check the php configuration (php.ini).'); -} +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +//there is no reason for the average user to edit anything below this comment +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # REMOVE_FROM_BUILD // include default configuration and language @@ -32,45 +26,32 @@ function pla_autoload($classname) // load optional configuration file $config_filename = './phpliteadmin.config.php'; -if (is_readable($config_filename)) -{ +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("VERSION", "1.9.7-dev"); +define("PAGE", basename(__FILE__)); +define("FORCETYPE", false); //force the extension that will be used (set to false in almost all circumstances except debugging) define("SYSTEMPASSWORD", $password); // Makes things easier. -define('PROJECT_URL','https://www.phpliteadmin.org/'); -define('DONATE_URL','https://www.phpliteadmin.org/donate/'); +define('PROJECT_URL','http://www.phpliteadmin.org/'); +define('DONATE_URL','http://www.phpliteadmin.org/donate/'); define('VERSION_CHECK_URL','https://www.phpliteadmin.org/current_version.php'); define('PROJECT_BUGTRACKER_LINK','https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open'); define('PROJECT_INSTALL_LINK','https://bitbucket.org/phpliteadmin/public/wiki/Installation'); -// 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'])) -{ +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(); +session_start(); if($debug==true) { @@ -81,9 +62,6 @@ function pla_autoload($classname) @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; @@ -94,26 +72,9 @@ function pla_autoload($classname) $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); -} - +// 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) ); //data types array $sqlite_datatypes = array("INTEGER", "REAL", "TEXT", "BLOB","NUMERIC","BOOLEAN","DATETIME"); @@ -123,40 +84,6 @@ function pla_autoload($classname) //- 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) { @@ -203,7 +130,7 @@ function explode_sql($delimiter, $sql) $i++; } continue 2; - } + } } $i++; } @@ -215,8 +142,8 @@ function explode_sql($delimiter, $sql) //function to scan entire directory tree and subdirectories function dir_tree($dir) { - $path = array(); - $stack = array($dir); + $path = ''; + $stack[] = $dir; while($stack) { $thisdir = array_pop($stack); @@ -249,7 +176,7 @@ function dir_tree($dir) function helpLink($name) { global $lang; - return "[?]"; + return "[?]"; } // function to encode value into HTML just like htmlentities, but with adjusted default settings @@ -258,60 +185,25 @@ function htmlencode($value, $flags=ENT_QUOTES, $encoding ="UTF-8") return htmlentities($value, $flags, $encoding); } -// reduce string chars -function subString($str) +// 22 August 2011: gkf added this function to support display of +// default values in the form used to INSERT new data. +function deQuoteSQL($s) { - global $charsNum, $params; - if($charsNum > 10 && (!isset($params->fulltexts) || !$params->fulltexts) && mb_strlen($str)>$charsNum) - { - $str = mb_substr($str, 0, $charsNum).'...'; - } - return $str; + return trim(trim($s), "'"); } -// marks searchwords and htmlencodes correctly -function markSearchWords($input, $field, $search) +// reduce string chars +function subString($str) { - $output = htmlencode($input); - if(isset($search['values'][$field]) && is_array($search['values'][$field])) + global $charsNum; + if($charsNum > 10 && (!isset($_SESSION[COOKIENAME.'fulltexts']) || !$_SESSION[COOKIENAME.'fulltexts']) && strlen($str)>$charsNum) { - // 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++ $betweenPart) - { - $output .= htmlencode($betweenPart); // part that does not match (might be empty) - if(isset($fldFoundParts[0][$index])) - $output .= ''.htmlencode($fldFoundParts[0][$index]).''; // the part that matched - } + $str = substr($str, 0, $charsNum).'...'; } - return $output; + return $str; } -// checks the (new) name of a database file +// checks the (new) name of a database file function checkDbName($name) { global $allowed_extensions; @@ -334,7 +226,7 @@ function isManagedDB($path) global $databases; foreach($databases as $db_key => $database) { - if($path === $database['path']) + if($path == $database['path']) { // a db we manage. Thats okay. // return the key. @@ -346,7 +238,7 @@ function isManagedDB($path) } // 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 +// see http://www.sqlite.org/datatype3.html section 2.1 for rules function get_type_affinity($type) { if (preg_match("/INT/i", $type)) @@ -362,55 +254,15 @@ function get_type_affinity($type) } -// 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'])) +if (isset($_POST['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') ); -} + $auth->attemptGrant($_POST['password'], isset($_POST['remember'])); //- Actions on database files and bulk data if ($auth->isAuthorized()) @@ -420,39 +272,35 @@ function parseSize($size) if(isset($_POST['new_dbname'])) { if($_POST['new_dbname']=='') - $params->redirect(array('table'=>null), $lang['err'].': '.$lang['db_blank']); + { + // TODO: Display an error message (do NOT echo here. echo below in the html-body!) + } else { - $str = preg_replace('@[^\w\-.]@u','', $_POST['new_dbname']); + $str = preg_replace('@[^\w-.]@','', $_POST['new_dbname']); $dbname = $str; $dbpath = $str; if(checkDbName($dbname)) { - $tdata = array(); + $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)).'
'.$lang['add_allowed_extension']); + if(is_file($dbname) || is_dir($dbname)) $dbexists = true; + else $extension_not_allowed=true; } } } - + //- 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) @@ -465,7 +313,7 @@ function parseSize($size) { 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) @@ -487,10 +335,9 @@ function parseSize($size) { foreach($databases as $db_id => $database) { - if($database['path'] === $tdata['path']) + if($database['path'] == $tdata['path']) { - $currentDB = $database; - $params->database = $database['path']; + $_SESSION[COOKIENAME.'currentDB'] = $database; break; } } @@ -513,7 +360,7 @@ function parseSize($size) $databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path'])); $databases[$i]['readable'] = is_writable(dirname($databases[$i]['path'])); } - else + else { $databases[$i]['writable'] = is_writable($databases[$i]['path']); $databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path'])); @@ -522,17 +369,10 @@ function parseSize($size) } 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']; - } - } - + // we now have the $databases array set. Check whethet currentDB is a managed Db (is in this array) + if(isset($_SESSION[COOKIENAME.'currentDB']) && isManagedDB($_SESSION[COOKIENAME.'currentDB']['path']) === false) + unset($_SESSION[COOKIENAME.'currentDB']); + //- Delete an existing database if(isset($_GET['database_delete'])) { @@ -542,12 +382,11 @@ function parseSize($size) if($checkDB !== false) { unlink($dbpath); - unset($params->database); - unset($currentDB); + unset($_SESSION[COOKIENAME.'currentDB']); unset($databases[$checkDB]); } else die($lang['err'].': '.$lang['delete_only_managed']); } - + //- Rename an existing database if(isset($_GET['database_rename'])) { @@ -568,9 +407,9 @@ function parseSize($size) // its okay, the new directory is within $directory $newpath = $_POST['newname']; } - else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['db_moved_outside']); + else die($lang['err'].': '.$lang['db_moved_outside']); } - + if(checkDbName($newpath)) { $checkDB = isManagedDB($oldpath); @@ -579,26 +418,22 @@ function parseSize($size) 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)."'."); + $_SESSION[COOKIENAME.'currentDB'] = $databases[$checkDB]; + $justrenamed = true; } - else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['rename_only_managed']); + else die($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)).'
'.$lang['add_allowed_extension']); + if(is_file($newpath) || is_dir($newpath)) $dbexists = true; + else $extension_not_allowed = true; } } - + //- 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") { @@ -616,8 +451,8 @@ function parseSize($size) $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); + $db = new Database($_SESSION[COOKIENAME.'currentDB']); + echo $db->export_sql($tables, $drop, $structure, $data, $transaction, $comments); } else if($_POST['export_type']=="csv") { @@ -638,16 +473,16 @@ function parseSize($size) $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); + $db = new Database($_SESSION[COOKIENAME.'currentDB']); + echo $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 = new Database($_SESSION[COOKIENAME.'currentDB']); $db->registerUserFunction($custom_functions); if($_POST['import_type']=="sql") { @@ -661,28 +496,12 @@ function parseSize($size) $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); + $importSuccess = $db->import_csv($_FILES["file"]["tmp_name"], $_POST['single_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"); @@ -690,997 +509,737 @@ function parseSize($size) readfile($_GET['download']); exit; } +} + +//- HTML: output starts here +header('Content-Type: text/html; charset=utf-8'); +?> + + + + + + +<?php echo PROJECT ?> + +", PHP_EOL; +else + // only use the default stylesheet if an external one does not exist + echo "", PHP_EOL; - //- Select database (from session or first available) - if(!isset($currentDB) && count($databases)>0) +// HTML: output help text, then exit +if(isset($_GET['help'])) +{ + //help section array + $help = array + ( + $lang['help1'] => sprintf($lang['help1_x'], PROJECT, PROJECT, PROJECT), $lang['help2'] => $lang['help2_x'], $lang['help3'] => $lang['help3_x'], + $lang['help4'] => $lang['help4_x'], $lang['help5'] => $lang['help5_x'], $lang['help6'] => $lang['help6_x'], + $lang['help7'] => $lang['help7_x'], $lang['help8'] => $lang['help8_x'], $lang['help9'] => $lang['help9_x'], $lang['help10'] => $lang['help10_x'] + ); + ?> + + +
+ "; + echo "".PROJECT." v".VERSION." ".$lang['help_doc']."

"; + foreach((array)$help as $key => $val) { - //set the current database to the first existing one in the array (default) - $currentDB = reset($databases); - $params->database = $currentDB['path']; + echo "".$key."
"; } - - if(isset($currentDB)) + echo "
"; + echo "

"; + foreach((array)$help as $key => $val) { - //- Open database (creates a Database object) - $db = new Database($currentDB); //create the Database object - $db->registerUserFunction($custom_functions); + echo "
"; + echo "".$key.""; + echo "
"; + echo $val; + echo "
"; + echo "".$lang['back_top'].""; + echo "
"; } + ?> + + + + 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; +//- Javascript include +?> + + + + +".$lang['bad_php_directive'].""; + echo ""; + exit(); +} + +//- HTML: login screen if not authorized, exit +if(!$auth->isAuthorized()) +{ + echo "
"; + echo "

v".VERSION."

"; + echo "
"; + if ($auth->isFailedLogin()) + echo "".$lang['passwd_incorrect']."

"; + echo "
"; + echo $lang['passwd'].":
"; + echo "

"; + echo ""; + echo ""; + echo "
"; + echo "
"; + echo "
"; + echo "
"; + echo "
"; + echo "".$lang['powered']." ".PROJECT." | "; + echo "
"; + echo ""; + exit(); +} + +//- User is authorized, display the main application - if(isset($_GET['numRows']) && intval($_GET['numRows'])>0) - $params->numRows = intval($_GET['numRows']); +//- Select database (from session or first available) +if(!isset($_SESSION[COOKIENAME.'currentDB']) && count($databases)>0) +{ + //set the current database to the first existing one in the array (default) + $_SESSION[COOKIENAME.'currentDB'] = reset($databases); +} +if(sizeof($databases)>0) + $currentDB = $_SESSION[COOKIENAME.'currentDB']; +else // the database array is empty, offer to create a new database +{ + //- HTML: form to create a new database, exit + if($directory!==false && is_writable($directory)) + { + echo "
"; + printf($lang['no_db'], PROJECT, PROJECT); + echo "
"; + if(isset($extension_not_allowed)) + { + echo "
"; + echo $lang['err'].': '.$lang['extension_not_allowed'].': '; + echo implode(', ', array_map('htmlencode', $allowed_extensions)); + echo '
'.$lang['add_allowed_extension']; + echo "

"; + } + echo "
".$lang['db_create'].""; + echo "
"; + echo " "; + echo "
"; + echo "
"; + } else - $params->numRows = $rowsNum; + { + echo "
"; + echo $lang['err'].": ".sprintf($lang['no_db2'], PROJECT); + echo "

"; + } + exit(); +} - //- Switch on $_GET['action'] for operations without output - if(isset($_GET['action']) && isset($_GET['confirm'])) +//- Switch to a different database with drop-down menu +if(isset($_POST['database_switch'])) +{ + foreach($databases as $db_id => $database) + { + if($database['path'] == $_POST['database_switch']) + { + $_SESSION[COOKIENAME."currentDB"] = $database; + break; + } + } + $currentDB = $_SESSION[COOKIENAME.'currentDB']; +} +else if(isset($_GET['switchdb'])) +{ + foreach($databases as $db_id => $database) { - switch($_GET['action']) + if($database['path'] == $_GET['switchdb']) { - //- Table actions + $_SESSION[COOKIENAME."currentDB"] = $database; + break; + } + } + $currentDB = $_SESSION[COOKIENAME.'currentDB']; +} +if(isset($_SESSION[COOKIENAME.'currentDB']) && in_array($_SESSION[COOKIENAME.'currentDB'], $databases)) + $currentDB = $_SESSION[COOKIENAME.'currentDB']; - //- Create table (=table_create) - case "table_create": - $num = intval($_POST['rows']); - $name = $_POST['tablename']; - $primary_keys = array(); - for($i=0; $i<$num; $i++) +//- 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; + +//- 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'])) { - if($_POST[$i.'_field']!="" && isset($_POST[$i.'_primarykey'])) - { - $primary_keys[] = $_POST[$i.'_field']; - } + $primary_keys[] = $_POST[$i.'_field']; } - $query = "CREATE TABLE ".$db->quote($name)." ("; - for($i=0; $i<$num; $i++) + } + $query = "CREATE TABLE ".$db->quote($name)." ("; + for($i=0; $i<$num; $i++) + { + if($_POST[$i.'_field']!="") { - if($_POST[$i.'_field']!="") + $query .= $db->quote($_POST[$i.'_field'])." "; + $query .= $_POST[$i.'_type']." "; + if(isset($_POST[$i.'_primarykey'])) { - $query .= $db->quote($_POST[$i.'_field'])." "; - $query .= $_POST[$i.'_type']." "; - if(isset($_POST[$i.'_primarykey'])) + if(count($primary_keys)==1) { - 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 .= "PRIMARY KEY "; + if(isset($_POST[$i.'_autoincrement']) && $db->getType() != "SQLiteDatabase") + $query .= "AUTOINCREMENT "; } - $query = substr($query, 0, -1); - $query .= ", "; + $query .= "NOT NULL "; } - } - if (count($primary_keys)>1) - { - $compound_key = ""; - foreach ($primary_keys as $primary_key) + 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') { - $compound_key .= ($compound_key=="" ? "" : ", ") . $db->quote($primary_key); + $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 .= "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'].".
".htmlencode($query).""; - $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)."; "; + $query = substr($query, 0, sizeof($query)-2); + $query .= ", "; } - $query1 .= "COMMIT; "; - $result1=$db->multiQuery($query1); - if($result1 === false) - $completed = $db->getError(true); - if(isset($_POST['vacuum']) && $_POST['vacuum']) + } + if (count($primary_keys)>1) + { + $compound_key = ""; + foreach ($primary_keys as $primary_key) { - $query2 = "VACUUM;"; - $result2 = $db->query($query2); + $compound_key .= ($compound_key=="" ? "" : ", ") . $db->quote($primary_key); } - else - $query2 = ""; - if($result1 !== false) - $completed = $lang['tbl']." '".htmlencode(implode(', ',$tables))."' ".$lang['emptied'].".
".htmlencode($query1)."
".htmlencode($query2)."
"; - if(count($tables)==1) - $action = array('action'=>'row_view'); - else - $action = array(); - $params->redirect(($result1===false ? array() : $action ), $completed); - break; + $query .= "PRIMARY KEY (".$compound_key."), "; + } + $query = substr($query, 0, sizeof($query)-3); + $query .= ")"; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($_POST['tablename'])."' ".$lang['created'].".
".htmlencode($query).""; + $backlinkParameters = "&action=column_view&table=".urlencode($name); + 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'].".
".htmlencode($query).""; - $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'].".
".htmlencode($query1)."
".htmlencode($query2)."
";; - } - $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'])."'.
".htmlencode($query).""; - $target_table = $_POST['newname']; - } - $params->redirect(array('action'=>'row_view', 'table'=>$_POST['newname']), $completed); - break; + //- Empty table (=table_empty) + case "table_empty": + $query = "DELETE FROM ".$db->quote_id($_POST['tablename']); + $result = $db->query($query); + if($result===false) + $error = true; + $query = "VACUUM"; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($_POST['tablename'])."' ".$lang['emptied'].".
".htmlencode($query).""; + $backlinkParameters = "&action=row_view&table=".urlencode($name); + break; - //- Search table (=table_search) - case "table_search": - $searchValues = array(); - $searchOperators = array(); + //- Create view (=view_create) + case "view_create": + $query = "CREATE VIEW ".$db->quote($_POST['viewname'])." AS ".$_POST['select']; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['view']." '".htmlencode($_POST['viewname'])."' ".$lang['created'].".
".htmlencode($query).""; + $backlinkParameters = "&action=column_view&table=".urlencode($_POST['viewname']); + break; - $tableInfo = $db->getTableInfo($target_table); - $j = 0; - $whereExpr = array(); - for($i=0; $iquote_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 $searchWhere, - 'values' => $searchValues, - 'operators' => $searchOperators - ); - $params->redirect(array('action'=>'table_search','search'=>$searchID)); + //- Drop table (=table_drop) + case "table_drop": + $query = "DROP TABLE ".$db->quote_id($_POST['tablename']); + $result=$db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($_POST['tablename'])."' ".$lang['dropped']."."; + $backlinkParameters = ""; break; - //- Row actions + //- Drop view (=view_drop) + case "view_drop": + $query = "DROP VIEW ".$db->quote_id($_POST['viewname']); + $result=$db->query($query); + if($result===false) + $error = true; + $completed = $lang['view']." '".htmlencode($_POST['viewname'])."' ".$lang['dropped']."."; + $backlinkParameters = ""; + break; - //- Create row (=row_create) - case "row_create": - $completed = ""; - $num = $_POST['newRows']; - $z = 0; - $error = false; + //- Rename table (=table_rename) + case "table_rename": + $query = "ALTER TABLE ".$db->quote_id($_POST['oldname'])." RENAME TO ".$db->quote($_POST['newname']); + if($db->getVersion()==3) + $result = $db->query($query, true); + else + $result = $db->query($query, false); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($_POST['oldname'])."' ".$lang['renamed']." '".htmlencode($_POST['newname'])."'.
".htmlencode($query).""; + $backlinkParameters = "&action=row_view&table=".urlencode($_POST['newname']); + break; - $tableInfo = $db->getTableInfo($target_table); + //- Row actions - for($i=0; $i<$num; $i++) + //- Create row (=row_create) + case "row_create": + $completed = ""; + $num = $_POST['numRows']; + $fields = explode(":", $_POST['fields']); + $z = 0; + + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + + for($i=0; $i<$num; $i++) + { + if(!isset($_POST[$i.":ignore"])) { - if(!isset($_POST[$i.":ignore"])) + $query_cols = ""; + $query_vals = ""; + $all_default = true; + for($j=0; $jquote_id($tableInfo[$j]['name']).","; - - $function = $_POST["function_".$j][$i]; - if($function!="") - $query_vals .= $function."("; - if(preg_match('/^BLOB/', $type) && !$hexblobs) - $query_vals .= ':blobval'.$j; - elseif(preg_match('/^BLOB/', $type) && $hexblobs) - $query_vals .= 'X'.$db->quote($value); - elseif(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null) - $query_vals .= $db->quote($value); - elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="") - $query_vals .= "NULL"; - elseif($null) - $query_vals .= "NULL"; - else - $query_vals .= $db->quote($value); - if($function!="") - $query_vals .= ")"; - $query_vals .= ","; - } - $query = "INSERT INTO ".$db->quote_id($target_table); - if(!$all_default) - { - $query_cols = substr($query_cols, 0, strlen($query_cols)-1); - $query_vals = substr($query_vals, 0, strlen($query_vals)-1); - - $query.=" (". $query_cols . ") VALUES (". $query_vals. ")"; - } else { - $query .= " DEFAULT VALUES"; - } - if(isset($blobFiles)) - { - // blob files need to be done using a prepared statement because the query size would be too large - $handle = $db->prepareQuery($query); - foreach($blobFiles as $j=>$filename) - $db->bindValue($handle, ':blobval'.$j, file_get_contents($filename), 'blob'); - - $result1 = $db->executePrepared($handle, false); - } + $query_cols .= $db->quote_id($fields[$j]).","; + + $type = $result[$j]['type']; + $typeAffinity = get_type_affinity($type); + $function = $_POST["function_".$i."_".$j]; + if($function!="") + $query_vals .= $function."("; + if(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null) + $query_vals .= $db->quote($value); + elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="") + $query_vals .= "NULL"; + elseif($null) + $query_vals .= "NULL"; else - $result1 = $db->query($query); - if($result1===false) - $error = true; - $completed .= "".htmlencode($query)."
"; - $z++; + $query_vals .= $db->quote($value); + if($function!="") + $query_vals .= ")"; + $query_vals .= ","; } + $query = "INSERT INTO ".$db->quote_id($target_table); + if(!$all_default) + { + $query_cols = substr($query_cols, 0, strlen($query_cols)-1); + $query_vals = substr($query_vals, 0, strlen($query_vals)-1); + + $query.=" (". $query_cols . ") VALUES (". $query_vals. ")"; + } else { + $query .= " DEFAULT VALUES"; + } + $result1 = $db->query($query); + if($result1===false) + $error = true; + $completed .= "".htmlencode($query)."
"; + $z++; } - if($error) - $completed = $db->getError(true) . $completed; - else - $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; - $params->redirect(array('action'=>'row_view'), $completed); - break; - - //- Delete row (=row_delete) - case "row_delete": - $pks = json_decode($_GET['pk']); - - $query = "DELETE FROM ".$db->quote_id($target_table)." WHERE (".$db->wherePK($target_table,json_decode($pks[0])).")"; - for($i=1; $iwherePK($target_table,json_decode($pks[$i])).")"; - } - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = sizeof($pks)." ".$lang['rows']." ".$lang['deleted'].".
".htmlencode($query).""; - $params->redirect(array('action'=>'row_view'), $completed); - break; + } + $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; - //- Edit row (=row_edit) - case "row_edit": - $pks = json_decode($_GET['pk']); - $z = 0; + //- Delete row (=row_delete) + case "row_delete": + $pks = json_decode($_GET['pk']); + + $query = "DELETE FROM ".$db->quote_id($target_table)." WHERE (".$db->wherePK($target_table,json_decode($pks[0])).")"; + for($i=1; $iwherePK($target_table,json_decode($pks[$i])).")"; + } + $result = $db->query($query); + if($result===false) + $error = true; + $completed = sizeof($pks)." ".$lang['rows']." ".$lang['deleted'].".
".htmlencode($query).""; + $backlinkParameters = "&action=row_view&table=".urlencode($target_table); + break; - $tableInfo = $db->getTableInfo($target_table); + //- Edit row (=row_edit) + case "row_edit": + $pks = json_decode($_GET['pk']); + $fields = explode(":", $_POST['fieldArray']); + + $z = 0; + + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + + if(isset($_POST['new_row'])) + $completed = ""; + else + $completed = sizeof($pks)." ".$lang['rows']." ".$lang['affected'].".

"; + for($i=0; $i
"; - - for($i=0; $iquote_id($tableInfo[$j]['name']).' AS \'blob\' FROM '.$db->quote_id($target_table).' WHERE '.$db->wherePK($target_table, json_decode($pks[$i])); - $bl = $db->select($select); - $blobFiles[$j] = $bl['blob']; - unset($bl); - } - else - { - if($_FILES[$i.":".$j]["error"] == UPLOAD_ERR_OK && is_file($_FILES[$i.":".$j]["tmp_name"])) - $blobFiles[$j] = file_get_contents($_FILES[$i.":".$j]["tmp_name"]); - else - $blobFiles[$j] = null; - } - } - else - $value = $_POST[$j][$i]; - } - else - $value = ""; - if(!preg_match('/^BLOB/', $type) && $value===$tableInfo[$j]['dflt_value']) - { - // if the value is the default value, skip it - continue; - } - $all_default = false; - $query_cols .= $db->quote_id($tableInfo[$j]['name']).","; - - $function = $_POST["function_".$j][$i]; - if($function!="") - $query_vals .= $function."("; - if(preg_match('/^BLOB/', $type) && !$hexblobs) - $query_vals .= ':blobval'.$j; - elseif(preg_match('/^BLOB/', $type) && $hexblobs) - $query_vals .= 'X'.$db->quote($value); - elseif(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null) - $query_vals .= $db->quote($value); - elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="") - $query_vals .= "NULL"; - elseif($null) - $query_vals .= "NULL"; - else - $query_vals .= $db->quote($value); - if($function!="") - $query_vals .= ")"; - $query_vals .= ","; - } - $query = "INSERT INTO ".$db->quote_id($target_table); - if(!$all_default) - { - $query_cols = substr($query_cols, 0, strlen($query_cols)-1); - $query_vals = substr($query_vals, 0, strlen($query_vals)-1); - - $query.=" (". $query_cols . ") VALUES (". $query_vals. ")"; - } else { - $query .= " DEFAULT VALUES"; + $value = $_POST[$j][$i]; } - - if(isset($blobFiles)) + else + $value = ""; + if($value===$result[$j]['dflt_value']) { - // blob files need to be done using a prepared statement because the query size would be too large - $handle = $db->prepareQuery($query); - foreach($blobFiles as $j=>$blobval) - $db->bindValue($handle, ':blobval'.$j, $blobval, 'blob'); - - $result1 = $db->executePrepared($handle, false); - } + // if the value is the default value, skip it + continue; + } else + $all_default = false; + $query_cols .= $db->quote_id($fields[$j]).","; + + $type = $result[$j]['type']; + $typeAffinity = get_type_affinity($type); + $function = $_POST["function_".$j][$i]; + if($function!="") + $query_vals .= $function."("; + if(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null) + $query_vals .= $db->quote($value); + elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="") + $query_vals .= "NULL"; + elseif($null) + $query_vals .= "NULL"; else - $result1 = $db->query($query); - if($result1===false) - $error = true; - $z++; + $query_vals .= $db->quote($value); + if($function!="") + $query_vals .= ")"; + $query_vals .= ","; } - else + $query = "INSERT INTO ".$db->quote_id($target_table); + if(!$all_default) { - $query = "UPDATE ".$db->quote_id($target_table)." SET "; - for($j=0; $jquote_id($tableInfo[$j]['name'])."="; - if($function!="") - $query .= $function."("; - if($null) - $query .= "NULL"; - else - { - if(preg_match('/^BLOB/', $type) && !$hexblobs) - $query .= ':blobval'.$j; - elseif(preg_match('/^BLOB/', $type) && $hexblobs) - $query .= 'X'.$db->quote($_POST[$j][$i]); - else - $query .= $db->quote($_POST[$j][$i]); - } - if($function!="") - $query .= ")"; - $query .= ", "; - } - $query = substr($query, 0, -2); - $query .= " WHERE ".$db->wherePK($target_table, json_decode($pks[$i])); - if(isset($blobFiles)) - { - // blob files need to be done using a prepared statement because the query size would be too large - $handle = $db->prepareQuery($query); - foreach($blobFiles as $j=>$filename) - $db->bindValue($handle, ':blobval'.$j, file_get_contents($filename), 'blob'); - - $result1 = $db->executePrepared($handle, false); - } - else - $result1 = $db->query($query); - if($result1===false) - { - $error = true; - } + $query_cols = substr($query_cols, 0, strlen($query_cols)-1); + $query_vals = substr($query_vals, 0, strlen($query_vals)-1); + + $query.=" (". $query_cols . ") VALUES (". $query_vals. ")"; + } else { + $query .= " DEFAULT VALUES"; } - $completed .= "".htmlencode($query)."
"; - } - if($error) - $completed = $db->getError(true) . $completed; - elseif(isset($_POST['new_row'])) - $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; - $params->redirect(array('action'=>'row_view'), $completed); - break; - - - case "row_get_blob": - $blobVal = $db->select("SELECT ".$db->quote_id($_GET['column'])." AS 'blob' FROM ".$db->quote_id($target_table)." WHERE ".$db->wherePK($target_table, json_decode($_GET['pk']))); - $filename = 'download'; - if(function_exists('getimagesizefromstring')) // introduced in PHP 5.4.0 - $imagesize = getimagesizefromstring($blobVal['blob']); - if(isset($imagesize) && $imagesize!==false && isset($imagesize['mime'])) - $mimetype = $imagesize['mime']; - elseif(class_exists('finfo')) // included since php 5.3.0, but might be disabled on Windows - { - $finfo = new finfo(FILEINFO_MIME); - $mimetype = $finfo->buffer($blobVal['blob']); + $result1 = $db->query($query); + if($result1===false) + $error = true; + $z++; } else - $mimetype = "application/octet-stream"; - - if(isset($imagesize) && $imagesize!==false && isset($imagesize[2])) - $extension = image_type_to_extension($imagesize[2]); - else - $extension = '.blob'; - ob_end_clean(); - header('Content-Length: '.strlen($blobVal['blob'])); - header("Content-type: ".$mimetype); - if(isset($_GET['download_blob']) && $_GET['download_blob']) - header('Content-Disposition: attachment; filename="'.$filename.$extension.'";'); - header("Pragma: no-cache"); - header("Expires: 0"); - echo $blobVal['blob']; - exit; - break; - - - //- Column actions - - //- Create column (=column_create) - case "column_create": - $num = intval($_POST['rows']); - for($i=0; $i<$num; $i++) { - if($_POST[$i.'_field']!="") + $query = "UPDATE ".$db->quote_id($target_table)." SET "; + for($j=0; $jquote_id($target_table)." ADD ".$db->quote($_POST[$i.'_field'])." "; - $query .= $_POST[$i.'_type']." "; - if(isset($_POST[$i.'_primarykey'])) - $query .= "PRIMARY KEY "; - if(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'])." "; - } - if($db->getVersion()==3 && - ($_POST[$i.'_defaultoption']=='defined' || $_POST[$i.'_defaultoption']=='none' || $_POST[$i.'_defaultoption']=='NULL') - // Sqlite3 cannot add columns with default values that are not constant - && !isset($_POST[$i.'_primarykey']) - // sqlite3 cannot add primary key columns - && (!isset($_POST[$i.'_notnull']) || $_POST[$i.'_defaultoption']!='none') - // SQLite3 cannot add NOT NULL columns without DEFAULT even if the table is empty - ) - // use SQLITE3 ALTER TABLE ADD COLUMN - $result = $db->query($query, true); + $function = $_POST["function_".$j][$i]; + $null = isset($_POST[$j."_null"][$i]); + $query .= $db->quote_id($fields[$j])."="; + if($function!="") + $query .= $function."("; + if($null) + $query .= "NULL"; else - // use ALTER TABLE workaround - $result = $db->query($query, false); - if($result===false) - $error = true; + $query .= $db->quote($_POST[$j][$i]); + if($function!="") + $query .= ")"; + $query .= ", "; + } + $query = substr($query, 0, sizeof($query)-3); + $query .= " WHERE ".$db->wherePK($target_table, json_decode($pks[$i])); + $result1 = $db->query($query); + if($result1===false) + { + $error = true; } } - if($error) - $completed = $db->getError(true); - else - $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; - $params->redirect(array('action'=>'column_view'), $completed); - break; - - //- Delete column (=column_delete) - case "column_delete": - $pks = explode(":", $_GET['pk']); - $query = "ALTER TABLE ".$db->quote_id($target_table).' DROP '.$db->quote_id($pks[0]); - for($i=1; $iquote_id($pks[$i]); - } - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; - $params->redirect(array('action'=>'column_view'), $completed); - break; - - //- Add a primary key (=primarykey_add) - case "primarykey_add": - $pks = explode(":", $_GET['pk']); - $query = "ALTER TABLE ".$db->quote_id($target_table).' ADD PRIMARY KEY ('.$db->quote_id($pks[0]); - for($i=1; $iquote_id($pks[$i]); - } - $query .= ")"; - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; - $params->redirect(array('action'=>'column_view'), $completed); - break; - - //- Edit column (=column_edit) - case "column_edit": - $query = "ALTER TABLE ".$db->quote_id($target_table).' CHANGE '.$db->quote_id($_POST['oldvalue'])." ".$db->quote($_POST['0_field'])." ".$_POST['0_type']; - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; - $params->redirect(array('action'=>'column_view'), $completed); - break; - - //- Delete trigger (=trigger_delete) - case "trigger_delete": - $query = "DROP TRIGGER ".$db->quote_id($_GET['pk']); - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['trigger']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".
".htmlencode($query).""; - $params->redirect(array('action'=>'column_view'), $completed); - break; + $completed .= "".htmlencode($query)."
"; + } + if(isset($_POST['new_row'])) + $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; + $backlinkParameters = "&action=row_view&table=".urlencode($target_table); + break; - //- Delete index (=index_delete) - case "index_delete": - $query = "DROP INDEX ".$db->quote_id($_GET['pk']); - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['index']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".
".htmlencode($query).""; - $params->redirect(array('action'=>'column_view'), $completed); - break; - - //- Create trigger (=trigger_create) - case "trigger_create": - $str = "CREATE TRIGGER ".$db->quote($_POST['trigger_name']); - if($_POST['beforeafter']!="") - $str .= " ".$_POST['beforeafter']; - $str .= " ".$_POST['event']." ON ".$db->quote_id($target_table); - if(isset($_POST['foreachrow'])) - $str .= " FOR EACH ROW"; - if($_POST['whenexpression']!="") - $str .= " WHEN ".$_POST['whenexpression']; - $str .= " BEGIN"; - $str .= " ".$_POST['triggersteps']; - $str .= " END"; - $query = $str; - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); - else - $completed = $lang['trigger']." ".$lang['created'].".
".htmlencode($query).""; - $params->redirect(array('action'=>'column_view'), $completed); - break; + //- Column actions - //- Create index (=index_create) - case "index_create": - $num = $_POST['num']; - if($_POST['name']=="") - { - $completed = $lang['blank_index']; - } - else if($_POST['0_field']=="") - { - $completed = $lang['one_index']; - } - else + //- Create column (=column_create) + case "column_create": + $num = intval($_POST['rows']); + for($i=0; $i<$num; $i++) + { + if($_POST[$i.'_field']!="") { - $str = "CREATE "; - if($_POST['duplicate']=="no") - $str .= "UNIQUE "; - $str .= "INDEX ".$db->quote($_POST['name'])." ON ".$db->quote_id($target_table)." ("; - $str .= $db->quote_id($_POST['0_field']).$_POST['0_order']; - for($i=1; $i<$num; $i++) + $query = "ALTER TABLE ".$db->quote_id($target_table)." ADD ".$db->quote($_POST[$i.'_field'])." "; + $query .= $_POST[$i.'_type']." "; + if(isset($_POST[$i.'_primarykey'])) + $query .= "PRIMARY KEY "; + if(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') { - if($_POST[$i.'_field']!="") - $str .= ", ".$db->quote_id($_POST[$i.'_field']).$_POST[$i.'_order']; + $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'])." "; } - $str .= ")"; - if(isset($_POST['where']) && $_POST['where']!='') - $str.=" WHERE ".$_POST['where']; - $query = $str; - $result = $db->query($query); - if($result === false) - $completed = $db->getError(true); + if($db->getVersion()==3 && + ($_POST[$i.'_defaultoption']=='defined' || $_POST[$i.'_defaultoption']=='none' || $_POST[$i.'_defaultoption']=='NULL') + // Sqlite3 cannot add columns with default values that are not constant + && !isset($_POST[$i.'_primarykey']) + // sqlite3 cannot add primary key columns + && (!isset($_POST[$i.'_notnull']) || $_POST[$i.'_defaultoption']!='none') + // SQLite3 cannot add NOT NULL columns without DEFAULT even if the table is empty + ) + // use SQLITE3 ALTER TABLE ADD COLUMN + $result = $db->query($query, true); else - $completed = $lang['index']." ".$lang['created'].".
".htmlencode($query).""; + // use ALTER TABLE workaround + $result = $db->query($query, false); + if($result===false) + $error = true; } - $params->redirect(array('action'=>'column_view'), $completed); - break; - } - } -} - -// if not in debug mode, destroy all output until here -if($debug) - $bufferedOutput = ob_get_contents(); -ob_end_clean(); - -//- HTML: output starts here -header('Content-Type: text/html; charset=utf-8'); -?> - - - - - - -<?php echo PROJECT ?> - -", PHP_EOL; -else - // only use the default stylesheet if an external one does not exist - echo "", PHP_EOL; + //- Delete column (=column_delete) + case "column_delete": + $pks = explode(":", $_GET['pk']); + $query = "ALTER TABLE ".$db->quote_id($target_table).' DROP '.$db->quote_id($pks[0]); + for($i=1; $iquote_id($pks[$i]); + } + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -// HTML: output help text, then exit -if(isset($_GET['help'])) -{ - //help section array - $help = array($lang['help1'] => sprintf($lang['help1_x'], PROJECT, PROJECT, PROJECT)); - for($i=2; isset($lang['help'.$i]); $i++) - $help[$lang['help'.$i]]=$lang['help'.$i.'_x']; - ?> - - -
- "; - echo "".PROJECT." v".VERSION." ".$lang['help_doc']."

"; - foreach((array)$help as $key => $val) - { - echo "".$key."
"; - } - echo "
"; - echo "

"; - foreach((array)$help as $key => $val) - { - echo "
"; - echo "".$key.""; - echo "
"; - echo $val; - echo "
"; - echo "".$lang['back_top'].""; - echo "
"; - } - ?> - - - - quote_id($target_table).' ADD PRIMARY KEY ('.$db->quote_id($pks[0]); + for($i=1; $iquote_id($pks[$i]); + } + $query .= ")"; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -if($auth->isAuthorized()) -{ - //- Javascript include - ?> - - - - - - - - - - - - - - -quote_id($target_table).' CHANGE '.$db->quote_id($_POST['oldvalue'])." ".$db->quote($_POST['0_field'])." ".$_POST['0_type']; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -if(ini_get("register_globals") == "on" || ini_get("register_globals")=="1") //check whether register_globals is turned on - if it is, we need to not continue -{ - echo "
".$lang['bad_php_directive']."
"; - echo ""; - exit(); -} + //- Delete trigger (=trigger_delete) + case "trigger_delete": + $query = "DROP TRIGGER ".$db->quote_id($_GET['pk']); + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['trigger']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".
".htmlencode($query).""; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -//- HTML: login screen if not authorized, exit -if(!$auth->isAuthorized()) -{ - echo "
"; - echo "

v".VERSION."

"; - echo "
"; - if (isset($_GET['failed'])) - echo "".$lang['passwd_incorrect']."

"; - echo $params->getForm(); - echo $lang['passwd'].":
"; - echo "

"; - echo ""; - echo ""; - echo ""; - echo "
"; - echo "
"; - echo "
"; - echo "
"; - echo "".$lang['powered']." ".PROJECT." | "; - printf($lang['page_gen'], $pageTimer); - echo "
"; - echo ""; - exit(); -} + //- Delete index (=index_delete) + case "index_delete": + $query = "DROP INDEX ".$db->quote_id($_GET['pk']); + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['index']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".
".htmlencode($query).""; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -//- User is authorized, display the main application + //- Create trigger (=trigger_create) + case "trigger_create": + $str = "CREATE TRIGGER ".$db->quote($_POST['trigger_name']); + if($_POST['beforeafter']!="") + $str .= " ".$_POST['beforeafter']; + $str .= " ".$_POST['event']." ON ".$db->quote_id($target_table); + if(isset($_POST['foreachrow'])) + $str .= " FOR EACH ROW"; + if($_POST['whenexpression']!="") + $str .= " WHEN ".$_POST['whenexpression']; + $str .= " BEGIN"; + $str .= " ".$_POST['triggersteps']; + $str .= " END"; + $query = $str; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['trigger']." ".$lang['created'].".
".htmlencode($query).""; + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; -if(count($databases)==0) // the database array is empty, offer to create a new database -{ - //- HTML: form to create a new database, exit - if($directory!==false && is_writable($directory) && (is_executable($directory) || DIRECTORY_SEPARATOR === '\\')) - { - echo "
"; - printf($lang['no_db'], PROJECT, PROJECT); - echo "
"; - //if the user has performed some action, show the resulting message - if(isset($_GET['message']) && isset($_SESSION[COOKIENAME.'messages'][$_GET['message']])) - { - echo "
"; - echo $_SESSION[COOKIENAME.'messages'][$_GET['message']]; - echo "

"; - unset($_SESSION[COOKIENAME.'messages'][$_GET['message']]); - } - echo "
".$lang['db_create'].""; - echo $params->getForm(array('table'=>null), 'post', false, 'create_database'); - echo " "; - if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO'))) - { - echo ""; - } - echo ""; - echo ""; - echo "
"; - } - elseif($directory!==false && !is_executable($directory) && DIRECTORY_SEPARATOR === '/') - { - echo "
"; - echo $lang['err'].": ".sprintf($lang['dir_not_executable'], PROJECT, $directory); - echo "

"; - } - else - { - echo "
"; - echo $lang['err'].": ".sprintf($lang['no_db2'], PROJECT); - echo "

"; + //- Create index (=index_create) + case "index_create": + $num = $_POST['num']; + if($_POST['name']=="") + { + $completed = $lang['blank_index']; + } + else if($_POST['0_field']=="") + { + $completed = $lang['one_index']; + } + else + { + $str = "CREATE "; + if($_POST['duplicate']=="no") + $str .= "UNIQUE "; + $str .= "INDEX ".$db->quote($_POST['name'])." ON ".$db->quote_id($target_table)." ("; + $str .= $db->quote_id($_POST['0_field']).$_POST['0_order']; + for($i=1; $i<$num; $i++) + { + if($_POST[$i.'_field']!="") + $str .= ", ".$db->quote_id($_POST[$i.'_field']).$_POST[$i.'_order']; + } + $str .= ")"; + if(isset($_POST['where']) && $_POST['where']!='') + $str.=" WHERE ".$_POST['where']; + $query = $str; + $result = $db->query($query); + if($result===false) + $error = true; + $completed = $lang['index']." ".$lang['created'].".
".htmlencode($query).""; + } + $backlinkParameters = "&action=column_view&table=".urlencode($target_table); + break; } - exit(); } +// are we working on a view? let's check once here +$target_table_type = $target_table ? $db->getTypeOfTable($target_table) : null; + //- HTML: sidebar echo '"; echo ""; - for($i=0; $i"; $tdWithClassLeft = ""; echo $tdWithClassLeft; @@ -2701,32 +2434,35 @@ function drawChart() echo htmlencode($type); echo ""; echo $tdWithClassLeft; - echo ""; echo ""; foreach (array_merge($sqlite_functions, $custom_functions) as $f) { echo ""; } echo ""; echo ""; + //we need to have a column dedicated to nulls -di echo $tdWithClassLeft; - if($tableInfo[$i]['notnull']==0) + if($result[$i]['notnull']==0) { - if($value===NULL) - echo ""; + if($result[$i]['dflt_value']==="NULL") + echo ""; else - echo ""; + echo ""; } echo ""; echo $tdWithClassLeft; - + if($result[$i]['dflt_value'] === "NULL") + $dflt_value = ""; + else + $dflt_value = htmlencode(deQuoteSQL($result[$i]['dflt_value'])); + if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") - echo ""; - elseif(preg_match('/^BLOB/', $type) && !$hexblobs) - echo ""; + echo ""; else - echo ""; - echo ""; - echo ""; + echo ""; + echo ""; + echo ""; } echo ""; echo ""; echo "
'; echo "
"; -echo "

"; +echo "

"; echo " v".VERSION.""; echo "

"; echo ""; //- HTML: database list $db->print_db_list(); echo "
"; -echo "null))."'"; +echo "25) - $name = "...".substr($name, strlen($name)-22, 22); -echo ">".htmlencode($name).""; +echo ">".htmlencode($currentDB['name']).""; echo ""; //- HTML: table list -$tables = $db->getTables(true, false); -foreach($tables as $tableName => $tableType) +$query = "SELECT type, name FROM sqlite_master WHERE type='table' OR type='view' ORDER BY name"; +$result = $db->selectArray($query); +$j=0; +for($i=0; $i"; - echo $params->getLink(array('action'=>'column_view', 'table'=>$tableName), "[".$lang[$tableType=='table'?'tbl':'view']."]"); - echo " "; - echo $params->getLink(array('action'=>'row_view', 'table'=>$tableName), htmlencode($tableName), - ($target_table == $tableName ? 'active_table' : '') ); - echo "
"; + if(substr($result[$i]['name'], 0, 7)!="sqlite_" && $result[$i]['name']!="") + { + echo "[".$lang[$result[$i]['type']=='table'?'tbl':'view']."] "; + echo "".htmlencode($result[$i]['name'])."
"; + $j++; + } } -if(count($tables)==0) +if($j==0) echo $lang['no_tbl']; echo "
"; //- HTML: form to create a new database if($directory!==false && is_writable($directory)) { - echo "
".$lang['db_create']." ".helpLink($lang['help2']).""; - echo $params->getForm(array('table'=>null), 'post', false, 'create_database'); - echo ""; - if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO'))) - { - echo ""; - } - echo ""; + echo "
".$lang['db_create']." ".helpLink($lang['help2']).""; + echo "
"; + echo " "; echo "
"; echo "
"; } echo "
"; -echo $params->getForm(array(),'get'); +echo "
"; echo ""; echo "
"; echo "
"; @@ -1688,156 +1247,161 @@ function parseSize($size) echo '

'; //- HTML: breadcrumb navigation -echo $params->getLink(array('table'=>null), htmlencode($currentDB['name'])); +echo "".htmlencode($currentDB['name']).""; if ($target_table) - echo " → ".$params->getLink(array('action'=>'row_view'), htmlencode($target_table)); + echo " → ".htmlencode($target_table).""; echo "

"; -//- Show the various tab views for a table -if($target_table) +//- HTML: confirmation panel +//if the user has performed some action, show the resulting message +if(isset($_GET['confirm'])) { - //- HTML: tabs - echo $params->getLink(array('action'=>'row_view'), $lang['browse'], - (in_array($_GET['action'], array('row_view', 'row_editordelete') ) ? 'tab_pressed' : 'tab')); - - echo $params->getLink(array('action'=>'column_view'), $lang['struct'], - (in_array($_GET['action'], array('column_view', 'column_edit', 'column_confirm', 'primarykey_add', 'column_create', 'index_create', 'index_delete', 'trigger_create', 'trigger_delete') ) ? 'tab_pressed' : 'tab')); - - echo $params->getLink(array('action'=>'table_sql'), $lang['sql'], - ($_GET['action']=="table_sql" ? 'tab_pressed' : 'tab')); - - echo $params->getLink(array( - 'action' => 'table_search', - 'oldSearch' => (isset($_GET['search'])?$_GET['search']:null) - ), $lang['srch'], ($_GET['action']=="table_search" ? 'tab_pressed' : 'tab')); - - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('action'=>'row_create'), $lang['insert'], - ($_GET['action']=="row_create" ? 'tab_pressed' : 'tab')); - - echo $params->getLink(array('action'=>'table_export'), $lang['export'], - ($_GET['action']=="table_export" ? 'tab_pressed' : 'tab')); - - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('action'=>'table_import'), $lang['import'], - ($_GET['action']=="table_import" ? 'tab_pressed' : 'tab')); - - if($db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('action'=>'table_rename'), $lang['rename'], - ($_GET['action']=="table_rename" ? 'tab_pressed' : 'tab')); + echo "
"; + echo "
"; + if(isset($error) && $error) //an error occured during the action, so show an error message + echo $lang['err'].": ".$db->getError()."
".$lang['bug_report'].' '.PROJECT_BUGTRACKER_LINK; + else //action was performed successfully - show success message + echo $completed; + echo "
"; + if($_GET['action']=="row_delete" || $_GET['action']=="row_create" || $_GET['action']=="row_edit") + echo "

".$lang['return'].""; + else if($_GET['action']=="column_create" || $_GET['action']=="column_delete" || $_GET['action']=="column_edit" || $_GET['action']=="index_create" || $_GET['action']=="index_delete" || $_GET['action']=="trigger_delete" || $_GET['action']=="trigger_create") + echo "

".$lang['return'].""; + else + echo "

".$lang['return'].""; + echo "
"; +} - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) +//- Show the various tab views for a table +if(!isset($_GET['confirm']) && $target_table && isset($_GET['action']) && ($_GET['action']=="table_export" || $_GET['action']=="table_import" || $_GET['action']=="table_sql" || $_GET['action']=="row_view" || $_GET['action']=="row_create" || $_GET['action']=="column_view" || $_GET['action']=="table_rename" || $_GET['action']=="table_search" || $_GET['action']=="table_triggers")) +{ + //- HTML: tabs for tables + if($target_table_type == 'table') { - echo $params->getLink(array('action'=>'table_confirm','action2'=>'table_empty'), $lang['empty'], - (isset($_GET['action2']) && $_GET['action2']=="table_empty" ? 'tab_pressed empty' : 'tab empty')); - - echo $params->getLink(array('action'=>'table_confirm','action2'=>'table_drop'), $lang['drop'], - (isset($_GET['action2']) && $_GET['action2']=="table_drop" ? 'tab_pressed drop' : 'tab drop')); - } elseif($db->isWritable() && $db->isDirWritable()) { - echo $params->getLink(array('action'=>'table_confirm','action2'=>'table_drop'), $lang['drop'], - (isset($_GET['action2']) && $_GET['action2']=="table_drop" ? 'tab_pressed drop' : 'tab drop')); + echo "".$lang['browse'].""; + echo "".$lang['struct'].""; + echo "".$lang['sql'].""; + echo "".$lang['srch'].""; + echo "".$lang['insert'].""; + echo "".$lang['export'].""; + echo "".$lang['import'].""; + echo "".$lang['rename'].""; + echo "".$lang['empty'].""; + echo "".$lang['drop'].""; + echo "
"; } -} -else -//- Show the various tab views for a database -{ - $view = isset($_GET['view']) ? $_GET['view'] : 'structure'; - - echo $params->getLink(array('view'=>'structure'), $lang['struct'], ($view=="structure" ? 'tab_pressed': 'tab') ); - - echo $params->getLink(array('view'=>'sql'), $lang['sql'], ($view=="sql" ? 'tab_pressed': 'tab') ); - - echo $params->getLink(array('view'=>'export'), $lang['export'], ($view=="export" ? 'tab_pressed': 'tab') ); - - if($db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('view'=>'import'), $lang['import'], ($view=="import" ? 'tab_pressed': 'tab') ); - - if($db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('view'=>'vacuum'), $lang['vac'], ($view=="vacuum" ? 'tab_pressed': 'tab') ); - - if($directory!==false && is_writable($directory)) + else + //- HTML: tabs for views { - - echo $params->getLink(array('view'=>'rename'), $lang['db_rename'], ($view=="rename" ? 'tab_pressed': 'tab') ); - - echo $params->getLink(array('view'=>'delete'), "".$lang['db_del']."", ($view=="delete" ? 'tab_pressed delete_db': 'tab delete_db') ); + echo "".$lang['browse'].""; + echo "".$lang['struct'].""; + echo "".$lang['sql'].""; + echo "".$lang['srch'].""; + echo "".$lang['export'].""; + echo "".$lang['drop'].""; + echo "
"; } } -echo "
"; -echo "
"; - -//- HTML: confirmation panel -//if the user has performed some action, show the resulting message -if(isset($_GET['message']) && isset($_SESSION[COOKIENAME.'messages'][$_GET['message']])) -{ - echo "
"; - echo $_SESSION[COOKIENAME.'messages'][$_GET['message']]; - echo "

"; - unset($_SESSION[COOKIENAME.'messages'][$_GET['message']]); -} - - //- Switch on $_GET['action'] for operations with output if(isset($_GET['action']) && !isset($_GET['confirm'])) { + echo "
"; switch($_GET['action']) { //- Table actions - - //- Confirm table action (=table_confirm) - case "table_confirm": - if(isset($_GET['check'])) - $pks = $_GET['check']; - elseif(isset($_GET['table'])) - $pks = array($_GET['table']); - else $pks = array(); - - if(sizeof($pks)==0) //nothing was selected so show an error - { - echo "
"; - echo $lang['err'].": ".$lang['no_sel']; - echo "
"; - echo "

"; - echo $params->getLink(array(), $lang['return']); - } - else - { - echo $params->getForm(array('action'=>$_GET['action2'], 'confirm'=>'1', 'pk'=>json_encode($pks))); - echo "
"; - printf($lang['ques_'.$_GET['action2']], htmlencode(implode(', ',$pks)), htmlencode($target_table)); - echo "

"; - echo " ".$lang['vac_on_empty']."

"; - echo " "; - if(count($pks)==1) - $action = array('action'=>'row_view'); - else - $action = array('table'=>null); - echo $params->getLink($action, $lang['cancel']); - echo "
"; - } - break; //- Create table (=table_create) case "table_create": - $query = "SELECT name FROM sqlite_master WHERE type='table' AND name=".$db->quote($_GET['tablename']); + $query = "SELECT name FROM sqlite_master WHERE type='table' AND name=".$db->quote($_POST['tablename']); $results = $db->selectArray($query); if(sizeof($results)>0) $exists = true; else $exists = false; - echo "

".$lang['create_tbl'].": '".htmlencode($_GET['tablename'])."'

"; - if($_GET['tablefields']=="" || intval($_GET['tablefields'])<=0) + echo "

".$lang['create_tbl'].": '".htmlencode($_POST['tablename'])."'

"; + if($_POST['tablefields']=="" || intval($_POST['tablefields'])<=0) echo $lang['specify_fields']; - else if($_GET['tablename']=="") + else if($_POST['tablename']=="") echo $lang['specify_tbl']; else if($exists) echo $lang['tbl_exists']; else { - $num = intval($_GET['tablefields']); - $name = $_GET['tablename']; - echo $params->getForm(array('action'=>'table_create', 'confirm'=>'1')); + $num = intval($_POST['tablefields']); + $name = $_POST['tablename']; + echo "
"; echo ""; echo ""; echo ""; @@ -1887,7 +1451,7 @@ function parseSize($size) echo ""; echo ""; echo ""; echo "
"; echo " "; - echo $params->getLink(array(), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; @@ -1898,6 +1462,7 @@ function parseSize($size) //- Perform SQL query on table (=table_sql) case "table_sql": + $isSelect = false; if(isset($_POST['query']) && $_POST['query']!="") { $delimiter = $_POST['delimiter']; @@ -1905,11 +1470,11 @@ function parseSize($size) //save the queries in history if necessary if($maxSavedQueries!=0 && $maxSavedQueries!=false) { - if(!isset($_SESSION[COOKIENAME.'query_history'])) - $_SESSION[COOKIENAME.'query_history'] = array(); - $_SESSION[COOKIENAME.'query_history'][md5(strtolower($queryStr))] = $queryStr; - if(sizeof($_SESSION[COOKIENAME.'query_history']) > $maxSavedQueries) - array_shift($_SESSION[COOKIENAME.'query_history']); + if(!isset($_SESSION['query_history'])) + $_SESSION['query_history'] = array(); + $_SESSION['query_history'][md5(strtolower($queryStr))] = $queryStr; + if(sizeof($_SESSION['query_history']) > $maxSavedQueries) + array_shift($_SESSION['query_history']); } $query = explode_sql($delimiter, $queryStr); //explode the query string into individual queries based on the delimiter @@ -1917,20 +1482,35 @@ function parseSize($size) { if(str_replace(" ", "", str_replace("\n", "", str_replace("\r", "", $query[$i])))!="") //make sure this query is not an empty string { - $queryTimer = new MicroTimer(); - $table_result = $db->query($query[$i]); - + $result = $db->selectArray($query[$i], "assoc"); + echo "
"; - echo "".htmlencode($query[$i]).""; - if($table_result === NULL || $table_result === false) + echo ""; + + if($result !== NULL) + { + + if(sizeof($result)>0 || $db->getAffectedRows()==0) + { + printf($lang['show_rows'], sizeof($result)); + } + if($db->getAffectedRows()>0 || sizeof($result)==0) + { + echo $db->getAffectedRows()." ".$lang['rows_aff']." "; + } + echo "
"; + } + else { - echo "
".$lang['err'].": ".htmlencode($db->getError())."
"; + echo $lang['err'].": ".$db->getError()."
"; } + + echo "".htmlencode($query[$i]).""; echo "

"; - if($row = $db->fetch($table_result, 'num')) + if(sizeof($result)>0) { - for($j=0; $jgetColumnName($table_result,$j); + $headers = array_keys($result[0]); + echo ""; echo ""; for($j=0; $j"; } echo ""; - $rowCount = 0; - for(; $rowCount==0 || $row = $db->fetch($table_result, 'num'); $rowCount++) + for($j=0; $j"; + $tdWithClass = ""; for($z=0; $zNULL"; else - echo htmlencode(subString($row[$z])); + echo htmlencode(subString($result[$j][$headers[$z]])); echo ""; } echo ""; } - $queryTimer->stop(); echo "
"; echo "


"; - - - if($table_result !== NULL && $table_result !== false) - { - echo "
"; - if($rowCount>0 || $db->getAffectedRows()==0) - { - printf($lang['show_rows'], $rowCount); - } - if($db->getAffectedRows()>0 || $rowCount==0) - { - echo $db->getAffectedRows()." ".$lang['rows_aff']." "; - } - printf($lang['query_time'], $queryTimer); - echo "
"; - } - - } } } @@ -1990,25 +1550,25 @@ function parseSize($size) echo "
"; echo "".sprintf($lang['run_sql'],htmlencode($db->getName())).""; - echo $params->getForm(array('action'=>'table_sql')); - if(isset($_SESSION[COOKIENAME.'query_history']) && sizeof($_SESSION[COOKIENAME.'query_history'])>0) + echo ""; + if(isset($_SESSION['query_history']) && sizeof($_SESSION['query_history'])>0) { echo "".$lang['recent_queries']."

"; } echo "
"; echo ""; - echo ""; echo "
"; echo "
"; echo $lang['fields']."
"; echo ""; echo ""; @@ -2020,23 +1580,56 @@ function parseSize($size) echo "
"; break; + //- Empty table (=table_empty) + case "table_empty": + echo ""; + echo ""; + echo "
"; + echo sprintf($lang['ques_empty'], htmlencode($target_table))."

"; + echo " "; + echo "".$lang['cancel'].""; + echo "
"; + break; + + //- Drop table (=table_drop) + case "table_drop": + echo ""; + echo ""; + echo "
"; + echo sprintf($lang['ques_drop'], htmlencode($target_table))."

"; + echo " "; + echo "".$lang['cancel'].""; + echo "
"; + break; + + //- Drop view (=view_drop) + case "view_drop": + echo ""; + echo ""; + echo "
"; + echo sprintf($lang['ques_drop_view'], htmlencode($target_table))."

"; + echo " "; + echo "".$lang['cancel'].""; + echo "
"; + break; + //- Export table (=table_export) case "table_export": - echo $params->getForm(); + echo ""; echo "
".$lang['export'].""; echo ""; echo ""; echo "
"; echo "
"; - + echo "
".$lang['options'].""; echo " ".helpLink($lang['help5'])."
"; - echo " ".helpLink($lang['help6'])."
"; - echo " ".helpLink($lang['help7'])."
"; + echo " ".helpLink($lang['help6'])."
"; + echo " ".helpLink($lang['help7'])."
"; echo " ".helpLink($lang['help8'])."
"; - echo " ".helpLink($lang['help9'])."
"; + echo " ".helpLink($lang['help9'])."
"; echo "
"; - + echo ""; - + echo "
"; echo "

"; echo "
".$lang['save_as'].""; @@ -2062,8 +1655,7 @@ function parseSize($size) echo " "; echo "
"; echo ""; - echo "
".sprintf($lang['backup_hint'], - $params->getLink(array('download' => $currentDB['path'], 'token' => $_SESSION[COOKIENAME.'token']), $lang["backup_hint_linktext"], '', $lang['backup']))."
"; + echo "
".sprintf($lang['backup_hint'], "".$lang["backup_hint_linktext"]."")."
"; break; //- Import table (=table_import) @@ -2074,19 +1666,19 @@ function parseSize($size) if($importSuccess===true) echo $lang['import_suc']; else - echo $lang['err'].': '.htmlencode($importSuccess); + echo $lang['err'].': '.$importSuccess; echo "

"; } - echo $params->getForm(array('action' => 'table_import'), 'post', true); + echo "
"; echo "
".$lang['import_into']." ".htmlencode($target_table).""; echo ""; echo "
"; echo "
"; - + echo "
".$lang['options'].""; echo $lang['no_opt']; echo "
"; - + echo ""; - + echo "
"; echo "

"; - + echo "
".$lang['import_f'].""; - echo "".$lang['max_file_size'].": ".number_format(fileUploadMaxSize()/1024/1024)." MiB ".helpLink($lang['help11'])."
"; - echo ""; - echo ""; + echo " "; echo "
"; break; //- Rename table (=table_rename) case "table_rename": - echo $params->getForm(array('action'=>'table_rename', 'confirm'=>'1')); + echo ""; + echo ""; printf($lang['rename_tbl'], htmlencode($target_table)); - echo " "; + echo " "; echo "
"; break; //- Search table (=table_search) case "table_search": - if(!isset($_GET['search'])) + $searchValues = array(); + if(isset($_GET['done'])) { - $tableInfo = $db->getTableInfo($target_table); + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + $primary_key = $db->getPrimaryKey($target_table); + $j = 0; + $arr = array(); + for($i=0; $iquote_id($field)." ".$operator; + else{ + if($operator == "LIKE%"){ + $operator = "LIKE"; + if(!preg_match('/(^%)|(%$)/', $value)) $value = '%'.$value.'%'; + $searchValues[$field] = array($value); + $value_quoted = $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([$db, 'quote'], $values); + $value_quoted = '(' .implode(', ', $values) . ')'; + } + else + { + $searchValues[$field] = array($value); + $value_quoted = $db->quote($value); + } + $arr[$j] = $db->quote_id($field)." ".$operator." ".$value_quoted; + } + $j++; + } + } + $query = "SELECT *"; + // select the primary key column(s) last (ROWID if there is no PK). + // this will be used to identify rows, e.g. when editing/deleting rows + $primary_key = $db->getPrimaryKey($target_table); + foreach($primary_key as $pk) + { + $query.= ', '.$db->quote_id($pk); + $query.= ', typeof('.$db->quote_id($pk).')'; + } + $query .= " FROM ".$db->quote_id($target_table); + $whereTo = ''; + if(sizeof($arr)>0) + { + $whereTo .= " WHERE ".$arr[0]; + for($i=1; $iquote_id($target_table) . $whereTo; + $arr = $db->selectArray($query); + + echo "
"; + echo ""; + if($arr!==false) + { + $affected = sizeof($arr); + echo $lang['showing']." ".$affected." ".$lang['rows'].". "; + echo "
"; + } + else + { + echo $lang['err'].": ".$db->getError().".
".$lang['bug_report'].' '.PROJECT_BUGTRACKER_LINK.'
'; + } + echo "".htmlencode($query_disp).""; + echo "

"; - echo $params->getForm(array('action'=>'table_search', 'confirm'=>'1')); + if(sizeof($arr)>0) + { + if($target_table_type == 'view') + { + echo sprintf($lang['readonly_tbl'], htmlencode($target_table))." http://en.wikipedia.org/wiki/View_(database)"; + echo "

"; + } + echo ""; + echo ""; + if($target_table_type == 'table') + { + echo ""; + } + + $header = array(); + for($j=0; $j"; + echo htmlencode($headers[$j]); + echo ""; + } + echo ""; + + $pkFirstCol = sizeof($result)+1; + for($j=0; $j $pk will always be the last columns in each row of the array because we are doing "SELECT *, PK_1, typeof(PK_1), PK2, typeof(PK_2), ... FROM ..." + $pk_arr = array(); + for($col = $pkFirstCol; array_key_exists($col, $arr[$j]); $col=$col+2) + { + // in $col we have the type and in $col-1 the value + if($arr[$j][$col]=='integer' || $arr[$j][$col]=='real') + // json encode as int or float, not string + $pk_arr[] = $arr[$j][$col-1]+0; + else + // encode as json string + $pk_arr[] = $arr[$j][$col-1]; + } + $pk = json_encode($pk_arr); + $tdWithClass = ""; + if($target_table_type == 'table') + { + echo $tdWithClass."".$lang['edit'].""; + echo $tdWithClass."".$lang['del'].""; + } + for($z=0; $z', ''), htmlencode($fldResult)); + echo ""; + } + echo ""; + } + echo "
"; + #todo: make sure the search keywords are kept + #echo ""; + #echo "&".($_SESSION[COOKIENAME.'fulltexts']?'r':'l')."arr; T &".($_SESSION[COOKIENAME.'fulltexts']?'l':'r')."arr;"; + echo "
"; + echo "


"; + } + + echo "".$lang['srch_again'].""; + } + else + { + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + + echo "
"; + echo ""; echo ""; echo ""; @@ -2138,24 +1889,13 @@ function parseSize($size) echo ""; echo ""; - for($i=0; $i"; $tdWithClassLeft = ""; echo $tdWithClassLeft; echo htmlencode($field); @@ -2164,28 +1904,38 @@ function parseSize($size) echo htmlencode($type); echo ""; echo $tdWithClassLeft; - echo ""; + echo ""; + if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") { - if($typeAffinity!="INTEGER" && $typeAffinity!="REAL" && $typeAffinity!="NUMERIC" && in_array($op, $operatorsNumbersOnly)) - continue; - if($typeAffinity!="TEXT" && $typeAffinity!="NONE" && in_array($op, $operatorsTextOnly)) - continue; - $display = (isset($operatorsDisplay[$op]) ? $operatorsDisplay[$op] : $op); - echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + } + else if($typeAffinity=="TEXT" || $typeAffinity=="NONE") + { + echo ""; + echo ""; } + echo ""; + if($typeAffinity=="TEXT" || $typeAffinity=="NONE") + echo ""; + else + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; echo ""; echo ""; echo $tdWithClassLeft; if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") - echo ""; + echo ""; else - echo ""; + echo ""; echo ""; echo ""; } @@ -2196,114 +1946,74 @@ function parseSize($size) echo ""; echo "
".$lang['fld']."".$lang['val']."
"; - if(isset($_GET['oldSearch']) && isset($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['values'][$field])) - $value = implode($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['values'][$field], ","); - else - $value = ''; - if(isset($_GET['oldSearch']) && isset($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['operators'][$field])) - $operator = $_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['operators'][$field]; - elseif($typeAffinity=="TEXT" || $typeAffinity=="NONE") - $operator = 'LIKE'; - else - $operator = '='; - echo "
"; echo "
"; - - break; - } - elseif(isset($_SESSION[COOKIENAME.'search'][$_GET['search']])) - { - $params->search = $_GET['search']; - $search = $_SESSION[COOKIENAME.'search'][$_GET['search']]; - // NOTICE: we do not break here!! we just do the same now like row_view-action does } + break; //- Row actions //- View row (=row_view) case "row_view": - if(!isset($_GET['startRow'])) - $_GET['startRow'] = 0; + if(!isset($_POST['startRow'])) + $_POST['startRow'] = 0; - if(isset($_SESSION[COOKIENAME.'currentTable']) && $_SESSION[COOKIENAME.'currentTable']!=$target_table) - { - unset($_SESSION[COOKIENAME.'sortRows']); - unset($_SESSION[COOKIENAME.'orderRows']); - } - if(isset($_GET['viewtype'])) - { - $_SESSION[COOKIENAME.'viewtype'] = $_GET['viewtype']; - } + if(isset($_POST['numRows'])) + $_SESSION[COOKIENAME.'numRows'] = $_POST['numRows']; - //- Query execution - if(!isset($_GET['sort'])) - $_GET['sort'] = NULL; - if(!isset($_GET['order'])) - $_GET['order'] = NULL; + if(!isset($_SESSION[COOKIENAME.'numRows'])) + $_SESSION[COOKIENAME.'numRows'] = $rowsNum; + + if(isset($_GET['fulltexts'])) + $_SESSION[COOKIENAME.'fulltexts'] = $_GET['fulltexts']; - $numRows = $params->numRows; - $startRow = $_GET['startRow']; - if(isset($_GET['sort'])) - { - $_SESSION[COOKIENAME.'sortRows'] = $_GET['sort']; - $_SESSION[COOKIENAME.'currentTable'] = $target_table; - } - if(isset($_GET['order'])) - { - $_SESSION[COOKIENAME.'orderRows'] = $_GET['order']; - $_SESSION[COOKIENAME.'currentTable'] = $target_table; - } - $query = "SELECT * "; - // select the primary key column(s) last (ROWID if there is no PK). - // this will be used to identify rows, e.g. when editing/deleting rows - $primary_key = $db->getPrimaryKey($target_table); - foreach($primary_key as $pk) + if(!isset($_SESSION[COOKIENAME.'fulltexts'])) + $_SESSION[COOKIENAME.'fulltexts'] = false; + + if(isset($_SESSION[COOKIENAME.'currentTable']) && $_SESSION[COOKIENAME.'currentTable']!=$target_table) { - $query.= ', '.$db->quote_id($pk); - $query.= ', typeof('.$db->quote_id($pk).')'; + unset($_SESSION[COOKIENAME.'sortRows']); + unset($_SESSION[COOKIENAME.'orderRows']); } - $query .= " FROM ".$db->quote_id($target_table); - $queryDisp = "SELECT * FROM ".$db->quote_id($target_table); - $queryCount = "SELECT COUNT(*) AS count FROM ".$db->quote_id($target_table); - $queryAdd = ""; - if(isset($search) && isset($search['where'])) + if(isset($_POST['viewtype'])) { - $queryAdd = $search['where']; - $queryCount .= $search['where']; + $_SESSION[COOKIENAME.'viewtype'] = $_POST['viewtype']; } - if(isset($_SESSION[COOKIENAME.'sortRows'])) - $queryAdd .= " ORDER BY ".$db->quote_id($_SESSION[COOKIENAME.'sortRows']); - if(isset($_SESSION[COOKIENAME.'orderRows'])) - $queryAdd .= " ".$_SESSION[COOKIENAME.'orderRows']; - $queryAdd .= " LIMIT ".$startRow.", ".$numRows; - $query .= $queryAdd; - $queryDisp .= $queryAdd; - - $resultRows = $db->select($queryCount); - $totalRows = $resultRows['count']; - $shownRows = min($resultRows['count']-$startRow, $numRows); - - //- HTML: pagination buttons - $lastPage = intval($totalRows / $params->numRows); - $remainder = intval($totalRows % $params->numRows); + + $rowCount = $db->numRows($target_table); + $lastPage = intval($rowCount / $_SESSION[COOKIENAME.'numRows']); + $remainder = intval($rowCount % $_SESSION[COOKIENAME.'numRows']); if($remainder==0) - $remainder = $params->numRows; - + $remainder = $_SESSION[COOKIENAME.'numRows']; + + //- HTML: pagination buttons echo "
"; //previous button - if($_GET['startRow']>0) + if($_POST['startRow']>0) { echo "
"; - echo $params->getForm(array('action'=>$_GET['action']),'get'); + echo "
"; echo ""; - echo " "; + echo " "; + echo " "; echo "
"; echo "
"; echo "
"; - echo $params->getForm(array('action'=>$_GET['action']),'get'); - echo "numRows))."'/>"; - echo " "; + echo "
"; + echo ""; + echo " "; + echo " "; echo "
"; echo "
"; } - + //show certain number buttons echo "
"; - echo $params->getForm(array('action'=>$_GET['action'], 'numRows'=>null),'get'); + echo "
"; echo " "; - echo " "; + echo " "; echo $lang['rows_records']; - if(intval($_GET['startRow']+$params->numRows) < $totalRows) - echo "numRows)."'/>"; + if(intval($_POST['startRow']+$_SESSION[COOKIENAME.'numRows']) < $rowCount) + echo ""; else echo " "; echo $lang['as_a']; @@ -2321,76 +2031,122 @@ function parseSize($size) echo ""; echo "
"; echo "
"; - + //next button - if(intval($_GET['startRow']+$params->numRows)<$totalRows) + if(intval($_POST['startRow']+$_SESSION[COOKIENAME.'numRows'])<$rowCount) { echo "
"; - echo $params->getForm(array('action'=>$_GET['action']),'get'); - echo "numRows)."'/>"; - echo " "; + echo "
"; + echo ""; + echo " "; + echo " "; echo "
"; echo "
"; echo "
"; - echo $params->getForm(array('action'=>$_GET['action']),'get'); - echo ""; - echo " "; + echo "
"; + echo ""; + echo " "; + echo " "; echo "
"; echo "
"; } echo "
"; echo "
"; + //- Query execution + if(!isset($_GET['sort'])) + $_GET['sort'] = NULL; + if(!isset($_GET['order'])) + $_GET['order'] = NULL; + + $numRows = $_SESSION[COOKIENAME.'numRows']; + $startRow = $_POST['startRow']; + if(isset($_GET['sort'])) + { + $_SESSION[COOKIENAME.'sortRows'] = $_GET['sort']; + $_SESSION[COOKIENAME.'currentTable'] = $target_table; + } + if(isset($_GET['order'])) + { + $_SESSION[COOKIENAME.'orderRows'] = $_GET['order']; + $_SESSION[COOKIENAME.'currentTable'] = $target_table; + } + $_SESSION[COOKIENAME.'numRows'] = $numRows; + $query = "SELECT * "; + // select the primary key column(s) last (ROWID if there is no PK). + // this will be used to identify rows, e.g. when editing/deleting rows + $primary_key = $db->getPrimaryKey($target_table); + foreach($primary_key as $pk) + { + $query.= ', '.$db->quote_id($pk); + $query.= ', typeof('.$db->quote_id($pk).')'; + } + $query .= " FROM ".$db->quote_id($target_table); + $queryDisp = "SELECT * FROM ".$db->quote_id($target_table); + $queryCount = "SELECT MIN(COUNT(*),".$numRows.") AS count FROM ".$db->quote_id($target_table); + $queryAdd = ""; + if(isset($_SESSION[COOKIENAME.'sortRows'])) + $queryAdd .= " ORDER BY ".$db->quote_id($_SESSION[COOKIENAME.'sortRows']); + if(isset($_SESSION[COOKIENAME.'orderRows'])) + $queryAdd .= " ".$_SESSION[COOKIENAME.'orderRows']; + $queryAdd .= " LIMIT ".$startRow.", ".$numRows; + $query .= $queryAdd; + $queryDisp .= $queryAdd; + + $resultRows = $db->select($queryCount)['count']; //- Show results - if($shownRows>0) + if($resultRows>0) { - $queryTimer = new MicroTimer(); $table_result = $db->query($query); - $queryTimer->stop(); - + echo "
"; - echo "".$lang['showing_rows']." ".$startRow." - ".($startRow + $shownRows-1).", ".$lang['total'].": ".$totalRows." "; - printf($lang['query_time'], $queryTimer); + echo "".$lang['showing_rows']." ".$startRow." - ".($startRow + $resultRows-1).", ".$lang['total'].": ".$rowCount." "; echo "
"; echo "".htmlencode($queryDisp).""; echo "

"; - + if($target_table_type == 'view') { - echo sprintf($lang['readonly_tbl'], htmlencode($target_table))." https://en.wikipedia.org/wiki/View_(SQL)"; - echo "

"; + echo sprintf($lang['readonly_tbl'], htmlencode($target_table))." http://en.wikipedia.org/wiki/View_(database)"; + echo "

"; } - - $tableInfo = $db->getTableInfo($target_table); - $pkFirstCol = sizeof($tableInfo)+1; + + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + $pkFirstCol = sizeof($result)+1; //- Table view if(!isset($_SESSION[COOKIENAME.'viewtype']) || $_SESSION[COOKIENAME.'viewtype']=="table") { - echo $params->getForm(array('action'=>'row_editordelete'), 'post', false, 'checkForm'); + echo "
"; echo ""; echo ""; - echo ""; + if($target_table_type == 'table') + { + echo ""; + } - for($i=0; $i"; + echo "getLink(array('action'=>$_GET['action'], 'sort'=>$tableInfo[$i]['name'], 'order'=>$orderTag ), htmlencode($tableInfo[$i]['name'])); - if(isset($_SESSION[COOKIENAME.'sortRows']) && $_SESSION[COOKIENAME.'sortRows']==$tableInfo[$i]['name']) + echo "&order=".$orderTag; + echo "'>".htmlencode($result[$i]['name']).""; + if(isset($_SESSION[COOKIENAME.'sortRows']) && $_SESSION[COOKIENAME.'sortRows']==$result[$i]['name']) echo (($_SESSION[COOKIENAME.'orderRows']=="ASC") ? " " : " "); echo ""; } echo ""; - for($i=0; $row = $db->fetch($table_result, 'num'); $i++) + for($i=0; $row = $db->fetch($table_result); $i++) { // -g-> $pk will always be the last columns in each row of the array because we are doing "SELECT *, PK_1, typeof(PK_1), PK2, typeof(PK_2), ... FROM ..." $pk_arr = array(); @@ -2402,30 +2158,28 @@ function parseSize($size) $pk_arr[] = $row[$col-1]+0; else // encode as json string - $pk_arr[] = $row[$col-1]; + $pk_arr[] = $row[$col-1]; } $pk = json_encode($pk_arr); $tdWithClass = ""; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') { echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; // -g-> Here, we need to put the PK in as the link for both the edit and delete. - echo $params->getLink(array('action'=>'row_editordelete', 'pk'=>$pk, 'type'=>'edit'),"".$lang['edit']."",'edit', $lang['edit']); + echo "".$lang['edit'].""; echo ""; echo $tdWithClass; - echo $params->getLink(array('action'=>'row_editordelete', 'pk'=>$pk, 'type'=>'delete'),"".$lang['del']."",'delete', $lang['del']); + echo "".$lang['del'].""; echo ""; - } else { - echo ""; } - for($j=0; $jNULL"; - elseif(preg_match('/^BLOB/i', $tableInfo[$j]['type']) && !$hexblobs) - { - echo "
"; - echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pk, 'column'=>$tableInfo[$j]['name'], 'download_blob'=>1),$lang["download"]).' | '; - echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pk, 'column'=>$tableInfo[$j]['name'], 'download_blob'=>0),$lang["open_in_browser"],'','','_blank'); - echo "
"; - echo 'Size: '.number_format(strlen($row[$j])).' Bytes'; - echo "
"; - } - elseif(preg_match('/^BLOB/i', $tableInfo[$j]['type']) && $hexblobs) - { - echo htmlencode(subString(bin2hex($row[$j]))); - } - elseif(isset($search)) - echo markSearchWords(subString($row[$j]),$tableInfo[$j]['name'], $search); else echo htmlencode(subString($row[$j])); echo ""; @@ -2456,7 +2195,7 @@ function parseSize($size) echo "
"; } echo "
"; - echo "$_GET['action'], 'fulltexts'=>($params->fulltexts?0:1) ))."' title='".$lang[($params->fulltexts?'no_full_texts':'full_texts')]."'>"; - echo "&".($params->fulltexts?'r':'l')."arr; T &".($params->fulltexts?'l':'r')."arr;"; - echo ""; + echo ""; + echo "&".($_SESSION[COOKIENAME.'fulltexts']?'r':'l')."arr; T &".($_SESSION[COOKIENAME.'fulltexts']?'l':'r')."arr;"; + echo "
"; $tdWithClassLeft = ""; echo "
"; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') { echo "".$lang['chk_all']." / ".$lang['unchk_all']." ".$lang['with_sel'].": "; echo ""; echo ""; else echo ""; @@ -2661,13 +2396,14 @@ function drawChart() echo " "; echo "
"; echo "
"; - echo $params->getForm(array('action'=>'row_create','confirm'=>'1'), 'post', true); - $tableInfo = $db->getTableInfo($target_table); - if(isset($_GET['newRows'])) - $num = $_GET['newRows']; + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + echo "
"; + if(isset($_POST['num'])) + $num = $_POST['num']; else $num = 1; - echo ""; + echo ""; for($j=0; $j<$num; $j++) { if($j>0) @@ -2681,17 +2417,14 @@ function drawChart() echo "
".$lang['val']."
"; echo "
"; @@ -2735,6 +2471,8 @@ function drawChart() echo "

"; } + $fieldStr = substr($fieldStr, 1); + echo ""; echo ""; break; @@ -2745,26 +2483,39 @@ function drawChart() else if(isset($_GET['pk'])) $pks = array($_GET['pk']); else $pks[0] = ""; - $str = implode(', ', $pks); + $str = $pks[0]; + for($i=1; $i"; echo $lang['err'].": ".$lang['no_sel']; echo ""; - echo "

".$params->getLink(array('action'=>'row_view'),$lang['return']); + echo "

".$lang['return'].""; } else { if((isset($_POST['type']) && $_POST['type']=="edit") || (isset($_GET['type']) && $_GET['type']=="edit")) //edit { - echo $params->getForm(array('action'=>'row_edit', 'confirm'=>'1', 'pk'=>json_encode($pks)),'post',true); - $tableInfo = $db->getTableInfo($target_table); + echo "
"; + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); + + //build the POST array of fields + $fieldStr = $result[0][1]; + for($j=1; $jgetPrimaryKey($target_table); + + echo ""; for($j=0; $jquote_id($target_table)." WHERE " . $db->wherePK($target_table, json_decode($pks[$j])); - $result1 = $db->select($query, 'num'); + $result1 = $db->select($query); echo ""; echo ""; @@ -2775,24 +2526,23 @@ function drawChart() echo ""; echo ""; - for($i=0; $i"; $tdWithClassLeft = ""; - echo $tdWithClassLeft; + echo $tdWithClass; echo htmlencode($field); echo ""; - echo $tdWithClassLeft; + echo $tdWithClass; echo htmlencode($type); echo ""; echo $tdWithClassLeft; - echo ""; echo ""; foreach (array_merge($sqlite_functions, $custom_functions) as $f) { echo ""; @@ -2800,34 +2550,19 @@ function drawChart() echo ""; echo ""; echo $tdWithClassLeft; - if($tableInfo[$i]['notnull']==0) + if($result[$i][3]==0) { if($value===NULL) - echo ""; + echo ""; else - echo ""; + echo ""; } echo ""; echo $tdWithClassLeft; if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") - echo ""; - elseif(preg_match('/^BLOB/', $type) && !$hexblobs) - { - if($value!==NULL) - { - echo ""; - echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pks[$j], 'column'=>$field, 'download_blob'=>1),$lang["download"]).' | '; - echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pks[$j], 'column'=>$field, 'download_blob'=>0),$lang["open_in_browser"],'','','_blank').'
'; - echo ""; - } - echo ""; - } + echo ""; else - echo ""; + echo ""; echo ""; echo ""; } @@ -2836,7 +2571,7 @@ function drawChart() // Note: the 'Save changes' button must be first in the code so it is the one used when submitting the form with the Enter key (issue #215) echo " "; echo " "; - echo $params->getLink(array('action'=>'row_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo ""; echo ""; echo "
".$lang['val']."
"; echo "
"; @@ -2846,12 +2581,12 @@ function drawChart() } else //delete { - echo $params->getForm(array('action'=>'row_delete', 'confirm'=>'1', 'pk'=>json_encode($pks))); + echo ""; echo "
"; - printf($lang['ques_row_delete'], htmlencode($str), htmlencode($target_table)); + printf($lang['ques_del_rows'], htmlencode($str), htmlencode($target_table)); echo "

"; echo " "; - echo $params->getLink(array('action'=>'row_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; } } @@ -2861,12 +2596,13 @@ function drawChart() //- View table structure (=column_view) case "column_view": - $tableInfo = $db->getTableInfo($target_table); + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); - echo $params->getForm(array('action'=>'column_confirm'), 'get', false, 'checkForm'); + echo ""; echo ""; echo ""; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') echo ""; echo ""; echo ""; @@ -2877,15 +2613,15 @@ function drawChart() echo ""; $noPrimaryKey = true; - - for($i=0; $i"; $tdWithClassLeft = ""; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') { echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; - echo $params->getLink(array('action'=>'column_edit', 'pk'=>$fieldVal),"".$lang['edit']."",'edit', $lang['edit']); + echo "".$lang['edit'].""; echo ""; echo $tdWithClass; - echo $params->getLink(array('action'=>'column_confirm', 'action2'=>'column_delete', 'pk'=>$fieldVal),"".$lang['del']."",'delete', $lang['del']); + echo "".$lang['del'].""; echo ""; } echo $tdWithClass; @@ -2941,7 +2677,7 @@ function drawChart() } echo "
".$lang['col']." #".$lang['fld']."
"; echo "
"; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') { echo "".$lang['chk_all']." / ".$lang['unchk_all']." ".$lang['with_sel'].": "; echo ""; } echo ""; - if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable()) + if($target_table_type == 'table') { echo "
"; - echo $params->getForm(array('action'=>'column_create'), 'get'); + echo "
"; + echo ""; echo $lang['add']." ".$lang['tbl_end']." "; echo "
"; } - + + $query = "SELECT sql FROM sqlite_master WHERE name=".$db->quote($target_table); + $master = $db->selectArray($query); + echo "
"; echo "
"; echo "
"; echo "".$lang['query_used_'.$target_table_type]."
"; - echo ""; - echo nl2br(htmlencode($db->export_sql(array($target_table),false,true,false,false,false,false))); - echo ""; + echo "".htmlencode($master[0]['sql']).""; echo "
"; echo "
"; if($target_table_type != 'view') { echo "


"; + //$query = "SELECT * FROM sqlite_master WHERE type='index' AND tbl_name='".$target_table."'"; $query = "PRAGMA index_list(".$db->quote_id($target_table).")"; $result = $db->selectArray($query); if(sizeof($result)>0) @@ -3005,7 +2744,7 @@ function drawChart() $tdWithClassLeftSpan = ""; echo ""; echo $tdWithClassSpan; - echo $params->getLink(array('action'=>'index_delete', 'pk'=>$result[$i]['name']), "".$lang['del']."", 'delete', $lang['del']); + echo "".$lang['del'].""; echo ""; echo $tdWithClassLeftSpan; echo $result[$i]['name']; @@ -3031,7 +2770,7 @@ function drawChart() } echo "

"; } - + $query = "SELECT * FROM sqlite_master WHERE type='trigger' AND tbl_name=".$db->quote($target_table)." ORDER BY name"; $result = $db->selectArray($query); //print_r($result); @@ -3050,7 +2789,7 @@ function drawChart() $tdWithClass = ""; echo ""; echo $tdWithClass; - echo $params->getLink(array('action'=>'trigger_delete', 'pk'=>$result[$i]['name']), "".$lang['del']."", 'delete', $lang['del']); + echo "".$lang['del'].""; echo ""; echo $tdWithClass; echo htmlencode($result[$i]['name']); @@ -3061,44 +2800,44 @@ function drawChart() } echo "

"; } - - if($db->isWritable() && $db->isDirWritable()) - { - echo $params->getForm(array('action'=>'index_create'),'get'); - echo "
"; - echo $lang['create_index2']." ".$lang['cols']." "; - echo "
"; - echo ""; - - echo $params->getForm(array('action'=>'trigger_create'),'get'); - echo "
"; - echo $lang['create_trigger2']." "; - echo "
"; - echo ""; - } + + echo "
"; + echo ""; + echo "
"; + echo $lang['create_index2']." ".$lang['cols']." "; + echo "
"; + echo "
"; + + echo "
"; + echo ""; + echo "
"; + echo $lang['create_trigger2']." "; + echo "
"; + echo "
"; } break; //- Create column (=column_create) case "column_create": - echo "

".sprintf($lang['new_fld'],htmlencode($_GET['table']))."

"; - if($_GET['tablefields']=="" || intval($_GET['tablefields'])<=0) + echo "

".sprintf($lang['new_fld'],htmlencode($_POST['tablename']))."

"; + if($_POST['tablefields']=="" || intval($_POST['tablefields'])<=0) echo $lang['specify_fields']; - else if($_GET['table']=="") + else if($_POST['tablename']=="") echo $lang['specify_tbl']; else { - $num = intval($_GET['tablefields']); - $name = $_GET['table']; - echo $params->getForm(array('action'=>'column_create', 'confirm'=>'1')); + $num = intval($_POST['tablefields']); + $name = $_POST['tablename']; + echo "
"; + echo ""; echo ""; echo ""; echo ""; - $headings = array($lang["fld"], $lang["type"], $lang["prim_key"]); + $headings = array($lang["fld"], $lang["type"], $lang["prim_key"]); if($db->getType() != "SQLiteDatabase") $headings[] = $lang["autoincrement"]; $headings[] = $lang["not_null"]; $headings[] = $lang["def_val"]; - + for($k=0; $k" . $headings[$k] . ""; echo ""; @@ -3140,7 +2879,7 @@ function drawChart() echo ""; echo ""; echo ""; echo "
"; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; @@ -3148,21 +2887,20 @@ function drawChart() } break; - //- Confirm column action (=column_confirm) + //- Delete column (=column_confirm) case "column_confirm": - if(isset($_GET['check'])) - $pks = $_GET['check']; + if(isset($_POST['check'])) + $pks = $_POST['check']; elseif(isset($_GET['pk'])) $pks = array($_GET['pk']); else $pks = array(); - + if(sizeof($pks)==0) //nothing was selected so show an error { echo "
"; echo $lang['err'].": ".$lang['no_sel']; echo "
"; - echo "

"; - echo $params->getLink(array('action'=>'column_view'), $lang['return']); + echo "

".$lang['return'].""; } else { @@ -3173,12 +2911,12 @@ function drawChart() $str .= ", ".$pks[$i]; $pkVal .= ":".$pks[$i]; } - echo $params->getForm(array('action'=>$_GET['action2'], 'confirm'=>'1', 'pk'=>$pkVal)); + echo ""; echo "
"; - printf($lang['ques_'.$_GET['action2']], htmlencode($str), htmlencode($target_table)); + printf($lang['ques_'.$_REQUEST['action2']], htmlencode($str), htmlencode($target_table)); echo "

"; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; } break; @@ -3186,139 +2924,134 @@ function drawChart() //- Edit column (=column_edit) case "column_edit": echo "

".sprintf($lang['edit_col'], htmlencode($_GET['pk']))." ".$lang['on_tbl']." '".htmlencode($target_table)."'

"; - echo $lang['sqlite_limit']."

"; - if(!isset($_GET['pk'])) - echo $lang['specify_col']; - else if (!$target_table) - echo $lang['specify_tbl']; - else - { - $tableInfo = $db->getTableInfo($target_table); - - for($i=0; $i".$lang['err'].": ".sprintf($lang['col_inexistent'], htmlencode($_GET['pk'])).""; - } - else - { - $name = $target_table; - echo $params->getForm(array('action'=>'column_edit', 'confirm'=>'1')); - echo ""; - echo ""; - echo ""; - //$headings = array("Field", "Type", "Primary Key", "Autoincrement", "Not NULL", "Default Value"); - $headings = array($lang["fld"], $lang["type"]); - for($k=0; $k".$headings[$k].""; - echo ""; - - $i = 0; - $tdWithClass = ""; - echo $tdWithClass; - echo ""; - echo ""; - echo $tdWithClass; - echo ""; - echo ""; - /* - echo $tdWithClass; - if($primarykeyVal) - echo " Yes"; - else - echo " Yes"; - echo ""; - echo $tdWithClass; - if(1==2) - echo " Yes"; - else - echo " Yes"; - echo ""; - echo $tdWithClass; - if($notnullVal) - echo " Yes"; - else - echo " Yes"; - echo ""; - echo $tdWithClass; - echo ""; - echo ""; - */ - echo ""; + echo $lang['sqlite_limit']."

"; + if(!isset($_GET['pk'])) + echo $lang['specify_col']; + else if (!$target_table) + echo $lang['specify_tbl']; + else + { + $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; + $result = $db->selectArray($query); - echo ""; - echo ""; - echo ""; - echo "
"; - echo "
"; - echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); - echo "
"; - echo ""; + for($i=0; $i"; + echo ""; + echo ""; + echo ""; + echo ""; + //$headings = array("Field", "Type", "Primary Key", "Autoincrement", "Not NULL", "Default Value"); + $headings = array($lang["fld"], $lang["type"]); + for($k=0; $k".$headings[$k].""; + echo ""; + + $i = 0; + $tdWithClass = ""; + echo $tdWithClass; + echo ""; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + /* + echo $tdWithClass; + if($primarykeyVal) + echo " Yes"; + else + echo " Yes"; + echo ""; + echo $tdWithClass; + if(1==2) + echo " Yes"; + else + echo " Yes"; + echo ""; + echo $tdWithClass; + if($notnullVal) + echo " Yes"; + else + echo " Yes"; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + */ + echo ""; + + echo ""; + echo ""; + echo ""; + echo "
"; + echo "
"; + echo " "; + echo "".$lang['cancel'].""; + echo "
"; + echo ""; } break; //- Delete index (=index_delete) case "index_delete": - echo $params->getForm(array('action'=>'index_delete', 'pk'=>$_GET['pk'], 'confirm'=>'1')); + echo "
"; echo "
"; - echo sprintf($lang['ques_index_delete'], htmlencode($_GET['pk']))."

"; + echo sprintf($lang['ques_del_index'], htmlencode($_GET['pk']))."

"; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; echo "
"; break; //- Delete trigger (=trigger_delete) case "trigger_delete": - echo $params->getForm(array('action'=>'trigger_delete', 'pk'=>$_GET['pk'], 'confirm'=>'1')); + echo "
"; echo "
"; - echo sprintf($lang['ques_trigger_delete'], htmlencode($_GET['pk']))."

"; + echo sprintf($lang['ques_del_trigger'], htmlencode($_GET['pk']))."

"; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; echo "
"; break; //- Create trigger (=trigger_create) case "trigger_create": - echo "

".$lang['create_trigger']." '".htmlencode($_GET['table'])."'

"; - if($_GET['table']=="") + echo "

".$lang['create_trigger']." '".htmlencode($_POST['tablename'])."'

"; + if($_POST['tablename']=="") echo $lang['specify_tbl']; else { - echo $params->getForm(array('action'=>'trigger_create', 'confirm'=>'1')); + echo "
"; echo $lang['trigger_name'].":

"; echo "
".$lang['db_event'].""; echo $lang['before']."/".$lang['after'].": "; echo ""; echo "

"; echo $lang['event'].": "; @@ -3337,23 +3070,25 @@ function drawChart() echo ""; echo "


"; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; } break; //- Create index (=index_create) case "index_create": - echo "

".$lang['create_index']." '".htmlencode($_GET['table'])."'

"; - if($_GET['numcolumns']=="" || intval($_GET['numcolumns'])<=0) + echo "

".$lang['create_index']." '".htmlencode($_POST['tablename'])."'

"; + if($_POST['numcolumns']=="" || intval($_POST['numcolumns'])<=0) echo $lang['specify_fields']; - else if($_GET['table']=="") + else if($_POST['tablename']=="") echo $lang['specify_tbl']; else { - echo $params->getForm(array('action'=>'index_create', 'confirm'=>'1')); - $num = intval($_GET['numcolumns']); - $tableInfo = $db->getTableInfo($_GET['table']); + echo "
"; + $num = intval($_POST['numcolumns']); + $query = "PRAGMA table_info(".$db->quote_id($_POST['tablename']).")"; + + $result = $db->selectArray($query); echo "
".$lang['define_index'].""; echo "
"; echo ""; @@ -3370,8 +3105,8 @@ function drawChart() { echo " "; echo ""; echo " "; - echo $params->getLink(array('action'=>'column_view'), $lang['cancel']); + echo "".$lang['cancel'].""; echo ""; } break; @@ -3391,218 +3126,295 @@ function drawChart() echo ""; } -//- HMTL: views for databases -if(!$target_table && !isset($_GET['confirm']) && (!isset($_GET['action']) || (isset($_GET['action']) && $_GET['action']!="table_create" && $_GET['action']!="table_confirm"))) //the absence of these fields means we are viewing the database homepage +$view = "structure"; + +//- HMTL: tabs for databases +if(!$target_table && !isset($_GET['confirm']) && (!isset($_GET['action']) || (isset($_GET['action']) && $_GET['action']!="table_create"))) //the absence of these fields means we are viewing the database homepage { + $view = isset($_GET['view']) ? $_GET['view'] : 'structure'; + + echo "".$lang['struct'].""; + echo "".$lang['sql'].""; + echo "".$lang['export'].""; + echo "".$lang['import'].""; + echo "".$lang['vac'].""; + if($directory!==false && is_writable($directory)) + { + echo "".$lang['db_rename'].""; + + echo "".$lang['db_del'].""; + } + echo "
"; + echo "
"; + //- Switch on $view (actually a series of if-else) if($view=="structure") { //- Database structure, shows all the tables (=structure) - + + if(isset($dbexists)) + { + echo "
"; + echo $lang['err'].': '.sprintf($lang['db_exists'], htmlencode($dbname)); + echo "

"; + } + if($db->isWritable() && !$db->isDirWritable()) { - echo "
"; + echo "
"; echo $lang['attention'].': '.$lang['directory_not_writable']; echo "

"; } - elseif(!$db->isWritable()) + + if(isset($extension_not_allowed)) { - echo "
"; - echo $lang['attention'].': '.$lang['database_not_writable']; + echo "
"; + echo $lang['extension_not_allowed'].': '; + echo implode(', ', array_map('htmlencode', $allowed_extensions)); + echo '
'.$lang['add_allowed_extension']; echo "

"; } if ($auth->isPasswordDefault()) { echo "
"; - echo sprintf($lang['warn_passwd'],(is_readable('phpliteadmin.config.php')?'phpliteadmin.config.php':basename(__FILE__)))."
".$lang['warn0']; - echo "
"; - } - - if (!extension_loaded('mbstring')) - { - echo "
"; - echo $lang['warn_mbstring']; + echo sprintf($lang['warn_passwd'],(is_readable('phpliteadmin.config.php')?'phpliteadmin.config.php':PAGE))."
".$lang['warn0']; echo "
"; } + echo "".$lang['db_name'].": ".htmlencode($db->getName())."
"; echo "".$lang['db_path'].": ".htmlencode($db->getPath())."
"; - echo "".$lang['db_size'].": ".number_format($db->getSize())." KiB
"; + echo "".$lang['db_size'].": ".$db->getSize()." KB
"; echo "".$lang['db_mod'].": ".$db->getDate()."
"; echo "".$lang['sqlite_v'].": ".$db->getSQLiteVersion()."
"; - echo "".$lang['sqlite_ext']." ".helpLink($lang['help1']).": ".$db->getType()."
"; + echo "".$lang['sqlite_ext']." ".helpLink($lang['help1']).": ".$db->getType()."
"; echo "".$lang['php_v'].": ".phpversion()."
"; echo "".PROJECT." ".$lang["ver"].": ".VERSION; echo "

"; echo ""; - + if(isset($_GET['sort']) && ($_GET['sort']=='type' || $_GET['sort']=='name')) $_SESSION[COOKIENAME.'sortTables'] = $_GET['sort']; if(isset($_GET['order']) && ($_GET['order']=='ASC' || $_GET['order']=='DESC')) $_SESSION[COOKIENAME.'orderTables'] = $_GET['order']; + + $query = "SELECT type, name FROM sqlite_master WHERE (type='table' OR type='view') AND name!='' AND name NOT LIKE 'sqlite_%'"; + $queryAdd = ""; + if(isset($_SESSION[COOKIENAME.'sortTables'])) + $queryAdd .= " ORDER BY ".$db->quote_id($_SESSION[COOKIENAME.'sortTables']); + else + $queryAdd .= " ORDER BY \"name\""; + if(isset($_SESSION[COOKIENAME.'orderTables'])) + $queryAdd .= " ".$_SESSION[COOKIENAME.'orderTables']; + $query .= $queryAdd; + $result = $db->selectArray($query); - if(!isset($_SESSION[COOKIENAME.'sortTables'])) - $_SESSION[COOKIENAME.'sortTables'] = 'name'; - - if(!isset($_SESSION[COOKIENAME.'orderTables'])) - $_SESSION[COOKIENAME.'orderTables'] = 'ASC'; - - $tables = $db->getTables(true, false, $_SESSION[COOKIENAME.'sortTables'], $_SESSION[COOKIENAME.'orderTables']); - - if(sizeof($tables)==0) + if(sizeof($result)==0) echo $lang['no_tbl']."

"; else { - echo $params->getForm(array('action'=>'table_confirm',), 'get', false, 'checkForm'); echo ""; echo ""; - - echo ""; - + echo ""; - + echo ""; echo ""; echo ""; - + $totalRecords = 0; $skippedTables = false; - $tableId = 0; - foreach($tables as $tableName => $tableType) + for($i=0; $inumRows($tableName, (!isset($_GET['forceCount']))); + $records = $db->numRows($result[$i]['name'], (!isset($_GET['forceCount']))); if($records == '?') { $skippedTables = true; - $records = $params->getLink(array('forceCount'=>'1'), '?'); + $records = "?"; } else $totalRecords += $records; $tdWithClass = ""; - echo $tdWithClass; - echo ""; - echo ""; - echo $tdWithClassLeft; - echo $params->getLink(array('table'=>$tableName, 'action'=>'row_view'), htmlencode($tableName)); - echo ""; - echo $tdWithClassLeft; - echo ($tableType=="table"? $lang['tbl'] : $lang['view']); - echo ""; - echo $tdWithClass; - echo $params->getLink(array('table'=>$tableName, 'action'=>'row_view'), $lang['browse']); - echo ""; - echo $tdWithClass; - echo $params->getLink(array('table'=>$tableName, 'action'=>'column_view'), $lang['struct']); - echo ""; - echo $tdWithClass; - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_sql'), $lang['sql']); - echo ""; - echo $tdWithClass; - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_search'), $lang['srch']); - echo ""; - echo $tdWithClass; - if($tableType=="table" && $db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('table'=>$tableName, 'action'=>'row_create'), $lang['insert']); - else - echo $lang['insert']; - echo ""; - echo $tdWithClass; - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_export'), $lang['export']); - echo ""; - echo $tdWithClass; - if($tableType=="table" && $db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_import'), $lang['import']); - else - echo $lang['import']; - echo ""; - echo $tdWithClass; - if($db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_rename'), $lang['rename']); - else - echo $lang['rename']; - echo ""; - echo $tdWithClass; - if($tableType=="table" && $db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('table'=>$tableName, 'action'=>'table_confirm', 'action2'=>'table_empty'), $lang['empty'], 'empty'); - else - echo $lang['empty']; - echo ""; - echo $tdWithClass; - if($db->isWritable() && $db->isDirWritable()) - echo $params->getLink(array('table'=>$tableName,'action'=>'table_confirm', 'action2'=>'table_drop'), $lang['drop'], 'drop'); + + if($result[$i]['type']=="table") + { + echo ""; + echo $tdWithClassLeft; + echo $lang['tbl']; + echo ""; + echo $tdWithClassLeft; + echo "".htmlencode($result[$i]['name']).""; + echo ""; + echo $tdWithClass; + echo "".$lang['browse'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['struct'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['sql'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['srch'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['insert'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['export'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['import'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['rename'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['empty'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['drop'].""; + echo ""; + echo $tdWithClass; + echo $records; + echo ""; + echo ""; + } else - echo $lang['drop']; - echo ""; - echo $tdWithClass; - echo $records; - echo ""; - echo ""; - $tableId++; + { + echo ""; + echo $tdWithClassLeft; + echo "View"; + echo ""; + echo $tdWithClassLeft; + echo "".htmlencode($result[$i]['name']).""; + echo ""; + echo $tdWithClass; + echo "".$lang['browse'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['struct'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['sql'].""; + echo ""; + echo $tdWithClass; + echo "".$lang['srch'].""; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + echo $tdWithClass; + echo "".$lang['export'].""; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + echo $tdWithClass; + echo ""; + echo ""; + echo $tdWithClass; + echo "".$lang['drop'].""; + echo ""; + echo $tdWithClass; + echo $records; + echo ""; + echo ""; + } } echo ""; - echo ""; - echo ""; + echo ""; + echo ""; echo ""; echo "
"; + + echo ""; + echo "getLink(array('sort'=>'name', 'order'=>$orderTag), $lang['name']); - if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="name") + echo "&order=".$orderTag; + echo "'>".$lang['type']." ".helpLink($lang['help3']); + if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="type") echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " " : " "); echo ""; + echo "getLink(array('sort'=>'type', 'order'=>$orderTag), $lang['type']); - echo helpLink($lang['help3']); - if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="type") + echo "&order=".$orderTag; + echo "'>".$lang['name'].""; + if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="name") echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " " : " "); echo "".$lang['act']."".$lang['rec']."
"; $tdWithClassLeft = ""; - - echo "
".sizeof($tables)." ".$lang['total']."".$totalRecords.($skippedTables?" ".$params->getLink(array('forceCount'=>'1'),'+ ?'):"")."".sizeof($result)." ".$lang['total']."".$totalRecords.($skippedTables?" + ?":"")."
"; - echo "".$lang['chk_all']." / ".$lang['unchk_all']." ".$lang['with_sel'].": "; - echo " "; - echo ""; - echo ""; echo "
"; if($skippedTables) - echo "
".sprintf($lang["counting_skipped"],"'1'))."'>","")."
"; - } - if($db->isWritable() && $db->isDirWritable()) - { - echo "
"; - echo "".$lang['create_tbl_db']." '".htmlencode($db->getName())."'"; - echo $params->getForm(array('action'=>'table_create'), 'get'); - echo $lang['name'].": "; - echo $lang['fld_num'].": "; - echo ""; - echo ""; - echo "
"; - echo "
"; - echo "
"; - echo "".$lang['create_view']." '".htmlencode($db->getName())."'"; - echo $params->getForm(array('action'=>'view_create', 'confirm'=>'1')); - echo $lang['name'].": "; - echo $lang['sel_state']." ".helpLink($lang['help4']).": "; - echo ""; - echo ""; - echo "
"; + echo "
".sprintf($lang["counting_skipped"],"","")."
"; } + echo "
"; + echo "".$lang['create_tbl_db']." '".htmlencode($db->getName())."'"; + echo "
"; + echo $lang['name'].": "; + echo $lang['fld_num'].": "; + echo ""; + echo "
"; + echo "
"; + echo "
"; + echo "
"; + echo "".$lang['create_view']." '".htmlencode($db->getName())."'"; + echo "
"; + echo $lang['name'].": "; + echo $lang['sel_state']." ".helpLink($lang['help4']).": "; + echo ""; + echo "
"; + echo "
"; } else if($view=="sql") { //- Database SQL editor (=sql) + $isSelect = false; if(isset($_POST['query']) && $_POST['query']!="") { $delimiter = $_POST['delimiter']; @@ -3610,11 +3422,11 @@ function drawChart() //save the queries in history if necessary if($maxSavedQueries!=0 && $maxSavedQueries!=false) { - if(!isset($_SESSION[COOKIENAME.'query_history'])) - $_SESSION[COOKIENAME.'query_history'] = array(); - $_SESSION[COOKIENAME.'query_history'][md5(strtolower($queryStr))] = $queryStr; - if(sizeof($_SESSION[COOKIENAME.'query_history']) > $maxSavedQueries) - array_shift($_SESSION[COOKIENAME.'query_history']); + if(!isset($_SESSION['query_history'])) + $_SESSION['query_history'] = array(); + $_SESSION['query_history'][md5(strtolower($queryStr))] = $queryStr; + if(sizeof($_SESSION['query_history']) > $maxSavedQueries) + array_shift($_SESSION['query_history']); } $query = explode_sql($delimiter, $queryStr); //explode the query string into individual queries based on the delimiter @@ -3622,20 +3434,34 @@ function drawChart() { if(str_replace(" ", "", str_replace("\n", "", str_replace("\r", "", $query[$i])))!="") //make sure this query is not an empty string { - $queryTimer = new MicroTimer(); - $table_result = $db->query($query[$i]); - + $result = $db->selectArray($query[$i], "assoc"); + echo "
"; - echo "".htmlencode($query[$i]).""; - if($table_result === NULL || $table_result === false) + echo ""; + + if($result !== NULL) + { + + if(sizeof($result)>0 || $db->getAffectedRows()==0) + { + printf($lang['show_rows'], sizeof($result)); + } + if($db->getAffectedRows()>0 || sizeof($result)==0) + { + echo $db->getAffectedRows()." ".$lang['rows_aff']." "; + } + echo "
"; + } + else { - echo "
".$lang['err'].": ".htmlencode($db->getError())."
"; + echo $lang['err'].": ".$db->getError()."
"; } + echo "".htmlencode($query[$i]).""; echo "

"; - if($row = $db->fetch($table_result, 'num')) + if(sizeof($result)>0) { - for($j=0; $jgetColumnName($table_result,$j); + $headers = array_keys($result[0]); + echo ""; echo ""; for($j=0; $j"; } echo ""; - $rowCount = 0; - for(; $rowCount==0 || $row = $db->fetch($table_result, 'num'); $rowCount++) + for($j=0; $j"; + $tdWithClass = ""; for($z=0; $zNULL"; else - echo htmlencode(subString($row[$z])); + echo htmlencode(subString($result[$j][$headers[$z]])); echo ""; } echo ""; } - $queryTimer->stop(); echo "
"; echo "


"; - - - if($table_result !== NULL && $table_result !== false) - { - echo "
"; - if($rowCount>0 || $db->getAffectedRows()==0) - { - printf($lang['show_rows'], $rowCount); - } - if($db->getAffectedRows()>0 || $rowCount==0) - { - echo $db->getAffectedRows()." ".$lang['rows_aff']." "; - } - printf($lang['query_time'], $queryTimer); - echo "
"; - } - - } - } + } } } else @@ -3695,18 +3501,17 @@ function drawChart() echo "
"; echo "".sprintf($lang['run_sql'],htmlencode($db->getName())).""; - echo $params->getForm(array('view'=>'sql')); - if(isset($_SESSION[COOKIENAME.'query_history']) && sizeof($_SESSION[COOKIENAME.'query_history'])>0) + echo "
"; + if(isset($_SESSION['query_history']) && sizeof($_SESSION['query_history'])>0) { echo "".$lang['recent_queries']."

"; } echo ""; - echo ""; echo $lang['delimit']." "; echo ""; echo "
"; @@ -3723,7 +3528,7 @@ function drawChart() printf($lang['db_vac'], htmlencode($db->getName())); echo "

"; } - echo $params->getForm(array('view'=>'vacuum')); + echo "
"; printf($lang['vac_desc'],htmlencode($db->getName())); echo "

"; echo ""; @@ -3732,28 +3537,30 @@ function drawChart() else if($view=="export") { //- Export view (=export) - echo $params->getForm(array('view'=>'export')); + echo ""; echo "
".$lang['export'].""; echo ""; echo "

"; echo ""; echo "
"; echo "
"; - + echo "
".$lang['options'].""; - echo " ".helpLink($lang['help5'])."
"; + echo " ".helpLink($lang['help5'])."
"; echo " ".helpLink($lang['help6'])."
"; - echo " ".helpLink($lang['help7'])."
"; + echo " ".helpLink($lang['help7'])."
"; echo " ".helpLink($lang['help8'])."
"; - echo " ".helpLink($lang['help9'])."
"; + echo " ".helpLink($lang['help9'])."
"; echo "
"; - + echo ""; - + echo "
"; echo "

"; echo "
".$lang['save_as'].""; @@ -3779,9 +3586,7 @@ function drawChart() echo " "; echo "
"; echo "
"; - echo "
".sprintf($lang['backup_hint'], - $params->getLink(array('download'=>$currentDB['path'], 'token'=>$_SESSION[COOKIENAME.'token']), $lang["backup_hint_linktext"], '', $lang['backup']) - )."
"; + echo "
".sprintf($lang['backup_hint'], "".$lang["backup_hint_linktext"]."")."
"; } else if($view=="import") { @@ -3795,25 +3600,26 @@ function drawChart() echo $importSuccess; echo "

"; } - - echo $params->getForm(array('view'=>'import'), 'post', true); + + echo "
"; echo "
".$lang['import'].""; echo ""; echo "
"; echo "
"; - + echo "
".$lang['options'].""; echo $lang['no_opt']; echo "
"; - + echo ""; - + echo "
"; echo "

"; - + echo "
".$lang['import_f'].""; - echo "".$lang['max_file_size'].": ".number_format(fileUploadMaxSize()/1024/1024)." MiB ".helpLink($lang['help11'])."
"; - echo ""; - echo ""; + echo " "; echo "
"; } else if($view=="rename") { //- Rename database confirmation (=rename) - echo $params->getForm(array('view'=>'rename', 'database_rename'=>'1')); + if(isset($extension_not_allowed)) + { + echo "
"; + echo $lang['extension_not_allowed'].': '; + echo implode(', ', array_map('htmlencode', $allowed_extensions)); + echo '
'.$lang['add_allowed_extension']; + echo "

"; + } + if(isset($dbexists)) + { + echo "
"; + if($oldpath==$newpath) + echo $lang['err'].": ".$lang['warn_dumbass']; + else{ + echo $lang['err'].": "; + printf($lang['db_exists'], htmlencode($newpath)); + } + echo "

"; + } + if(isset($justrenamed)) + { + echo "
"; + printf($lang['db_renamed'], htmlencode($oldpath)); + echo " '".htmlencode($newpath)."'."; + echo "

"; + } + echo ""; echo ""; echo $lang['db_rename']." '".htmlencode($db->getPath())."' ".$lang['to']." "; - echo "
"; + echo ""; } else if($view=="delete") { //- Delete database confirmation (=delete) - echo $params->getForm(array('database_delete'=>'1')); + echo "
"; echo "
"; - echo sprintf($lang['ques_database_delete'],htmlencode($db->getPath()))."

"; + echo sprintf($lang['ques_del_db'],htmlencode($db->getPath()))."

"; echo ""; echo " "; - echo $params->getLink(array(), $lang['cancel']); + echo "".$lang['cancel'].""; echo "
"; - echo "
"; + echo ""; } echo ""; } -echo ""; //- HTML: page footer echo "
"; echo "".$lang['powered']." ".PROJECT." | "; echo $lang['free_software']." ".$lang['please_donate']." | "; -printf($lang['page_gen'], $pageTimer); echo ""; echo ""; $db->close(); //close the database From 6a9c197bdeb86dd84697721bea87f3838cc5e849 Mon Sep 17 00:00:00 2001 From: schucan Date: Sun, 19 May 2024 23:10:33 +0200 Subject: [PATCH 2/2] Delete classes/MicroTimer.php: removing Microtimer for this to work in PHP 8.2 --- classes/MicroTimer.php | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 classes/MicroTimer.php diff --git a/classes/MicroTimer.php b/classes/MicroTimer.php deleted file mode 100644 index 5dbb3ac..0000000 --- a/classes/MicroTimer.php +++ /dev/null @@ -1,37 +0,0 @@ -startTime = microtime(true); - } - - // stops a timer - public function stop() - { - $this->stopTime = microtime(true); - } - - // returns the number of seconds from the timer's creation, or elapsed - // between creation and call to ->stop() - public function elapsed() - { - if ($this->stopTime) - return round($this->stopTime - $this->startTime, 4); - - return round(microtime(true) - $this->startTime, 4); - } - - // called when using a MicroTimer object as a string - public function __toString() - { - return (string) $this->elapsed(); - } - -}