. // // //////////////////////////////////////////////////////////////////////// // // Please report any bugs you may encounter to our issue tracker here: // https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open // // This is sample configuration file // // You can configure phpliteadmin in one of 2 ways: // 1. Rename phpliteadmin.config.sample.php to phpliteadmin.config.php and change parameters in there. // You can set only your custom settings in phpliteadmin.config.php. All other settings will be set to defaults. // 2. Change parameters directly in main phpliteadmin.php file // // Please see https://bitbucket.org/phpliteadmin/public/wiki/Configuration for more details //password to gain access $password = ''; //directory relative to this file to search for databases (if false, manually list databases in the $databases variable) $directory = false; //whether or not to scan the subdirectories of the above directory infinitely deep $subdirectories = false; //if the above $directory variable is set to false, you must specify the databases manually in an array as the next variable //if any of the databases do not exist as they are referenced by their path, they will be created automatically $databases = array( array( 'path'=> '../data/data.db', 'name'=> 'php-epg' ), ); /* ---- Interface settings ---- */ // Theme! If you want to change theme, save the CSS file in same folder of phpliteadmin or in folder "themes" $theme = 'phpliteadmin.css'; // the default language! If you want to change it, save the language file in same folder of phpliteadmin or in folder "languages" // More about localizations (downloads, how to translate etc.): https://bitbucket.org/phpliteadmin/public/wiki/Localization $language = 'en'; // set default number of rows. You need to relog after changing the number $rowsNum = 500; // reduce string characters by a number bigger than 10 $charsNum = 300; // maximum number of SQL queries to save in the history $maxSavedQueries = 10; /* ---- Custom functions ---- */ //a list of custom functions that can be applied to columns in the databases //make sure to define every function below if it is not a core PHP function $custom_functions = array( 'md5', 'sha1', 'time', 'strtotime', // add the names of your custom functions to this array /* 'leet_text', */ ); // define your custom functions here /* function leet_text($value) { return strtr($value, 'eaAsSOl', '344zZ01'); } */ /* ---- Advanced options ---- */ //changing the following variable allows multiple phpLiteAdmin installs to work under the same domain. $cookie_name = 'pla3412'; //whether or not to put the app in debug mode where errors are outputted $debug = false; // the user is allowed to create databases with only these extensions $allowed_extensions = array('db','db3','sqlite','sqlite3'); // English language-texts. // Read our wiki on how to translate: https://bitbucket.org/phpliteadmin/public/wiki/Localization $lang = array( "direction" => "LTR", "date_format" => 'g:ia \o\n F j, Y (T)', // see http://php.net/manual/en/function.date.php for what the letters stand for "ver" => "版本", "for" => "for", "to" => "to", "go" => "执行", "yes" => "是", "no" => "否", "sql" => "SQL", "csv" => "CSV", "csv_tbl" => "Table that CSV pertains to", "srch" => "搜索", "srch_again" => "继续搜索", "login" => "登录", "logout" => "登出", "view" => "预览", "confirm" => "确认", "cancel" => "取消", "save_as" => "另存为", "options" => "选项", "no_opt" => "无选项", "help" => "帮助", "installed" => "已安装", "not_installed" => "未安装", "done" => "完成", "insert" => "插入", "export" => "导出", "import" => "导入", "rename" => "重命名", "empty" => "清空表", "drop" => "删除表", "tbl" => "数据表", "chart" => "图表", "err" => "错误", "act" => "动作", "rec" => "数据量", "col" => "所在列", "cols" => "列", "rows" => "行", "edit" => "编辑", "del" => "删除", "add" => "添加", "backup" => "备份数据库为文件", "before" => "Before", "after" => "After", "passwd" => "密码", "passwd_incorrect" => "密码错误", "chk_ext" => "Checking supported SQLite PHP extensions", "autoincrement" => "自动递增", "not_null" => "不为 NULL", "attention" => "Attention", "none" => "None", "as_defined" => "As defined", "expression" => "Expression", "sqlite_ext" => "SQLite 扩展", "sqlite_ext_support" => "It appears that none of the supported SQLite library extensions are available in your installation of PHP. You may not use %s until you install at least one of them.", "sqlite_v" => "数据库版本", "sqlite_v_error" => "It appears that your database is of SQLite version %s but your installation of PHP does not contain the necessary extensions to handle this version. To fix the problem, either delete the database and allow %s to create it automatically or recreate it manually as SQLite version %s.", "report_issue" => "The problem cannot be diagnosed properly. Please file an issue report at", "sqlite_limit" => "Due to the limitations of SQLite, only the field name and data type can be modified.", "php_v" => "PHP 版本", "new_version" => "There is a new version!", "db_dump" => "database dump", "db_f" => "数据库文件", "db_ch" => "更改数据库", "db_event" => "Database Event", "db_name" => "数据库名称", "db_rename" => "重命名数据库", "db_renamed" => "Database '%s' has been renamed to", "db_del" => "删除数据库", "db_path" => "数据库目录", "db_size" => "数据库大小", "db_mod" => "数据库上次修改时间", "db_create" => "创建新的数据库", "db_vac" => "The database, '%s', has been VACUUMed.", "db_not_writeable" => "The database, '%s', does not exist and cannot be created because the containing directory, '%s', is not writable. The application is unusable until you make it writable.", "db_setup" => "There was a problem setting up your database, %s. An attempt will be made to find out what's going on so you can fix the problem more easily", "db_exists" => "A database, other file or directory of the name '%s' already exists.", "exported" => "已导出", "struct" => "结构", "struct_for" => "structure for", "on_tbl" => "on table", "data_dump" => "Data dump for", "backup_hint" => "提示:要备份数据库,最简单的方法是 %s.", "backup_hint_linktext" => "下载数据库文件", "total_rows" => "总共有 %s 行", "total" => "总数", "not_dir" => "The directory you specified to scan for databases does not exist or is not a directory.", "bad_php_directive" => "It appears that the PHP directive, 'register_globals' is enabled. This is bad. You need to disable it before continuing.", "page_gen" => "Page generated in %s seconds.", "powered" => "Powered by", "free_software" => "This is free software.", "please_donate" => "Please donate.", "remember" => "Remember me", "no_db" => "Welcome to %s. It appears that you have selected to scan a directory for databases to manage. However, %s could not find any valid SQLite databases. You may use the form below to create your first database.", "no_db2" => "The directory you specified does not contain any existing databases to manage, and the directory is not writable. This means you can't create any new databases using %s. Either make the directory writable or manually upload databases to the directory.", "create" => "创建", "created" => "has been created", "create_tbl" => "创建新的数据表", "create_tbl_db" => "在数据库中创建新的数据表", "create_trigger" => "Creating new trigger on table", "create_index" => "在数据表中创建索引", "create_index1" => "创建索引", "create_view" => "Create new view on database", "trigger" => "Trigger", "triggers" => "Triggers", "trigger_name" => "Trigger name", "trigger_act" => "Trigger Action", "trigger_step" => "Trigger Steps (semicolon terminated)", "when_exp" => "WHEN expression (type expression without 'WHEN')", "index" => "Index", "indexes" => "Indexes", "index_name" => "索引名称", "name" => "名称", "unique" => "Unique", "seq_no" => "Seq. No.", "emptied" => "has been emptied", "dropped" => "has been dropped", "renamed" => "has been renamed to", "altered" => "has been altered successfully", "inserted" => "已插入", "deleted" => "已删除", "affected" => "affected", "blank_index" => "Index name must not be blank.", "one_index" => "You must specify at least one index column.", "docu" => "使用文档", "license" => "版权许可证", "proj_site" => "项目主页", "bug_report" => "This may be a bug that needs to be reported at", "return" => "返回", "browse" => "浏览", "fld" => "字段", "fld_num" => "Number of Fields", "fields" => "字段", "type" => "类型", "operator" => "运算符", "val" => "值", "update" => "更新", "comments" => "数据库备注", "specify_fields" => "You must specify the number of table fields.", "specify_tbl" => "You must specify a table name.", "specify_col" => "You must specify a column.", "tbl_exists" => "Table of the same name already exists.", "show" => "显示", "show_rows" => "显示 %s 行. ", "showing" => "显示", "showing_rows" => "显示行数范围", "query_time" => "(本次搜查询共耗时 %s 秒)", "syntax_err" => "There is a problem with the syntax of your query (Query was not executed)", "run_sql" => "对数据库 '%s' 执行SQL语句", "recent_queries" => "最近查询语句", "full_texts" => "Show full texts", "no_full_texts" => "Shorten long texts", "ques_empty" => "是否要清空数据表 '%s'?", "ques_drop" => "是否要删除数据表 '%s'?", "ques_drop_view" => "是否要删除视图 '%s'?", "ques_del_rows" => "是否要删除行 %s 在数据表 '%s' 中?", "ques_del_db" => "是否要删除数据库 '%s'?", "ques_column_delete" => "是否要删除列 %s 在数据表 '%s' 中?", "ques_del_index" => "是否要删除索引 '%s'?", "ques_del_trigger" => "是否要删除触发器 '%s'?", "ques_primarykey_add" => "是否要添加主键列 %s 在数据表 '%s' 中?", "export_struct" => "导出结构", "export_data" => "导出数据", "add_drop" => "添加清除表", "add_transact" => "添加事务", "fld_terminated" => "Fields terminated by", "fld_enclosed" => "Fields enclosed by", "fld_escaped" => "Fields escaped by", "fld_names" => "Field names in first row", "rep_null" => "Replace NULL by", "rem_crlf" => "Remove CRLF characters within fields", "put_fld" => "Put field names in first row", "null_represent" => "NULL represented by", "import_suc" => "导入成功", "import_into" => "导入到", "import_f" => "使用文件导入", "rename_tbl" => "重命名表 '%s' 为", "rows_records" => "行, 开始行数(0为第一行)为 ", "rows_aff" => "行 被修改", "as_a" => "在", "readonly_tbl" => "'%s' is a view, which means it is a SELECT statement treated as a read-only table. You may not edit or insert records.", "chk_all" => "全选", "unchk_all" => "取消全选", "with_sel" => "选定的项目执行", "no_tbl" => "数据库中没有数据表", "no_chart" => "If you can read this, it means the chart could not be generated. The data you are trying to view may not be appropriate for a chart.", "no_rows" => "There are no rows in the table for the range you selected.", "no_sel" => "您未选择任何数据", "chart_type" => "Chart Type", "chart_bar" => "Bar Chart", "chart_pie" => "Pie Chart", "chart_line" => "Line Chart", "lbl" => "Labels", "empty_tbl" => "This table is empty.", "click" => "Click here", "insert_rows" => "to insert rows.", "restart_insert" => "本页显示插入框数量为", "ignore" => "忽略", "func" => "函数", "new_insert" => "插入新行", "save_ch" => "保存更改", "def_val" => "默认值", "prim_key" => "主键", "tbl_end" => "个字段在表末尾", "query_used_table" => "创建表语句", "query_used_view" => "Query used to create this view", "create_index2" => "创建一个索引在第", "create_trigger2" => "创建一个新的触发器", "new_fld" => "Adding new field(s) to table '%s'", "add_flds" => "Add Fields", "edit_col" => "Editing column '%s'", "vac" => "Vacuum", "vac_desc" => "Large databases sometimes need to be VACUUMed to reduce their footprint on the server. Click the button below to VACUUM the database '%s'.", "event" => "Event", "each_row" => "For Each Row", "define_index" => "Define index properties", "dup_val" => "Duplicate values", "allow" => "Allowed", "not_allow" => "Not Allowed", "asc" => "Ascending", "desc" => "Descending", "warn0" => "You have been warned.", "warn_passwd" => "You are using the default password, which can be dangerous. You can change it easily at the top of %s.", "warn_dumbass" => "You didn't change the value dumbass ;-)", "counting_skipped" => "Counting of records has been skipped for some tables because your database is comparably big and some tables don't have primary keys assigned to them so counting might be slow. Add a primary key to these tables or %sforce counting%s.", "sel_state" => "Select Statement", "delimit" => "分隔符", "back_top" => "Back to Top", "choose_f" => "Choose File", "instead" => "Instead of", "define_in_col" => "Define index column(s)", "delete_only_managed" => "You can only delete databases managed by this tool!", "rename_only_managed" => "You can only rename databases managed by this tool!", "db_moved_outside" => "You either tried to move the database into a directory where it cannot be managed anylonger, or the check if you did this failed because of missing rights.", "extension_not_allowed" => "The extension you provided is not within the list of allowed extensions. Please use one of the following extensions", "add_allowed_extension" => "You can add extensions to this list by adding your extension to \$allowed_extensions in the configuration.", "directory_not_writable" => "The database-file itself is writable, but to write into it, the containing directory needs to be writable as well. This is because SQLite puts temporary files in there for locking.", "tbl_inexistent" => "Table %s does not exist", // errors that can happen when ALTER TABLE fails. You don't necessarily have to translate these. "alter_failed" => "Altering of Table %s failed", "alter_tbl_name_not_replacable" => "could not replace the table name with the temporary one", "alter_no_def" => "no ALTER definition", "alter_parse_failed" =>"failed to parse ALTER definition", "alter_action_not_recognized" => "ALTER action could not be recognized", "alter_no_add_col" => "no column to add detected in ALTER statement", "alter_pattern_mismatch"=>"Pattern did not match on your original CREATE TABLE statement", "alter_col_not_recognized" => "could not recognize new or old column name", "alter_unknown_operation" => "Unknown ALTER operation!", /* Help documentation */ "help_doc" => "帮助文档", "help1" => "SQLite Library Extensions", "help1_x" => "%s uses PHP library extensions that allow interaction with SQLite databases. Currently, %s supports PDO, SQLite3, and SQLiteDatabase. Both PDO and SQLite3 deal with version 3 of SQLite, while SQLiteDatabase deals with version 2. So, if your PHP installation includes more than one SQLite library extension, PDO and SQLite3 will take precedence to make use of the better technology. However, if you have existing databases that are of version 2 of SQLite, %s will be forced to use SQLiteDatabase for only those databases. Not all databases need to be of the same version. During the database creation, however, the most advanced extension will be used.", "help2" => "创建新的数据库", "help2_x" => "When you create a new database, the name you entered will be appended with the appropriate file extension (.db, .db3, .sqlite, etc.) if you do not include it yourself. The database will be created in the directory you specified as the \$directory variable.", "help3" => "Tables vs. Views", "help3_x" => "On the main database page, there is a list of tables and views. Since views are read-only, certain operations will be disabled. These disabled operations will be apparent by their omission in the location where they should appear on the row for a view. If you want to change the data for a view, you need to drop that view and create a new view with the appropriate SELECT statement that queries other existing tables. For more information, see http://en.wikipedia.org/wiki/View_(database)", "help4" => "Writing a Select Statement for a New View", "help4_x" => "When you create a new view, you must write an SQL SELECT statement that it will use as its data. A view is simply a read-only table that can be accessed and queried like a regular table, except it cannot be modified through insertion, column editing, or row editing. It is only used for conveniently fetching data.", "help5" => "导出数据结构为文件", "help5_x" => "During the process for exporting to an SQL file, you may choose to include the queries that create the table and columns.", "help6" => "Export Data to SQL File", "help6_x" => "During the process for exporting to an SQL file, you may choose to include the queries that populate the table(s) with the current records of the table(s).", "help7" => "Add Drop Table to Exported SQL File", "help7_x" => "During the process for exporting to an SQL file, you may choose to include queries to DROP the existing tables before adding them so that problems do not occur when trying to create tables that already exist.", "help8" => "Add Transaction to Exported SQL File", "help8_x" => "During the process for exporting to an SQL file, you may choose to wrap the queries around a TRANSACTION so that if an error occurs at any time during the importation process using the exported file, the database can be reverted to its previous state, preventing partially updated data from populating the database.", "help9" => "Add Comments to Exported SQL File", "help9_x" => "During the process for exporting to an SQL file, you may choose to include comments that explain each step of the process so that a human can better understand what is happening.", "help10" => "Partial Indexes", "help10_x" => "Partial indexes are indexes over a subset of the rows of a table specified by a WHERE clause. Note this requires at least SQLite 3.8.0 and database files with partial indexes won't be readable or writable by older versions. See the SQLite documentation." ); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //there is no reason for the average user to edit anything below this comment //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //- Initialization // load optional configuration file $config_filename = './phpliteadmin.config.php'; if (is_readable($config_filename)) { include_once $config_filename; } //constants 1 define("PROJECT", "phpLiteAdmin"); define("VERSION", "1.9.7.1"); 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','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'); // Resource output (css and javascript files) // we get out of the main code as soon as possible, without inizializing the session if (isset($_GET['resource'])) { Resources::output($_GET['resource']); exit(); } // don't mess with this - required for the login session ini_set('session.cookie_httponly', '1'); session_start(); // 检查是否有权限访问 phpliteadmin.php if (!isset($_SESSION['can_access_phpliteadmin']) || $_SESSION['can_access_phpliteadmin'] !== true) { // 显示错误信息并跳转到 manage.php echo '
请通过管理页面访问。
正在跳转……
'; // 设置跳转延迟,给用户时间看到消息 echo ""; exit; } // generate CSRF token if (empty($_SESSION['token'])) { if (function_exists('mcrypt_create_iv')) { $_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); } else { $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); } } $token = $_SESSION['token']; $token_html = ''; // checking CSRF token if($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['download'])) // all POST forms need tokens! downloads are protected as well { if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token'])) $check_token=$_POST['token']; elseif($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['token'])) $check_token=$_GET['token']; if (!isset($check_token)) { die("CSRF token missing"); } elseif ((function_exists('hash_equals') && !hash_equals($_SESSION['token'], $check_token)) || (!function_exists('hash_equals') && $_SESSION['token']!==$check_token) ) // yes, timing attacks might be possible here. update your php ;) { die("CSRF token is wrong - please try to login again"); } } if($debug==true) { ini_set("display_errors", 1); error_reporting(E_STRICT | E_ALL); } else { @ini_set("display_errors", 0); } // class MicroTimer (issue #146) // wraps calls to microtime(), calculating the elapsed time and rounding output // class MicroTimer { private $startTime, $stopTime; // creates and starts a timer function __construct() { $this->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(); } } // start the timer to record page load time $pageTimer = new MicroTimer(); // load language file if($language != 'en') { $temp_lang=$lang; if(is_file('languages/lang_'.$language.'.php')) include('languages/lang_'.$language.'.php'); elseif(is_file('lang_'.$language.'.php')) include('lang_'.$language.'.php'); $lang = array_merge($temp_lang, $lang); unset($temp_lang); } // 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) ); // 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 ( function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ) { $get_magic_quotes_gpc = (($quotes_gpc = ini_get('magic_quotes_gpc')) && strtolower($quotes_gpc) !== 'off'); // 结果和 get_magic_quotes_gpc()的结果等效 if ( function_exists('get_magic_quotes_gpc') && $get_magic_quotes_gpc ) { $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST); while (list($key, $val) = each($process)) { 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); } // 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 //data types array $sqlite_datatypes = array("INTEGER", "REAL", "TEXT", "BLOB","NUMERIC","BOOLEAN","DATETIME"); //available SQLite functions array (don't add anything here or there will be problems) $sqlite_functions = array("abs", "hex", "length", "lower", "ltrim", "random", "round", "rtrim", "trim", "typeof", "upper"); //- Support functions //function that allows SQL delimiter to be ignored inside comments or strings function explode_sql($delimiter, $sql) { $ign = array('"' => '"', "'" => "'", "/*" => "*/", "--" => "\n"); // Ignore sequences. $out = array(); $last = 0; $slen = strlen($sql); $dlen = strlen($delimiter); $i = 0; while($i < $slen) { // Split on delimiter if($slen - $i >= $dlen && substr($sql, $i, $dlen) == $delimiter) { array_push($out, substr($sql, $last, $i - $last)); $last = $i + $dlen; $i += $dlen; continue; } // Eat comments and string literals foreach($ign as $start => $end) { $ilen = strlen($start); if($slen - $i >= $ilen && substr($sql, $i, $ilen) == $start) { $i+=strlen($start); $elen = strlen($end); while($i < $slen) { if($slen - $i >= $elen && substr($sql, $i, $elen) == $end) { // SQL comment characters can be escaped by doubling the character. This recognizes and skips those. if($start == $end && $slen - $i >= $elen*2 && substr($sql, $i, $elen*2) == $end.$end) { $i += $elen * 2; continue; } else { $i += $elen; continue 3; } } $i++; } continue 2; } } $i++; } if($last < $slen) array_push($out, substr($sql, $last, $slen - $last)); return $out; } //function to scan entire directory tree and subdirectories function dir_tree($dir) { $path = ''; $stack[] = $dir; while($stack) { $thisdir = array_pop($stack); if($dircont = scandir($thisdir)) { $i=0; while(isset($dircont[$i])) { if($dircont[$i] !== '.' && $dircont[$i] !== '..') { $current_file = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i]; if(is_file($current_file)) { $path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i]; } elseif (is_dir($current_file)) { $path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i]; $stack[] = $current_file; } } $i++; } } } return $path; } //the function echo the help [?] links to the documentation function helpLink($name) { global $lang; return "[?]"; } // function to encode value into HTML just like htmlentities, but with adjusted default settings function htmlencode($value, $flags=ENT_QUOTES, $encoding ="UTF-8") { return htmlentities($value, $flags, $encoding); } // 22 August 2011: gkf added this function to support display of // default values in the form used to INSERT new data. function deQuoteSQL($s) { return trim(trim($s), "'"); } // reduce string chars function subString($str) { global $charsNum; if($charsNum > 10 && (!isset($_SESSION[COOKIENAME.'fulltexts']) || !$_SESSION[COOKIENAME.'fulltexts']) && mb_strlen($str)>$charsNum) { $str = mb_substr($str, 0, $charsNum).'...'; } return $str; } // checks the (new) name of a database file function checkDbName($name) { global $allowed_extensions; $info = pathinfo($name); if(isset($info['extension']) && !in_array($info['extension'], $allowed_extensions)) { return false; } else { return (!is_file($name) && !is_dir($name)); } } // check whether a path is a db managed by this tool // requires that $databases is already filled! // returns the key of the db if managed, false otherwise. function isManagedDB($path) { global $databases; foreach($databases as $db_key => $database) { if($path == $database['path']) { // a db we manage. Thats okay. // return the key. return $db_key; } } // not a db we manage! return false; } // from a typename of a colun, get the type of the column's affinty // see http://www.sqlite.org/datatype3.html section 2.1 for rules function get_type_affinity($type) { if (preg_match("/INT/i", $type)) return "INTEGER"; else if (preg_match("/(?:CHAR|CLOB|TEXT)/i", $type)) return "TEXT"; else if (preg_match("/BLOB/i", $type) || $type=="") return "NONE"; else if (preg_match("/(?:REAL|FLOA|DOUB)/i", $type)) return "REAL"; else return "NUMERIC"; } //- Check user authentication, login and logout $auth = new Authorization(); //create authorization object // check if user has attempted to log out if (isset($_POST['logout'])) $auth->revoke(); // check if user has attempted to log in else if (isset($_POST['login']) && isset($_POST['password'])) $auth->attemptGrant($_POST['password'], isset($_POST['remember'])); //- Actions on database files and bulk data if ($auth->isAuthorized()) { //- Create a new database if(isset($_POST['new_dbname'])) { if($_POST['new_dbname']=='') { // TODO: Display an error message (do NOT echo here. echo below in the html-body!) } else { $str = preg_replace('@[^\w-.]@','', $_POST['new_dbname']); $dbname = $str; $dbpath = $str; if(checkDbName($dbname)) { $tdata = array(); $tdata['name'] = $dbname; $tdata['path'] = $directory.DIRECTORY_SEPARATOR.$dbpath; if(isset($_POST['new_dbtype'])) $tdata['type'] = $_POST['new_dbtype']; else $tdata['type'] = 3; $td = new Database($tdata); $td->query("VACUUM"); } else { if(is_file($dbname) || is_dir($dbname)) $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) $arr = dir_tree($directory); else $arr = scandir($directory); $databases = array(); $j = 0; for($i=0; $i $database) { if($database['path'] == $tdata['path']) { $_SESSION[COOKIENAME.'currentDB'] = $database; break; } } } } else //the directory is not valid - display error and exit { echo "
".$lang['not_dir']."
"; exit(); } } else { for($i=0; $iexport_sql($tables, $drop, $structure, $data, $transaction, $comments); } else if($_POST['export_type']=="csv") { header("Content-type: application/csv"); header('Content-Disposition: attachment; filename="'.$export_filename.'.'.$_POST['export_type'].'";'); header("Pragma: no-cache"); header("Expires: 0"); if(isset($_POST['tables'])) $tables = $_POST['tables']; else { $tables = array(); $tables[0] = $_POST['single_table']; } $field_terminate = $_POST['export_csv_fieldsterminated']; $field_enclosed = $_POST['export_csv_fieldsenclosed']; $field_escaped = $_POST['export_csv_fieldsescaped']; $null = $_POST['export_csv_replacenull']; $crlf = isset($_POST['export_csv_crlf']); $fields_in_first_row = isset($_POST['export_csv_fieldnames']); $db = new Database($_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($_SESSION[COOKIENAME.'currentDB']); $db->registerUserFunction($custom_functions); if($_POST['import_type']=="sql") { $data = file_get_contents($_FILES["file"]["tmp_name"]); $importSuccess = $db->import_sql($data); } else { $field_terminate = $_POST['import_csv_fieldsterminated']; $field_enclosed = $_POST['import_csv_fieldsenclosed']; $field_escaped = $_POST['import_csv_fieldsescaped']; $null = $_POST['import_csv_replacenull']; $fields_in_first_row = isset($_POST['import_csv_fieldnames']); $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) { header("Content-type: application/octet-stream"); header('Content-Disposition: attachment; filename="'.basename($_GET['download']).'";'); header("Pragma: no-cache"); header("Expires: 0"); readfile($_GET['download']); exit; } } //- 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; // 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) { echo "".$key."
"; } echo "
"; echo "

