6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
26 function main($id, $mode)
28 global $cache, $db, $user, $auth, $template, $table_prefix;
29 global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;
31 $user->add_lang('acp/database');
33 $this->tpl_name = 'acp_database';
34 $this->page_title = 'ACP_DATABASE';
36 $action = request_var('action', '');
37 $submit = (isset($_POST['submit'])) ? true : false;
39 $template->assign_vars(array(
47 $this->page_title = 'ACP_BACKUP';
52 $type = request_var('type', '');
53 $table = request_var('table', array(''));
54 $format = request_var('method', '');
55 $where = request_var('where', '');
59 trigger_error($user->lang['TABLE_SELECT_ERROR'] . adm_back_link($this->u_action), E_USER_WARNING);
62 $store = $download = $structure = $schema_data = false;
64 if ($where == 'store_and_download' || $where == 'store')
69 if ($where == 'store_and_download' || $where == 'download')
74 if ($type == 'full' || $type == 'structure')
79 if ($type == 'full' || $type == 'data')
84 @set_time_limit(1200);
89 $filename = 'backup_' . $time . '_' . unique_id();
90 switch ($db->sql_layer)
95 $extractor = new mysql_extractor($download, $store, $format, $filename, $time);
99 $extractor = new sqlite_extractor($download, $store, $format, $filename, $time);
103 $extractor = new postgres_extractor($download, $store, $format, $filename, $time);
107 $extractor = new oracle_extractor($download, $store, $format, $filename, $time);
113 $extractor = new mssql_extractor($download, $store, $format, $filename, $time);
117 $extractor = new firebird_extractor($download, $store, $format, $filename, $time);
121 $extractor->write_start($table_prefix);
123 foreach ($table as $table_name)
125 // Get the table structure
128 $extractor->write_table($table_name);
132 // We might wanna empty out all that junk :D
133 switch ($db->sql_layer)
137 $extractor->flush('DELETE FROM ' . $table_name . ";\n");
143 $extractor->flush('TRUNCATE TABLE ' . $table_name . "GO\n");
147 $extractor->flush('TRUNCATE TABLE ' . $table_name . "/\n");
151 $extractor->flush('TRUNCATE TABLE ' . $table_name . ";\n");
159 $extractor->write_data($table_name);
163 $extractor->write_end();
165 add_log('admin', 'LOG_DB_BACKUP');
167 if ($download == true)
172 trigger_error($user->lang['BACKUP_SUCCESS'] . adm_back_link($this->u_action));
176 include($phpbb_root_path . 'includes/functions_install.' . $phpEx);
177 $tables = get_tables($db);
179 foreach ($tables as $table_name)
181 if (strlen($table_prefix) === 0 || stripos($table_name, $table_prefix) === 0)
183 $template->assign_block_vars('tables', array(
184 'TABLE' => $table_name
190 $template->assign_vars(array(
191 'U_ACTION' => $this->u_action . '&action=download'
194 $available_methods = array('gzip' => 'zlib', 'bzip2' => 'bz2');
196 foreach ($available_methods as $type => $module)
198 if (!@extension_loaded($module))
203 $template->assign_block_vars('methods', array(
208 $template->assign_block_vars('methods', array(
217 $this->page_title = 'ACP_RESTORE';
222 $delete = request_var('delete', '');
223 $file = request_var('file', '');
224 $download = request_var('download', '');
226 if (!preg_match('#^backup_\d{10,}_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches))
228 trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING);
231 $file_name = $phpbb_root_path . 'store/' . $matches[0];
233 if (!file_exists($file_name) || !is_readable($file_name))
235 trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING);
240 if (confirm_box(true))
243 add_log('admin', 'LOG_DB_DELETE');
244 trigger_error($user->lang['BACKUP_DELETE'] . adm_back_link($this->u_action));
248 confirm_box(false, $user->lang['DELETE_SELECTED_BACKUP'], build_hidden_fields(array('delete' => $delete, 'file' => $file)));
251 else if ($download || confirm_box(true))
260 $mimetype = 'text/x-sql';
263 $mimetype = 'application/x-bzip2';
266 $mimetype = 'application/x-gzip';
270 header('Pragma: no-cache');
271 header("Content-Type: $mimetype; name=\"$name\"");
272 header("Content-disposition: attachment; filename=$name");
276 $fp = @fopen($file_name, 'rb');
282 echo fread($fp, 8192);
294 $fp = fopen($file_name, 'rb');
303 $fp = bzopen($file_name, 'r');
308 $fgetd = 'fgetd_seekless';
312 $fp = gzopen($file_name, 'rb');
321 switch ($db->sql_layer)
327 while (($sql = $fgetd($fp, ";\n", $read, $seek, $eof)) !== false)
329 $db->sql_query($sql);
335 while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false)
338 if (substr($query, 0, 8) === 'SET TERM')
340 $delim = $query[9] . "\n";
343 $db->sql_query($query);
349 while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false)
353 if (substr($query, 0, 13) == 'CREATE DOMAIN')
355 list(, , $domain) = explode(' ', $query);
356 $sql = "SELECT domain_name
357 FROM information_schema.domains
358 WHERE domain_name = '$domain';";
359 $result = $db->sql_query($sql);
360 if (!$db->sql_fetchrow($result))
362 $db->sql_query($query);
364 $db->sql_freeresult($result);
368 $db->sql_query($query);
371 if (substr($query, 0, 4) == 'COPY')
373 while (($sub = $fgetd($fp, "\n", $read, $seek, $eof)) !== '\.')
377 trigger_error($user->lang['RESTORE_FAILURE'] . adm_back_link($this->u_action), E_USER_WARNING);
379 pg_put_line($db->db_connect_id, $sub . "\n");
381 pg_put_line($db->db_connect_id, "\\.\n");
382 pg_end_copy($db->db_connect_id);
388 while (($sql = $fgetd($fp, "/\n", $read, $seek, $eof)) !== false)
390 $db->sql_query($sql);
397 while (($sql = $fgetd($fp, "GO\n", $read, $seek, $eof)) !== false)
399 $db->sql_query($sql);
406 // Purge the cache due to updated data
409 add_log('admin', 'LOG_DB_RESTORE');
410 trigger_error($user->lang['RESTORE_SUCCESS'] . adm_back_link($this->u_action));
415 confirm_box(false, $user->lang['RESTORE_SELECTED_BACKUP'], build_hidden_fields(array('file' => $file)));
419 $methods = array('sql');
420 $available_methods = array('sql.gz' => 'zlib', 'sql.bz2' => 'bz2');
422 foreach ($available_methods as $type => $module)
424 if (!@extension_loaded($module))
431 $dir = $phpbb_root_path . 'store/';
432 $dh = @opendir($dir);
434 $backup_files = array();
438 while (($file = readdir($dh)) !== false)
440 if (preg_match('#^backup_(\d{10,})_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches))
442 if (in_array($matches[2], $methods))
444 $backup_files[(int) $matches[1]] = $file;
451 if (!empty($backup_files))
453 krsort($backup_files);
455 foreach ($backup_files as $name => $file)
457 $template->assign_block_vars('files', array(
459 'NAME' => $user->format_date($name, 'd-m-Y H:i:s', true),
465 $template->assign_vars(array(
466 'U_ACTION' => $this->u_action . '&action=submit'
488 var $run_comp = false;
490 function base_extractor($download = false, $store = false, $format, $filename, $time)
492 $this->download = $download;
493 $this->store = $store;
495 $this->format = $format;
502 $this->write = 'fwrite';
503 $this->close = 'fclose';
504 $mimetype = 'text/x-sql';
509 $this->write = 'bzwrite';
510 $this->close = 'bzclose';
511 $mimetype = 'application/x-bzip2';
516 $this->write = 'gzwrite';
517 $this->close = 'gzclose';
518 $mimetype = 'application/x-gzip';
522 if ($download == true)
524 $name = $filename . $ext;
525 header('Pragma: no-cache');
526 header("Content-Type: $mimetype; name=\"$name\"");
527 header("Content-disposition: attachment; filename=$name");
536 if ((isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'msie') === false)
538 ob_start('ob_gzhandler');
542 $this->run_comp = true;
550 global $phpbb_root_path;
551 $file = $phpbb_root_path . 'store/' . $filename . $ext;
553 $this->fp = $open($file, 'w');
557 trigger_error('FILE_WRITE_FAIL', E_USER_ERROR);
570 $close = $this->close;
575 // bzip2 must be written all the way at the end
576 if ($this->download && $this->format === 'bzip2')
583 function flush($data)
586 if ($this->store === true)
590 $write = $this->write;
592 $write($this->fp, $data);
595 if ($this->download === true)
597 if ($this->format === 'bzip2' || $this->format === 'text' || ($this->format === 'gzip' && !$this->run_comp))
602 // we can write the gzip data as soon as we get it
603 if ($this->format === 'gzip')
607 echo gzencode($data);
622 class mysql_extractor extends base_extractor
624 function write_start($table_prefix)
627 $sql_data .= "# phpBB Backup Script\n";
628 $sql_data .= "# Dump of tables for $table_prefix\n";
629 $sql_data .= "# DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
631 $this->flush($sql_data);
634 function write_table($table_name)
639 if ($new_extract === null)
641 if ($db->sql_layer === 'mysqli' || version_compare($db->sql_server_info(true), '3.23.20', '>='))
647 $new_extract = false;
653 $this->new_write_table($table_name);
657 $this->old_write_table($table_name);
661 function write_data($table_name)
664 if ($db->sql_layer === 'mysqli')
666 $this->write_data_mysqli($table_name);
670 $this->write_data_mysql($table_name);
674 function write_data_mysqli($table_name)
679 $result = mysqli_query($db->db_connect_id, $sql, MYSQLI_USE_RESULT);
680 if ($result != false)
682 $fields_cnt = mysqli_num_fields($result);
684 // Get field information
685 $field = mysqli_fetch_fields($result);
686 $field_set = array();
688 for ($j = 0; $j < $fields_cnt; $j++)
690 $field_set[] = $field[$j]->name;
693 $search = array("\\", "'", "\x00", "\x0a", "\x0d", "\x1a", '"');
694 $replace = array("\\\\", "\\'", '\0', '\n', '\r', '\Z', '\\"');
695 $fields = implode(', ', $field_set);
696 $sql_data = 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES ';
699 $max_len = get_usable_memory();
701 while ($row = mysqli_fetch_row($result))
706 $query = $sql_data . '(';
713 for ($j = 0; $j < $fields_cnt; $j++)
715 if (!isset($row[$j]) || is_null($row[$j]))
717 $values[$j] = 'NULL';
719 else if (($field[$j]->flags & 32768) && !($field[$j]->flags & 1024))
721 $values[$j] = $row[$j];
725 $values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
728 $query .= implode(', ', $values) . ')';
730 $query_len += strlen($query);
731 if ($query_len > $max_len)
733 $this->flush($query . ";\n\n");
743 mysqli_free_result($result);
745 // check to make sure we have nothing left to flush
746 if (!$first_set && $query)
748 $this->flush($query . ";\n\n");
753 function write_data_mysql($table_name)
758 $result = mysql_unbuffered_query($sql, $db->db_connect_id);
760 if ($result != false)
762 $fields_cnt = mysql_num_fields($result);
764 // Get field information
766 for ($i = 0; $i < $fields_cnt; $i++)
768 $field[] = mysql_fetch_field($result, $i);
770 $field_set = array();
772 for ($j = 0; $j < $fields_cnt; $j++)
774 $field_set[] = $field[$j]->name;
777 $search = array("\\", "'", "\x00", "\x0a", "\x0d", "\x1a", '"');
778 $replace = array("\\\\", "\\'", '\0', '\n', '\r', '\Z', '\\"');
779 $fields = implode(', ', $field_set);
780 $sql_data = 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES ';
783 $max_len = get_usable_memory();
785 while ($row = mysql_fetch_row($result))
790 $query = $sql_data . '(';
797 for ($j = 0; $j < $fields_cnt; $j++)
799 if (!isset($row[$j]) || is_null($row[$j]))
801 $values[$j] = 'NULL';
803 else if ($field[$j]->numeric && ($field[$j]->type !== 'timestamp'))
805 $values[$j] = $row[$j];
809 $values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
812 $query .= implode(', ', $values) . ')';
814 $query_len += strlen($query);
815 if ($query_len > $max_len)
817 $this->flush($query . ";\n\n");
827 mysql_free_result($result);
829 // check to make sure we have nothing left to flush
830 if (!$first_set && $query)
832 $this->flush($query . ";\n\n");
837 function new_write_table($table_name)
841 $sql = 'SHOW CREATE TABLE ' . $table_name;
842 $result = $db->sql_query($sql);
843 $row = $db->sql_fetchrow($result);
845 $sql_data = '# Table: ' . $table_name . "\n";
846 $sql_data .= "DROP TABLE IF EXISTS $table_name;\n";
847 $this->flush($sql_data . $row['Create Table'] . ";\n\n");
849 $db->sql_freeresult($result);
852 function old_write_table($table_name)
856 $sql_data = '# Table: ' . $table_name . "\n";
857 $sql_data .= "DROP TABLE IF EXISTS $table_name;\n";
858 $sql_data .= "CREATE TABLE $table_name(\n";
863 $result = $db->sql_query($sql);
865 while ($row = $db->sql_fetchrow($result))
867 $line = ' ' . $row['Field'] . ' ' . $row['Type'];
869 if (!is_null($row['Default']))
871 $line .= " DEFAULT '{$row['Default']}'";
874 if ($row['Null'] != 'YES')
876 $line .= ' NOT NULL';
879 if ($row['Extra'] != '')
881 $line .= ' ' . $row['Extra'];
886 $db->sql_freeresult($result);
891 $result = $db->sql_query($sql);
894 while ($row = $db->sql_fetchrow($result))
896 $kname = $row['Key_name'];
898 if ($kname != 'PRIMARY')
900 if ($row['Non_unique'] == 0)
902 $kname = "UNIQUE|$kname";
906 if ($row['Sub_part'])
908 $row['Column_name'] .= '(' . $row['Sub_part'] . ')';
910 $index[$kname][] = $row['Column_name'];
912 $db->sql_freeresult($result);
914 foreach ($index as $key => $columns)
918 if ($key == 'PRIMARY')
920 $line .= 'PRIMARY KEY (' . implode(', ', $columns) . ')';
922 else if (strpos($key, 'UNIQUE') === 0)
924 $line .= 'UNIQUE ' . substr($key, 7) . ' (' . implode(', ', $columns) . ')';
926 else if (strpos($key, 'FULLTEXT') === 0)
928 $line .= 'FULLTEXT ' . substr($key, 9) . ' (' . implode(', ', $columns) . ')';
932 $line .= "KEY $key (" . implode(', ', $columns) . ')';
938 $sql_data .= implode(",\n", $rows);
939 $sql_data .= "\n);\n\n";
941 $this->flush($sql_data);
948 class sqlite_extractor extends base_extractor
950 function write_start($prefix)
953 $sql_data .= "-- phpBB Backup Script\n";
954 $sql_data .= "-- Dump of tables for $prefix\n";
955 $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
957 $sql_data .= "BEGIN TRANSACTION;\n";
958 $this->flush($sql_data);
961 function write_table($table_name)
964 $sql_data = '-- Table: ' . $table_name . "\n";
965 $sql_data .= "DROP TABLE $table_name;\n";
970 AND name = '" . $db->sql_escape($table_name) . "'
971 ORDER BY type DESC, name;";
972 $result = $db->sql_query($sql);
973 $row = $db->sql_fetchrow($result);
974 $db->sql_freeresult($result);
977 $sql_data .= $row['sql'] . ";\n";
979 $result = $db->sql_query("PRAGMA index_list('" . $db->sql_escape($table_name) . "');");
982 while ($row = $db->sql_fetchrow($result))
986 $db->sql_freeresult($result);
988 foreach ($ar as $value)
990 if (strpos($value['name'], 'autoindex') !== false)
995 $result = $db->sql_query("PRAGMA index_info('" . $db->sql_escape($value['name']) . "');");
998 while ($row = $db->sql_fetchrow($result))
1000 $fields[] = $row['name'];
1002 $db->sql_freeresult($result);
1004 $sql_data .= 'CREATE ' . ($value['unique'] ? 'UNIQUE ' : '') . 'INDEX ' . $value['name'] . ' on ' . $table_name . ' (' . implode(', ', $fields) . ");\n";
1007 $this->flush($sql_data . "\n");
1010 function write_data($table_name)
1015 if (is_null($proper))
1017 $proper = version_compare(PHP_VERSION, '5.1.3', '>=');
1022 $col_types = sqlite_fetch_column_types($db->db_connect_id, $table_name);
1028 WHERE type = 'table'
1029 AND name = '" . $table_name . "'";
1030 $table_data = sqlite_single_query($db->db_connect_id, $sql);
1031 $table_data = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', '', $table_data);
1032 $table_data = trim($table_data);
1034 preg_match('#\((.*)\)#s', $table_data, $matches);
1036 $table_cols = explode(',', trim($matches[1]));
1037 foreach ($table_cols as $declaration)
1039 $entities = preg_split('#\s+#', trim($declaration));
1040 $column_name = preg_replace('/"?([^"]+)"?/', '\1', $entities[0]);
1042 // Hit a primary key, those are not what we need :D
1043 if (empty($entities[1]) || (strtolower($entities[0]) === 'primary' && strtolower($entities[1]) === 'key'))
1047 $col_types[$column_name] = $entities[1];
1053 $result = sqlite_unbuffered_query($db->db_connect_id, $sql);
1054 $rows = sqlite_fetch_all($result, SQLITE_ASSOC);
1055 $sql_insert = 'INSERT INTO ' . $table_name . ' (' . implode(', ', array_keys($col_types)) . ') VALUES (';
1056 foreach ($rows as $row)
1058 foreach ($row as $column_name => $column_data)
1060 if (is_null($column_data))
1062 $row[$column_name] = 'NULL';
1064 else if ($column_data == '')
1066 $row[$column_name] = "''";
1068 else if (strpos($col_types[$column_name], 'text') !== false || strpos($col_types[$column_name], 'char') !== false || strpos($col_types[$column_name], 'blob') !== false)
1070 $row[$column_name] = sanitize_data_generic(str_replace("'", "''", $column_data));
1073 $this->flush($sql_insert . implode(', ', $row) . ");\n");
1077 function write_end()
1079 $this->flush("COMMIT;\n");
1080 parent::write_end();
1087 class postgres_extractor extends base_extractor
1089 function write_start($prefix)
1092 $sql_data .= "-- phpBB Backup Script\n";
1093 $sql_data .= "-- Dump of tables for $prefix\n";
1094 $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
1095 $sql_data .= "--\n";
1096 $sql_data .= "BEGIN TRANSACTION;\n";
1097 $this->flush($sql_data);
1100 function write_table($table_name)
1103 static $domains_created = array();
1105 $sql = "SELECT a.domain_name, a.data_type, a.character_maximum_length, a.domain_default
1106 FROM INFORMATION_SCHEMA.domains a, INFORMATION_SCHEMA.column_domain_usage b
1107 WHERE a.domain_name = b.domain_name
1108 AND b.table_name = '{$table_name}'";
1109 $result = $db->sql_query($sql);
1110 while ($row = $db->sql_fetchrow($result))
1112 if (empty($domains_created[$row['domain_name']]))
1114 $domains_created[$row['domain_name']] = true;
1115 //$sql_data = "DROP DOMAIN {$row['domain_name']};\n";
1116 $sql_data = "CREATE DOMAIN {$row['domain_name']} as {$row['data_type']}";
1117 if (!empty($row['character_maximum_length']))
1119 $sql_data .= '(' . $row['character_maximum_length'] . ')';
1121 $sql_data .= ' NOT NULL';
1122 if (!empty($row['domain_default']))
1124 $sql_data .= ' DEFAULT ' . $row['domain_default'];
1126 $this->flush($sql_data . ";\n");
1130 $sql_data = '-- Table: ' . $table_name . "\n";
1131 $sql_data .= "DROP TABLE $table_name;\n";
1132 // PGSQL does not "tightly" bind sequences and tables, we must guess...
1133 $sql = "SELECT relname
1136 AND relname = '{$table_name}_seq'";
1137 $result = $db->sql_query($sql);
1138 // We don't even care about storing the results. We already know the answer if we get rows back.
1139 if ($db->sql_fetchrow($result))
1141 $sql_data .= "DROP SEQUENCE {$table_name}_seq;\n";
1142 $sql_data .= "CREATE SEQUENCE {$table_name}_seq;\n";
1144 $db->sql_freeresult($result);
1146 $field_query = "SELECT a.attnum, a.attname as field, t.typname as type, a.attlen as length, a.atttypmod as lengthvar, a.attnotnull as notnull
1147 FROM pg_class c, pg_attribute a, pg_type t
1148 WHERE c.relname = '" . $db->sql_escape($table_name) . "'
1150 AND a.attrelid = c.oid
1151 AND a.atttypid = t.oid
1153 $result = $db->sql_query($field_query);
1155 $sql_data .= "CREATE TABLE $table_name(\n";
1157 while ($row = $db->sql_fetchrow($result))
1159 // Get the data from the table
1160 $sql_get_default = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault
1161 FROM pg_attrdef d, pg_class c
1162 WHERE (c.relname = '" . $db->sql_escape($table_name) . "')
1163 AND (c.oid = d.adrelid)
1164 AND d.adnum = " . $row['attnum'];
1165 $def_res = $db->sql_query($sql_get_default);
1166 $def_row = $db->sql_fetchrow($def_res);
1167 $db->sql_freeresult($def_res);
1169 if (empty($def_row))
1171 unset($row['rowdefault']);
1175 $row['rowdefault'] = $def_row['rowdefault'];
1178 if ($row['type'] == 'bpchar')
1180 // Internally stored as bpchar, but isn't accepted in a CREATE TABLE statement.
1181 $row['type'] = 'char';
1184 $line = ' ' . $row['field'] . ' ' . $row['type'];
1186 if (strpos($row['type'], 'char') !== false)
1188 if ($row['lengthvar'] > 0)
1190 $line .= '(' . ($row['lengthvar'] - 4) . ')';
1194 if (strpos($row['type'], 'numeric') !== false)
1197 $line .= sprintf("%s,%s", (($row['lengthvar'] >> 16) & 0xffff), (($row['lengthvar'] - 4) & 0xffff));
1201 if (isset($row['rowdefault']))
1203 $line .= ' DEFAULT ' . $row['rowdefault'];
1206 if ($row['notnull'] == 't')
1208 $line .= ' NOT NULL';
1213 $db->sql_freeresult($result);
1216 // Get the listing of primary keys.
1217 $sql_pri_keys = "SELECT ic.relname as index_name, bc.relname as tab_name, ta.attname as column_name, i.indisunique as unique_key, i.indisprimary as primary_key
1218 FROM pg_class bc, pg_class ic, pg_index i, pg_attribute ta, pg_attribute ia
1219 WHERE (bc.oid = i.indrelid)
1220 AND (ic.oid = i.indexrelid)
1221 AND (ia.attrelid = i.indexrelid)
1222 AND (ta.attrelid = bc.oid)
1223 AND (bc.relname = '" . $db->sql_escape($table_name) . "')
1224 AND (ta.attrelid = i.indrelid)
1225 AND (ta.attnum = i.indkey[ia.attnum-1])
1226 ORDER BY index_name, tab_name, column_name";
1228 $result = $db->sql_query($sql_pri_keys);
1230 $index_create = $index_rows = $primary_key = array();
1232 // We do this in two steps. It makes placing the comma easier
1233 while ($row = $db->sql_fetchrow($result))
1235 if ($row['primary_key'] == 't')
1237 $primary_key[] = $row['column_name'];
1238 $primary_key_name = $row['index_name'];
1242 // We have to store this all this info because it is possible to have a multi-column key...
1243 // we can loop through it again and build the statement
1244 $index_rows[$row['index_name']]['table'] = $table_name;
1245 $index_rows[$row['index_name']]['unique'] = ($row['unique_key'] == 't') ? true : false;
1246 $index_rows[$row['index_name']]['column_names'][] = $row['column_name'];
1249 $db->sql_freeresult($result);
1251 if (!empty($index_rows))
1253 foreach ($index_rows as $idx_name => $props)
1255 $index_create[] = 'CREATE ' . ($props['unique'] ? 'UNIQUE ' : '') . "INDEX $idx_name ON $table_name (" . implode(', ', $props['column_names']) . ");";
1259 if (!empty($primary_key))
1261 $lines[] = " CONSTRAINT $primary_key_name PRIMARY KEY (" . implode(', ', $primary_key) . ")";
1264 // Generate constraint clauses for CHECK constraints
1265 $sql_checks = "SELECT conname as index_name, consrc
1266 FROM pg_constraint, pg_class bc
1267 WHERE conrelid = bc.oid
1268 AND bc.relname = '" . $db->sql_escape($table_name) . "'
1271 FROM pg_constraint as c, pg_inherits as i
1272 WHERE i.inhrelid = pg_constraint.conrelid
1273 AND c.conname = pg_constraint.conname
1274 AND c.consrc = pg_constraint.consrc
1275 AND c.conrelid = i.inhparent
1277 $result = $db->sql_query($sql_checks);
1279 // Add the constraints to the sql file.
1280 while ($row = $db->sql_fetchrow($result))
1282 if (!is_null($row['consrc']))
1284 $lines[] = ' CONSTRAINT ' . $row['index_name'] . ' CHECK ' . $row['consrc'];
1287 $db->sql_freeresult($result);
1289 $sql_data .= implode(", \n", $lines);
1290 $sql_data .= "\n);\n";
1292 if (!empty($index_create))
1294 $sql_data .= implode("\n", $index_create) . "\n\n";
1296 $this->flush($sql_data);
1299 function write_data($table_name)
1302 // Grab all of the data from current table.
1305 $result = $db->sql_query($sql);
1307 $i_num_fields = pg_num_fields($result);
1310 for ($i = 0; $i < $i_num_fields; $i++)
1312 $ary_type[] = pg_field_type($result, $i);
1313 $ary_name[] = pg_field_name($result, $i);
1316 $sql = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault
1317 FROM pg_attrdef d, pg_class c
1318 WHERE (c.relname = '{$table_name}')
1319 AND (c.oid = d.adrelid)
1320 AND d.adnum = " . strval($i + 1);
1321 $result2 = $db->sql_query($sql);
1322 if ($row = $db->sql_fetchrow($result2))
1324 // Determine if we must reset the sequences
1325 if (strpos($row['rowdefault'], "nextval('") === 0)
1327 $seq .= "SELECT SETVAL('{$table_name}_seq',(select case when max({$ary_name[$i]})>0 then max({$ary_name[$i]})+1 else 1 end FROM {$table_name}));\n";
1332 $this->flush("COPY $table_name (" . implode(', ', $ary_name) . ') FROM stdin;' . "\n");
1333 while ($row = $db->sql_fetchrow($result))
1335 $schema_vals = array();
1337 // Build the SQL statement to recreate the data.
1338 for ($i = 0; $i < $i_num_fields; $i++)
1340 $str_val = $row[$ary_name[$i]];
1342 if (preg_match('#char|text|bool|bytea#i', $ary_type[$i]))
1344 $str_val = str_replace(array("\n", "\t", "\r", "\b", "\f", "\v"), array('\n', '\t', '\r', '\b', '\f', '\v'), addslashes($str_val));
1352 if (empty($str_val) && $str_val !== '0')
1354 $str_val = $str_empty;
1357 $schema_vals[] = $str_val;
1360 // Take the ordered fields and their associated data and build it
1361 // into a valid sql statement to recreate that field in the data.
1362 $this->flush(implode("\t", $schema_vals) . "\n");
1364 $db->sql_freeresult($result);
1365 $this->flush("\\.\n");
1367 // Write out the sequence statements
1371 function write_end()
1373 $this->flush("COMMIT;\n");
1374 parent::write_end();
1381 class mssql_extractor extends base_extractor
1383 function write_end()
1385 $this->flush("COMMIT\nGO\n");
1386 parent::write_end();
1389 function write_start($prefix)
1392 $sql_data .= "-- phpBB Backup Script\n";
1393 $sql_data .= "-- Dump of tables for $prefix\n";
1394 $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
1395 $sql_data .= "--\n";
1396 $sql_data .= "BEGIN TRANSACTION\n";
1397 $sql_data .= "GO\n";
1398 $this->flush($sql_data);
1401 function write_table($table_name)
1404 $sql_data = '-- Table: ' . $table_name . "\n";
1405 $sql_data .= "IF OBJECT_ID(N'$table_name', N'U') IS NOT NULL\n";
1406 $sql_data .= "DROP TABLE $table_name;\n";
1407 $sql_data .= "GO\n";
1408 $sql_data .= "\nCREATE TABLE [$table_name] (\n";
1413 $sql = "SELECT COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') as IS_IDENTITY
1414 FROM INFORMATION_SCHEMA.COLUMNS
1415 WHERE TABLE_NAME = '$table_name'";
1416 $result = $db->sql_query($sql);
1418 while ($row = $db->sql_fetchrow($result))
1420 $line = "\t[{$row['COLUMN_NAME']}] [{$row['DATA_TYPE']}]";
1422 if ($row['DATA_TYPE'] == 'text')
1427 if ($row['IS_IDENTITY'])
1429 $line .= ' IDENTITY (1 , 1)';
1432 if ($row['CHARACTER_MAXIMUM_LENGTH'] && $row['DATA_TYPE'] !== 'text')
1434 $line .= ' (' . $row['CHARACTER_MAXIMUM_LENGTH'] . ')';
1437 if ($row['IS_NULLABLE'] == 'YES')
1443 $line .= ' NOT NULL';
1446 if ($row['COLUMN_DEFAULT'])
1448 $line .= ' DEFAULT ' . $row['COLUMN_DEFAULT'];
1453 $db->sql_freeresult($result);
1455 $sql_data .= implode(",\n", $rows);
1456 $sql_data .= "\n) ON [PRIMARY]";
1460 $sql_data .= " TEXTIMAGE_ON [PRIMARY]";
1463 $sql_data .= "\nGO\n\n";
1466 $sql = "SELECT CONSTRAINT_NAME, COLUMN_NAME
1467 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
1468 WHERE TABLE_NAME = '$table_name'";
1469 $result = $db->sql_query($sql);
1470 while ($row = $db->sql_fetchrow($result))
1474 $sql_data .= "ALTER TABLE [$table_name] WITH NOCHECK ADD\n";
1475 $sql_data .= "\tCONSTRAINT [{$row['CONSTRAINT_NAME']}] PRIMARY KEY CLUSTERED \n\t(\n";
1477 $rows[] = "\t\t[{$row['COLUMN_NAME']}]";
1481 $sql_data .= implode(",\n", $rows);
1482 $sql_data .= "\n\t) ON [PRIMARY] \nGO\n";
1484 $db->sql_freeresult($result);
1487 $sql = "EXEC sp_statistics '$table_name'";
1488 $result = $db->sql_query($sql);
1489 while ($row = $db->sql_fetchrow($result))
1491 if ($row['TYPE'] == 3)
1493 $index[$row['INDEX_NAME']][] = '[' . $row['COLUMN_NAME'] . ']';
1496 $db->sql_freeresult($result);
1498 foreach ($index as $index_name => $column_name)
1500 $index[$index_name] = implode(', ', $column_name);
1503 foreach ($index as $index_name => $columns)
1505 $sql_data .= "\nCREATE INDEX [$index_name] ON [$table_name]($columns) ON [PRIMARY]\nGO\n";
1507 $this->flush($sql_data);
1510 function write_data($table_name)
1514 if ($db->sql_layer === 'mssql')
1516 $this->write_data_mssql($table_name);
1518 else if($db->sql_layer === 'mssqlnative')
1520 $this->write_data_mssqlnative($table_name);
1524 $this->write_data_odbc($table_name);
1528 function write_data_mssql($table_name)
1531 $ary_type = $ary_name = array();
1535 // Grab all of the data from current table.
1538 $result = $db->sql_query($sql);
1540 $retrieved_data = mssql_num_rows($result);
1542 $i_num_fields = mssql_num_fields($result);
1544 for ($i = 0; $i < $i_num_fields; $i++)
1546 $ary_type[$i] = mssql_field_type($result, $i);
1547 $ary_name[$i] = mssql_field_name($result, $i);
1550 if ($retrieved_data)
1552 $sql = "SELECT 1 as has_identity
1553 FROM INFORMATION_SCHEMA.COLUMNS
1554 WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
1555 $result2 = $db->sql_query($sql);
1556 $row2 = $db->sql_fetchrow($result2);
1557 if (!empty($row2['has_identity']))
1559 $sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
1562 $db->sql_freeresult($result2);
1565 while ($row = $db->sql_fetchrow($result))
1567 $schema_vals = $schema_fields = array();
1569 // Build the SQL statement to recreate the data.
1570 for ($i = 0; $i < $i_num_fields; $i++)
1572 $str_val = $row[$ary_name[$i]];
1574 if (preg_match('#char|text|bool|varbinary#i', $ary_type[$i]))
1578 $str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
1580 else if (preg_match('#date|timestamp#i', $ary_type[$i]))
1582 if (empty($str_val))
1594 $str_empty = 'NULL';
1597 if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val)))
1599 $str_val = $str_empty;
1602 $schema_vals[$i] = $str_quote . $str_val . $str_quote;
1603 $schema_fields[$i] = $ary_name[$i];
1606 // Take the ordered fields and their associated data and build it
1607 // into a valid sql statement to recreate that field in the data.
1608 $sql_data .= "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
1610 $this->flush($sql_data);
1613 $db->sql_freeresult($result);
1615 if ($retrieved_data && $ident_set)
1617 $sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
1619 $this->flush($sql_data);
1622 function write_data_mssqlnative($table_name)
1625 $ary_type = $ary_name = array();
1629 // Grab all of the data from current table.
1630 $sql = "SELECT * FROM $table_name";
1631 $db->mssqlnative_set_query_options(array('Scrollable' => SQLSRV_CURSOR_STATIC));
1632 $result = $db->sql_query($sql);
1634 $retrieved_data = $db->mssqlnative_num_rows($result);
1636 if (!$retrieved_data)
1638 $db->sql_freeresult($result);
1642 $sql = "SELECT * FROM $table_name";
1643 $result_fields = $db->sql_query_limit($sql, 1);
1645 $row = new result_mssqlnative($result_fields);
1646 $i_num_fields = $row->num_fields();
1648 for ($i = 0; $i < $i_num_fields; $i++)
1650 $ary_type[$i] = $row->field_type($i);
1651 $ary_name[$i] = $row->field_name($i);
1653 $db->sql_freeresult($result_fields);
1655 $sql = "SELECT 1 as has_identity
1656 FROM INFORMATION_SCHEMA.COLUMNS
1657 WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
1658 $result2 = $db->sql_query($sql);
1659 $row2 = $db->sql_fetchrow($result2);
1661 if (!empty($row2['has_identity']))
1663 $sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
1666 $db->sql_freeresult($result2);
1668 while ($row = $db->sql_fetchrow($result))
1670 $schema_vals = $schema_fields = array();
1672 // Build the SQL statement to recreate the data.
1673 for ($i = 0; $i < $i_num_fields; $i++)
1675 $str_val = $row[$ary_name[$i]];
1677 // defaults to type number - better quote just to be safe, so check for is_int too
1678 if (is_int($ary_type[$i]) || preg_match('#char|text|bool|varbinary#i', $ary_type[$i]))
1682 $str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
1684 else if (preg_match('#date|timestamp#i', $ary_type[$i]))
1686 if (empty($str_val))
1698 $str_empty = 'NULL';
1701 if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val)))
1703 $str_val = $str_empty;
1706 $schema_vals[$i] = $str_quote . $str_val . $str_quote;
1707 $schema_fields[$i] = $ary_name[$i];
1710 // Take the ordered fields and their associated data and build it
1711 // into a valid sql statement to recreate that field in the data.
1712 $sql_data .= "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
1714 $this->flush($sql_data);
1717 $db->sql_freeresult($result);
1721 $sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
1723 $this->flush($sql_data);
1726 function write_data_odbc($table_name)
1729 $ary_type = $ary_name = array();
1733 // Grab all of the data from current table.
1736 $result = $db->sql_query($sql);
1738 $retrieved_data = odbc_num_rows($result);
1740 if ($retrieved_data)
1742 $sql = "SELECT 1 as has_identity
1743 FROM INFORMATION_SCHEMA.COLUMNS
1744 WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
1745 $result2 = $db->sql_query($sql);
1746 $row2 = $db->sql_fetchrow($result2);
1747 if (!empty($row2['has_identity']))
1749 $sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
1752 $db->sql_freeresult($result2);
1755 $i_num_fields = odbc_num_fields($result);
1757 for ($i = 0; $i < $i_num_fields; $i++)
1759 $ary_type[$i] = odbc_field_type($result, $i + 1);
1760 $ary_name[$i] = odbc_field_name($result, $i + 1);
1763 while ($row = $db->sql_fetchrow($result))
1765 $schema_vals = $schema_fields = array();
1767 // Build the SQL statement to recreate the data.
1768 for ($i = 0; $i < $i_num_fields; $i++)
1770 $str_val = $row[$ary_name[$i]];
1772 if (preg_match('#char|text|bool|varbinary#i', $ary_type[$i]))
1776 $str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
1778 else if (preg_match('#date|timestamp#i', $ary_type[$i]))
1780 if (empty($str_val))
1792 $str_empty = 'NULL';
1795 if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val)))
1797 $str_val = $str_empty;
1800 $schema_vals[$i] = $str_quote . $str_val . $str_quote;
1801 $schema_fields[$i] = $ary_name[$i];
1804 // Take the ordered fields and their associated data and build it
1805 // into a valid sql statement to recreate that field in the data.
1806 $sql_data .= "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
1808 $this->flush($sql_data);
1813 $db->sql_freeresult($result);
1815 if ($retrieved_data && $ident_set)
1817 $sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
1819 $this->flush($sql_data);
1827 class oracle_extractor extends base_extractor
1829 function write_table($table_name)
1832 $sql_data = '-- Table: ' . $table_name . "\n";
1833 $sql_data .= "DROP TABLE $table_name\n/\n";
1834 $sql_data .= "\nCREATE TABLE $table_name (\n";
1836 $sql = "SELECT COLUMN_NAME, DATA_TYPE, DATA_PRECISION, DATA_LENGTH, NULLABLE, DATA_DEFAULT
1838 WHERE table_name = '{$table_name}'";
1839 $result = $db->sql_query($sql);
1842 while ($row = $db->sql_fetchrow($result))
1844 $line = ' "' . $row['column_name'] . '" ' . $row['data_type'];
1846 if ($row['data_type'] !== 'CLOB')
1848 if ($row['data_type'] !== 'VARCHAR2' && $row['data_type'] !== 'CHAR')
1850 $line .= '(' . $row['data_precision'] . ')';
1854 $line .= '(' . $row['data_length'] . ')';
1858 if (!empty($row['data_default']))
1860 $line .= ' DEFAULT ' . $row['data_default'];
1863 if ($row['nullable'] == 'N')
1865 $line .= ' NOT NULL';
1869 $db->sql_freeresult($result);
1871 $sql = "SELECT A.CONSTRAINT_NAME, A.COLUMN_NAME
1872 FROM USER_CONS_COLUMNS A, USER_CONSTRAINTS B
1873 WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
1874 AND B.CONSTRAINT_TYPE = 'P'
1875 AND A.TABLE_NAME = '{$table_name}'";
1876 $result = $db->sql_query($sql);
1878 $primary_key = array();
1879 $contraint_name = '';
1880 while ($row = $db->sql_fetchrow($result))
1882 $constraint_name = '"' . $row['constraint_name'] . '"';
1883 $primary_key[] = '"' . $row['column_name'] . '"';
1885 $db->sql_freeresult($result);
1887 if (sizeof($primary_key))
1889 $rows[] = " CONSTRAINT {$constraint_name} PRIMARY KEY (" . implode(', ', $primary_key) . ')';
1892 $sql = "SELECT A.CONSTRAINT_NAME, A.COLUMN_NAME
1893 FROM USER_CONS_COLUMNS A, USER_CONSTRAINTS B
1894 WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
1895 AND B.CONSTRAINT_TYPE = 'U'
1896 AND A.TABLE_NAME = '{$table_name}'";
1897 $result = $db->sql_query($sql);
1900 $contraint_name = '';
1901 while ($row = $db->sql_fetchrow($result))
1903 $constraint_name = '"' . $row['constraint_name'] . '"';
1904 $unique[] = '"' . $row['column_name'] . '"';
1906 $db->sql_freeresult($result);
1908 if (sizeof($unique))
1910 $rows[] = " CONSTRAINT {$constraint_name} UNIQUE (" . implode(', ', $unique) . ')';
1913 $sql_data .= implode(",\n", $rows);
1914 $sql_data .= "\n)\n/\n";
1916 $sql = "SELECT A.REFERENCED_NAME, C.*
1917 FROM USER_DEPENDENCIES A, USER_TRIGGERS B, USER_SEQUENCES C
1918 WHERE A.REFERENCED_TYPE = 'SEQUENCE'
1919 AND A.NAME = B.TRIGGER_NAME
1920 AND B.TABLE_NAME = '{$table_name}'
1921 AND C.SEQUENCE_NAME = A.REFERENCED_NAME";
1922 $result = $db->sql_query($sql);
1924 $type = request_var('type', '');
1926 while ($row = $db->sql_fetchrow($result))
1928 $sql_data .= "\nDROP SEQUENCE \"{$row['referenced_name']}\"\n/\n";
1929 $sql_data .= "\nCREATE SEQUENCE \"{$row['referenced_name']}\"";
1931 if ($type == 'full')
1933 $sql_data .= ' START WITH ' . $row['last_number'];
1936 $sql_data .= "\n/\n";
1938 $db->sql_freeresult($result);
1940 $sql = "SELECT DESCRIPTION, WHEN_CLAUSE, TRIGGER_BODY
1942 WHERE TABLE_NAME = '{$table_name}'";
1943 $result = $db->sql_query($sql);
1944 while ($row = $db->sql_fetchrow($result))
1946 $sql_data .= "\nCREATE OR REPLACE TRIGGER {$row['description']}WHEN ({$row['when_clause']})\n{$row['trigger_body']}\n/\n";
1948 $db->sql_freeresult($result);
1950 $sql = "SELECT A.INDEX_NAME, B.COLUMN_NAME
1951 FROM USER_INDEXES A, USER_IND_COLUMNS B
1952 WHERE A.UNIQUENESS = 'NONUNIQUE'
1953 AND A.INDEX_NAME = B.INDEX_NAME
1954 AND B.TABLE_NAME = '{$table_name}'";
1955 $result = $db->sql_query($sql);
1959 while ($row = $db->sql_fetchrow($result))
1961 $index[$row['index_name']][] = $row['column_name'];
1964 foreach ($index as $index_name => $column_names)
1966 $sql_data .= "\nCREATE INDEX $index_name ON $table_name(" . implode(', ', $column_names) . ")\n/\n";
1968 $db->sql_freeresult($result);
1969 $this->flush($sql_data);
1972 function write_data($table_name)
1975 $ary_type = $ary_name = array();
1977 // Grab all of the data from current table.
1980 $result = $db->sql_query($sql);
1982 $i_num_fields = ocinumcols($result);
1984 for ($i = 0; $i < $i_num_fields; $i++)
1986 $ary_type[$i] = ocicolumntype($result, $i + 1);
1987 $ary_name[$i] = ocicolumnname($result, $i + 1);
1992 while ($row = $db->sql_fetchrow($result))
1994 $schema_vals = $schema_fields = array();
1996 // Build the SQL statement to recreate the data.
1997 for ($i = 0; $i < $i_num_fields; $i++)
1999 // Oracle uses uppercase - we use lowercase
2000 $str_val = $row[strtolower($ary_name[$i])];
2002 if (preg_match('#char|text|bool|raw|clob#i', $ary_type[$i]))
2006 $str_val = sanitize_data_oracle($str_val);
2008 else if (preg_match('#date|timestamp#i', $ary_type[$i]))
2010 if (empty($str_val))
2022 $str_empty = 'NULL';
2025 if (empty($str_val) && $str_val !== '0')
2027 $str_val = $str_empty;
2030 $schema_vals[$i] = $str_quote . $str_val . $str_quote;
2031 $schema_fields[$i] = '"' . $ary_name[$i] . '"';
2034 // Take the ordered fields and their associated data and build it
2035 // into a valid sql statement to recreate that field in the data.
2036 $sql_data = "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ")\n/\n";
2038 $this->flush($sql_data);
2040 $db->sql_freeresult($result);
2043 function write_start($prefix)
2046 $sql_data .= "-- phpBB Backup Script\n";
2047 $sql_data .= "-- Dump of tables for $prefix\n";
2048 $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
2049 $sql_data .= "--\n";
2050 $this->flush($sql_data);
2057 class firebird_extractor extends base_extractor
2059 function write_start($prefix)
2062 $sql_data .= "-- phpBB Backup Script\n";
2063 $sql_data .= "-- Dump of tables for $prefix\n";
2064 $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
2065 $sql_data .= "--\n";
2066 $this->flush($sql_data);
2069 function write_data($table_name)
2072 $ary_type = $ary_name = array();
2074 // Grab all of the data from current table.
2077 $result = $db->sql_query($sql);
2079 $i_num_fields = ibase_num_fields($result);
2081 for ($i = 0; $i < $i_num_fields; $i++)
2083 $info = ibase_field_info($result, $i);
2084 $ary_type[$i] = $info['type'];
2085 $ary_name[$i] = $info['name'];
2088 while ($row = $db->sql_fetchrow($result))
2090 $schema_vals = $schema_fields = array();
2092 // Build the SQL statement to recreate the data.
2093 for ($i = 0; $i < $i_num_fields; $i++)
2095 $str_val = $row[strtolower($ary_name[$i])];
2097 if (preg_match('#char|text|bool|varbinary|blob#i', $ary_type[$i]))
2101 $str_val = sanitize_data_generic(str_replace("'", "''", $str_val));
2103 else if (preg_match('#date|timestamp#i', $ary_type[$i]))
2105 if (empty($str_val))
2117 $str_empty = 'NULL';
2120 if (empty($str_val) && $str_val !== '0')
2122 $str_val = $str_empty;
2125 $schema_vals[$i] = $str_quote . $str_val . $str_quote;
2126 $schema_fields[$i] = '"' . $ary_name[$i] . '"';
2129 // Take the ordered fields and their associated data and build it
2130 // into a valid sql statement to recreate that field in the data.
2131 $sql_data = "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\n";
2133 $this->flush($sql_data);
2135 $db->sql_freeresult($result);
2138 function write_table($table_name)
2142 $sql_data = '-- Table: ' . $table_name . "\n";
2143 $sql_data .= "DROP TABLE $table_name;\n";
2145 $data_types = array(7 => 'SMALLINT', 8 => 'INTEGER', 10 => 'FLOAT', 12 => 'DATE', 13 => 'TIME', 14 => 'CHARACTER', 27 => 'DOUBLE PRECISION', 35 => 'TIMESTAMP', 37 => 'VARCHAR', 40 => 'CSTRING', 261 => 'BLOB', 701 => 'DECIMAL', 702 => 'NUMERIC');
2147 $sql_data .= "\nCREATE TABLE $table_name (\n";
2149 $sql = 'SELECT DISTINCT R.RDB$FIELD_NAME as FNAME, R.RDB$NULL_FLAG as NFLAG, R.RDB$DEFAULT_SOURCE as DSOURCE, F.RDB$FIELD_TYPE as FTYPE, F.RDB$FIELD_SUB_TYPE as STYPE, F.RDB$FIELD_LENGTH as FLEN
2150 FROM RDB$RELATION_FIELDS R
2151 JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME
2152 LEFT JOIN RDB$FIELD_DIMENSIONS D ON R.RDB$FIELD_SOURCE = D.RDB$FIELD_NAME
2153 WHERE F.RDB$SYSTEM_FLAG = 0
2154 AND R.RDB$RELATION_NAME = \''. $table_name . '\'
2155 ORDER BY R.RDB$FIELD_POSITION';
2156 $result = $db->sql_query($sql);
2159 while ($row = $db->sql_fetchrow($result))
2161 $line = "\t" . '"' . $row['fname'] . '" ' . $data_types[$row['ftype']];
2163 if ($row['ftype'] == 261 && $row['stype'] == 1)
2165 $line .= ' SUB_TYPE TEXT';
2168 if ($row['ftype'] == 37 || $row['ftype'] == 14)
2170 $line .= ' (' . $row['flen'] . ')';
2173 if (!empty($row['dsource']))
2175 $line .= ' ' . $row['dsource'];
2178 if (!empty($row['nflag']))
2180 $line .= ' NOT NULL';
2184 $db->sql_freeresult($result);
2186 $sql_data .= implode(",\n", $rows);
2187 $sql_data .= "\n);\n";
2190 $sql = 'SELECT I.RDB$FIELD_NAME as NAME
2191 FROM RDB$RELATION_CONSTRAINTS RC, RDB$INDEX_SEGMENTS I, RDB$INDICES IDX
2192 WHERE (I.RDB$INDEX_NAME = RC.RDB$INDEX_NAME)
2193 AND (IDX.RDB$INDEX_NAME = RC.RDB$INDEX_NAME)
2194 AND (RC.RDB$RELATION_NAME = \''. $table_name . '\')
2195 ORDER BY I.RDB$FIELD_POSITION';
2196 $result = $db->sql_query($sql);
2198 while ($row = $db->sql_fetchrow($result))
2200 $keys[] = $row['name'];
2205 $sql_data .= "\nALTER TABLE $table_name ADD PRIMARY KEY (" . implode(', ', $keys) . ');';
2208 $db->sql_freeresult($result);
2210 $sql = 'SELECT I.RDB$INDEX_NAME as INAME, I.RDB$UNIQUE_FLAG as UFLAG, S.RDB$FIELD_NAME as FNAME
2211 FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON S.RDB$INDEX_NAME=I.RDB$INDEX_NAME
2212 WHERE (I.RDB$SYSTEM_FLAG IS NULL OR I.RDB$SYSTEM_FLAG=0)
2213 AND I.RDB$FOREIGN_KEY IS NULL
2214 AND I.RDB$RELATION_NAME = \''. $table_name . '\'
2215 AND I.RDB$INDEX_NAME NOT STARTING WITH \'RDB$\'
2216 ORDER BY S.RDB$FIELD_POSITION';
2217 $result = $db->sql_query($sql);
2220 while ($row = $db->sql_fetchrow($result))
2222 $index[$row['iname']]['unique'] = !empty($row['uflag']);
2223 $index[$row['iname']]['values'][] = $row['fname'];
2226 foreach ($index as $index_name => $data)
2228 $sql_data .= "\nCREATE ";
2229 if ($data['unique'])
2231 $sql_data .= 'UNIQUE ';
2233 $sql_data .= "INDEX $index_name ON $table_name(" . implode(', ', $data['values']) . ");";
2237 $db->sql_freeresult($result);
2239 $sql = 'SELECT D1.RDB$DEPENDENT_NAME as DNAME, D1.RDB$FIELD_NAME as FNAME, D1.RDB$DEPENDENT_TYPE, R1.RDB$RELATION_NAME
2240 FROM RDB$DEPENDENCIES D1
2241 LEFT JOIN RDB$RELATIONS R1 ON ((D1.RDB$DEPENDENT_NAME = R1.RDB$RELATION_NAME) AND (NOT (R1.RDB$VIEW_BLR IS NULL)))
2242 WHERE (D1.RDB$DEPENDED_ON_TYPE = 0)
2243 AND (D1.RDB$DEPENDENT_TYPE <> 3)
2244 AND (D1.RDB$DEPENDED_ON_NAME = \'' . $table_name . '\')
2245 UNION SELECT DISTINCT F2.RDB$RELATION_NAME, D2.RDB$FIELD_NAME, D2.RDB$DEPENDENT_TYPE, R2.RDB$RELATION_NAME FROM RDB$DEPENDENCIES D2, RDB$RELATION_FIELDS F2
2246 LEFT JOIN RDB$RELATIONS R2 ON ((F2.RDB$RELATION_NAME = R2.RDB$RELATION_NAME) AND (NOT (R2.RDB$VIEW_BLR IS NULL)))
2247 WHERE (D2.RDB$DEPENDENT_TYPE = 3)
2248 AND (D2.RDB$DEPENDENT_NAME = F2.RDB$FIELD_SOURCE)
2249 AND (D2.RDB$DEPENDED_ON_NAME = \'' . $table_name . '\')
2251 $result = $db->sql_query($sql);
2252 while ($row = $db->sql_fetchrow($result))
2254 $sql = 'SELECT T1.RDB$DEPENDED_ON_NAME as GEN, T1.RDB$FIELD_NAME, T1.RDB$DEPENDED_ON_TYPE
2255 FROM RDB$DEPENDENCIES T1
2256 WHERE (T1.RDB$DEPENDENT_NAME = \'' . $row['dname'] . '\')
2257 AND (T1.RDB$DEPENDENT_TYPE = 2 AND T1.RDB$DEPENDED_ON_TYPE = 14)
2258 UNION ALL SELECT DISTINCT D.RDB$DEPENDED_ON_NAME, D.RDB$FIELD_NAME, D.RDB$DEPENDED_ON_TYPE
2259 FROM RDB$DEPENDENCIES D, RDB$RELATION_FIELDS F
2260 WHERE (D.RDB$DEPENDENT_TYPE = 3)
2261 AND (D.RDB$DEPENDENT_NAME = F.RDB$FIELD_SOURCE)
2262 AND (F.RDB$RELATION_NAME = \'' . $row['dname'] . '\')
2264 $result2 = $db->sql_query($sql);
2265 $row2 = $db->sql_fetchrow($result2);
2266 $db->sql_freeresult($result2);
2267 $gen_name = $row2['gen'];
2269 $sql_data .= "\nDROP GENERATOR " . $gen_name . ";";
2270 $sql_data .= "\nSET TERM ^ ;";
2271 $sql_data .= "\nCREATE GENERATOR " . $gen_name . "^";
2272 $sql_data .= "\nSET GENERATOR " . $gen_name . " TO 0^\n";
2273 $sql_data .= "\nCREATE TRIGGER {$row['dname']} FOR $table_name";
2274 $sql_data .= "\nBEFORE INSERT\nAS\nBEGIN";
2275 $sql_data .= "\n NEW.{$row['fname']} = GEN_ID(" . $gen_name . ", 1);";
2276 $sql_data .= "\nEND^\n";
2277 $sql_data .= "\nSET TERM ; ^\n";
2280 $this->flush($sql_data);
2282 $db->sql_freeresult($result);
2286 // get how much space we allow for a chunk of data, very similar to phpMyAdmin's way of doing things ;-) (hey, we only do this for MySQL anyway :P)
2287 function get_usable_memory()
2289 $val = trim(@ini_get('memory_limit'));
2291 if (preg_match('/(\\d+)([mkg]?)/i', $val, $regs))
2293 $memory_limit = (int) $regs[1];
2299 $memory_limit *= 1024;
2304 $memory_limit *= 1048576;
2309 $memory_limit *= 1073741824;
2313 // how much memory PHP requires at the start of export (it is really a little less)
2314 if ($memory_limit > 6100000)
2316 $memory_limit -= 6100000;
2319 // allow us to consume half of the total memory available
2324 // set the buffer to 1M if we have no clue how much memory PHP will give us :P
2325 $memory_limit = 1048576;
2328 return $memory_limit;
2331 function sanitize_data_mssql($text)
2333 $data = preg_split('/[\n\t\r\b\f]/', $text);
2334 preg_match_all('/[\n\t\r\b\f]/', $text, $matches);
2338 foreach ($data as $value)
2342 $val[] = "'" . $value . "'";
2344 if (sizeof($matches[0]))
2346 $val[] = 'char(' . ord(array_shift($matches[0])) . ')';
2350 return implode('+', $val);
2353 function sanitize_data_oracle($text)
2355 // $data = preg_split('/[\0\n\t\r\b\f\'"\/\\\]/', $text);
2356 // preg_match_all('/[\0\n\t\r\b\f\'"\/\\\]/', $text, $matches);
2357 $data = preg_split('/[\0\b\f\'\/]/', $text);
2358 preg_match_all('/[\0\r\b\f\'\/]/', $text, $matches);
2362 foreach ($data as $value)
2366 $val[] = "'" . $value . "'";
2368 if (sizeof($matches[0]))
2370 $val[] = 'chr(' . ord(array_shift($matches[0])) . ')';
2374 return implode('||', $val);
2377 function sanitize_data_generic($text)
2379 $data = preg_split('/[\n\t\r\b\f]/', $text);
2380 preg_match_all('/[\n\t\r\b\f]/', $text, $matches);
2384 foreach ($data as $value)
2388 $val[] = "'" . $value . "'";
2390 if (sizeof($matches[0]))
2392 $val[] = "'" . array_shift($matches[0]) . "'";
2396 return implode('||', $val);
2399 // modified from PHP.net
2400 function fgetd(&$fp, $delim, $read, $seek, $eof, $buffer = 8192)
2403 $delim_len = strlen($delim);
2407 $pos = strpos($record, $delim);
2410 $record .= $read($fp, $buffer);
2411 if ($eof($fp) && ($pos = strpos($record, $delim)) !== false)
2413 $seek($fp, $pos + $delim_len - strlen($record), SEEK_CUR);
2414 return substr($record, 0, $pos);
2419 $seek($fp, $pos + $delim_len - strlen($record), SEEK_CUR);
2420 return substr($record, 0, $pos);
2427 function fgetd_seekless(&$fp, $delim, $read, $seek, $eof, $buffer = 8192)
2429 static $array = array();
2430 static $record = '';
2432 if (!sizeof($array))
2436 if (strpos($record, $delim) !== false)
2438 $array = explode($delim, $record);
2439 $record = array_pop($array);
2444 $record .= $read($fp, $buffer);
2447 if ($eof($fp) && strpos($record, $delim) !== false)
2449 $array = explode($delim, $record);
2450 $record = array_pop($array);
2456 return array_shift($array);