Blame Identity/Webenv/phpBB/3.0.4/includes/acp/acp_database.php

ef5584
ef5584
/**
ef5584
*
ef5584
* @package acp
ef5584
* @version $Id: acp_database.php 8814 2008-09-04 12:01:47Z acydburn $
ef5584
* @copyright (c) 2005 phpBB Group
ef5584
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
ef5584
*
ef5584
*/
ef5584
ef5584
/**
ef5584
* @ignore
ef5584
*/
ef5584
if (!defined('IN_PHPBB'))
ef5584
{
ef5584
	exit;
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class acp_database
ef5584
{
ef5584
	var $u_action;
ef5584
ef5584
	function main($id, $mode)
ef5584
	{
ef5584
		global $cache, $db, $user, $auth, $template, $table_prefix;
ef5584
		global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;
ef5584
		
ef5584
		$user->add_lang('acp/database');
ef5584
ef5584
		$this->tpl_name = 'acp_database';
ef5584
		$this->page_title = 'ACP_DATABASE';
ef5584
ef5584
		$action	= request_var('action', '');
ef5584
		$submit = (isset($_POST['submit'])) ? true : false;
ef5584
ef5584
		$template->assign_vars(array(
ef5584
			'MODE'	=> $mode
ef5584
		));
ef5584
ef5584
		switch ($mode)
ef5584
		{
ef5584
			case 'backup':
ef5584
ef5584
				$this->page_title = 'ACP_BACKUP';
ef5584
ef5584
				switch ($action)
ef5584
				{
ef5584
					case 'download':
ef5584
						$type	= request_var('type', '');
ef5584
						$table	= request_var('table', array(''));
ef5584
						$format	= request_var('method', '');
ef5584
						$where	= request_var('where', '');
ef5584
ef5584
						if (!sizeof($table))
ef5584
						{
ef5584
							trigger_error($user->lang['TABLE_SELECT_ERROR'] . adm_back_link($this->u_action), E_USER_WARNING);
ef5584
						}
ef5584
ef5584
						$store = $download = $structure = $schema_data = false;
ef5584
ef5584
						if ($where == 'store_and_download' || $where == 'store')
ef5584
						{
ef5584
							$store = true;
ef5584
						}
ef5584
ef5584
						if ($where == 'store_and_download' || $where == 'download')
ef5584
						{
ef5584
							$download = true;
ef5584
						}
ef5584
ef5584
						if ($type == 'full' || $type == 'structure')
ef5584
						{
ef5584
							$structure = true;
ef5584
						}
ef5584
ef5584
						if ($type == 'full' || $type == 'data')
ef5584
						{
ef5584
							$schema_data = true;
ef5584
						}
ef5584
ef5584
						@set_time_limit(1200);
ef5584
ef5584
						$time = time();
ef5584
ef5584
						$filename = 'backup_' . $time . '_' . unique_id();
ef5584
						switch ($db->sql_layer)
ef5584
						{
ef5584
							case 'mysqli':
ef5584
							case 'mysql4':
ef5584
							case 'mysql':
ef5584
								$extractor = new mysql_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
ef5584
							case 'sqlite':
ef5584
								$extractor = new sqlite_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
ef5584
							case 'postgres':
ef5584
								$extractor = new postgres_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
ef5584
							case 'oracle':
ef5584
								$extractor = new oracle_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
ef5584
							case 'mssql':
ef5584
							case 'mssql_odbc':
ef5584
								$extractor = new mssql_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
ef5584
							case 'firebird':
ef5584
								$extractor = new firebird_extractor($download, $store, $format, $filename, $time);
ef5584
							break;
ef5584
						}
ef5584
ef5584
						$extractor->write_start($table_prefix);
ef5584
ef5584
						foreach ($table as $table_name)
ef5584
						{
ef5584
							// Get the table structure
ef5584
							if ($structure)
ef5584
							{
ef5584
								$extractor->write_table($table_name);
ef5584
							}
ef5584
							else
ef5584
							{
ef5584
								// We might wanna empty out all that junk :D
ef5584
								switch ($db->sql_layer)
ef5584
								{
ef5584
									case 'sqlite':
ef5584
									case 'firebird':
ef5584
										$extractor->flush('DELETE FROM ' . $table_name . ";\n");
ef5584
									break;
ef5584
ef5584
									case 'mssql':
ef5584
									case 'mssql_odbc':
ef5584
										$extractor->flush('TRUNCATE TABLE ' . $table_name . "GO\n");
ef5584
									break;
ef5584
ef5584
									case 'oracle':
ef5584
										$extractor->flush('TRUNCATE TABLE ' . $table_name . "\\\n");
ef5584
									break;
ef5584
ef5584
									default:
ef5584
										$extractor->flush('TRUNCATE TABLE ' . $table_name . ";\n");
ef5584
									break;
ef5584
								}
ef5584
							}
ef5584
ef5584
							// Data
ef5584
							if ($schema_data)
ef5584
							{
ef5584
								$extractor->write_data($table_name);
ef5584
							}
ef5584
						}
ef5584
ef5584
						$extractor->write_end();
ef5584
ef5584
						add_log('admin', 'LOG_DB_BACKUP');
ef5584
ef5584
						if ($download == true)
ef5584
						{
ef5584
							exit;
ef5584
						}
ef5584
ef5584
						trigger_error($user->lang['BACKUP_SUCCESS'] . adm_back_link($this->u_action));
ef5584
					break;
ef5584
ef5584
					default:
ef5584
						include($phpbb_root_path . 'includes/functions_install.' . $phpEx);
ef5584
						$tables = get_tables($db);
ef5584
						asort($tables);
ef5584
						foreach ($tables as $table_name)
ef5584
						{
ef5584
							if (strlen($table_prefix) === 0 || stripos($table_name, $table_prefix) === 0)
ef5584
							{
ef5584
								$template->assign_block_vars('tables', array(
ef5584
									'TABLE'	=> $table_name
ef5584
								));
ef5584
							}
ef5584
						}
ef5584
						unset($tables);
ef5584
ef5584
						$template->assign_vars(array(
ef5584
							'U_ACTION'	=> $this->u_action . '&action=download'
ef5584
						));
ef5584
						
ef5584
						$available_methods = array('gzip' => 'zlib', 'bzip2' => 'bz2');
ef5584
ef5584
						foreach ($available_methods as $type => $module)
ef5584
						{
ef5584
							if (!@extension_loaded($module))
ef5584
							{
ef5584
								continue;
ef5584
							}
ef5584
ef5584
							$template->assign_block_vars('methods', array(
ef5584
								'TYPE'	=> $type
ef5584
							));
ef5584
						}
ef5584
ef5584
						$template->assign_block_vars('methods', array(
ef5584
							'TYPE'	=> 'text'
ef5584
						));
ef5584
					break;
ef5584
				}
ef5584
			break;
ef5584
ef5584
			case 'restore':
ef5584
ef5584
				$this->page_title = 'ACP_RESTORE';
ef5584
ef5584
				switch ($action)
ef5584
				{
ef5584
					case 'submit':
ef5584
						$delete = request_var('delete', '');
ef5584
						$file = request_var('file', '');
ef5584
ef5584
						if (!preg_match('#^backup_\d{10,}_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches))
ef5584
						{
ef5584
							trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING);
ef5584
						}
ef5584
ef5584
						$file_name = $phpbb_root_path . 'store/' . $matches[0];
ef5584
ef5584
						if (!file_exists($file_name) || !is_readable($file_name))
ef5584
						{
ef5584
							trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING);
ef5584
						}
ef5584
ef5584
						if ($delete)
ef5584
						{
ef5584
							if (confirm_box(true))
ef5584
							{
ef5584
								unlink($file_name);
ef5584
								add_log('admin', 'LOG_DB_DELETE');
ef5584
								trigger_error($user->lang['BACKUP_DELETE'] . adm_back_link($this->u_action));
ef5584
							}
ef5584
							else
ef5584
							{
ef5584
								confirm_box(false, $user->lang['DELETE_SELECTED_BACKUP'], build_hidden_fields(array('delete' => $delete, 'file' => $file)));
ef5584
							}
ef5584
						}
ef5584
						else
ef5584
						{
ef5584
							$download = request_var('download', '');
ef5584
ef5584
							if ($download)
ef5584
							{
ef5584
								$name = $matches[0];
ef5584
ef5584
								switch ($matches[1])
ef5584
								{
ef5584
									case 'sql':
ef5584
										$mimetype = 'text/x-sql';
ef5584
									break;
ef5584
									case 'sql.bz2':
ef5584
										$mimetype = 'application/x-bzip2';
ef5584
									break;
ef5584
									case 'sql.gz':
ef5584
										$mimetype = 'application/x-gzip';
ef5584
									break;
ef5584
								}
ef5584
ef5584
								header('Pragma: no-cache');
ef5584
								header("Content-Type: $mimetype; name=\"$name\"");
ef5584
								header("Content-disposition: attachment; filename=$name");
ef5584
ef5584
								@set_time_limit(0);
ef5584
ef5584
								$fp = @fopen($file_name, 'rb');
ef5584
ef5584
								if ($fp !== false)
ef5584
								{
ef5584
									while (!feof($fp))
ef5584
									{
ef5584
										echo fread($fp, 8192);
ef5584
									}
ef5584
									fclose($fp);
ef5584
								}
ef5584
ef5584
								flush();
ef5584
								exit;
ef5584
							}
ef5584
ef5584
							switch ($matches[1])
ef5584
							{
ef5584
								case 'sql':
ef5584
									$fp = fopen($file_name, 'rb');
ef5584
									$read = 'fread';
ef5584
									$seek = 'fseek';
ef5584
									$eof = 'feof';
ef5584
									$close = 'fclose';
ef5584
									$fgetd = 'fgetd';
ef5584
								break;
ef5584
ef5584
								case 'sql.bz2':
ef5584
									$fp = bzopen($file_name, 'r');
ef5584
									$read = 'bzread';
ef5584
									$seek = '';
ef5584
									$eof = 'feof';
ef5584
									$close = 'bzclose';
ef5584
									$fgetd = 'fgetd_seekless';
ef5584
								break;
ef5584
ef5584
								case 'sql.gz':
ef5584
									$fp = gzopen($file_name, 'rb');
ef5584
									$read = 'gzread';
ef5584
									$seek = 'gzseek';
ef5584
									$eof = 'gzeof';
ef5584
									$close = 'gzclose';
ef5584
									$fgetd = 'fgetd';
ef5584
								break;
ef5584
							}
ef5584
ef5584
							switch ($db->sql_layer)
ef5584
							{
ef5584
								case 'mysql':
ef5584
								case 'mysql4':
ef5584
								case 'mysqli':
ef5584
								case 'sqlite':
ef5584
									while (($sql = $fgetd($fp, ";\n", $read, $seek, $eof)) !== false)
ef5584
									{
ef5584
										$db->sql_query($sql);
ef5584
									}
ef5584
								break;
ef5584
ef5584
								case 'firebird':
ef5584
									$delim = ";\n";
ef5584
									while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false)
ef5584
									{
ef5584
										$query = trim($sql);
ef5584
										if (substr($query, 0, 8) === 'SET TERM')
ef5584
										{
ef5584
											$delim = $query[9] . "\n";
ef5584
											continue;
ef5584
										}
ef5584
										$db->sql_query($query);
ef5584
									}
ef5584
								break;
ef5584
ef5584
								case 'postgres':
ef5584
									$delim = ";\n";
ef5584
									while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false)
ef5584
									{
ef5584
										$query = trim($sql);
ef5584
ef5584
										if (substr($query, 0, 13) == 'CREATE DOMAIN')
ef5584
										{
ef5584
											list(, , $domain) = explode(' ', $query);
ef5584
											$sql = "SELECT domain_name
ef5584
												FROM information_schema.domains
ef5584
												WHERE domain_name = '$domain';";
ef5584
											$result = $db->sql_query($sql);
ef5584
											if (!$db->sql_fetchrow($result))
ef5584
											{
ef5584
												$db->sql_query($query);
ef5584
											}
ef5584
											$db->sql_freeresult($result);
ef5584
										}
ef5584
										else
ef5584
										{
ef5584
											$db->sql_query($query);
ef5584
										}
ef5584
ef5584
										if (substr($query, 0, 4) == 'COPY')
ef5584
										{
ef5584
											while (($sub = $fgetd($fp, "\n", $read, $seek, $eof)) !== '\.')
ef5584
											{
ef5584
												if ($sub === false)
ef5584
												{
ef5584
													trigger_error($user->lang['RESTORE_FAILURE'] . adm_back_link($this->u_action), E_USER_WARNING);
ef5584
												}
ef5584
												pg_put_line($db->db_connect_id, $sub . "\n");
ef5584
											}
ef5584
											pg_put_line($db->db_connect_id, "\\.\n");
ef5584
											pg_end_copy($db->db_connect_id);
ef5584
										}
ef5584
									}
ef5584
								break;
ef5584
ef5584
								case 'oracle':
ef5584
									while (($sql = $fgetd($fp, "/\n", $read, $seek, $eof)) !== false)
ef5584
									{
ef5584
										$db->sql_query($sql);
ef5584
									}
ef5584
								break;
ef5584
ef5584
								case 'mssql':
ef5584
								case 'mssql_odbc':
ef5584
									while (($sql = $fgetd($fp, "GO\n", $read, $seek, $eof)) !== false)
ef5584
									{
ef5584
										$db->sql_query($sql);
ef5584
									}
ef5584
								break;
ef5584
							}
ef5584
ef5584
							$close($fp);
ef5584
ef5584
							// Purge the cache due to updated data
ef5584
							$cache->purge();
ef5584
ef5584
							add_log('admin', 'LOG_DB_RESTORE');
ef5584
							trigger_error($user->lang['RESTORE_SUCCESS'] . adm_back_link($this->u_action));
ef5584
							break;
ef5584
						}
ef5584
ef5584
					default:
ef5584
						$methods = array('sql');
ef5584
						$available_methods = array('sql.gz' => 'zlib', 'sql.bz2' => 'bz2');
ef5584
ef5584
						foreach ($available_methods as $type => $module)
ef5584
						{
ef5584
							if (!@extension_loaded($module))
ef5584
							{
ef5584
								continue;
ef5584
							}
ef5584
							$methods[] = $type;
ef5584
						}
ef5584
ef5584
						$dir = $phpbb_root_path . 'store/';
ef5584
						$dh = @opendir($dir);
ef5584
ef5584
						if ($dh)
ef5584
						{
ef5584
							while (($file = readdir($dh)) !== false)
ef5584
							{
ef5584
								if (preg_match('#^backup_(\d{10,})_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches))
ef5584
								{
ef5584
									$supported = in_array($matches[2], $methods);
ef5584
ef5584
									if ($supported == 'true')
ef5584
									{
ef5584
										$template->assign_block_vars('files', array(
ef5584
											'FILE'		=> $file,
ef5584
											'NAME'		=> gmdate("d-m-Y H:i:s", $matches[1]),
ef5584
											'SUPPORTED'	=> $supported
ef5584
										));
ef5584
									}
ef5584
								}
ef5584
							}
ef5584
							closedir($dh);
ef5584
						}
ef5584
ef5584
						$template->assign_vars(array(
ef5584
							'U_ACTION'	=> $this->u_action . '&action=submit'
ef5584
						));
ef5584
					break;
ef5584
				}
ef5584
			break;
ef5584
		}
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class base_extractor
ef5584
{
ef5584
	var $fh;
ef5584
	var $fp;
ef5584
	var $write;
ef5584
	var $close;
ef5584
	var $store;
ef5584
	var $download;
ef5584
	var $time;
ef5584
	var $format;
ef5584
	var $run_comp = false;
ef5584
ef5584
	function base_extractor($download = false, $store = false, $format, $filename, $time)
ef5584
	{
ef5584
		$this->download = $download;
ef5584
		$this->store = $store;
ef5584
		$this->time = $time;
ef5584
		$this->format = $format;
ef5584
ef5584
		switch ($format)
ef5584
		{
ef5584
			case 'text':
ef5584
				$ext = '.sql';
ef5584
				$open = 'fopen';
ef5584
				$this->write = 'fwrite';
ef5584
				$this->close = 'fclose';
ef5584
				$mimetype = 'text/x-sql';
ef5584
			break;
ef5584
			case 'bzip2':
ef5584
				$ext = '.sql.bz2';
ef5584
				$open = 'bzopen';
ef5584
				$this->write = 'bzwrite';
ef5584
				$this->close = 'bzclose';
ef5584
				$mimetype = 'application/x-bzip2';
ef5584
			break;
ef5584
			case 'gzip':
ef5584
				$ext = '.sql.gz';
ef5584
				$open = 'gzopen';
ef5584
				$this->write = 'gzwrite';
ef5584
				$this->close = 'gzclose';
ef5584
				$mimetype = 'application/x-gzip';
ef5584
			break;
ef5584
		}
ef5584
ef5584
		if ($download == true)
ef5584
		{
ef5584
			$name = $filename . $ext;
ef5584
			header('Pragma: no-cache');
ef5584
			header("Content-Type: $mimetype; name=\"$name\"");
ef5584
			header("Content-disposition: attachment; filename=$name");
ef5584
	
ef5584
			switch ($format)
ef5584
			{
ef5584
				case 'bzip2':
ef5584
					ob_start();
ef5584
				break;
ef5584
ef5584
				case 'gzip':
ef5584
					if ((isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'msie') === false)
ef5584
					{
ef5584
						ob_start('ob_gzhandler');
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$this->run_comp = true;
ef5584
					}
ef5584
				break;
ef5584
			}
ef5584
		}
ef5584
		
ef5584
		if ($store == true)
ef5584
		{
ef5584
			global $phpbb_root_path;
ef5584
			$file = $phpbb_root_path . 'store/' . $filename . $ext;
ef5584
	
ef5584
			$this->fp = $open($file, 'w');
ef5584
	
ef5584
			if (!$this->fp)
ef5584
			{
ef5584
				trigger_error('Unable to write temporary file to storage folder', E_USER_ERROR);
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_end()
ef5584
	{
ef5584
		static $close;
ef5584
		if ($this->store)
ef5584
		{
ef5584
			if ($close === null)
ef5584
			{
ef5584
				$close = $this->close;
ef5584
			}
ef5584
			$close($this->fp);
ef5584
		}
ef5584
ef5584
		// bzip2 must be written all the way at the end
ef5584
		if ($this->download && $this->format === 'bzip2')
ef5584
		{
ef5584
			$c = ob_get_clean();
ef5584
			echo bzcompress($c);
ef5584
		}
ef5584
	}
ef5584
ef5584
	function flush($data)
ef5584
	{
ef5584
		static $write;
ef5584
		if ($this->store === true)
ef5584
		{
ef5584
			if ($write === null)
ef5584
			{
ef5584
				$write = $this->write;
ef5584
			}
ef5584
			$write($this->fp, $data);
ef5584
		}
ef5584
ef5584
		if ($this->download === true)
ef5584
		{
ef5584
			if ($this->format === 'bzip2' || $this->format === 'text' || ($this->format === 'gzip' && !$this->run_comp))
ef5584
			{
ef5584
				echo $data;
ef5584
			}
ef5584
ef5584
			// we can write the gzip data as soon as we get it
ef5584
			if ($this->format === 'gzip')
ef5584
			{
ef5584
				if ($this->run_comp)
ef5584
				{
ef5584
					echo gzencode($data);
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					ob_flush();
ef5584
					flush();
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class mysql_extractor extends base_extractor
ef5584
{
ef5584
	function write_start($table_prefix)
ef5584
	{
ef5584
		$sql_data = "#\n";
ef5584
		$sql_data .= "# phpBB Backup Script\n";
ef5584
		$sql_data .= "# Dump of tables for $table_prefix\n";
ef5584
		$sql_data .= "# DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "#\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		static $new_extract;
ef5584
ef5584
		if ($new_extract === null)
ef5584
		{
ef5584
			if ($db->sql_layer === 'mysqli' || version_compare($db->sql_server_info(true), '3.23.20', '>='))
ef5584
			{
ef5584
				$new_extract = true;
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$new_extract = false;
ef5584
			}
ef5584
		}
ef5584
ef5584
		if ($new_extract)
ef5584
		{
ef5584
			$this->new_write_table($table_name);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->old_write_table($table_name);
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		if ($db->sql_layer === 'mysqli')
ef5584
		{
ef5584
			$this->write_data_mysqli($table_name);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->write_data_mysql($table_name);
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_data_mysqli($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = mysqli_query($db->db_connect_id, $sql, MYSQLI_USE_RESULT);
ef5584
		if ($result != false)
ef5584
		{
ef5584
			$fields_cnt = mysqli_num_fields($result);
ef5584
		
ef5584
			// Get field information
ef5584
			$field = mysqli_fetch_fields($result);
ef5584
			$field_set = array();
ef5584
		
ef5584
			for ($j = 0; $j < $fields_cnt; $j++)
ef5584
			{
ef5584
				$field_set[] = $field[$j]->name;
ef5584
			}
ef5584
ef5584
			$search			= array("\\", "'", "\x00", "\x0a", "\x0d", "\x1a", '"');
ef5584
			$replace		= array("\\\\", "\\'", '\0', '\n', '\r', '\Z', '\\"');
ef5584
			$fields			= implode(', ', $field_set);
ef5584
			$sql_data		= 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES ';
ef5584
			$first_set		= true;
ef5584
			$query_len		= 0;
ef5584
			$max_len		= get_usable_memory();
ef5584
		
ef5584
			while ($row = mysqli_fetch_row($result))
ef5584
			{
ef5584
				$values	= array();
ef5584
				if ($first_set)
ef5584
				{
ef5584
					$query = $sql_data . '(';
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$query  .= ',(';
ef5584
				}
ef5584
ef5584
				for ($j = 0; $j < $fields_cnt; $j++)
ef5584
				{
ef5584
					if (!isset($row[$j]) || is_null($row[$j]))
ef5584
					{
ef5584
						$values[$j] = 'NULL';
ef5584
					}
ef5584
					else if (($field[$j]->flags & 32768) && !($field[$j]->flags & 1024))
ef5584
					{
ef5584
						$values[$j] = $row[$j];
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
ef5584
					}
ef5584
				}
ef5584
				$query .= implode(', ', $values) . ')';
ef5584
ef5584
				$query_len += strlen($query);
ef5584
				if ($query_len > $max_len)
ef5584
				{
ef5584
					$this->flush($query . ";\n\n");
ef5584
					$query = '';
ef5584
					$query_len = 0;
ef5584
					$first_set = true;
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$first_set = false;
ef5584
				}
ef5584
			}
ef5584
			mysqli_free_result($result);
ef5584
ef5584
			// check to make sure we have nothing left to flush
ef5584
			if (!$first_set && $query)
ef5584
			{
ef5584
				$this->flush($query . ";\n\n");
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_data_mysql($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = mysql_unbuffered_query($sql, $db->db_connect_id);
ef5584
ef5584
		if ($result != false)
ef5584
		{
ef5584
			$fields_cnt = mysql_num_fields($result);
ef5584
ef5584
			// Get field information
ef5584
			$field = array();
ef5584
			for ($i = 0; $i < $fields_cnt; $i++)
ef5584
			{
ef5584
				$field[] = mysql_fetch_field($result, $i);
ef5584
			}
ef5584
			$field_set = array();
ef5584
			
ef5584
			for ($j = 0; $j < $fields_cnt; $j++)
ef5584
			{
ef5584
				$field_set[] = $field[$j]->name;
ef5584
			}
ef5584
ef5584
			$search			= array("\\", "'", "\x00", "\x0a", "\x0d", "\x1a", '"');
ef5584
			$replace		= array("\\\\", "\\'", '\0', '\n', '\r', '\Z', '\\"');
ef5584
			$fields			= implode(', ', $field_set);
ef5584
			$sql_data		= 'INSERT INTO ' . $table_name . ' (' . $fields . ') VALUES ';
ef5584
			$first_set		= true;
ef5584
			$query_len		= 0;
ef5584
			$max_len		= get_usable_memory();
ef5584
ef5584
			while ($row = mysql_fetch_row($result))
ef5584
			{
ef5584
				$values = array();
ef5584
				if ($first_set)
ef5584
				{
ef5584
					$query = $sql_data . '(';
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$query  .= ',(';
ef5584
				}
ef5584
ef5584
				for ($j = 0; $j < $fields_cnt; $j++)
ef5584
				{
ef5584
					if (!isset($row[$j]) || is_null($row[$j]))
ef5584
					{
ef5584
						$values[$j] = 'NULL';
ef5584
					}
ef5584
					else if ($field[$j]->numeric && ($field[$j]->type !== 'timestamp'))
ef5584
					{
ef5584
						$values[$j] = $row[$j];
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$values[$j] = "'" . str_replace($search, $replace, $row[$j]) . "'";
ef5584
					}
ef5584
				}
ef5584
				$query .= implode(', ', $values) . ')';
ef5584
ef5584
				$query_len += strlen($query);
ef5584
				if ($query_len > $max_len)
ef5584
				{
ef5584
					$this->flush($query . ";\n\n");
ef5584
					$query = '';
ef5584
					$query_len = 0;
ef5584
					$first_set = true;
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$first_set = false;
ef5584
				}
ef5584
			}
ef5584
			mysql_free_result($result);
ef5584
ef5584
			// check to make sure we have nothing left to flush
ef5584
			if (!$first_set && $query)
ef5584
			{
ef5584
				$this->flush($query . ";\n\n");
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	function new_write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		$sql = 'SHOW CREATE TABLE ' . $table_name;
ef5584
		$result = $db->sql_query($sql);
ef5584
		$row = $db->sql_fetchrow($result);
ef5584
ef5584
		$sql_data = '# Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE IF EXISTS $table_name;\n";
ef5584
		$this->flush($sql_data . $row['Create Table'] . ";\n\n");
ef5584
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	function old_write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		$sql_data = '# Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE IF EXISTS $table_name;\n";
ef5584
		$sql_data .= "CREATE TABLE $table_name(\n";
ef5584
		$rows = array();
ef5584
ef5584
		$sql = "SHOW FIELDS
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$line = '   ' . $row['Field'] . ' ' . $row['Type'];
ef5584
ef5584
			if (!is_null($row['Default']))
ef5584
			{
ef5584
				$line .= " DEFAULT '{$row['Default']}'";
ef5584
			}
ef5584
ef5584
			if ($row['Null'] != 'YES')
ef5584
			{
ef5584
				$line .= ' NOT NULL';
ef5584
			}
ef5584
ef5584
			if ($row['Extra'] != '')
ef5584
			{
ef5584
				$line .= ' ' . $row['Extra'];
ef5584
			}
ef5584
ef5584
			$rows[] = $line;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = "SHOW KEYS
ef5584
			FROM $table_name";
ef5584
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$index = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$kname = $row['Key_name'];
ef5584
ef5584
			if ($kname != 'PRIMARY')
ef5584
			{
ef5584
				if ($row['Non_unique'] == 0)
ef5584
				{
ef5584
					$kname = "UNIQUE|$kname";
ef5584
				}
ef5584
			}
ef5584
ef5584
			if ($row['Sub_part'])
ef5584
			{
ef5584
				$row['Column_name'] .= '(' . $row['Sub_part'] . ')';
ef5584
			}
ef5584
			$index[$kname][] = $row['Column_name'];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		foreach ($index as $key => $columns)
ef5584
		{
ef5584
			$line = '   ';
ef5584
ef5584
			if ($key == 'PRIMARY')
ef5584
			{
ef5584
				$line .= 'PRIMARY KEY (' . implode(', ', $columns) . ')';
ef5584
			}
ef5584
			else if (strpos($key, 'UNIQUE') === 0)
ef5584
			{
ef5584
				$line .= 'UNIQUE ' . substr($key, 7) . ' (' . implode(', ', $columns) . ')';
ef5584
			}
ef5584
			else if (strpos($key, 'FULLTEXT') === 0)
ef5584
			{
ef5584
				$line .= 'FULLTEXT ' . substr($key, 9) . ' (' . implode(', ', $columns) . ')';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$line .= "KEY $key (" . implode(', ', $columns) . ')';
ef5584
			}
ef5584
ef5584
			$rows[] = $line;
ef5584
		}
ef5584
ef5584
		$sql_data .= implode(",\n", $rows);
ef5584
		$sql_data .= "\n);\n\n";
ef5584
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class sqlite_extractor extends base_extractor
ef5584
{
ef5584
	function write_start($prefix)
ef5584
	{
ef5584
		$sql_data = "--\n";
ef5584
		$sql_data .= "-- phpBB Backup Script\n";
ef5584
		$sql_data .= "-- Dump of tables for $prefix\n";
ef5584
		$sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "--\n";
ef5584
		$sql_data .= "BEGIN TRANSACTION;\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$sql_data = '-- Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE $table_name;\n";
ef5584
ef5584
		$sql = "SELECT sql
ef5584
			FROM sqlite_master
ef5584
			WHERE type = 'table'
ef5584
				AND name = '" . $db->sql_escape($table_name) . "'
ef5584
			ORDER BY type DESC, name;";
ef5584
		$result = $db->sql_query($sql);
ef5584
		$row = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		// Create Table
ef5584
		$sql_data .= $row['sql'] . ";\n";
ef5584
ef5584
		$result = $db->sql_query("PRAGMA index_list('" . $db->sql_escape($table_name) . "');");
ef5584
ef5584
		$ar = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$ar[] = $row;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
		
ef5584
		foreach ($ar as $value)
ef5584
		{
ef5584
			if (strpos($value['name'], 'autoindex') !== false)
ef5584
			{
ef5584
				continue;
ef5584
			}
ef5584
ef5584
			$result = $db->sql_query("PRAGMA index_info('" . $db->sql_escape($value['name']) . "');");
ef5584
ef5584
			$fields = array();
ef5584
			while ($row = $db->sql_fetchrow($result))
ef5584
			{
ef5584
				$fields[] = $row['name'];
ef5584
			}
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			$sql_data .= 'CREATE ' . ($value['unique'] ? 'UNIQUE ' : '') . 'INDEX ' . $value['name'] . ' on ' . $table_name . ' (' . implode(', ', $fields) . ");\n";
ef5584
		}
ef5584
ef5584
		$this->flush($sql_data . "\n");
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		static $proper;
ef5584
ef5584
		if (is_null($proper))
ef5584
		{
ef5584
			$proper = version_compare(PHP_VERSION, '5.1.3', '>=');
ef5584
		}
ef5584
ef5584
		if ($proper)
ef5584
		{
ef5584
			$col_types = sqlite_fetch_column_types($db->db_connect_id, $table_name);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$sql = "SELECT sql
ef5584
				FROM sqlite_master
ef5584
				WHERE type = 'table'
ef5584
					AND name = '" . $table_name . "'";
ef5584
			$table_data = sqlite_single_query($db->db_connect_id, $sql);
ef5584
			$table_data = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', '', $table_data);
ef5584
			$table_data = trim($table_data);
ef5584
ef5584
			preg_match('#\((.*)\)#s', $table_data, $matches);
ef5584
ef5584
			$table_cols = explode(',', trim($matches[1]));
ef5584
			foreach ($table_cols as $declaration)
ef5584
			{
ef5584
				$entities = preg_split('#\s+#', trim($declaration));
ef5584
				$column_name = preg_replace('/"?([^"]+)"?/', '\1', $entities[0]);
ef5584
ef5584
				// Hit a primary key, those are not what we need :D
ef5584
				if (empty($entities[1]) || (strtolower($entities[0]) === 'primary' && strtolower($entities[1]) === 'key'))
ef5584
				{
ef5584
					continue;
ef5584
				}
ef5584
				$col_types[$column_name] = $entities[1];
ef5584
			}
ef5584
		}
ef5584
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = sqlite_unbuffered_query($db->db_connect_id, $sql);
ef5584
		$rows = sqlite_fetch_all($result, SQLITE_ASSOC);
ef5584
		$sql_insert = 'INSERT INTO ' . $table_name . ' (' . implode(', ', array_keys($col_types)) . ') VALUES (';
ef5584
		foreach ($rows as $row)
ef5584
		{
ef5584
			foreach ($row as $column_name => $column_data)
ef5584
			{
ef5584
				if (is_null($column_data))
ef5584
				{
ef5584
					$row[$column_name] = 'NULL';
ef5584
				}
ef5584
				else if ($column_data == '')
ef5584
				{
ef5584
					$row[$column_name] = "''";
ef5584
				}
ef5584
				else if (strpos($col_types[$column_name], 'text') !== false || strpos($col_types[$column_name], 'char') !== false || strpos($col_types[$column_name], 'blob') !== false)
ef5584
				{
ef5584
					$row[$column_name] = sanitize_data_generic(str_replace("'", "''", $column_data));
ef5584
				}
ef5584
			}
ef5584
			$this->flush($sql_insert . implode(', ', $row) . ");\n");
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_end()
ef5584
	{
ef5584
		$this->flush("COMMIT;\n");
ef5584
		parent::write_end();
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class postgres_extractor extends base_extractor
ef5584
{
ef5584
	function write_start($prefix)
ef5584
	{
ef5584
		$sql_data = "--\n";
ef5584
		$sql_data .= "-- phpBB Backup Script\n";
ef5584
		$sql_data .= "-- Dump of tables for $prefix\n";
ef5584
		$sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "--\n";
ef5584
		$sql_data .= "BEGIN TRANSACTION;\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		static $domains_created = array();
ef5584
ef5584
		$sql = "SELECT a.domain_name, a.data_type, a.character_maximum_length, a.domain_default
ef5584
			FROM INFORMATION_SCHEMA.domains a, INFORMATION_SCHEMA.column_domain_usage b
ef5584
			WHERE a.domain_name = b.domain_name
ef5584
				AND b.table_name = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			if (empty($domains_created[$row['domain_name']]))
ef5584
			{
ef5584
				$domains_created[$row['domain_name']] = true;
ef5584
				//$sql_data = "DROP DOMAIN {$row['domain_name']};\n";
ef5584
				$sql_data = "CREATE DOMAIN {$row['domain_name']} as {$row['data_type']}";
ef5584
				if (!empty($row['character_maximum_length']))
ef5584
				{
ef5584
					$sql_data .= '(' . $row['character_maximum_length'] . ')';
ef5584
				}
ef5584
				$sql_data .= ' NOT NULL';
ef5584
				if (!empty($row['domain_default']))
ef5584
				{
ef5584
					$sql_data .= ' DEFAULT ' . $row['domain_default'];
ef5584
				}
ef5584
				$this->flush($sql_data . ";\n");
ef5584
			}
ef5584
		}
ef5584
ef5584
		$sql_data = '-- Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE $table_name;\n";
ef5584
		// PGSQL does not "tightly" bind sequences and tables, we must guess...
ef5584
		$sql = "SELECT relname
ef5584
			FROM pg_class
ef5584
			WHERE relkind = 'S'
ef5584
				AND relname = '{$table_name}_seq'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		// We don't even care about storing the results. We already know the answer if we get rows back.
ef5584
		if ($db->sql_fetchrow($result))
ef5584
		{
ef5584
			$sql_data .= "DROP SEQUENCE {$table_name}_seq;\n";
ef5584
			$sql_data .= "CREATE SEQUENCE {$table_name}_seq;\n";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	
ef5584
		$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
ef5584
			FROM pg_class c, pg_attribute a, pg_type t
ef5584
			WHERE c.relname = '" . $db->sql_escape($table_name) . "'
ef5584
				AND a.attnum > 0
ef5584
				AND a.attrelid = c.oid
ef5584
				AND a.atttypid = t.oid
ef5584
			ORDER BY a.attnum";
ef5584
		$result = $db->sql_query($field_query);
ef5584
ef5584
		$sql_data .= "CREATE TABLE $table_name(\n";
ef5584
		$lines = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			// Get the data from the table
ef5584
			$sql_get_default = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault
ef5584
				FROM pg_attrdef d, pg_class c
ef5584
				WHERE (c.relname = '" . $db->sql_escape($table_name) . "')
ef5584
					AND (c.oid = d.adrelid)
ef5584
					AND d.adnum = " . $row['attnum'];
ef5584
			$def_res = $db->sql_query($sql_get_default);
ef5584
ef5584
			if (!$def_res)
ef5584
			{
ef5584
				unset($row['rowdefault']);
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$row['rowdefault'] = $db->sql_fetchfield('rowdefault', false, $def_res);
ef5584
			}
ef5584
			$db->sql_freeresult($def_res);
ef5584
ef5584
			if ($row['type'] == 'bpchar')
ef5584
			{
ef5584
				// Internally stored as bpchar, but isn't accepted in a CREATE TABLE statement.
ef5584
				$row['type'] = 'char';
ef5584
			}
ef5584
ef5584
			$line = '  ' . $row['field'] . ' ' . $row['type'];
ef5584
ef5584
			if (strpos($row['type'], 'char') !== false)
ef5584
			{
ef5584
				if ($row['lengthvar'] > 0)
ef5584
				{
ef5584
					$line .= '(' . ($row['lengthvar'] - 4) . ')';
ef5584
				}
ef5584
			}
ef5584
ef5584
			if (strpos($row['type'], 'numeric') !== false)
ef5584
			{
ef5584
				$line .= '(';
ef5584
				$line .= sprintf("%s,%s", (($row['lengthvar'] >> 16) & 0xffff), (($row['lengthvar'] - 4) & 0xffff));
ef5584
				$line .= ')';
ef5584
			}
ef5584
ef5584
			if (isset($row['rowdefault']))
ef5584
			{
ef5584
				$line .= ' DEFAULT ' . $row['rowdefault'];
ef5584
			}
ef5584
ef5584
			if ($row['notnull'] == 't')
ef5584
			{
ef5584
				$line .= ' NOT NULL';
ef5584
			}
ef5584
			
ef5584
			$lines[] = $line;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
ef5584
		// Get the listing of primary keys.
ef5584
		$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
ef5584
			FROM pg_class bc, pg_class ic, pg_index i, pg_attribute ta, pg_attribute ia
ef5584
			WHERE (bc.oid = i.indrelid)
ef5584
				AND (ic.oid = i.indexrelid)
ef5584
				AND (ia.attrelid = i.indexrelid)
ef5584
				AND	(ta.attrelid = bc.oid)
ef5584
				AND (bc.relname = '" . $db->sql_escape($table_name) . "')
ef5584
				AND (ta.attrelid = i.indrelid)
ef5584
				AND (ta.attnum = i.indkey[ia.attnum-1])
ef5584
			ORDER BY index_name, tab_name, column_name";
ef5584
ef5584
		$result = $db->sql_query($sql_pri_keys);
ef5584
ef5584
		$index_create = $index_rows = $primary_key = array();
ef5584
ef5584
		// We do this in two steps. It makes placing the comma easier
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			if ($row['primary_key'] == 't')
ef5584
			{
ef5584
				$primary_key[] = $row['column_name'];
ef5584
				$primary_key_name = $row['index_name'];
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				// We have to store this all this info because it is possible to have a multi-column key...
ef5584
				// we can loop through it again and build the statement
ef5584
				$index_rows[$row['index_name']]['table'] = $table_name;
ef5584
				$index_rows[$row['index_name']]['unique'] = ($row['unique_key'] == 't') ? true : false;
ef5584
				$index_rows[$row['index_name']]['column_names'][] = $row['column_name'];
ef5584
			}
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if (!empty($index_rows))
ef5584
		{
ef5584
			foreach ($index_rows as $idx_name => $props)
ef5584
			{
ef5584
				$index_create[] = 'CREATE ' . ($props['unique'] ? 'UNIQUE ' : '') . "INDEX $idx_name ON $table_name (" . implode(', ', $props['column_names']) . ");";
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (!empty($primary_key))
ef5584
		{
ef5584
			$lines[] = "  CONSTRAINT $primary_key_name PRIMARY KEY (" . implode(', ', $primary_key) . ")";
ef5584
		}
ef5584
ef5584
		// Generate constraint clauses for CHECK constraints
ef5584
		$sql_checks = "SELECT conname as index_name, consrc
ef5584
			FROM pg_constraint, pg_class bc
ef5584
			WHERE conrelid = bc.oid
ef5584
				AND bc.relname = '" . $db->sql_escape($table_name) . "'
ef5584
				AND NOT EXISTS (
ef5584
					SELECT *
ef5584
						FROM pg_constraint as c, pg_inherits as i
ef5584
						WHERE i.inhrelid = pg_constraint.conrelid
ef5584
							AND c.conname = pg_constraint.conname
ef5584
							AND c.consrc = pg_constraint.consrc
ef5584
							AND c.conrelid = i.inhparent
ef5584
				)";
ef5584
		$result = $db->sql_query($sql_checks);
ef5584
ef5584
		// Add the constraints to the sql file.
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			if (!is_null($row['consrc']))
ef5584
			{
ef5584
				$lines[] = '  CONSTRAINT ' . $row['index_name'] . ' CHECK ' . $row['consrc'];
ef5584
			}
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql_data .= implode(", \n", $lines);
ef5584
		$sql_data .= "\n);\n";
ef5584
ef5584
		if (!empty($index_create))
ef5584
		{
ef5584
			$sql_data .= implode("\n", $index_create) . "\n\n";
ef5584
		}
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		// Grab all of the data from current table.
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$i_num_fields = pg_num_fields($result);
ef5584
		$seq = '';
ef5584
ef5584
		for ($i = 0; $i < $i_num_fields; $i++)
ef5584
		{
ef5584
			$ary_type[] = pg_field_type($result, $i);
ef5584
			$ary_name[] = pg_field_name($result, $i);
ef5584
ef5584
ef5584
			$sql = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault
ef5584
				FROM pg_attrdef d, pg_class c
ef5584
				WHERE (c.relname = '{$table_name}')
ef5584
					AND (c.oid = d.adrelid)
ef5584
					AND d.adnum = " . strval($i + 1);
ef5584
			$result2 = $db->sql_query($sql);
ef5584
			if ($row = $db->sql_fetchrow($result2))
ef5584
			{
ef5584
				// Determine if we must reset the sequences
ef5584
				if (strpos($row['rowdefault'], "nextval('") === 0)
ef5584
				{
ef5584
					$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";
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		$this->flush("COPY $table_name (" . implode(', ', $ary_name) . ') FROM stdin;' . "\n");
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$schema_vals = array();
ef5584
ef5584
			// Build the SQL statement to recreate the data.
ef5584
			for ($i = 0; $i < $i_num_fields; $i++)
ef5584
			{
ef5584
				$str_val = $row[$ary_name[$i]];
ef5584
ef5584
				if (preg_match('#char|text|bool|bytea#i', $ary_type[$i]))
ef5584
				{
ef5584
					$str_val = str_replace(array("\n", "\t", "\r", "\b", "\f", "\v"), array('\n', '\t', '\r', '\b', '\f', '\v'), addslashes($str_val));
ef5584
					$str_empty = '';
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$str_empty = '\N';
ef5584
				}
ef5584
ef5584
				if (empty($str_val) && $str_val !== '0')
ef5584
				{
ef5584
					$str_val = $str_empty;
ef5584
				}
ef5584
ef5584
				$schema_vals[] = $str_val;
ef5584
			}
ef5584
ef5584
			// Take the ordered fields and their associated data and build it
ef5584
			// into a valid sql statement to recreate that field in the data.
ef5584
			$this->flush(implode("\t", $schema_vals) . "\n");
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
		$this->flush("\\.\n");
ef5584
ef5584
		// Write out the sequence statements
ef5584
		$this->flush($seq);
ef5584
	}
ef5584
ef5584
	function write_end()
ef5584
	{
ef5584
		$this->flush("COMMIT;\n");
ef5584
		parent::write_end();
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class mssql_extractor extends base_extractor
ef5584
{
ef5584
	function write_end()
ef5584
	{
ef5584
		$this->flush("COMMIT\nGO\n");
ef5584
		parent::write_end();
ef5584
	}
ef5584
ef5584
	function write_start($prefix)
ef5584
	{
ef5584
		$sql_data = "--\n";
ef5584
		$sql_data .= "-- phpBB Backup Script\n";
ef5584
		$sql_data .= "-- Dump of tables for $prefix\n";
ef5584
		$sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "--\n";
ef5584
		$sql_data .= "BEGIN TRANSACTION\n";
ef5584
		$sql_data .= "GO\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$sql_data = '-- Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "IF OBJECT_ID(N'$table_name', N'U') IS NOT NULL\n";
ef5584
		$sql_data .= "DROP TABLE $table_name;\n";
ef5584
		$sql_data .= "GO\n";
ef5584
		$sql_data .= "\nCREATE TABLE [$table_name] (\n";
ef5584
		$rows = array();
ef5584
	
ef5584
		$text_flag = false;
ef5584
	
ef5584
		$sql = "SELECT COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') as IS_IDENTITY
ef5584
			FROM INFORMATION_SCHEMA.COLUMNS
ef5584
			WHERE TABLE_NAME = '$table_name'";
ef5584
		$result = $db->sql_query($sql);
ef5584
	
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$line = "\t[{$row['COLUMN_NAME']}] [{$row['DATA_TYPE']}]";
ef5584
	
ef5584
			if ($row['DATA_TYPE'] == 'text')
ef5584
			{
ef5584
				$text_flag = true;
ef5584
			}
ef5584
	
ef5584
			if ($row['IS_IDENTITY'])
ef5584
			{
ef5584
				$line .= ' IDENTITY (1 , 1)';
ef5584
			}
ef5584
	
ef5584
			if ($row['CHARACTER_MAXIMUM_LENGTH'] && $row['DATA_TYPE'] !== 'text')
ef5584
			{
ef5584
				$line .= ' (' . $row['CHARACTER_MAXIMUM_LENGTH'] . ')';
ef5584
			}
ef5584
	
ef5584
			if ($row['IS_NULLABLE'] == 'YES')
ef5584
			{
ef5584
				$line .= ' NULL';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$line .= ' NOT NULL';
ef5584
			}
ef5584
	
ef5584
			if ($row['COLUMN_DEFAULT'])
ef5584
			{
ef5584
				$line .= ' DEFAULT ' . $row['COLUMN_DEFAULT'];
ef5584
			}
ef5584
	
ef5584
			$rows[] = $line;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	
ef5584
		$sql_data .= implode(",\n", $rows);
ef5584
		$sql_data .= "\n) ON [PRIMARY]";
ef5584
	
ef5584
		if ($text_flag)
ef5584
		{
ef5584
			$sql_data .= " TEXTIMAGE_ON [PRIMARY]";
ef5584
		}
ef5584
	
ef5584
		$sql_data .= "\nGO\n\n";
ef5584
		$rows = array();
ef5584
	
ef5584
		$sql = "SELECT CONSTRAINT_NAME, COLUMN_NAME
ef5584
			FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
ef5584
			WHERE TABLE_NAME = '$table_name'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			if (!sizeof($rows))
ef5584
			{
ef5584
				$sql_data .= "ALTER TABLE [$table_name] WITH NOCHECK ADD\n";
ef5584
				$sql_data .= "\tCONSTRAINT [{$row['CONSTRAINT_NAME']}] PRIMARY KEY  CLUSTERED \n\t(\n";
ef5584
			}
ef5584
			$rows[] = "\t\t[{$row['COLUMN_NAME']}]";
ef5584
		}
ef5584
		if (sizeof($rows))
ef5584
		{
ef5584
			$sql_data .= implode(",\n", $rows);
ef5584
			$sql_data .= "\n\t)  ON [PRIMARY] \nGO\n";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	
ef5584
		$index = array();
ef5584
		$sql = "EXEC sp_statistics '$table_name'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			if ($row['TYPE'] == 3)
ef5584
			{
ef5584
				$index[$row['INDEX_NAME']][] = '[' . $row['COLUMN_NAME'] . ']';
ef5584
			}
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	
ef5584
		foreach ($index as $index_name => $column_name)
ef5584
		{
ef5584
			$index[$index_name] = implode(', ', $column_name);
ef5584
		}
ef5584
	
ef5584
		foreach ($index as $index_name => $columns)
ef5584
		{
ef5584
			$sql_data .= "\nCREATE  INDEX [$index_name] ON [$table_name]($columns) ON [PRIMARY]\nGO\n";
ef5584
		}
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		if ($db->sql_layer === 'mssql')
ef5584
		{
ef5584
			$this->write_data_mssql($table_name);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->write_data_odbc($table_name);
ef5584
		}
ef5584
	}
ef5584
ef5584
	function write_data_mssql($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$ary_type = $ary_name = array();
ef5584
		$ident_set = false;
ef5584
		$sql_data = '';
ef5584
		
ef5584
		// Grab all of the data from current table.
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$retrieved_data = mssql_num_rows($result);
ef5584
ef5584
		$i_num_fields = mssql_num_fields($result);
ef5584
ef5584
		for ($i = 0; $i < $i_num_fields; $i++)
ef5584
		{
ef5584
			$ary_type[$i] = mssql_field_type($result, $i);
ef5584
			$ary_name[$i] = mssql_field_name($result, $i);
ef5584
		}
ef5584
ef5584
		if ($retrieved_data)
ef5584
		{
ef5584
			$sql = "SELECT 1 as has_identity
ef5584
				FROM INFORMATION_SCHEMA.COLUMNS
ef5584
				WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
ef5584
			$result2 = $db->sql_query($sql);
ef5584
			$row2 = $db->sql_fetchrow($result2);
ef5584
			if (!empty($row2['has_identity']))
ef5584
			{
ef5584
				$sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
ef5584
				$ident_set = true;
ef5584
			}
ef5584
			$db->sql_freeresult($result2);
ef5584
		}
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$schema_vals = $schema_fields = array();
ef5584
ef5584
			// Build the SQL statement to recreate the data.
ef5584
			for ($i = 0; $i < $i_num_fields; $i++)
ef5584
			{
ef5584
				$str_val = $row[$ary_name[$i]];
ef5584
ef5584
				if (preg_match('#char|text|bool|varbinary#i', $ary_type[$i]))
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = "''";
ef5584
					$str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
ef5584
				}
ef5584
				else if (preg_match('#date|timestamp#i', $ary_type[$i]))
ef5584
				{
ef5584
					if (empty($str_val))
ef5584
					{
ef5584
						$str_quote = '';
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$str_quote = "'";
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = 'NULL';
ef5584
				}
ef5584
ef5584
				if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val)))
ef5584
				{
ef5584
					$str_val = $str_empty;
ef5584
				}
ef5584
ef5584
				$schema_vals[$i] = $str_quote . $str_val . $str_quote;
ef5584
				$schema_fields[$i] = $ary_name[$i];
ef5584
			}
ef5584
ef5584
			// Take the ordered fields and their associated data and build it
ef5584
			// into a valid sql statement to recreate that field in the data.
ef5584
			$sql_data .= "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
ef5584
ef5584
			$this->flush($sql_data);
ef5584
			$sql_data = '';
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if ($retrieved_data && $ident_set)
ef5584
		{
ef5584
			$sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
ef5584
		}
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_data_odbc($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$ary_type = $ary_name = array();
ef5584
		$ident_set = false;
ef5584
		$sql_data = '';
ef5584
		
ef5584
		// Grab all of the data from current table.
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$retrieved_data = odbc_num_rows($result);
ef5584
ef5584
		if ($retrieved_data)
ef5584
		{
ef5584
			$sql = "SELECT 1 as has_identity
ef5584
				FROM INFORMATION_SCHEMA.COLUMNS
ef5584
				WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
ef5584
			$result2 = $db->sql_query($sql);
ef5584
			$row2 = $db->sql_fetchrow($result2);
ef5584
			if (!empty($row2['has_identity']))
ef5584
			{
ef5584
				$sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
ef5584
				$ident_set = true;
ef5584
			}
ef5584
			$db->sql_freeresult($result2);
ef5584
		}
ef5584
ef5584
		$i_num_fields = odbc_num_fields($result);
ef5584
ef5584
		for ($i = 0; $i < $i_num_fields; $i++)
ef5584
		{
ef5584
			$ary_type[$i] = odbc_field_type($result, $i + 1);
ef5584
			$ary_name[$i] = odbc_field_name($result, $i + 1);
ef5584
		}
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$schema_vals = $schema_fields = array();
ef5584
ef5584
			// Build the SQL statement to recreate the data.
ef5584
			for ($i = 0; $i < $i_num_fields; $i++)
ef5584
			{
ef5584
				$str_val = $row[$ary_name[$i]];
ef5584
ef5584
				if (preg_match('#char|text|bool|varbinary#i', $ary_type[$i]))
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = "''";
ef5584
					$str_val = sanitize_data_mssql(str_replace("'", "''", $str_val));
ef5584
				}
ef5584
				else if (preg_match('#date|timestamp#i', $ary_type[$i]))
ef5584
				{
ef5584
					if (empty($str_val))
ef5584
					{
ef5584
						$str_quote = '';
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$str_quote = "'";
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = 'NULL';
ef5584
				}
ef5584
ef5584
				if (empty($str_val) && $str_val !== '0' && !(is_int($str_val) || is_float($str_val)))
ef5584
				{
ef5584
					$str_val = $str_empty;
ef5584
				}
ef5584
ef5584
				$schema_vals[$i] = $str_quote . $str_val . $str_quote;
ef5584
				$schema_fields[$i] = $ary_name[$i];
ef5584
			}
ef5584
ef5584
			// Take the ordered fields and their associated data and build it
ef5584
			// into a valid sql statement to recreate that field in the data.
ef5584
			$sql_data .= "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\nGO\n";
ef5584
ef5584
			$this->flush($sql_data);
ef5584
ef5584
			$sql_data = '';
ef5584
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		if ($retrieved_data && $ident_set)
ef5584
		{
ef5584
			$sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
ef5584
		}
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class oracle_extractor extends base_extractor
ef5584
{
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$sql_data = '-- Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE $table_name;\n";
ef5584
		$sql_data .= '\\' . "\n";
ef5584
		$sql_data .= "\nCREATE TABLE $table_name (\n";
ef5584
ef5584
		$sql = "SELECT COLUMN_NAME, DATA_TYPE, DATA_PRECISION, DATA_LENGTH, NULLABLE, DATA_DEFAULT
ef5584
			FROM ALL_TAB_COLS
ef5584
			WHERE table_name = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$rows = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$line = '  "' . $row['column_name'] . '" ' . $row['data_type'];
ef5584
ef5584
			if ($row['data_type'] !== 'CLOB')
ef5584
			{
ef5584
				if ($row['data_type'] !== 'VARCHAR2')
ef5584
				{
ef5584
					$line .= '(' . $row['data_precision'] . ')';
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$line .= '(' . $row['data_length'] . ')';
ef5584
				}
ef5584
			}
ef5584
ef5584
			if (!empty($row['data_default']))
ef5584
			{
ef5584
				$line .= ' DEFAULT ' . $row['data_default'];
ef5584
			}
ef5584
ef5584
			if ($row['nullable'] == 'N')
ef5584
			{
ef5584
				$line .= ' NOT NULL';
ef5584
			}
ef5584
			$rows[] = $line;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = "SELECT A.CONSTRAINT_NAME, A.COLUMN_NAME
ef5584
			FROM USER_CONS_COLUMNS A, USER_CONSTRAINTS B
ef5584
			WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
ef5584
				AND B.CONSTRAINT_TYPE = 'P'
ef5584
				AND A.TABLE_NAME = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$rows[] = "  CONSTRAINT {$row['constraint_name']} PRIMARY KEY ({$row['column_name']})";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = "SELECT A.CONSTRAINT_NAME, A.COLUMN_NAME
ef5584
			FROM USER_CONS_COLUMNS A, USER_CONSTRAINTS B
ef5584
			WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
ef5584
				AND B.CONSTRAINT_TYPE = 'U'
ef5584
				AND A.TABLE_NAME = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$rows[] = "  CONSTRAINT {$row['constraint_name']} UNIQUE ({$row['column_name']})";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql_data .= implode(",\n", $rows);
ef5584
		$sql_data .= "\n)\n\\";
ef5584
ef5584
		$sql = "SELECT A.REFERENCED_NAME
ef5584
			FROM USER_DEPENDENCIES A, USER_TRIGGERS B
ef5584
			WHERE A.REFERENCED_TYPE = 'SEQUENCE'
ef5584
				AND A.NAME = B.TRIGGER_NAME
ef5584
				AND B. TABLE_NAME = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$sql_data .= "\nCREATE SEQUENCE {$row['referenced_name']}\\\n";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = "SELECT DESCRIPTION, WHEN_CLAUSE, TRIGGER_BODY
ef5584
			FROM USER_TRIGGERS
ef5584
			WHERE TABLE_NAME = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$sql_data .= "\nCREATE OR REPLACE TRIGGER {$row['description']}WHEN ({$row['when_clause']})\n{$row['trigger_body']}\\";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = "SELECT A.INDEX_NAME, B.COLUMN_NAME
ef5584
			FROM USER_INDEXES A, USER_IND_COLUMNS B
ef5584
			WHERE A.UNIQUENESS = 'NONUNIQUE'
ef5584
				AND A.INDEX_NAME = B.INDEX_NAME
ef5584
				AND B.TABLE_NAME = '{$table_name}'";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$index = array();
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$index[$row['index_name']][] = $row['column_name'];
ef5584
		}
ef5584
ef5584
		foreach ($index as $index_name => $column_names)
ef5584
		{
ef5584
			$sql_data .= "\nCREATE INDEX $index_name ON $table_name(" . implode(', ', $column_names) . ")\n\\";
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$ary_type = $ary_name = array();
ef5584
		
ef5584
		// Grab all of the data from current table.
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$i_num_fields = ocinumcols($result);
ef5584
ef5584
		for ($i = 0; $i < $i_num_fields; $i++)
ef5584
		{
ef5584
			$ary_type[$i] = ocicolumntype($result, $i + 1);
ef5584
			$ary_name[$i] = ocicolumnname($result, $i + 1);
ef5584
		}
ef5584
ef5584
		$sql_data = '';
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$schema_vals = $schema_fields = array();
ef5584
ef5584
			// Build the SQL statement to recreate the data.
ef5584
			for ($i = 0; $i < $i_num_fields; $i++)
ef5584
			{
ef5584
				$str_val = $row[$ary_name[$i]];
ef5584
ef5584
				if (preg_match('#char|text|bool|raw#i', $ary_type[$i]))
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = "''";
ef5584
					$str_val = sanitize_data_oracle($str_val);
ef5584
				}
ef5584
				else if (preg_match('#date|timestamp#i', $ary_type[$i]))
ef5584
				{
ef5584
					if (empty($str_val))
ef5584
					{
ef5584
						$str_quote = '';
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$str_quote = "'";
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = 'NULL';
ef5584
				}
ef5584
ef5584
				if (empty($str_val) && $str_val !== '0')
ef5584
				{
ef5584
					$str_val = $str_empty;
ef5584
				}
ef5584
ef5584
				$schema_vals[$i] = $str_quote . $str_val . $str_quote;
ef5584
				$schema_fields[$i] = '"' . $ary_name[$i] . "'";
ef5584
			}
ef5584
ef5584
			// Take the ordered fields and their associated data and build it
ef5584
			// into a valid sql statement to recreate that field in the data.
ef5584
			$sql_data = "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\n";
ef5584
ef5584
			$this->flush($sql_data);
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	function write_start($prefix)
ef5584
	{
ef5584
		$sql_data = "--\n";
ef5584
		$sql_data .= "-- phpBB Backup Script\n";
ef5584
		$sql_data .= "-- Dump of tables for $prefix\n";
ef5584
		$sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "--\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* @package acp
ef5584
*/
ef5584
class firebird_extractor extends base_extractor
ef5584
{
ef5584
	function write_start($prefix)
ef5584
	{
ef5584
		$sql_data = "--\n";
ef5584
		$sql_data .= "-- phpBB Backup Script\n";
ef5584
		$sql_data .= "-- Dump of tables for $prefix\n";
ef5584
		$sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n";
ef5584
		$sql_data .= "--\n";
ef5584
		$this->flush($sql_data);
ef5584
	}
ef5584
ef5584
	function write_data($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
		$ary_type = $ary_name = array();
ef5584
		
ef5584
		// Grab all of the data from current table.
ef5584
		$sql = "SELECT *
ef5584
			FROM $table_name";
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$i_num_fields = ibase_num_fields($result);
ef5584
ef5584
		for ($i = 0; $i < $i_num_fields; $i++)
ef5584
		{
ef5584
			$info = ibase_field_info($result, $i);
ef5584
			$ary_type[$i] = $info['type'];
ef5584
			$ary_name[$i] = $info['name'];
ef5584
		}
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$schema_vals = $schema_fields = array();
ef5584
ef5584
			// Build the SQL statement to recreate the data.
ef5584
			for ($i = 0; $i < $i_num_fields; $i++)
ef5584
			{
ef5584
				$str_val = $row[strtolower($ary_name[$i])];
ef5584
ef5584
				if (preg_match('#char|text|bool|varbinary|blob#i', $ary_type[$i]))
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = "''";
ef5584
					$str_val = sanitize_data_generic(str_replace("'", "''", $str_val));
ef5584
				}
ef5584
				else if (preg_match('#date|timestamp#i', $ary_type[$i]))
ef5584
				{
ef5584
					if (empty($str_val))
ef5584
					{
ef5584
						$str_quote = '';
ef5584
					}
ef5584
					else
ef5584
					{
ef5584
						$str_quote = "'";
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$str_quote = '';
ef5584
					$str_empty = 'NULL';
ef5584
				}
ef5584
ef5584
				if (empty($str_val) && $str_val !== '0')
ef5584
				{
ef5584
					$str_val = $str_empty;
ef5584
				}
ef5584
ef5584
				$schema_vals[$i] = $str_quote . $str_val . $str_quote;
ef5584
				$schema_fields[$i] = '"' . $ary_name[$i] . '"';
ef5584
			}
ef5584
ef5584
			// Take the ordered fields and their associated data and build it
ef5584
			// into a valid sql statement to recreate that field in the data.
ef5584
			$sql_data = "INSERT INTO $table_name (" . implode(', ', $schema_fields) . ') VALUES (' . implode(', ', $schema_vals) . ");\n";
ef5584
ef5584
			$this->flush($sql_data);
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	function write_table($table_name)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		$sql_data = '-- Table: ' . $table_name . "\n";
ef5584
		$sql_data .= "DROP TABLE $table_name;\n";
ef5584
ef5584
		$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');
ef5584
ef5584
		$sql_data .= "\nCREATE TABLE $table_name (\n";
ef5584
ef5584
		$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
ef5584
			FROM RDB$RELATION_FIELDS R
ef5584
			JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME
ef5584
			LEFT JOIN RDB$FIELD_DIMENSIONS D ON R.RDB$FIELD_SOURCE = D.RDB$FIELD_NAME
ef5584
			WHERE F.RDB$SYSTEM_FLAG = 0
ef5584
				AND R.RDB$RELATION_NAME = \''. $table_name . '\'
ef5584
			ORDER BY R.RDB$FIELD_POSITION';
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$rows = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$line = "\t" . '"' . $row['fname'] . '" ' . $data_types[$row['ftype']];
ef5584
ef5584
			if ($row['ftype'] == 261 && $row['stype'] == 1)
ef5584
			{
ef5584
				$line .= ' SUB_TYPE TEXT';
ef5584
			}
ef5584
ef5584
			if ($row['ftype'] == 37 || $row['ftype'] == 14)
ef5584
			{
ef5584
				$line .= ' (' . $row['flen'] . ')';
ef5584
			}
ef5584
ef5584
			if (!empty($row['dsource']))
ef5584
			{
ef5584
				$line .= ' ' . $row['dsource'];
ef5584
			}
ef5584
ef5584
			if (!empty($row['nflag']))
ef5584
			{
ef5584
				$line .= ' NOT NULL';
ef5584
			}
ef5584
			$rows[] = $line;
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql_data .= implode(",\n", $rows);
ef5584
		$sql_data .= "\n);\n";
ef5584
		$keys = array();
ef5584
ef5584
		$sql = 'SELECT I.RDB$FIELD_NAME as NAME
ef5584
			FROM RDB$RELATION_CONSTRAINTS RC, RDB$INDEX_SEGMENTS I, RDB$INDICES IDX
ef5584
			WHERE (I.RDB$INDEX_NAME = RC.RDB$INDEX_NAME)
ef5584
				AND (IDX.RDB$INDEX_NAME = RC.RDB$INDEX_NAME)
ef5584
				AND (RC.RDB$RELATION_NAME = \''. $table_name . '\')
ef5584
			ORDER BY I.RDB$FIELD_POSITION';
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$keys[] = $row['name'];
ef5584
		}
ef5584
ef5584
		if (sizeof($keys))
ef5584
		{
ef5584
			$sql_data .= "\nALTER TABLE $table_name ADD PRIMARY KEY (" . implode(', ', $keys) . ');';
ef5584
		}
ef5584
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = 'SELECT I.RDB$INDEX_NAME as INAME, I.RDB$UNIQUE_FLAG as UFLAG, S.RDB$FIELD_NAME as FNAME
ef5584
			FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON S.RDB$INDEX_NAME=I.RDB$INDEX_NAME
ef5584
			WHERE (I.RDB$SYSTEM_FLAG IS NULL  OR  I.RDB$SYSTEM_FLAG=0)
ef5584
				AND I.RDB$FOREIGN_KEY IS NULL
ef5584
				AND I.RDB$RELATION_NAME = \''. $table_name . '\'
ef5584
				AND I.RDB$INDEX_NAME NOT STARTING WITH \'RDB$\'
ef5584
			ORDER BY S.RDB$FIELD_POSITION';
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$index = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$index[$row['iname']]['unique'] = !empty($row['uflag']);
ef5584
			$index[$row['iname']]['values'][] = $row['fname'];
ef5584
		}
ef5584
ef5584
		foreach ($index as $index_name => $data)
ef5584
		{
ef5584
			$sql_data .= "\nCREATE ";
ef5584
			if ($data['unique'])
ef5584
			{
ef5584
				$sql_data .= 'UNIQUE ';
ef5584
			}
ef5584
			$sql_data .= "INDEX $index_name ON $table_name(" . implode(', ', $data['values']) . ");";
ef5584
		}
ef5584
		$sql_data .= "\n";
ef5584
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = 'SELECT D1.RDB$DEPENDENT_NAME as DNAME, D1.RDB$FIELD_NAME as FNAME, D1.RDB$DEPENDENT_TYPE, R1.RDB$RELATION_NAME
ef5584
			FROM RDB$DEPENDENCIES D1
ef5584
			LEFT JOIN RDB$RELATIONS R1 ON ((D1.RDB$DEPENDENT_NAME = R1.RDB$RELATION_NAME) AND (NOT (R1.RDB$VIEW_BLR IS NULL)))
ef5584
			WHERE (D1.RDB$DEPENDED_ON_TYPE = 0)
ef5584
				AND (D1.RDB$DEPENDENT_TYPE <> 3)
ef5584
				AND (D1.RDB$DEPENDED_ON_NAME = \'' . $table_name . '\')
ef5584
			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
ef5584
			LEFT JOIN RDB$RELATIONS R2 ON ((F2.RDB$RELATION_NAME = R2.RDB$RELATION_NAME) AND (NOT (R2.RDB$VIEW_BLR IS NULL)))
ef5584
			WHERE (D2.RDB$DEPENDENT_TYPE = 3)
ef5584
				AND (D2.RDB$DEPENDENT_NAME = F2.RDB$FIELD_SOURCE)
ef5584
				AND (D2.RDB$DEPENDED_ON_NAME = \'' . $table_name . '\')
ef5584
			ORDER BY 1, 2';
ef5584
		$result = $db->sql_query($sql);
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$sql = 'SELECT T1.RDB$DEPENDED_ON_NAME as GEN, T1.RDB$FIELD_NAME, T1.RDB$DEPENDED_ON_TYPE
ef5584
				FROM RDB$DEPENDENCIES T1
ef5584
				WHERE (T1.RDB$DEPENDENT_NAME = \'' . $row['dname'] . '\')
ef5584
					AND (T1.RDB$DEPENDENT_TYPE = 2 AND T1.RDB$DEPENDED_ON_TYPE = 14)
ef5584
				UNION ALL SELECT DISTINCT D.RDB$DEPENDED_ON_NAME, D.RDB$FIELD_NAME, D.RDB$DEPENDED_ON_TYPE
ef5584
				FROM RDB$DEPENDENCIES D, RDB$RELATION_FIELDS F
ef5584
				WHERE (D.RDB$DEPENDENT_TYPE = 3)
ef5584
					AND (D.RDB$DEPENDENT_NAME = F.RDB$FIELD_SOURCE)
ef5584
					AND (F.RDB$RELATION_NAME = \'' . $row['dname'] . '\')
ef5584
				ORDER BY 1,2';
ef5584
			$result2 = $db->sql_query($sql);
ef5584
			$row2 = $db->sql_fetchrow($result2);
ef5584
			$db->sql_freeresult($result2);
ef5584
			$gen_name = $row2['gen'];
ef5584
ef5584
			$sql_data .= "\nDROP GENERATOR " . $gen_name . ";";
ef5584
			$sql_data .= "\nSET TERM ^ ;";
ef5584
			$sql_data .= "\nCREATE GENERATOR " . $gen_name . "^";
ef5584
			$sql_data .= "\nSET GENERATOR  " . $gen_name . " TO 0^\n";
ef5584
			$sql_data .= "\nCREATE TRIGGER {$row['dname']} FOR $table_name";
ef5584
			$sql_data .= "\nBEFORE INSERT\nAS\nBEGIN";
ef5584
			$sql_data .= "\n  NEW.{$row['fname']} = GEN_ID(" . $gen_name . ", 1);";
ef5584
			$sql_data .= "\nEND^\n";
ef5584
			$sql_data .= "\nSET TERM ; ^\n";
ef5584
		}
ef5584
ef5584
		$this->flush($sql_data);
ef5584
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
}
ef5584
ef5584
// 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)
ef5584
function get_usable_memory()
ef5584
{
ef5584
	$val = trim(@ini_get('memory_limit'));
ef5584
ef5584
	if (preg_match('/(\\d+)([mkg]?)/i', $val, $regs))
ef5584
	{
ef5584
		$memory_limit = (int) $regs[1];
ef5584
		switch ($regs[2])
ef5584
		{
ef5584
ef5584
			case 'k':
ef5584
			case 'K':
ef5584
				$memory_limit *= 1024;
ef5584
			break;
ef5584
ef5584
			case 'm':
ef5584
			case 'M':
ef5584
				$memory_limit *= 1048576;
ef5584
			break;
ef5584
ef5584
			case 'g':
ef5584
			case 'G':
ef5584
				$memory_limit *= 1073741824;
ef5584
			break;
ef5584
		}
ef5584
ef5584
		// how much memory PHP requires at the start of export (it is really a little less)
ef5584
		if ($memory_limit > 6100000)
ef5584
		{
ef5584
			$memory_limit -= 6100000;
ef5584
		}
ef5584
ef5584
		// allow us to consume half of the total memory available
ef5584
		$memory_limit /= 2;
ef5584
	}
ef5584
	else
ef5584
	{
ef5584
		// set the buffer to 1M if we have no clue how much memory PHP will give us :P
ef5584
		$memory_limit = 1048576;
ef5584
	}
ef5584
ef5584
	return $memory_limit;
ef5584
}
ef5584
ef5584
function sanitize_data_mssql($text)
ef5584
{
ef5584
	$data = preg_split('/[\n\t\r\b\f]/', $text);
ef5584
	preg_match_all('/[\n\t\r\b\f]/', $text, $matches);
ef5584
ef5584
	$val = array();
ef5584
ef5584
	foreach ($data as $value)
ef5584
	{
ef5584
		if (strlen($value))
ef5584
		{
ef5584
			$val[] = "'" . $value . "'";
ef5584
		}
ef5584
		if (sizeof($matches[0]))
ef5584
		{
ef5584
			$val[] = 'char(' . ord(array_shift($matches[0])) . ')';
ef5584
		}
ef5584
	}
ef5584
ef5584
	return implode('+', $val);
ef5584
}
ef5584
ef5584
function sanitize_data_oracle($text)
ef5584
{
ef5584
	$data = preg_split('/[\0\n\t\r\b\f\'"\\\]/', $text);
ef5584
	preg_match_all('/[\0\n\t\r\b\f\'"\\\]/', $text, $matches);
ef5584
ef5584
	$val = array();
ef5584
ef5584
	foreach ($data as $value)
ef5584
	{
ef5584
		if (strlen($value))
ef5584
		{
ef5584
			$val[] = "'" . $value . "'";
ef5584
		}
ef5584
		if (sizeof($matches[0]))
ef5584
		{
ef5584
			$val[] = 'chr(' . ord(array_shift($matches[0])) . ')';
ef5584
		}
ef5584
	}
ef5584
ef5584
	return implode('||', $val);
ef5584
}
ef5584
ef5584
function sanitize_data_generic($text)
ef5584
{
ef5584
	$data = preg_split('/[\n\t\r\b\f]/', $text);
ef5584
	preg_match_all('/[\n\t\r\b\f]/', $text, $matches);
ef5584
ef5584
	$val = array();
ef5584
ef5584
	foreach ($data as $value)
ef5584
	{
ef5584
		if (strlen($value))
ef5584
		{
ef5584
			$val[] = "'" . $value . "'";
ef5584
		}
ef5584
		if (sizeof($matches[0]))
ef5584
		{
ef5584
			$val[] = "'" . array_shift($matches[0]) . "'";
ef5584
		}
ef5584
	}
ef5584
ef5584
	return implode('||', $val);
ef5584
}
ef5584
ef5584
// modified from PHP.net
ef5584
function fgetd(&$fp, $delim, $read, $seek, $eof, $buffer = 8192)
ef5584
{
ef5584
	$record = '';
ef5584
	$delim_len = strlen($delim);
ef5584
	
ef5584
	while (!$eof($fp))
ef5584
	{
ef5584
		$pos = strpos($record, $delim);
ef5584
		if ($pos === false)
ef5584
		{
ef5584
			$record .= $read($fp, $buffer);
ef5584
			if ($eof($fp) && ($pos = strpos($record, $delim)) !== false)
ef5584
			{
ef5584
				$seek($fp, $pos + $delim_len - strlen($record), SEEK_CUR);
ef5584
				return substr($record, 0, $pos);
ef5584
			}
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$seek($fp, $pos + $delim_len - strlen($record), SEEK_CUR);
ef5584
			return substr($record, 0, $pos);
ef5584
		}
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
function fgetd_seekless(&$fp, $delim, $read, $seek, $eof, $buffer = 8192)
ef5584
{
ef5584
	static $array = array();
ef5584
	static $record = '';
ef5584
ef5584
	if (!sizeof($array))
ef5584
	{
ef5584
		while (!$eof($fp))
ef5584
		{
ef5584
			if (strpos($record, $delim) !== false)
ef5584
			{
ef5584
				$array = explode($delim, $record);
ef5584
				$record = array_pop($array);
ef5584
				break;
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$record .= $read($fp, $buffer);
ef5584
			}
ef5584
		}
ef5584
		if ($eof($fp) && strpos($record, $delim) !== false)
ef5584
		{
ef5584
			$array = explode($delim, $record);
ef5584
			$record = array_pop($array);
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (sizeof($array))
ef5584
	{
ef5584
		return array_shift($array);
ef5584
	}
ef5584
ef5584
	return false;
ef5584
}
ef5584
ef5584
?>