"; foreach((array)$help as $key => $val) { echo "
"; echo "".$key.""; echo "
"; echo $val; echo "
"; echo "".$lang['back_top'].""; echo "
"; } ?> ".$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 $token_html; echo $lang['passwd'].":
"; echo "

"; echo ""; echo ""; echo "
"; echo "
"; echo "
"; echo "
"; echo "
"; echo "".$lang['powered']." ".PROJECT." | "; printf($lang['page_gen'], $pageTimer); echo "
"; echo ""; exit(); } //- User is authorized, display the main application //- 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 $token_html; echo " "; if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO'))) { echo ""; } echo ""; echo "
"; echo "
"; } else { echo "
"; echo $lang['err'].": ".sprintf($lang['no_db2'], PROJECT); echo "

"; } exit(); } //- 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) { if($database['path'] == $_GET['switchdb']) { $_SESSION[COOKIENAME."currentDB"] = $database; break; } } $currentDB = $_SESSION[COOKIENAME.'currentDB']; } if(isset($_SESSION[COOKIENAME.'currentDB']) && in_array($_SESSION[COOKIENAME.'currentDB'], $databases)) $currentDB = $_SESSION[COOKIENAME.'currentDB']; //- Open database (creates a Database object) $db = new Database($currentDB); //create the Database object $db->registerUserFunction($custom_functions); // collect parameters early, just once $target_table = isset($_GET['table']) ? $_GET['table'] : null; //- Switch on $_GET['action'] for operations without output if(isset($_GET['action']) && isset($_GET['confirm'])) { switch($_GET['action']) { //- Table actions //- Create table (=table_create) case "table_create": $num = intval($_POST['rows']); $name = $_POST['tablename']; $primary_keys = array(); for($i=0; $i<$num; $i++) { if($_POST[$i.'_field']!="" && isset($_POST[$i.'_primarykey'])) { $primary_keys[] = $_POST[$i.'_field']; } } $query = "CREATE TABLE ".$db->quote($name)." ("; for($i=0; $i<$num; $i++) { if($_POST[$i.'_field']!="") { $query .= $db->quote($_POST[$i.'_field'])." "; $query .= $_POST[$i.'_type']." "; if(isset($_POST[$i.'_primarykey'])) { if(count($primary_keys)==1) { $query .= "PRIMARY KEY "; if(isset($_POST[$i.'_autoincrement']) && $db->getType() != "SQLiteDatabase") $query .= "AUTOINCREMENT "; } $query .= "NOT NULL "; } if(!isset($_POST[$i.'_primarykey']) && isset($_POST[$i.'_notnull'])) $query .= "NOT NULL "; if($_POST[$i.'_defaultoption']!='defined' && $_POST[$i.'_defaultoption']!='none' && $_POST[$i.'_defaultoption']!='expr') $query .= "DEFAULT ".$_POST[$i.'_defaultoption']." "; elseif($_POST[$i.'_defaultoption']=='expr') $query .= "DEFAULT (".$_POST[$i.'_defaultvalue'].") "; elseif(isset($_POST[$i.'_defaultvalue']) && $_POST[$i.'_defaultoption']=='defined') { $typeAffinity = get_type_affinity($_POST[$i.'_type']); if(($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") && is_numeric($_POST[$i.'_defaultvalue'])) $query .= "DEFAULT ".$_POST[$i.'_defaultvalue']." "; else $query .= "DEFAULT ".$db->quote($_POST[$i.'_defaultvalue'])." "; } $query = substr($query, 0, sizeof($query)-2); $query .= ", "; } } if (count($primary_keys)>1) { $compound_key = ""; foreach ($primary_keys as $primary_key) { $compound_key .= ($compound_key=="" ? "" : ", ") . $db->quote($primary_key); } $query .= "PRIMARY KEY (".$compound_key."), "; } $query = substr($query, 0, 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; //- 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; //- 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; //- 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; //- 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; //- 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; //- Row actions //- 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"])) { $query_cols = ""; $query_vals = ""; $all_default = true; for($j=0; $jquote_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 $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++; } } $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; $backlinkParameters = "&action=column_view&table=".urlencode($target_table); 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) $error = true; $completed = sizeof($pks)." ".$lang['rows']." ".$lang['deleted'].".
".htmlencode($query).""; $backlinkParameters = "&action=row_view&table=".urlencode($target_table); break; //- 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; $iquote_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 $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; $z++; } else { $query = "UPDATE ".$db->quote_id($target_table)." SET "; for($j=0; $jquote_id($fields[$j])."="; if($function!="") $query .= $function."("; if($null) $query .= "NULL"; else $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; } } $completed .= "".htmlencode($query)."
"; } if(isset($_POST['new_row'])) $completed = $z." ".$lang['rows']." ".$lang['inserted'].".

".$completed; $backlinkParameters = "&action=row_view&table=".urlencode($target_table); 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 = "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') { $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); else // use ALTER TABLE workaround $result = $db->query($query, false); if($result===false) $error = true; } } $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; $backlinkParameters = "&action=column_view&table=".urlencode($target_table); 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) $error = true; $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; $backlinkParameters = "&action=column_view&table=".urlencode($target_table); 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) $error = true; $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; $backlinkParameters = "&action=column_view&table=".urlencode($target_table); 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) $error = true; $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered']."."; $backlinkParameters = "&action=column_view&table=".urlencode($target_table); break; //- 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; //- 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; //- 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; //- 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; } } // 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 "
"; echo "

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

"; echo ""; //- HTML: database list $db->print_db_list(); echo "
"; echo "25) $name = "...".mb_substr($name, mb_strlen($name)-22, 22); echo ">".htmlencode($name).""; echo ""; //- HTML: table list $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[".$lang[$result[$i]['type']=='table'?'tbl':'view']."] "; echo "".htmlencode($result[$i]['name'])."
"; $j++; } } 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 "
"; echo $token_html; echo ""; if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO'))) { echo ""; } echo ""; echo "
"; echo "
"; } echo "
"; echo "
"; echo $token_html; echo ""; echo "
"; echo "
"; echo "
"; echo '
'; //- HTML: breadcrumb navigation echo "".htmlencode($currentDB['name']).""; if ($target_table) echo " → ".htmlencode($target_table).""; echo "

"; //- HTML: confirmation panel //if the user has performed some action, show the resulting message if(isset($_GET['confirm'])) { echo "
"; echo "
"; if(isset($error) && $error) //an error occured during the action, so show an error message echo $lang['err'].": ".htmlencode($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 "
"; } //- 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 "".$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 //- HTML: tabs for views { echo "".$lang['browse'].""; echo "".$lang['struct'].""; echo "".$lang['sql'].""; echo "".$lang['srch'].""; echo "".$lang['export'].""; echo "".$lang['drop'].""; echo "
"; } } //- Switch on $_GET['action'] for operations with output if(isset($_GET['action']) && !isset($_GET['confirm'])) { echo "
"; switch($_GET['action']) { //- Table actions //- Create table (=table_create) case "table_create": $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($_POST['tablename'])."'

"; if($_POST['tablefields']=="" || intval($_POST['tablefields'])<=0) echo $lang['specify_fields']; else if($_POST['tablename']=="") echo $lang['specify_tbl']; else if($exists) echo $lang['tbl_exists']; else { $num = intval($_POST['tablefields']); $name = $_POST['tablename']; echo "
"; echo $token_html; echo ""; echo ""; echo ""; echo ""; $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 ""; for($i=0; $i<$num; $i++) { $tdWithClass = ""; echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; if($db->getType() != "SQLiteDatabase") { echo $tdWithClass; echo ""; echo ""; } echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; echo ""; echo ""; } echo ""; echo ""; echo ""; echo "
"; echo "
"; echo " "; echo "".$lang['cancel'].""; echo "
"; echo "
"; if($db->getType() != "SQLiteDatabase") echo ""; } break; //- Perform SQL query on table (=table_sql) case "table_sql": if(isset($_POST['query']) && $_POST['query']!="") { $delimiter = $_POST['delimiter']; $queryStr = $_POST['queryval']; //save the queries in history if necessary if($maxSavedQueries!=0 && $maxSavedQueries!=false) { 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 for($i=0; $iquery($query[$i]); echo "
"; echo "".htmlencode($query[$i]).""; if($table_result === NULL || $table_result === false) { echo "
".$lang['err'].": ".htmlencode($db->getError())."
"; } echo "

"; if($row = $db->fetch($table_result, 'assoc')) { $headers = array_keys($row); echo ""; echo ""; for($j=0; $j"; echo htmlencode($headers[$j]); echo ""; } echo ""; $rowCount = 0; for(; $rowCount==0 || $row = $db->fetch($table_result, 'assoc'); $rowCount++) { $tdWithClass = ""; for($z=0; $zNULL"; else echo htmlencode(subString($row[$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 { $delimiter = ";"; $queryStr = "SELECT * FROM ".$db->quote_id($target_table)." WHERE 1"; } echo "
"; echo "".sprintf($lang['run_sql'],htmlencode($db->getName())).""; echo "
"; echo $token_html; if(isset($_SESSION['query_history']) && sizeof($_SESSION['query_history'])>0) { echo "".$lang['recent_queries']."

"; } echo "
"; echo ""; echo "
"; echo "
"; echo $lang['fields']."
"; echo ""; echo ""; echo "
"; echo "
"; echo $lang['delimit']." "; echo ""; echo "
"; echo "
"; break; //- Empty table (=table_empty) case "table_empty": echo "
"; echo $token_html; 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 $token_html; 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 $token_html; 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 ""; echo $token_html; 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['help8'])."
"; echo " ".helpLink($lang['help9'])."
"; echo "
"; echo ""; echo "
"; echo "

"; echo "
".$lang['save_as'].""; $file = pathinfo($db->getPath()); $name = $file['filename']; echo " "; echo "
"; echo "
"; echo "
".sprintf($lang['backup_hint'], "".$lang["backup_hint_linktext"]."")."
"; break; //- Import table (=table_import) case "table_import": if(isset($_POST['import'])) { echo "
"; if($importSuccess===true) echo $lang['import_suc']; else echo $lang['err'].': '.htmlencode($importSuccess); echo "

"; } echo "
"; echo $token_html; 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 " "; echo "
"; break; //- Rename table (=table_rename) case "table_rename": echo ""; echo $token_html; echo ""; printf($lang['rename_tbl'], htmlencode($target_table)); echo " "; echo "
"; break; //- Search table (=table_search) case "table_search": $searchValues = array(); if(isset($_GET['done'])) { $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(array($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; $queryTimer = new MicroTimer(); $arr = $db->selectArray($query); $queryTimer->stop(); echo "
"; echo ""; if($arr!==false) { $affected = sizeof($arr); echo $lang['showing']." ".$affected." ".$lang['rows'].". "; printf($lang['query_time'], $queryTimer); echo "
"; } else { echo $lang['err'].": ".htmlencode($db->getError()).".
".$lang['bug_report'].' '.PROJECT_BUGTRACKER_LINK.'
'; } echo "".htmlencode($query_disp).""; echo "

"; 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 $token_html; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; for($i=0; $i"; $tdWithClassLeft = ""; echo $tdWithClassLeft; echo htmlencode($field); echo ""; echo $tdWithClassLeft; echo htmlencode($type); echo ""; echo $tdWithClassLeft; echo ""; echo ""; echo $tdWithClassLeft; if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") echo ""; else echo ""; echo ""; echo ""; } echo ""; echo ""; echo ""; echo "
".$lang['fld']."".$lang['type']."".$lang['operator']."".$lang['val']."
"; echo "
"; echo ""; echo "
"; echo "
"; } break; //- Row actions //- View row (=row_view) case "row_view": if(!isset($_POST['startRow'])) $_POST['startRow'] = 0; if(isset($_POST['numRows'])) $_SESSION[COOKIENAME.'numRows'] = intval($_POST['numRows']); if(!isset($_SESSION[COOKIENAME.'numRows'])) $_SESSION[COOKIENAME.'numRows'] = $rowsNum; if(isset($_GET['fulltexts'])) $_SESSION[COOKIENAME.'fulltexts'] = $_GET['fulltexts']; if(!isset($_SESSION[COOKIENAME.'fulltexts'])) $_SESSION[COOKIENAME.'fulltexts'] = false; if(isset($_SESSION[COOKIENAME.'currentTable']) && $_SESSION[COOKIENAME.'currentTable']!=$target_table) { unset($_SESSION[COOKIENAME.'sortRows']); unset($_SESSION[COOKIENAME.'orderRows']); } if(isset($_POST['viewtype'])) { $_SESSION[COOKIENAME.'viewtype'] = $_POST['viewtype']; } $rowCount = $db->numRows($target_table); $lastPage = intval($rowCount / $_SESSION[COOKIENAME.'numRows']); $remainder = intval($rowCount % $_SESSION[COOKIENAME.'numRows']); if($remainder==0) $remainder = $_SESSION[COOKIENAME.'numRows']; //- HTML: pagination buttons echo "
"; //previous button if($_POST['startRow']>0) { echo "
"; echo "
"; echo $token_html; echo ""; echo " "; echo " "; echo "
"; echo "
"; echo "
"; echo "
"; echo $token_html; echo ""; echo " "; echo " "; echo "
"; echo "
"; } //show certain number buttons echo "
"; echo "
"; echo $token_html; echo " "; echo " "; echo $lang['rows_records']; if(intval($_POST['startRow']+$_SESSION[COOKIENAME.'numRows']) < $rowCount) echo ""; else echo " "; echo $lang['as_a']; echo " "; echo "
"; echo "
"; //next button if(intval($_POST['startRow']+$_SESSION[COOKIENAME.'numRows'])<$rowCount) { echo "
"; echo "
"; echo $token_html; echo ""; echo " "; echo " "; echo "
"; echo "
"; echo "
"; echo "
"; echo $token_html; 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); $resultRows = $resultRows['count']; //- Show results if($resultRows>0) { $queryTimer = new MicroTimer(); $table_result = $db->query($query); $queryTimer->stop(); echo "
"; echo "".$lang['showing_rows']." ".$startRow." - ".($startRow + $resultRows-1).", ".$lang['total'].": ".$rowCount." "; printf($lang['query_time'], $queryTimer); echo "
"; echo "".htmlencode($queryDisp).""; echo "

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

"; } $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 "
"; echo $token_html; echo ""; echo ""; if($target_table_type == 'table') { echo ""; } for($i=0; $i"; 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); $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(); for($col = $pkFirstCol; array_key_exists($col, $row); $col=$col+2) { // in $col we have the type and in $col-1 the value if($row[$col]=='integer' || $row[$col]=='real') // json encode as int or float, not string $pk_arr[] = $row[$col-1]+0; else // encode as json string $pk_arr[] = $row[$col-1]; } $pk = json_encode($pk_arr); $tdWithClass = ""; 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 "".$lang['edit'].""; echo ""; echo $tdWithClass; echo "".$lang['del'].""; echo ""; } for($j=0; $jNULL"; else echo htmlencode(subString($row[$j])); echo ""; } echo ""; } echo "
"; echo ""; echo "&".($_SESSION[COOKIENAME.'fulltexts']?'r':'l')."arr; T &".($_SESSION[COOKIENAME.'fulltexts']?'l':'r')."arr;"; echo "
"; $tdWithClassLeft = ""; echo "
"; if($target_table_type == 'table') { echo "".$lang['chk_all']." / ".$lang['unchk_all']." ".$lang['with_sel'].": "; echo " "; echo ""; } echo "
"; } else //- Chart view { if(!isset($_SESSION[COOKIENAME.$target_table.'chartlabels'])) { // No label-column set. Try to pick a text-column as label-column. for($i=0; $i
Chart Settings"; echo "
"; echo $token_html; echo $lang['chart_type'].": "; echo "

"; echo $lang['lbl'].": "; echo "

"; echo $lang['val'].": "; echo "

"; echo ""; echo "
"; echo ""; echo "
"; //end chart view } } else if($rowCount>0)//no rows - do nothing { echo "

".$lang['no_rows']; } elseif($target_table_type == 'table') { echo "

".$lang['empty_tbl']." ".$lang['click']." ".$lang['insert_rows']; } break; //- Create new row (=row_create) case "row_create": $fieldStr = ""; echo "
"; echo $token_html; echo $lang['restart_insert']; echo " "; echo $lang['rows']; echo " "; echo "
"; echo "
"; $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; $result = $db->selectArray($query); echo "
"; echo $token_html; if(isset($_POST['num'])) $num = $_POST['num']; else $num = 1; echo ""; for($j=0; $j<$num; $j++) { if($j>0) echo "
"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; for($i=0; $i"; $tdWithClassLeft = ""; echo $tdWithClassLeft; echo htmlencode($field); echo ""; echo $tdWithClassLeft; echo htmlencode($type); echo ""; echo $tdWithClassLeft; echo ""; echo ""; //we need to have a column dedicated to nulls -di echo $tdWithClassLeft; if($result[$i]['notnull']==0) { if($result[$i]['dflt_value']==="NULL") echo ""; else 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 ""; else echo ""; echo ""; echo ""; } echo ""; echo ""; echo ""; echo "
".$lang['fld']."".$lang['type']."".$lang['func']."Null".$lang['val']."
"; echo "
"; echo ""; echo "

"; } $fieldStr = substr($fieldStr, 1); echo ""; echo "
"; break; //- Edit or delete row (=row_editordelete) case "row_editordelete": if(isset($_POST['check'])) $pks = $_POST['check']; else if(isset($_GET['pk'])) $pks = array($_GET['pk']); else $pks[0] = ""; $str = $pks[0]; for($i=1; $i"; echo $lang['err'].": ".$lang['no_sel']; echo ""; echo "

".$lang['return'].""; } else { if((isset($_POST['type']) && $_POST['type']=="edit") || (isset($_GET['type']) && $_GET['type']=="edit")) //edit { echo "
"; echo $token_html; $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); echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; for($i=0; $i"; $tdWithClassLeft = ""; echo $tdWithClass; echo htmlencode($field); echo ""; echo $tdWithClass; echo htmlencode($type); echo ""; echo $tdWithClassLeft; echo ""; echo ""; echo $tdWithClassLeft; if($result[$i][3]==0) { if($value===NULL) echo ""; else echo ""; } echo ""; echo $tdWithClassLeft; if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") echo ""; else echo ""; echo ""; echo ""; } echo ""; echo ""; echo ""; echo "
".$lang['fld']."".$lang['type']."".$lang['func']."Null".$lang['val']."
"; echo "
"; // 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 "".$lang['cancel'].""; echo "
"; echo "
"; } echo ""; } else //delete { echo "
"; echo $token_html; echo "
"; printf($lang['ques_del_rows'], htmlencode($str), htmlencode($target_table)); echo "

"; echo " "; echo "".$lang['cancel'].""; echo "
"; } } break; //- Column actions //- View table structure (=column_view) case "column_view": $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; $result = $db->selectArray($query); echo ""; echo $token_html; echo ""; echo ""; if($target_table_type == 'table') echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; $noPrimaryKey = true; for($i=0; $i"; $tdWithClassLeft = ""; if($target_table_type == 'table') { echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo "".$lang['edit'].""; echo ""; echo $tdWithClass; echo "".$lang['del'].""; echo ""; } echo $tdWithClass; echo htmlencode($colVal); echo ""; echo $tdWithClassLeft; echo htmlencode($fieldVal); echo ""; echo $tdWithClassLeft; echo htmlencode($typeVal); echo ""; echo $tdWithClassLeft; echo htmlencode($notnullVal); echo ""; echo $tdWithClassLeft; if($defaultVal===NULL) echo "".$lang['none'].""; elseif($defaultVal==="NULL") echo "NULL"; else echo htmlencode($defaultVal); echo ""; echo $tdWithClassLeft; echo htmlencode($primarykeyVal); echo ""; echo ""; } echo "
".$lang['col']." #".$lang['fld']."".$lang['type']."".$lang['not_null']."".$lang['def_val']."".$lang['prim_key']."
"; echo "
"; if($target_table_type == 'table') { echo "".$lang['chk_all']." / ".$lang['unchk_all']." ".$lang['with_sel'].": "; echo " "; echo ""; } echo "
"; if($target_table_type == 'table') { echo "
"; echo "
"; echo $token_html; 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 "".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) { echo "

".$lang['indexes'].":

"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; for($i=0; $iquote_id($result[$i]['name']).")"; $info = $db->selectArray($query); $span = sizeof($info); $tdWithClass = ""; echo $tdWithClassSpan; echo "".$lang['del'].""; echo ""; echo $tdWithClassLeftSpan; echo $result[$i]['name']; echo ""; echo $tdWithClassLeftSpan; echo $unique; echo ""; for($j=0; $j<$span; $j++) { if($j!=0) echo ""; echo $tdWithClassLeft; echo htmlencode($info[$j]['seqno']); echo ""; echo $tdWithClassLeft; echo htmlencode($info[$j]['cid']); echo ""; echo $tdWithClassLeft; echo htmlencode($info[$j]['name']); echo ""; echo ""; } } echo "
"; echo "".$lang['name']."".$lang['unique']."".$lang['seq_no']."".$lang['col']." #".$lang['fld']."
"; $tdWithClassLeft = ""; $tdWithClassSpan = ""; $tdWithClassLeftSpan = ""; 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); if(sizeof($result)>0) { echo "

".$lang['triggers'].":

"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; for($i=0; $i"; echo ""; echo $tdWithClass; echo "".$lang['del'].""; echo ""; echo $tdWithClass; echo htmlencode($result[$i]['name']); echo ""; echo $tdWithClass; echo htmlencode($result[$i]['sql']); echo ""; } echo "
"; echo "".$lang['name']."".$lang['sql']."


"; } echo "
"; echo $token_html; echo ""; echo "
"; echo $lang['create_index2']." ".$lang['cols']." "; echo "
"; echo "
"; echo "
"; echo $token_html; echo ""; echo "
"; echo $lang['create_trigger2']." "; echo "
"; echo "
"; } break; //- Create column (=column_create) case "column_create": echo "

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

"; if($_POST['tablefields']=="" || intval($_POST['tablefields'])<=0) echo $lang['specify_fields']; else if($_POST['tablename']=="") echo $lang['specify_tbl']; else { $num = intval($_POST['tablefields']); $name = $_POST['tablename']; echo "
"; echo $token_html; echo ""; echo ""; echo ""; echo ""; $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 ""; for($i=0; $i<$num; $i++) { $tdWithClass = ""; echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; if($db->getType() != "SQLiteDatabase") { echo $tdWithClass; echo ""; echo ""; } echo $tdWithClass; echo ""; echo ""; echo $tdWithClass; echo ""; echo ""; echo ""; echo ""; } echo ""; echo ""; echo ""; echo "
"; echo "
"; echo " "; echo "".$lang['cancel'].""; echo "
"; echo "
"; } break; //- Delete column (=column_confirm) case "column_confirm": 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 "

".$lang['return'].""; } else { $str = $pks[0]; $pkVal = $pks[0]; for($i=1; $i"; echo $token_html; echo "
"; printf($lang['ques_'.$_REQUEST['action2']], htmlencode($str), htmlencode($target_table)); echo "

"; echo " "; echo "".$lang['cancel'].""; echo "
"; } break; //- 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 { $query = "PRAGMA table_info(".$db->quote_id($target_table).")"; $result = $db->selectArray($query); for($i=0; $i"; echo $token_html; 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 "
"; echo $token_html; echo "
"; echo sprintf($lang['ques_del_index'], htmlencode($_GET['pk']))."

"; echo " "; echo "".$lang['cancel'].""; echo "
"; echo "
"; break; //- Delete trigger (=trigger_delete) case "trigger_delete": echo "
"; echo $token_html; echo "
"; echo sprintf($lang['ques_del_trigger'], htmlencode($_GET['pk']))."

"; echo " "; echo "".$lang['cancel'].""; echo "
"; echo "
"; break; //- Create trigger (=trigger_create) case "trigger_create": echo "

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

"; if($_POST['tablename']=="") echo $lang['specify_tbl']; else { echo "
"; echo $token_html; echo $lang['trigger_name'].":

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

"; echo $lang['event'].": "; echo ""; echo "


"; echo "
".$lang['trigger_act'].""; echo "

"; echo $lang['when_exp'].":
"; echo ""; echo "

"; echo $lang['trigger_step'].":
"; echo ""; echo "


"; echo " "; echo "".$lang['cancel'].""; echo "
"; } break; //- Create index (=index_create) case "index_create": echo "

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

"; if($_POST['numcolumns']=="" || intval($_POST['numcolumns'])<=0) echo $lang['specify_fields']; else if($_POST['tablename']=="") echo $lang['specify_tbl']; else { echo "
"; echo $token_html; $num = intval($_POST['numcolumns']); $query = "PRAGMA table_info(".$db->quote_id($_POST['tablename']).")"; $result = $db->selectArray($query); echo "
".$lang['define_index'].""; echo "
"; echo ""; echo "
"; if(version_compare($db->getSQLiteVersion(),'3.8.0')>=0) echo " ".helpLink($lang['help10']); echo "
"; echo "
"; echo "
".$lang['define_in_col'].""; for($i=0; $i<$num; $i++) { echo " "; echo "
"; } echo "
"; echo "

"; echo ""; echo " "; echo "".$lang['cancel'].""; echo "
"; } break; } echo ""; } $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 $lang['attention'].': '.$lang['directory_not_writable']; echo "

"; } 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 ($auth->isPasswordDefault()) { echo "
"; 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'].": ".$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['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(sizeof($result)==0) echo $lang['no_tbl']."

"; else { echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; $totalRecords = 0; $skippedTables = false; for($i=0; $inumRows($result[$i]['name'], (!isset($_GET['forceCount']))); if($records == '?') { $skippedTables = true; $records = "?"; } else $totalRecords += $records; $tdWithClass = ""; 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 ""; echo $tdWithClassLeft; echo $lang['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 "".$lang['type']." ".helpLink($lang['help3']); if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="type") echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " " : " "); echo ""; echo "".$lang['name'].""; if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="name") echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " " : " "); echo "".$lang['act']."".$lang['rec']."
"; $tdWithClassLeft = ""; if($result[$i]['type']=="table") { echo "
".sizeof($result)." ".$lang['total']."".$totalRecords.($skippedTables?" + ?":"")."
"; echo "
"; if($skippedTables) echo "
".sprintf($lang["counting_skipped"],"","")."
"; } echo "
"; echo "".$lang['create_tbl_db']." '".htmlencode($db->getName())."'"; echo "
"; echo $token_html; echo $lang['name'].": "; echo $lang['fld_num'].": "; echo ""; echo "
"; echo "
"; echo "
"; echo "
"; echo "".$lang['create_view']." '".htmlencode($db->getName())."'"; echo "
"; echo $token_html; echo $lang['name'].": "; echo $lang['sel_state']." ".helpLink($lang['help4']).": "; echo ""; echo "
"; echo "
"; } else if($view=="sql") { //- Database SQL editor (=sql) if(isset($_POST['query']) && $_POST['query']!="") { $delimiter = $_POST['delimiter']; $queryStr = $_POST['queryval']; //save the queries in history if necessary if($maxSavedQueries!=0 && $maxSavedQueries!=false) { 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 for($i=0; $iquery($query[$i]); echo "
"; echo "".htmlencode($query[$i]).""; if($table_result === NULL || $table_result === false) { echo "
".$lang['err'].": ".htmlencode($db->getError())."
"; } echo "

"; if($row = $db->fetch($table_result, 'assoc')) { $headers = array_keys($row); echo ""; echo ""; for($j=0; $j"; echo htmlencode($headers[$j]); echo ""; } echo ""; $rowCount = 0; for(; $rowCount==0 || $row = $db->fetch($table_result, 'assoc'); $rowCount++) { $tdWithClass = ""; for($z=0; $zNULL"; else echo htmlencode(subString($row[$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 { $delimiter = ";"; $queryStr = ""; } echo "
"; echo "".sprintf($lang['run_sql'],htmlencode($db->getName())).""; echo "
"; echo $token_html; if(isset($_SESSION['query_history']) && sizeof($_SESSION['query_history'])>0) { echo "".$lang['recent_queries']."

"; } echo ""; echo $lang['delimit']." "; echo ""; echo "
"; echo "
"; } else if($view=="vacuum") { //- Vacuum database confirmation (=vacuum) if(isset($_POST['vacuum'])) { $query = "VACUUM"; $db->query($query); echo "
"; printf($lang['db_vac'], htmlencode($db->getName())); echo "

"; } echo "
"; echo $token_html; printf($lang['vac_desc'],htmlencode($db->getName())); echo "

"; echo ""; echo "
"; } else if($view=="export") { //- Export view (=export) echo "
"; echo $token_html; echo "
".$lang['export'].""; echo ""; echo "

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

"; echo "
".$lang['save_as'].""; $file = pathinfo($db->getPath()); $name = $file['filename']; echo " "; echo "
"; echo "
"; echo "
".sprintf($lang['backup_hint'], "".$lang["backup_hint_linktext"]."")."
"; } else if($view=="import") { //- Import view (=import) if(isset($_POST['import'])) { echo "
"; if($importSuccess===true) echo $lang['import_suc']; else echo $importSuccess; echo "

"; } echo "
"; echo $token_html; echo "
".$lang['import'].""; echo ""; echo "
"; echo "
"; echo "
".$lang['options'].""; echo $lang['no_opt']; echo "
"; echo ""; echo "
"; echo "

"; echo "
".$lang['import_f'].""; echo " "; echo "
"; } else if($view=="rename") { //- Rename database confirmation (=rename) 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 $token_html; echo ""; echo $lang['db_rename']." '".htmlencode($db->getPath())."' ".$lang['to']." "; echo "
"; } else if($view=="delete") { //- Delete database confirmation (=delete) echo "
"; echo $token_html; echo "
"; echo sprintf($lang['ques_del_db'],htmlencode($db->getPath()))."

"; echo ""; echo " "; echo "".$lang['cancel'].""; 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 echo ""; echo ""; //- End of main code // Authorization class // Maintains user's logged-in state and security of application // class Authorization { private $authorized; private $login_failed; private $system_password_encrypted; public function __construct() { // the salt and password encrypting is probably unnecessary protection but is done just // for the sake of being very secure if(!isset($_SESSION[COOKIENAME.'_salt']) && !isset($_COOKIE[COOKIENAME.'_salt'])) { // create a random salt for this session if a cookie doesn't already exist for it $_SESSION[COOKIENAME.'_salt'] = self::generateSalt(20); } else if(!isset($_SESSION[COOKIENAME.'_salt']) && isset($_COOKIE[COOKIENAME.'_salt'])) { // session doesn't exist, but cookie does so grab it $_SESSION[COOKIENAME.'_salt'] = $_COOKIE[COOKIENAME.'_salt']; } // salted and encrypted password used for checking $this->system_password_encrypted = md5(SYSTEMPASSWORD."_".$_SESSION[COOKIENAME.'_salt']); $this->authorized = // no password SYSTEMPASSWORD == '' // correct password stored in session || isset($_SESSION[COOKIENAME.'password']) && $_SESSION[COOKIENAME.'password'] == $this->system_password_encrypted // correct password stored in cookie || isset($_COOKIE[COOKIENAME]) && isset($_COOKIE[COOKIENAME.'_salt']) && md5(SYSTEMPASSWORD."_".$_COOKIE[COOKIENAME.'_salt']) == $_COOKIE[COOKIENAME]; } public function attemptGrant($password, $remember) { if ($password == SYSTEMPASSWORD) { if ($remember) { // user wants to be remembered, so set a cookie $expire = time()+60*60*24*30; //set expiration to 1 month from now setcookie(COOKIENAME, $this->system_password_encrypted, $expire, null, null, null, true); setcookie(COOKIENAME."_salt", $_SESSION[COOKIENAME.'_salt'], $expire, null, null, null, true); } else { // user does not want to be remembered, so destroy any potential cookies setcookie(COOKIENAME, "", time()-86400, null, null, null, true); setcookie(COOKIENAME."_salt", "", time()-86400, null, null, null, true); unset($_COOKIE[COOKIENAME]); unset($_COOKIE[COOKIENAME.'_salt']); } $_SESSION[COOKIENAME.'password'] = $this->system_password_encrypted; $this->authorized = true; return true; } $this->login_failed = true; return false; } public function revoke() { //destroy everything - cookies and session vars setcookie(COOKIENAME, "", time()-86400, null, null, null, true); setcookie(COOKIENAME."_salt", "", time()-86400, null, null, null, true); unset($_COOKIE[COOKIENAME]); unset($_COOKIE[COOKIENAME.'_salt']); session_unset(); session_destroy(); $this->authorized = false; } public function isAuthorized() { return $this->authorized; } public function isFailedLogin() { return $this->login_failed; } public function isPasswordDefault() { return SYSTEMPASSWORD == 'admin'; } private static function generateSalt($saltSize) { $set = 'ABCDEFGHiJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $setLast = strlen($set) - 1; $salt = ''; while ($saltSize-- > 0) { $salt .= $set[mt_rand(0, $setLast)]; } return $salt; } } // Database class // Generic database abstraction class to manage interaction with database without worrying about SQLite vs. PHP versions // class Database { protected $db; //reference to the DB object protected $type; //the extension for PHP that handles SQLite protected $data; protected $lastResult; protected $alterError; public function __construct($data) { global $lang; $this->data = $data; try { if(!file_exists($this->data["path"]) && !is_writable(dirname($this->data["path"]))) //make sure the containing directory is writable if the database does not exist { echo "
"; printf($lang['db_not_writeable'], htmlencode($this->data["path"]), htmlencode(dirname($this->data["path"]))); echo "
"; echo ''; echo ""; echo "
"; echo "

"; exit(); } $ver = $this->getVersion(); switch(true) { case ((!isset($data['type']) || $data['type']!=2) && (FORCETYPE=="PDO" || (FORCETYPE==false && class_exists("PDO") && in_array("sqlite", PDO::getAvailableDrivers()) && ($ver==-1 || $ver==3)))): $this->db = new PDO("sqlite:".$this->data['path']); if($this->db!=NULL) { $this->type = "PDO"; break; } case ((!isset($data['type']) || $data['type']!=2) && (FORCETYPE=="SQLite3" || (FORCETYPE==false && class_exists("SQLite3") && ($ver==-1 || $ver==3)))): $this->db = new SQLite3($this->data['path']); if($this->db!=NULL) { $this->type = "SQLite3"; break; } case (FORCETYPE=="SQLiteDatabase" || (FORCETYPE==false && class_exists("SQLiteDatabase") && ($ver==-1 || $ver==2))): $this->db = new SQLiteDatabase($this->data['path']); if($this->db!=NULL) { $this->type = "SQLiteDatabase"; break; } default: $this->showError(); exit(); } $this->query("PRAGMA foreign_keys = ON"); } catch(Exception $e) { $this->showError(); exit(); } } public function registerUserFunction($ids) { // in case a single function id was passed if (is_string($ids)) $ids = array($ids); if ($this->type == 'PDO') { foreach ($ids as $id) { $this->db->sqliteCreateFunction($id, $id, 1); } } else { // type is Sqlite3 or SQLiteDatabase foreach ($ids as $id) { $this->db->createFunction($id, $id, 1); } } } public function getError() { if($this->alterError!='') { $error = $this->alterError; $this->alterError = ""; return $error; } else if($this->type=="PDO") { $e = $this->db->errorInfo(); return $e[2]; } else if($this->type=="SQLite3") { return $this->db->lastErrorMsg(); } else { return sqlite_error_string($this->db->lastError()); } } public function showError() { global $lang; $classPDO = class_exists("PDO"); $classSQLite3 = class_exists("SQLite3"); $classSQLiteDatabase = class_exists("SQLiteDatabase"); if($classPDO) // PDO is there, check if the SQLite driver for PDO is missing $PDOSqliteDriver = (in_array("sqlite", PDO::getAvailableDrivers() )); else $PDOSqliteDriver = false; echo "
"; printf($lang['db_setup'], $this->getPath()); echo ".

".$lang['chk_ext']."...

"; echo "PDO: ".($classPDO ? $lang['installed'] : $lang['not_installed'])."
"; echo "PDO SQLite Driver: ".($PDOSqliteDriver ? $lang['installed'] : $lang['not_installed'])."
"; echo "SQLite3: ".($classSQLite3 ? $lang['installed'] : $lang['not_installed'])."
"; echo "SQLiteDatabase: ".($classSQLiteDatabase ? $lang['installed'] : $lang['not_installed'])."
"; echo "
...".$lang['done'].".


"; if(!$classPDO && !$classSQLite3 && !$classSQLiteDatabase) printf($lang['sqlite_ext_support'], PROJECT); else { if(!$PDOSqliteDriver && !$classSQLite3 && $this->getVersion()==3) printf($lang['sqlite_v_error'], 3, PROJECT, 2); else if(!$classSQLiteDatabase && $this->getVersion()==2) printf($lang['sqlite_v_error'], 2, PROJECT, 3); else echo $lang['report_issue'].' '.PROJECT_BUGTRACKER_LINK.'.'; } echo "

See ".PROJECT_INSTALL_LINK." for help.

"; $this->print_db_list(); echo "
"; } // print the list of databases public function print_db_list() { global $databases, $lang; echo "
".$lang['db_ch'].""; if(sizeof($databases)<10) //if there aren't a lot of databases, just show them as a list of links instead of drop down menu { $i=0; foreach($databases as $database) { $i++; $name = $database['name']; if(mb_strlen($name)>25) $name = "...".mb_substr($name, mb_strlen($name)-22, 22); echo '[' . ($database['readable'] ? 'r':' ' ) . ($database['writable'] && $database['writable_dir'] ? 'w':' ' ) . '] '; if($database == $_SESSION[COOKIENAME.'currentDB']) echo "".htmlencode($name)."  [↓]"; else echo "".htmlencode($name)."  [↓]"; if($i"; } } else //there are a lot of databases - show a drop down menu { echo "
"; echo ''; echo " "; echo ""; echo "
"; } echo "
"; } public function __destruct() { if($this->db) $this->close(); } //get the exact PHP extension being used for SQLite public function getType() { return $this->type; } // get the version of the SQLite library public function getSQLiteVersion() { $queryVersion = $this->select("SELECT sqlite_version() AS sqlite_version"); return $queryVersion['sqlite_version']; } //get the name of the database public function getName() { return $this->data["name"]; } //get the filename of the database public function getPath() { return $this->data["path"]; } //is the db-file writable? public function isWritable() { return $this->data["writable"]; } //is the db-folder writable? public function isDirWritable() { return $this->data["writable_dir"]; } //get the version of the database public function getVersion() { if(file_exists($this->data['path'])) //make sure file exists before getting its contents { $content = strtolower(file_get_contents($this->data['path'], NULL, NULL, 0, 40)); //get the first 40 characters of the database file $p = strpos($content, "** this file contains an sqlite 2"); //this text is at the beginning of every SQLite2 database if($p!==false) //the text is found - this is version 2 return 2; else return 3; } else //return -1 to indicate that it does not exist and needs to be created { return -1; } } //get the size of the database (in KB) public function getSize() { return round(filesize($this->data["path"])*0.0009765625, 1); } //get the last modified time of database public function getDate() { global $lang; return date($lang['date_format'], filemtime($this->data['path'])); } //get number of affected rows from last query public function getAffectedRows() { if($this->type=="PDO") if(!is_object($this->lastResult)) // in case it was an alter table statement, there is no lastResult object return 0; else return $this->lastResult->rowCount(); else if($this->type=="SQLite3") return $this->db->changes(); else if($this->type=="SQLiteDatabase") return $this->db->changes(); } public function getTypeOfTable($table) { $result = $this->select("SELECT `type` FROM `sqlite_master` WHERE `name`=" . $this->quote($table), 'assoc'); return $result['type']; } public function close() { if($this->type=="PDO") $this->db = NULL; else if($this->type=="SQLite3") $this->db->close(); else if($this->type=="SQLiteDatabase") $this->db = NULL; } public function beginTransaction() { $this->query("BEGIN"); } public function commitTransaction() { $this->query("COMMIT"); } public function rollbackTransaction() { $this->query("ROLLBACK"); } //generic query wrapper //returns false on error and the query result on success public function query($query, $ignoreAlterCase=false) { global $debug; if(strtolower(substr(ltrim($query),0,5))=='alter' && $ignoreAlterCase==false) //this query is an ALTER query - call the necessary function { preg_match("/^\s*ALTER\s+TABLE\s+\"((?:[^\"]|\"\")+)\"\s+(.*)$/i",$query,$matches); if(!isset($matches[1]) || !isset($matches[2])) { if($debug) echo "SQL?
"; return false; } $tablename = str_replace('""','"',$matches[1]); $alterdefs = $matches[2]; if($debug) echo "ALTER TABLE QUERY=(".htmlencode($query)."), tablename=($tablename), alterdefs=($alterdefs)
"; $result = $this->alterTable($tablename, $alterdefs); } else //this query is normal - proceed as normal { $result = $this->db->query($query); if($debug) echo "SQL?
"; } if($result===false) return false; $this->lastResult = $result; return $result; } //wrapper for an INSERT and returns the ID of the inserted row public function insert($query) { $result = $this->query($query); if($this->type=="PDO") return $this->db->lastInsertId(); else if($this->type=="SQLite3") return $this->db->lastInsertRowID(); else if($this->type=="SQLiteDatabase") return $this->db->lastInsertRowid(); } //returns an array for SELECT public function select($query, $mode="both") { $result = $this->query($query); if(!$result) //make sure the result is valid return NULL; if($this->type=="PDO") { if($mode=="assoc") $mode = PDO::FETCH_ASSOC; else if($mode=="num") $mode = PDO::FETCH_NUM; else $mode = PDO::FETCH_BOTH; return $result->fetch($mode); } else if($this->type=="SQLite3") { if($mode=="assoc") $mode = SQLITE3_ASSOC; else if($mode=="num") $mode = SQLITE3_NUM; else $mode = SQLITE3_BOTH; return $result->fetchArray($mode); } else if($this->type=="SQLiteDatabase") { if($mode=="assoc") $mode = SQLITE_ASSOC; else if($mode=="num") $mode = SQLITE_NUM; else $mode = SQLITE_BOTH; return $result->fetch($mode); } } //returns an array of arrays after doing a SELECT public function selectArray($query, $mode="both") { $result = $this->query($query); //make sure the result is valid if($result=== false || $result===NULL) return NULL; // error if(!is_object($result)) // no rows returned return array(); if($this->type=="PDO") { if($mode=="assoc") $mode = PDO::FETCH_ASSOC; else if($mode=="num") $mode = PDO::FETCH_NUM; else $mode = PDO::FETCH_BOTH; return $result->fetchAll($mode); } else if($this->type=="SQLite3") { if($mode=="assoc") $mode = SQLITE3_ASSOC; else if($mode=="num") $mode = SQLITE3_NUM; else $mode = SQLITE3_BOTH; $arr = array(); $i = 0; while($res = $result->fetchArray($mode)) { $arr[$i] = $res; $i++; } return $arr; } else if($this->type=="SQLiteDatabase") { if($mode=="assoc") $mode = SQLITE_ASSOC; else if($mode=="num") $mode = SQLITE_NUM; else $mode = SQLITE_BOTH; return $result->fetchAll($mode); } } //returns an array of the next row in $result public function fetch($result, $mode="both") { //make sure the result is valid if($result=== false || $result===NULL) return NULL; // error if(!is_object($result)) // no rows returned return array(); if($this->type=="PDO") { if($mode=="assoc") $mode = PDO::FETCH_ASSOC; else if($mode=="num") $mode = PDO::FETCH_NUM; else $mode = PDO::FETCH_BOTH; return $result->fetch($mode); } else if($this->type=="SQLite3") { if($mode=="assoc") $mode = SQLITE3_ASSOC; else if($mode=="num") $mode = SQLITE3_NUM; else $mode = SQLITE3_BOTH; return $result->fetchArray($mode); } else if($this->type=="SQLiteDatabase") { if($mode=="assoc") $mode = SQLITE_ASSOC; else if($mode=="num") $mode = SQLITE_NUM; else $mode = SQLITE_BOTH; return $result->fetch($mode); } } // SQlite supports multiple ways of surrounding names in quotes: // single-quotes, double-quotes, backticks, square brackets. // As sqlite does not keep this strict, we also need to be flexible here. // This function generates a regex that matches any of the possibilities. private function sqlite_surroundings_preg($name,$preg_quote=true,$notAllowedCharsIfNone="'\"",$notAllowedName=false) { if($name=="*" || $name=="+") { if($notAllowedName!==false && $preg_quote) $notAllowedName = preg_quote($notAllowedName,"/"); // use possesive quantifiers to save memory // (There is a bug in PCRE starting in 8.13 and fixed in PCRE 8.36 // why we can't use posesive quantifiers - See issue #310). if(version_compare(strstr(constant('PCRE_VERSION'), ' ', true), '8.36', '>=') || version_compare(strstr(constant('PCRE_VERSION'), ' ', true), '8.12', '<=')) $posessive='+'; else $posessive=''; $nameSingle = ($notAllowedName!==false?"(?!".$notAllowedName."')":"")."(?:[^']$name+|'')$name".$posessive; $nameDouble = ($notAllowedName!==false?"(?!".$notAllowedName."\")":"")."(?:[^\"]$name+|\"\")$name".$posessive; $nameBacktick = ($notAllowedName!==false?"(?!".$notAllowedName."`)":"")."(?:[^`]$name+|``)$name".$posessive; $nameSquare = ($notAllowedName!==false?"(?!".$notAllowedName."\])":"")."(?:[^\]]$name+|\]\])$name".$posessive; $nameNo = ($notAllowedName!==false?"(?!".$notAllowedName."\s)":"")."[^".$notAllowedCharsIfNone."]$name"; } else { if($preg_quote) $name = preg_quote($name,"/"); $nameSingle = str_replace("'","''",$name); $nameDouble = str_replace('"','""',$name); $nameBacktick = str_replace('`','``',$name); $nameSquare = str_replace(']',']]',$name); $nameNo = $name; } $preg = "(?:'".$nameSingle."'|". // single-quote surrounded or not in quotes (correct SQL for values/new names) $nameNo."|". // not surrounded (correct SQL if not containing reserved words, spaces or some special chars) "\"".$nameDouble."\"|". // double-quote surrounded (correct SQL for identifiers) "`".$nameBacktick."`|". // backtick surrounded (MySQL-Style) "\[".$nameSquare."\])"; // square-bracket surrounded (MS Access/SQL server-Style) return $preg; } // Returns the last PREG error as a string, '' if no error occured private function getPregError() { $error = preg_last_error(); switch ($error) { case PREG_NO_ERROR: return 'No error'; case PREG_INTERNAL_ERROR: return 'There is an internal error!'; case PREG_BACKTRACK_LIMIT_ERROR: return 'Backtrack limit was exhausted!'; case PREG_RECURSION_LIMIT_ERROR: return 'Recursion limit was exhausted!'; case PREG_BAD_UTF8_ERROR: return 'Bad UTF8 error!'; // PREG_BAD_UTF8_OFFSET_ERROR is introduced in PHP 5.3.0, which is not yet required by PLA, so we use its value 5 instead so long case 5: return 'Bad UTF8 offset error!'; default: return 'Unknown Error'; } } // function that is called for an alter table statement in a query // code borrowed with permission from http://code.jenseng.com/db/ // this has been completely debugged / rewritten by Christopher Kramer public function alterTable($table, $alterdefs) { global $debug, $lang; $this->alterError=""; $errormsg = sprintf($lang['alter_failed'],htmlencode($table)).' - '; if($debug) echo "ALTER TABLE: table=($table), alterdefs=($alterdefs), PCRE version=(".PCRE_VERSION.")

"; if($alterdefs != '') { $recreateQueries = array(); $resultArr = $this->selectArray("SELECT sql,name,type FROM sqlite_master WHERE tbl_name = ".$this->quote($table)); if(sizeof($resultArr)<1) { $this->alterError = $errormsg . sprintf($lang['tbl_inexistent'], htmlencode($table)); if($debug) echo "ERROR: unknown table

"; return false; } for($i=0; $i"; } } else { // ALTER the table $tmpname = 't'.time(); $origsql = $row['sql']; $preg_remove_create_table = "/^\s*+CREATE\s++TABLE\s++".$this->sqlite_surroundings_preg($table)."\s*+(\(.*+)$/is"; $origsql_no_create = preg_replace($preg_remove_create_table, '$1', $origsql, 1); if($debug) echo "origsql=($origsql)
preg_remove_create_table=($preg_remove_create_table)
"; if($origsql_no_create == $origsql) { $this->alterError = $errormsg . $lang['alter_tbl_name_not_replacable']; if($debug) echo "ERROR: could not get rid of CREATE TABLE
"; return false; } $createtemptableSQL = "CREATE TABLE ".$this->quote($tmpname)." ".$origsql_no_create; if($debug) echo "createtemptableSQL=($createtemptableSQL)
"; $createindexsql = array(); $preg_alter_part = "/(?:DROP(?! PRIMARY KEY)|ADD(?! PRIMARY KEY)|CHANGE|RENAME TO|ADD PRIMARY KEY|DROP PRIMARY KEY)" // the ALTER command ."(?:" ."\s+\(".$this->sqlite_surroundings_preg("+",false,"\"'\[`)")."+\)" // stuff in brackets (in case of ADD PRIMARY KEY) ."|" // or ."\s+".$this->sqlite_surroundings_preg("+",false,",'\"\[`") // column names and stuff like this .")*/i"; if($debug) echo "preg_alter_part=(".$preg_alter_part.")
"; preg_match_all($preg_alter_part,$alterdefs,$matches); $defs = $matches[0]; $get_oldcols_query = "PRAGMA table_info(".$this->quote_id($table).")"; $result_oldcols = $this->selectArray($get_oldcols_query); $newcols = array(); $coltypes = array(); $primarykey = array(); foreach($result_oldcols as $column_info) { $newcols[$column_info['name']] = $column_info['name']; $coltypes[$column_info['name']] = $column_info['type']; if($column_info['pk']) $primarykey[] = $column_info['name']; } $newcolumns = ''; $oldcolumns = ''; reset($newcols); while(list($key, $val) = each($newcols)) { $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val); $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key); } $copytotempsql = 'INSERT INTO '.$this->quote_id($tmpname).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($table); $dropoldsql = 'DROP TABLE '.$this->quote_id($table); $createtesttableSQL = $createtemptableSQL; if(count($defs)<1) { $this->alterError = $errormsg . $lang['alter_no_def']; if($debug) echo "ERROR: defs<1

"; return false; } foreach($defs as $def) { if($debug) echo "
def=$def
"; $preg_parse_def = "/^(DROP(?! PRIMARY KEY)|ADD(?! PRIMARY KEY)|CHANGE|RENAME TO|ADD PRIMARY KEY|DROP PRIMARY KEY)" // $matches[1]: command ."(?:" // this is either ."(?:\s+\((.+)\)\s*$)" // anything in brackets (for ADD PRIMARY KEY) // then $matches[2] is what there is in brackets ."|" // OR: ."(?:\s+\"((?:[^\"]|\"\")+)\"|\s+'((?:[^']|'')+)')"// (first) column name, either in single or double quotes // in case of RENAME TO, it is the new a table name // $matches[3] will be the column/table name without the quotes if double quoted // $matches[4] will be the column/table name without the quotes if single quoted ."(" // $matches[5]: anything after the column name ."(?:\s+'((?:[^']|'')+)')?" // $matches[6] (optional): a second column name surrounded with single quotes // (the match does not contain the quotes) ."\s+" ."((?:[A-Z]+\s*)+(?:\(\s*[+-]?\s*[0-9]+(?:\s*,\s*[+-]?\s*[0-9]+)?\s*\))?)\s*" // $matches[7]: a type name .".*". ")" ."?\s*$" .")?\s*$/i"; // in case of DROP PRIMARY KEY, there is nothing after the command if($debug) echo "preg_parse_def=$preg_parse_def
"; $parse_def = preg_match($preg_parse_def,$def,$matches); if($parse_def===false) { $this->alterError = $errormsg . $lang['alter_parse_failed']; if($debug) echo "ERROR: !parse_def

"; return false; } if(!isset($matches[1])) { $this->alterError = $errormsg . $lang['alter_action_not_recognized']; if($debug) echo "ERROR: !isset(matches[1])

"; return false; } $action = strtolower($matches[1]); if(($action == 'add' || $action == 'rename to') && isset($matches[4]) && $matches[4]!='') $column = str_replace("''","'",$matches[4]); // enclosed in '' elseif($action == 'add primary key' && isset($matches[2]) && $matches[2]!='') $column = $matches[2]; elseif($action == 'drop primary key') $column = ''; // DROP PRIMARY KEY has no column definition elseif(isset($matches[3]) && $matches[3]!='') $column = str_replace('""','"',$matches[3]); // enclosed in "" else $column = ''; $column_escaped = str_replace("'","''",$column); if($debug) echo "action=($action), column=($column), column_escaped=($column_escaped)
"; /* we build a regex that devides the CREATE TABLE statement parts: Part example Group Explanation 1. CREATE TABLE t... ( $1 2. 'col1' ..., 'col2' ..., 'colN' ..., $3 (with col1-colN being columns that are not changed and listed before the col to change) 3. 'colX' ..., (with colX being the column to change/drop) 4. 'colX+1' ..., ..., 'colK') $5 (with colX+1-colK being columns after the column to change/drop) */ $preg_create_table = "\s*+(CREATE\s++TABLE\s++".preg_quote($this->quote($tmpname),"/")."\s*+\()"; // This is group $1 (keep unchanged) $preg_column_definiton = "\s*+".$this->sqlite_surroundings_preg("+",true," '\"\[`,",$column)."(?:\s*+".$this->sqlite_surroundings_preg("*",false,"'\",`\[ ").")++"; // catches a complete column definition, even if it is // 'column' TEXT NOT NULL DEFAULT 'we have a comma, here and a double ''quote!' // this definition does NOT match columns with the column name $column if($debug) echo "preg_column_definition=(".$preg_column_definiton.")
"; $preg_columns_before = // columns before the one changed/dropped (keep) "(?:". "(". // group $2. Keep this one unchanged! "(?:". "$preg_column_definiton,\s*+". // column definition + comma ")*". // there might be any number of such columns here $preg_column_definiton. // last column definition ")". // end of group $2 ",\s*+" // the last comma of the last column before the column to change. Do not keep it! .")?"; // there might be no columns before if($debug) echo "preg_columns_before=(".$preg_columns_before.")
"; $preg_columns_after = "(,\s*(.+))?"; // the columns after the column to drop. This is group $3 (drop) or $4(change) (keep!) // we could remove the comma using $6 instead of $5, but then we might have no comma at all. // Keeping it leaves a problem if we drop the first column, so we fix that case in another regex. $table_new = $table; switch($action) { case 'add': if($column=='') { $this->alterError = $errormsg . ' (add) - '. $lang['alter_no_add_col']; return false; } $new_col_definition = "'$column_escaped' ".(isset($matches[5])?$matches[5]:''); $preg_pattern_add = "/^".$preg_create_table. // the CREATE TABLE statement ($1) "((?:(?!,\s*(?:PRIMARY\s+KEY\s*\(|CONSTRAINT\s|UNIQUE\s*\(|CHECK\s*\(|FOREIGN\s+KEY\s*\()).)*)". // column definitions ($2) "(.*)\\)\s*$/si"; // table-constraints like PRIMARY KEY(a,b) ($3) and the closing bracket // append the column definiton in the CREATE TABLE statement $newSQL = preg_replace($preg_pattern_add, '$1$2, '.strtr($new_col_definition, array('\\' => '\\\\', '$' => '\$')).' $3', $createtesttableSQL).')'; $preg_error = $this->getPregError(); if($debug) { echo $createtesttableSQL."

"; echo $newSQL."

"; echo $preg_pattern_add."

"; } if($newSQL==$createtesttableSQL) // pattern did not match, so column adding did not succed { $this->alterError = $errormsg . ' (add) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error; return false; } $createtesttableSQL = $newSQL; break; case 'change': if(!isset($matches[6]) || !isset($matches[7])) { $this->alterError = $errormsg . ' (change) - '.$lang['alter_col_not_recognized']; return false; } $new_col_name = $matches[6]; $new_col_type = $matches[7]; $new_col_definition = "'$new_col_name' $new_col_type"; $preg_column_to_change = "\s*".$this->sqlite_surroundings_preg($column)."(?:\s+".preg_quote($coltypes[$column]).")?(\s+(?:".$this->sqlite_surroundings_preg("*",false,",'\"`\[").")+)?"; // replace this part (we want to change this column) // group $3 contains the column constraints (keep!). the name & data type is replaced. $preg_pattern_change = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_change.$preg_columns_after."\s*\\)\s*$/s"; // replace the column definiton in the CREATE TABLE statement $newSQL = preg_replace($preg_pattern_change, '$1$2,'.strtr($new_col_definition, array('\\' => '\\\\', '$' => '\$')).'$3$4)', $createtesttableSQL); $preg_error = $this->getPregError(); // remove comma at the beginning if the first column is changed // probably somebody is able to put this into the first regex (using lookahead probably). $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL); if($debug) { echo "preg_column_to_change=(".$preg_column_to_change.")

"; echo $createtesttableSQL."

"; echo $newSQL."

"; echo $preg_pattern_change."

"; } if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed { $this->alterError = $errormsg . ' (change) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error; return false; } $createtesttableSQL = $newSQL; $newcols[$column] = str_replace("''","'",$new_col_name); break; case 'drop': $preg_column_to_drop = "\s*".$this->sqlite_surroundings_preg($column)."\s+(?:".$this->sqlite_surroundings_preg("*",false,",'\"\[`").")+"; // delete this part (we want to drop this column) $preg_pattern_drop = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_drop.$preg_columns_after."\s*\\)\s*$/s"; // remove the column out of the CREATE TABLE statement $newSQL = preg_replace($preg_pattern_drop, '$1$2$3)', $createtesttableSQL); $preg_error = $this->getPregError(); // remove comma at the beginning if the first column is removed // probably somebody is able to put this into the first regex (using lookahead probably). $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL); if($debug) { echo $createtesttableSQL."

"; echo $newSQL."

"; echo $preg_pattern_drop."

"; } if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed { $this->alterError = $errormsg . ' (drop) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error; return false; } $createtesttableSQL = $newSQL; unset($newcols[$column]); break; case 'rename to': // don't change column definition at all $newSQL = $createtesttableSQL; // only change the name of the table $table_new = $column; break; case 'add primary key': // we want to add a primary key for the column(s) stored in $column $newSQL = preg_replace("/\)\s*$/", ", PRIMARY KEY (".$column.") )", $createtesttableSQL); $createtesttableSQL = $newSQL; break; case 'drop primary key': // we want to drop the primary key if($debug) echo "DROP"; if(sizeof($primarykey)==1) { // if not compound primary key, might be a column constraint -> try removal $column = $primarykey[0]; if($debug) echo "
Trying to drop column constraint for column $column
"; /* TODO: This does not work yet: CREATE TABLE 't12' ('t1' INTEGER CONSTRAINT "bla" NOT NULL CONSTRAINT 'pk' PRIMARY KEY ); ALTER TABLE "t12" DROP PRIMARY KEY This does: ! ! CREATE TABLE 't12' ('t1' INTEGER CONSTRAINT bla NOT NULL CONSTRAINT 'pk' PRIMARY KEY ); ALTER TABLE "t12" DROP PRIMARY KEY */ $preg_column_to_change = "(\s*".$this->sqlite_surroundings_preg($column).")". // column ($3) "(?:". // opt. type and column constraints "(\s+(?:".$this->sqlite_surroundings_preg("(?:[^PC,'\"`\[]|P(?!RIMARY\s+KEY)|". "C(?!ONSTRAINT\s+".$this->sqlite_surroundings_preg("+",false," ,'\"\[`")."\s+PRIMARY\s+KEY))",false,",'\"`\[").")*)". // column constraints before PRIMARY KEY ($3) // primary key constraint (remove this!): "(?:CONSTRAINT\s+".$this->sqlite_surroundings_preg("+",false," ,'\"\[`")."\s+)?". "PRIMARY\s+KEY". "(?:\s+(?:ASC|DESC))?". "(?:\s+ON\s+CONFLICT\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?". "(?:\s+AUTOINCREMENT)?". "((?:".$this->sqlite_surroundings_preg("*",false,",'\"`\[").")*)". // column constraints after PRIMARY KEY ($4) ")"; // replace this part (we want to change this column) // group $3 (column) $4 (constraints before) and $5 (constraints after) contain the part to keep $preg_pattern_change = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_change.$preg_columns_after."\s*\\)\s*$/si"; // replace the column definiton in the CREATE TABLE statement $newSQL = preg_replace($preg_pattern_change, '$1$2,$3$4$5$6)', $createtesttableSQL); // remove comma at the beginning if the first column is changed // probably somebody is able to put this into the first regex (using lookahead probably). $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL); if($debug) { echo "preg_column_to_change=(".$preg_column_to_change.")

"; echo $createtesttableSQL."

"; echo $newSQL."

"; echo $preg_pattern_change."

"; } if($newSQL!=$createtesttableSQL && $newSQL!="") // pattern did match, so PRIMARY KEY constraint removed :) { $createtesttableSQL = $newSQL; if($debug) echo "
SUCCEEDED
"; } else { if($debug) echo "NO LUCK"; // TODO: try removing table constraint return false; } $createtesttableSQL = $newSQL; } else // TODO: Try removing table constraint return false; break; default: if($debug) echo 'ERROR: unknown alter operation!

'; $this->alterError = $errormsg . $lang['alter_unknown_operation']; return false; } } $droptempsql = 'DROP TABLE '.$this->quote_id($tmpname); $createnewtableSQL = "CREATE TABLE ".$this->quote($table_new)." ".preg_replace("/^\s*CREATE\s+TABLE\s+'?".str_replace("'","''",preg_quote($tmpname,"/"))."'?\s+(.*)$/is", '$1', $createtesttableSQL, 1); $newcolumns = ''; $oldcolumns = ''; reset($newcols); while(list($key,$val) = each($newcols)) { $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val); $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key); } $copytonewsql = 'INSERT INTO '.$this->quote_id($table_new).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($tmpname); } } $alter_transaction = 'BEGIN; '; $alter_transaction .= $createtemptableSQL.'; '; //create temp table $alter_transaction .= $copytotempsql.'; '; //copy to table $alter_transaction .= $dropoldsql.'; '; //drop old table $alter_transaction .= $createnewtableSQL.'; '; //recreate original table $alter_transaction .= $copytonewsql.'; '; //copy back to original table $alter_transaction .= $droptempsql.'; '; //drop temp table $preg_index="/^\s*(CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*ON\s+)(".$this->sqlite_surroundings_preg($table).")(\s*\((?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*\)\s*)\s*$/i"; foreach($recreateQueries as $recreate_query) { if($recreate_query['type']=='index') { // this is an index. We need to make sure the index is not on a column that we drop. If it is, we drop the index as well. $indexInfos = $this->selectArray('PRAGMA index_info('.$this->quote_id($recreate_query['name']).')'); foreach($indexInfos as $indexInfo) { if(!isset($newcols[$indexInfo['name']])) { if($debug) echo 'Not recreating the following index:

'.htmlencode($recreate_query['sql']).'

'; // Index on a column that was dropped. Skip recreation. continue 2; } } } // TODO: In case we renamed a column on which there is an index, we need to recreate the index with the column name adjusted. // recreate triggers / indexes if($table == $table_new) { // we had no RENAME TO, so we can recreate indexes/triggers just like the original ones $alter_transaction .= $recreate_query['sql'].';'; } else { // we had a RENAME TO, so we need to exchange the table-name in the CREATE-SQL of triggers & indexes switch ($recreate_query['type']) { case 'index': $recreate_queryIndex = preg_replace($preg_index, '$1'.$this->quote_id(strtr($table_new, array('\\' => '\\\\', '$' => '\$'))).'$3 ', $recreate_query['sql']); if($recreate_queryIndex!=$recreate_query['sql'] && $recreate_queryIndex != NULL) $alter_transaction .= $recreate_queryIndex.';'; else { // the CREATE INDEX regex did not match. this normally should not happen if($debug) echo 'ERROR: CREATE INDEX regex did not match!?

'; // just try to recreate the index originally (will fail most likely) $alter_transaction .= $recreate_query['sql'].';'; } break; case 'trigger': // TODO: IMPLEMENT $alter_transaction .= $recreate_query['sql'].';'; break; default: if($debug) echo 'ERROR: Unknown type '.htmlencode($recreate_query['type']).'

'; $alter_transaction .= $recreate_query['sql'].';'; } } } $alter_transaction .= 'COMMIT;'; if($debug) echo $alter_transaction; return $this->multiQuery($alter_transaction); } } //multiple query execution //returns true on success, false otherwise. Use getError() to fetch the error. public function multiQuery($query) { if($this->type=="PDO") $success = $this->db->exec($query); else if($this->type=="SQLite3") $success = $this->db->exec($query); else $success = $this->db->queryExec($query, $error); return $success; } // checks whether a table has a primary key public function hasPrimaryKey($table) { $query = "PRAGMA table_info(".$this->quote_id($table).")"; $table_info = $this->selectArray($query); foreach($table_info as $row_id => $row_data) { if($row_data['pk']) { return true; } } return false; } // Returns an array of columns by which rows can be uniquely adressed. // For tables with a rowid column, this is always array('rowid') // for tables without rowid, this is an array of the primary key columns. public function getPrimaryKey($table) { $primary_key = array(); // check if this table has a rowid $getRowID = $this->select('SELECT ROWID FROM '.$this->quote_id($table).' LIMIT 0,1'); if(isset($getRowID[0])) // it has, so we prefer addressing rows by rowid return array('rowid'); else { // the table is without rowid, so use the primary key $query = "PRAGMA table_info(".$this->quote_id($table).")"; $table_info = $this->selectArray($query); foreach($table_info as $row_id => $row_data) { if($row_data['pk']) $primary_key[] = $row_data['name']; } } return $primary_key; } // selects a row by a given key $pk, which is an array of values // for the columns by which a row can be adressed (rowid or primary key) public function wherePK($table, $pk) { $where = ""; $primary_key = $this->getPrimaryKey($table); foreach($primary_key as $pk_index => $column) { if($where!="") $where .= " AND "; $where .= $this->quote_id($column) . ' = '; if(is_int($pk[$pk_index]) || is_float($pk[$pk_index])) $where .= $pk[$pk_index]; else $where .= $this->quote($pk[$pk_index]); } return $where; } //get number of rows in table public function numRows($table, $dontTakeLong = false) { // as Count(*) can be slow on huge tables without PK, // if $dontTakeLong is set and the size is > 2MB only count() if there is a PK if(!$dontTakeLong || $this->getSize() <= 2000 || $this->hasPrimaryKey($table)) { $result = $this->select("SELECT Count(*) FROM ".$this->quote_id($table)); return $result[0]; } else { return '?'; } } //correctly escape a string to be injected into an SQL query public function quote($value) { if($this->type=="PDO") { // PDO quote() escapes and adds quotes return $this->db->quote($value); } else if($this->type=="SQLite3") { return "'".$this->db->escapeString($value)."'"; } else { return "'".sqlite_escape_string($value)."'"; } } //correctly escape an identifier (column / table / trigger / index name) to be injected into an SQL query public function quote_id($value) { // double-quotes need to be escaped by doubling them $value = str_replace('"','""',$value); return '"'.$value.'"'; } //import sql //returns true on success, error message otherwise public function import_sql($query) { $this->beginTransaction(); $import = $this->multiQuery($query); if(!$import) { $this->rollbackTransaction(); return $this->getError(); }else{ $this->commitTransaction(); return true; } } //import csv //returns true on success, error message otherwise public function import_csv($filename, $table, $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row) { // CSV import implemented by Christopher Kramer - http://www.christosoft.de $csv_handle = fopen($filename,'r'); $csv_insert = "BEGIN;\n"; $csv_number_of_rows = 0; // PHP requires enclosure defined, but has no problem if it was not used if($field_enclosed=="") $field_enclosed='"'; // PHP requires escaper defined if($field_escaped=="") $field_escaped='\\'; while($csv_handle!==false && !feof($csv_handle)) { $csv_data = fgetcsv($csv_handle, 0, $field_terminate, $field_enclosed, $field_escaped); if($csv_data[0] != NULL || count($csv_data)>1) { $csv_number_of_rows++; if($fields_in_first_row && $csv_number_of_rows==1) { $fields_in_first_row = false; continue; } $csv_col_number = count($csv_data); $csv_insert .= "INSERT INTO ".$this->quote_id($table)." VALUES ("; foreach($csv_data as $csv_col => $csv_cell) { if($csv_cell == $null) $csv_insert .= "NULL"; else { $csv_insert.= $this->quote($csv_cell); } if($csv_col == $csv_col_number-2 && $csv_data[$csv_col+1]=='') { // the CSV row ends with the separator (like old phpliteadmin exported) break; } if($csv_col < $csv_col_number-1) $csv_insert .= ","; } $csv_insert .= ");\n"; if($csv_number_of_rows > 5000) { $csv_insert .= "COMMIT;\nBEGIN;\n"; $csv_number_of_rows = 0; } } } if($csv_handle === false) return "Error reading CSV file"; else { $csv_insert .= "COMMIT;"; fclose($csv_handle); $this->beginTransaction(); $import = $this->multiQuery($csv_insert); if(!$import) { $this->rollbackTransaction(); return $this->getError(); }else{ $this->commitTransaction(); return true; } } } //export csv public function export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row) { @set_time_limit(-1); $query = "SELECT * FROM sqlite_master WHERE type='table' or type='view' ORDER BY type DESC"; $result = $this->selectArray($query); for($i=0; $iquote_id($result[$i]['tbl_name']).")"; $temp = $this->selectArray($query); $cols = array(); for($z=0; $zquote_id($result[$i]['tbl_name']); $table_result = $this->query($query); $firstRow=true; while($row = $this->fetch($table_result, "assoc")) { if(!$firstRow) echo "\r\n"; else $firstRow=false; for($y=0; $ygetPath()."\r\n"; echo "----\r\n"; } $query = "SELECT * FROM sqlite_master WHERE type='table' OR type='index' OR type='view' OR type='trigger' ORDER BY type='trigger', type='index', type='view', type='table'"; $result = $this->selectArray($query); if($transaction) echo "BEGIN TRANSACTION;\r\n"; //iterate through each table for($i=0; $iquote_id($result[$i]['name']).";\r\n"; } if($structure) { if($comments) { echo "\r\n----\r\n"; if($result[$i]['type']=="table" || $result[$i]['type']=="view") echo "-- ".ucfirst($result[$i]['type'])." ".$lang['struct_for']." ".$result[$i]['tbl_name']."\r\n"; else // index or trigger echo "-- ".$lang['struct_for']." ".$result[$i]['type']." ".$result[$i]['name']." ".$lang['on_tbl']." ".$result[$i]['tbl_name']."\r\n"; echo "----\r\n"; } echo $result[$i]['sql'].";\r\n"; } if($data && $result[$i]['type']=="table") { $query = "SELECT * FROM ".$this->quote_id($result[$i]['tbl_name']); $table_result = $this->query($query, "assoc"); if($comments) { $numRows = $this->numRows($result[$i]['tbl_name']); echo "\r\n----\r\n"; echo "-- ".$lang['data_dump']." ".$result[$i]['tbl_name'].", ".sprintf($lang['total_rows'], $numRows)."\r\n"; echo "----\r\n"; } $query = "PRAGMA table_info(".$this->quote_id($result[$i]['tbl_name']).")"; $temp = $this->selectArray($query); $cols = array(); $cols_quoted = array(); for($z=0; $zquote_id($temp[$z][1]); } while($row = $this->fetch($table_result)) { $vals = array(); for($y=0; $yquote($row[$cols[$y]]); } echo "INSERT INTO ".$this->quote_id($result[$i]['tbl_name'])." (".implode(",", $cols_quoted).") VALUES (".implode(",", $vals).");\r\n"; } } } } if($transaction) echo "COMMIT;\r\n"; } } // class Resources (issue #157) // outputs secondary files, such as css and javascript // data is stored gzipped (gzencode) and encoded (base64_encode) // class Resources { // set this to the file containing getInternalResource; // currently unused in split mode; set to __FILE__ for built PLA. public static $embedding_file = __FILE__; private static $_resources = array( 'css' => array( 'mime' => 'text/css', 'data' => 'resources/phpliteadmin.css', ), 'javascript' => array( 'mime' => 'text/javascript', 'data' => 'resources/phpliteadmin.js', ), 'favicon' => array( 'mime' => 'image/x-icon', 'data' => 'resources/favicon.ico', 'base64' => 'true', ), ); // outputs the specified resource, if defined in this class. // the main script should do no further output after calling this function. public static function output($resource) { if (isset(self::$_resources[$resource])) { $res =& self::$_resources[$resource]; if (function_exists('getInternalResource') && $data = getInternalResource($res['data'])) { $filename = self::$embedding_file; } else { $filename = $res['data']; } // use last-modified time as etag; etag must be quoted $etag = '"' . filemtime($filename) . '"'; // check headers for matching etag; if etag hasn't changed, use the cached version if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header('HTTP/1.0 304 Not Modified'); return; } header('Etag: ' . $etag); // cache file for at most 30 days header('Cache-control: max-age=2592000'); // output resource header('Content-type: ' . $res['mime']); if (isset($data)) { if (isset($res['base64'])) { echo base64_decode($data); } else { echo $data; } } else { readfile($filename); } } } } // returns data from internal resources, available in single-file mode function getInternalResource($res) { $resources = array('resources/phpliteadmin.css'=>array(0=>0,1=>4047,),'resources/phpliteadmin.js'=>array(0=>4047,1=>4169,),'resources/favicon.ico'=>array(0=>8216,1=>1448,),); if (isset($resources[$res]) && $f = fopen(__FILE__, 'r')) { fseek($f, __COMPILER_HALT_OFFSET__ + $resources[$res][0]); $data = fread($f, $resources[$res][1]); fclose($f); return $data; } return false; } // resources embedded below, do not edit! __halt_compiler() ?>body{margin:0px;padding:0px;font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#000;background-color:#e0ebf6;overflow:auto}.body_tbl td{padding:9px 2px 9px 9px}.left_td{width:100px}a{color:#03F;text-decoration:none;cursor:pointer}a:hover{color:#06F}hr{height:1px;border:0;color:#bbb;background-color:#bbb;width:100%}h1{margin:0px;padding:5px;font-size:24px;background-color:#f3cece;text-align:center;color:#000;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}#headerlinks{text-align:center;margin-bottom:10px;padding:5px 15px;border-color:#03F;border-width:1px;border-style:solid;border-left-style:none;border-right-style:none;font-size:12px;background-color:#e0ebf6;font-weight:bold}h1 #version{color:#000;font-size:16px}h1 #logo{color:#000}h2{margin:0px;padding:0px;font-size:14px;margin-bottom:20px}input,select,textarea{font-family:Arial,Helvetica,sans-serif;background-color:#eaeaea;color:#03F;border-color:#03F;border-style:solid;border-width:1px;margin:5px;border-radius:5px;-moz-border-radius:5px;padding:3px}input.btn{cursor:pointer}input.btn:hover{background-color:#ccc}fieldset label{min-width:200px;display:block;float:left}fieldset{padding:15px;border-color:#03F;border-width:1px;border-style:solid;border-radius:5px;-moz-border-radius:5px;background-color:#f9f9f9}#container{padding:10px}#leftNav{min-width:250px;padding:0px;border-color:#03F;border-width:1px;border-style:solid;background-color:#FFF;padding-bottom:15px;border-radius:5px;-moz-border-radius:5px}.databaseList select{max-width:200px}.viewTable tr td{padding:1px}#loginBox{width:500px;margin-left:auto;margin-right:auto;margin-top:50px;border-color:#03F;border-width:1px;border-style:solid;background-color:#FFF;border-radius:5px;-moz-border-radius:5px}#main{border-color:#03F;border-width:1px;border-style:solid;padding:15px;background-color:#FFF;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top-right-radius:5px;-moz-border-radius-bottomleft:5px;-moz-border-radius-bottomright:5px;-moz-border-radius-topright:5px}.td1{background-color:#f9e3e3;text-align:right;font-size:12px;padding-left:10px;padding-right:10px}.td2{background-color:#f3cece;text-align:right;font-size:12px;padding-left:10px;padding-right:10px}.tdheader{border-color:#03F;border-width:1px;border-style:solid;font-weight:bold;font-size:12px;padding-left:10px;padding-right:10px;background-color:#e0ebf6;border-radius:5px;-moz-border-radius:5px}.confirm{border-color:#03F;border-width:1px;border-style:dashed;padding:15px;background-color:#e0ebf6}.tab{display:block;padding:5px;padding-right:8px;padding-left:8px;border-color:#03F;border-width:1px;border-style:solid;margin-right:5px;float:left;border-bottom-style:none;position:relative;top:1px;padding-bottom:4px;background-color:#eaeaea;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}.tab_pressed{display:block;padding:5px;padding-right:8px;padding-left:8px;border-color:#03F;border-width:1px;border-style:solid;margin-right:5px;float:left;border-bottom-style:none;position:relative;top:1px;background-color:#FFF;cursor:default;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}.helpq{font-size:11px;font-weight:normal}#help_container{padding:0px;font-size:12px;margin-left:auto;margin-right:auto;background-color:#fff}.help_outer{background-color:#FFF;padding:0px;height:300px;position:relative}.help_list{padding:10px;height:auto}.headd{font-size:14px;font-weight:bold;display:block;padding:10px;background-color:#e0ebf6;border-color:#03F;border-width:1px;border-style:solid;border-left-style:none;border-right-style:none}.help_inner{padding:10px}.help_top{display:block;position:absolute;right:10px;bottom:10px}.warning,.delete,.empty,.drop,.delete_db{color:red}.sidebar_table{font-size:11px}.active_table,.active_db{text-decoration:underline}.null{color:#888}.found{background:#FF0;text-decoration:none} function initAutoincrement() {var i=0;while(document.getElementById('i'+i+'_autoincrement')!=undefined) {document.getElementById('i'+i+'_autoincrement').disabled=true;i++;}} function toggleAutoincrement(i) {var type=document.getElementById('i'+i+'_type');var primarykey=document.getElementById('i'+i+'_primarykey');var autoincrement=document.getElementById('i'+i+'_autoincrement');if(!autoincrement)return false;if(type.value=='INTEGER'&&primarykey.checked) autoincrement.disabled=false;else {autoincrement.disabled=true;autoincrement.checked=false;}} function toggleNull(i) {var pk=document.getElementById('i'+i+'_primarykey');var notnull=document.getElementById('i'+i+'_notnull');if(pk.checked) {notnull.disabled=true;notnull.checked=true;} else {notnull.disabled=false;}} function checkAll(field) {var i=0;while(document.getElementById('check_'+i)!=undefined) {document.getElementById('check_'+i).checked=true;i++;}} function uncheckAll(field) {var i=0;while(document.getElementById('check_'+i)!=undefined) {document.getElementById('check_'+i).checked=false;i++;}} function changeIgnore(area,e,u) {if(area.value!="") {if(document.getElementById(e)!=undefined) document.getElementById(e).checked=false;if(document.getElementById(u)!=undefined) document.getElementById(u).checked=false;}} function moveFields() {var fields=document.getElementById("fieldcontainer");var selected=[];for(var i=0;i