private function restore_backup_db($working_dir, $working_dir_localpath, &$import_table_prefix) { do_action('updraftplus_restore_db_pre'); # This is now a legacy option (at least on the front end), so we should not see it much $this->prior_upload_path = get_option('upload_path'); // There is a file backup.db(.gz) inside the working directory # The 'off' check is for badly configured setups - http://wordpress.org/support/topic/plugin-wp-super-cache-warning-php-safe-mode-enabled-but-safe-mode-is-off if (@ini_get('safe_mode') && 'off' != strtolower(@ini_get('safe_mode'))) { echo "<p>" . __('Warning: PHP safe_mode is active on your server. Timeouts are much more likely. If these happen, then you will need to manually restore the file via phpMyAdmin or another method.', 'updraftplus') . "</p><br/>"; } $db_basename = 'backup.db.gz'; if (!empty($this->ud_foreign)) { $plugins = apply_filters('updraftplus_accept_archivename', array()); if (empty($plugins[$this->ud_foreign])) { return new WP_Error('unknown', sprintf(__('Backup created by unknown source (%s) - cannot be restored.', 'updraftplus'), $this->ud_foreign)); } if (!file_exists($working_dir_localpath . '/' . $db_basename) && file_exists($working_dir_localpath . '/backup.db')) { $db_basename = 'backup.db'; } elseif (!file_exists($working_dir_localpath . '/' . $db_basename) && file_exists($working_dir_localpath . '/backup.db.bz2')) { $db_basename = 'backup.db.bz2'; } if (!file_exists($working_dir_localpath . '/' . $db_basename)) { $separatedb = empty($plugins[$this->ud_foreign]['separatedb']) ? false : true; $filtered_db_name = apply_filters('updraftplus_foreign_dbfilename', false, $this->ud_foreign, $this->ud_backup_info, $working_dir_localpath, $separatedb); if (is_string($filtered_db_name)) { $db_basename = $filtered_db_name; } } } // wp_filesystem has no gzopen method, so we switch to using the local filesystem (which is harmless, since we are performing read-only operations) if (false === $db_basename || !is_readable($working_dir_localpath . '/' . $db_basename)) { return new WP_Error('dbopen_failed', __('Failed to find database file', 'updraftplus') . " ({$working_dir}/" . $db_basename . ")"); } global $wpdb, $updraftplus; $this->skin->feedback('restore_database'); $is_plain = substr($db_basename, -3, 3) == '.db'; $is_bz2 = substr($db_basename, -7, 7) == '.db.bz2'; // Read-only access: don't need to go through WP_Filesystem if ($is_plain) { $dbhandle = fopen($working_dir_localpath . '/' . $db_basename, 'r'); } elseif ($is_bz2) { if (!function_exists('bzopen')) { $updraftplus->log_e("Your web server's PHP installation has these functions disabled: %s.", 'bzopen'); $updraftplus->log_e('Your hosting company must enable these functions before %s can work.', __('restoration', 'updraftplus')); } $dbhandle = bzopen($working_dir_localpath . '/' . $db_basename, 'r'); } else { $dbhandle = gzopen($working_dir_localpath . '/' . $db_basename, 'r'); } if (!$dbhandle) { return new WP_Error('dbopen_failed', __('Failed to open database file', 'updraftplus')); } $this->line = 0; if (true == $this->use_wpdb) { $updraftplus->log_e('Database access: Direct MySQL access is not available, so we are falling back to wpdb (this will be considerably slower)'); } else { $updraftplus->log("Using direct MySQL access; value of use_mysqli is: " . ($this->use_mysqli ? '1' : '0')); if ($this->use_mysqli) { @mysqli_query($this->mysql_dbh, 'SET SESSION query_cache_type = OFF;'); } else { @mysql_query('SET SESSION query_cache_type = OFF;', $this->mysql_dbh); } } // Find the supported engines - in case the dump had something else (case seen: saved from MariaDB with engine Aria; imported into plain MySQL without) $supported_engines = $wpdb->get_results("SHOW ENGINES", OBJECT_K); $this->errors = 0; $this->statements_run = 0; $this->insert_statements_run = 0; $this->tables_created = 0; $sql_line = ""; $sql_type = -1; $this->start_time = microtime(true); $old_wpversion = ''; $this->old_siteurl = ''; $this->old_home = ''; $this->old_content = ''; $old_table_prefix = defined('UPDRAFTPLUS_OVERRIDE_IMPORT_PREFIX') && UPDRAFTPLUS_OVERRIDE_IMPORT_PREFIX ? UPDRAFTPLUS_OVERRIDE_IMPORT_PREFIX : ''; $old_siteinfo = array(); $gathering_siteinfo = true; $this->create_forbidden = false; $this->drop_forbidden = false; $this->last_error = ''; $random_table_name = 'updraft_tmp_' . rand(0, 9999999) . md5(microtime(true)); # The only purpose in funnelling queries directly here is to be able to get the error number if ($this->use_wpdb) { $req = $wpdb->query("CREATE TABLE {$random_table_name}"); if (!$req) { $this->last_error = $wpdb->last_error; } $this->last_error_no = false; } else { if ($this->use_mysqli) { $req = mysqli_query($this->mysql_dbh, "CREATE TABLE {$random_table_name}"); } else { $req = mysql_unbuffered_query("CREATE TABLE {$random_table_name}", $this->mysql_dbh); } if (!$req) { $this->last_error = $this->use_mysqli ? mysqli_error($this->mysql_dbh) : mysql_error($this->mysql_dbh); $this->last_error_no = $this->use_mysqli ? mysqli_errno($this->mysql_dbh) : mysql_errno($this->mysql_dbh); } } if (!$req && ($this->use_wpdb || 1142 === $this->last_error_no)) { $this->create_forbidden = true; # If we can't create, then there's no point dropping $this->drop_forbidden = true; echo '<strong>' . __('Warning:', 'updraftplus') . '</strong> '; $updraftplus->log_e('Your database user does not have permission to create tables. We will attempt to restore by simply emptying the tables; this should work as long as a) you are restoring from a WordPress version with the same database structure, and b) Your imported database does not contain any tables which are not already present on the importing site.', ' (' . $this->last_error . ')'); } else { if ($this->use_wpdb) { $req = $wpdb->query("DROP TABLE {$random_table_name}"); if (!$req) { $this->last_error = $wpdb->last_error; } $this->last_error_no = false; } else { if ($this->use_mysqli) { $req = mysqli_query($this->mysql_dbh, "DROP TABLE {$random_table_name}"); } else { $req = mysql_unbuffered_query("DROP TABLE {$random_table_name}", $this->mysql_dbh); } if (!$req) { $this->last_error = $this->use_mysqli ? mysqli_error($this->mysql_dbh) : mysql_error($this->mysql_dbh); $this->last_error_no = $this->use_mysqli ? mysqli_errno($this->mysql_dbh) : mysql_errno($this->mysql_dbh); } } if (!$req && ($this->use_wpdb || $this->last_error_no === 1142)) { $this->drop_forbidden = true; echo '<strong>' . __('Warning:', 'updraftplus') . '</strong> '; $updraftplus->log_e('Your database user does not have permission to drop tables. We will attempt to restore by simply emptying the tables; this should work as long as you are restoring from a WordPress version with the same database structure (%s)', ' (' . $this->last_error . ')'); } } $restoring_table = ''; $this->max_allowed_packet = $updraftplus->get_max_packet_size(); $updraftplus->log("Entering maintenance mode"); $this->maintenance_mode(true); // N.B. There is no such function as bzeof() - we have to detect that another way while ($is_plain && !feof($dbhandle) || !$is_plain && ($is_bz2 || !$is_bz2 && !gzeof($dbhandle))) { // Up to 1Mb if ($is_plain) { $buffer = rtrim(fgets($dbhandle, 1048576)); } elseif ($is_bz2) { if (!isset($bz2_buffer)) { $bz2_buffer = ''; } $buffer = ''; if (strlen($bz2_buffer) < 524288) { $bz2_buffer .= bzread($dbhandle, 1048576); } if (bzerrno($dbhandle) !== 0) { $updraftplus->log("bz2 error: " . bzerrstr($dbhandle) . " (code: " . bzerrno($bzhandle) . ")"); break; } if (false !== $bz2_buffer && '' !== $bz2_buffer) { if (false !== ($p = strpos($bz2_buffer, "\n"))) { $buffer .= substr($bz2_buffer, 0, $p + 1); $bz2_buffer = substr($bz2_buffer, $p + 1); } else { $buffer .= $bz2_buffer; $bz2_buffer = ''; } } else { break; } $buffer = rtrim($buffer); } else { $buffer = rtrim(gzgets($dbhandle, 1048576)); } // Discard comments if (empty($buffer) || substr($buffer, 0, 1) == '#' || preg_match('/^--(\\s|$)/', substr($buffer, 0, 3))) { if ('' == $this->old_siteurl && preg_match('/^\\# Backup of: (http(.*))$/', $buffer, $matches)) { $this->old_siteurl = untrailingslashit($matches[1]); $updraftplus->log_e('<strong>Backup of:</strong> %s', htmlspecialchars($this->old_siteurl)); do_action('updraftplus_restore_db_record_old_siteurl', $this->old_siteurl); $this->save_configuration_bundle(); } elseif (false === $this->created_by_version && preg_match('/^\\# Created by UpdraftPlus version ([\\d\\.]+)/', $buffer, $matches)) { $this->created_by_version = trim($matches[1]); echo '<strong>' . __('Backup created by:', 'updraftplus') . '</strong> ' . htmlspecialchars($this->created_by_version) . '<br>'; $updraftplus->log('Backup created by: ' . $this->created_by_version); } elseif ('' == $this->old_home && preg_match('/^\\# Home URL: (http(.*))$/', $buffer, $matches)) { $this->old_home = untrailingslashit($matches[1]); if ($this->old_siteurl && $this->old_home != $this->old_siteurl) { echo '<strong>' . __('Site home:', 'updraftplus') . '</strong> ' . htmlspecialchars($this->old_home) . '<br>'; $updraftplus->log('Site home: ' . $this->old_home); } do_action('updraftplus_restore_db_record_old_home', $this->old_home); } elseif ('' == $this->old_content && preg_match('/^\\# Content URL: (http(.*))$/', $buffer, $matches)) { $this->old_content = untrailingslashit($matches[1]); echo '<strong>' . __('Content URL:', 'updraftplus') . '</strong> ' . htmlspecialchars($this->old_content) . '<br>'; $updraftplus->log('Content URL: ' . $this->old_content); do_action('updraftplus_restore_db_record_old_content', $this->old_content); } elseif ('' == $old_table_prefix && (preg_match('/^\\# Table prefix: (\\S+)$/', $buffer, $matches) || preg_match('/^-- Table Prefix: (\\S+)$/i', $buffer, $matches))) { # We also support backwpup style: # -- Table Prefix: wp_ $old_table_prefix = $matches[1]; echo '<strong>' . __('Old table prefix:', 'updraftplus') . '</strong> ' . htmlspecialchars($old_table_prefix) . '<br>'; $updraftplus->log("Old table prefix: " . $old_table_prefix); } elseif ($gathering_siteinfo && preg_match('/^\\# Site info: (\\S+)$/', $buffer, $matches)) { if ('end' == $matches[1]) { $gathering_siteinfo = false; // Sanity checks if (isset($old_siteinfo['multisite']) && !$old_siteinfo['multisite'] && is_multisite()) { // Just need to check that you're crazy if (!defined('UPDRAFTPLUS_EXPERIMENTAL_IMPORTINTOMULTISITE') || UPDRAFTPLUS_EXPERIMENTAL_IMPORTINTOMULTISITE != true) { return new WP_Error('multisite_error', $this->strings['multisite_error']); } // Got the needed code? if (!class_exists('UpdraftPlusAddOn_MultiSite') || !class_exists('UpdraftPlus_Addons_Migrator')) { return new WP_Error('missing_addons', __('To import an ordinary WordPress site into a multisite installation requires both the multisite and migrator add-ons.', 'updraftplus')); } } } elseif (preg_match('/^([^=]+)=(.*)$/', $matches[1], $kvmatches)) { $key = $kvmatches[1]; $val = $kvmatches[2]; echo '<strong>' . __('Site information:', 'updraftplus') . '</strong>' . ' ' . htmlspecialchars($key) . ' = ' . htmlspecialchars($val) . '<br>'; $updraftplus->log("Site information: " . $key . "=" . $val); $old_siteinfo[$key] = $val; if ('multisite' == $key) { if ($val) { $this->ud_backup_is_multisite = 1; } else { $this->ud_backup_is_multisite = 0; } } } } continue; } // Detect INSERT commands early, so that we can split them if necessary if (preg_match('/^\\s*(insert into \\`?([^\\`]*)\\`?\\s+(values|\\())/i', $sql_line . $buffer, $matches)) { $sql_type = 3; $insert_prefix = $matches[1]; } # Deal with case where adding this line will take us over the MySQL max_allowed_packet limit - must split, if we can (if it looks like consecutive rows) # ALlow a 100-byte margin for error (including searching/replacing table prefix) if (3 == $sql_type && $sql_line && strlen($sql_line . $buffer) > $this->max_allowed_packet - 100 && preg_match('/,\\s*$/', $sql_line) && preg_match('/^\\s*\\(/', $buffer)) { // Remove the final comma; replace with semi-colon $sql_line = substr(rtrim($sql_line), 0, strlen($sql_line) - 1) . ';'; if ('' != $old_table_prefix && $import_table_prefix != $old_table_prefix) { $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line); } # Run the SQL command; then set up for the next one. $this->line++; echo __("Split line to avoid exceeding maximum packet size", 'updraftplus') . " (" . strlen($sql_line) . " + " . strlen($buffer) . " : " . $this->max_allowed_packet . ")<br>"; $updraftplus->log("Split line to avoid exceeding maximum packet size (" . strlen($sql_line) . " + " . strlen($buffer) . " : " . $this->max_allowed_packet . ")"); $do_exec = $this->sql_exec($sql_line, $sql_type, $import_table_prefix); if (is_wp_error($do_exec)) { return $do_exec; } # Reset, then carry on $sql_line = $insert_prefix . " "; } $sql_line .= $buffer; # Do we have a complete line yet? We used to just test the final character for ';' here (up to 1.8.12), but that was too unsophisticated if (3 == $sql_type && !preg_match('/\\)\\s*;$/', substr($sql_line, -3, 3)) || 3 != $sql_type && ';' != substr($sql_line, -1, 1)) { continue; } $this->line++; # We now have a complete line - process it if (3 == $sql_type && $sql_line && strlen($sql_line) > $this->max_allowed_packet) { $this->log_oversized_packet($sql_line); # Reset $sql_line = ''; $sql_type = -1; # If this is the very first SQL line of the options table, we need to bail; it's essential if (0 == $this->insert_statements_run && $restoring_table && $restoring_table == $import_table_prefix . 'options') { $updraftplus->log("Leaving maintenance mode"); $this->maintenance_mode(false); return new WP_Error('initial_db_error', sprintf(__('An error occurred on the first %s command - aborting run', 'updraftplus'), 'INSERT (options)')); } continue; } # The timed overhead of this is negligible if (preg_match('/^\\s*drop table if exists \\`?([^\\`]*)\\`?\\s*;/i', $sql_line, $matches)) { $sql_type = 1; if (!isset($printed_new_table_prefix)) { $import_table_prefix = $this->pre_sql_actions($import_table_prefix); if (false === $import_table_prefix || is_wp_error($import_table_prefix)) { return $import_table_prefix; } $printed_new_table_prefix = true; } $this->table_name = $matches[1]; // Legacy, less reliable - in case it was not caught before if ('' == $old_table_prefix && preg_match('/^([a-z0-9]+)_.*$/i', $this->table_name, $tmatches)) { $old_table_prefix = $tmatches[1] . '_'; echo '<strong>' . __('Old table prefix:', 'updraftplus') . '</strong> ' . htmlspecialchars($old_table_prefix) . '<br>'; $updraftplus->log("Old table prefix (detected from first table): {$old_table_prefix}"); } $this->new_table_name = $old_table_prefix ? $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $this->table_name) : $this->table_name; if ('' != $old_table_prefix && $import_table_prefix != $old_table_prefix) { $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line); } $this->tables_been_dropped[] = $this->new_table_name; } elseif (preg_match('/^\\s*create table \\`?([^\\`\\(]*)\\`?\\s*\\(/i', $sql_line, $matches)) { $sql_type = 2; $this->insert_statements_run = 0; $this->table_name = $matches[1]; // Legacy, less reliable - in case it was not caught before. We added it in here (CREATE) as well as in DROP because of SQL dumps which lack DROP statements. if ('' == $old_table_prefix && preg_match('/^([a-z0-9]+)_.*$/i', $this->table_name, $tmatches)) { $old_table_prefix = $tmatches[1] . '_'; echo '<strong>' . __('Old table prefix:', 'updraftplus') . '</strong> ' . htmlspecialchars($old_table_prefix) . '<br>'; $updraftplus->log("Old table prefix (detected from creating first table): {$old_table_prefix}"); } // MySQL 4.1 outputs TYPE=, but accepts ENGINE=; 5.1 onwards accept *only* ENGINE= $sql_line = $updraftplus->str_lreplace('TYPE=', 'ENGINE=', $sql_line); if (empty($printed_new_table_prefix)) { $import_table_prefix = $this->pre_sql_actions($import_table_prefix); if (false === $import_table_prefix || is_wp_error($import_table_prefix)) { return $import_table_prefix; } $printed_new_table_prefix = true; } $this->new_table_name = $old_table_prefix ? $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $this->table_name) : $this->table_name; // This CREATE TABLE command may be the de-facto mark for the end of processing a previous table (which is so if this is not the first table in the SQL dump) if ($restoring_table) { # Attempt to reconnect if the DB connection dropped (may not succeed, of course - but that will soon become evident) $updraftplus->check_db_connection($this->wpdb_obj); // After restoring the options table, we can set old_siteurl if on legacy (i.e. not already set) if ($restoring_table == $import_table_prefix . 'options') { if ('' == $this->old_siteurl || '' == $this->old_home || '' == $this->old_content) { global $updraftplus_addons_migrator; if (isset($updraftplus_addons_migrator->new_blogid)) { switch_to_blog($updraftplus_addons_migrator->new_blogid); } if ('' == $this->old_siteurl) { $this->old_siteurl = untrailingslashit($wpdb->get_row("SELECT option_value FROM {$wpdb->options} WHERE option_name='siteurl'")->option_value); do_action('updraftplus_restore_db_record_old_siteurl', $this->old_siteurl); } if ('' == $this->old_home) { $this->old_home = untrailingslashit($wpdb->get_row("SELECT option_value FROM {$wpdb->options} WHERE option_name='home'")->option_value); do_action('updraftplus_restore_db_record_old_home', $this->old_home); } if ('' == $this->old_content) { $this->old_content = $this->old_siteurl . '/wp-content'; do_action('updraftplus_restore_db_record_old_content', $this->old_content); } if (isset($updraftplus_addons_migrator->new_blogid)) { restore_current_blog(); } } } if ($restoring_table != $this->new_table_name) { $this->restored_table($restoring_table, $import_table_prefix, $old_table_prefix); } } $engine = "(?)"; $engine_change_message = ''; if (preg_match('/ENGINE=([^\\s;]+)/', $sql_line, $eng_match)) { $engine = $eng_match[1]; if (isset($supported_engines[$engine])) { #echo sprintf(__('Requested table engine (%s) is present.', 'updraftplus'), $engine); if ('myisam' == strtolower($engine)) { $sql_line = preg_replace('/PAGE_CHECKSUM=\\d\\s?/', '', $sql_line, 1); } } else { $engine_change_message = sprintf(__('Requested table engine (%s) is not present - changing to MyISAM.', 'updraftplus'), $engine) . "<br>"; $sql_line = $updraftplus->str_lreplace("ENGINE={$eng_match}", "ENGINE=MyISAM", $sql_line); // Remove (M)aria options if ('maria' == strtolower($engine) || 'aria' == strtolower($engine)) { $sql_line = preg_replace('/PAGE_CHECKSUM=\\d\\s?/', '', $sql_line, 1); $sql_line = preg_replace('/TRANSACTIONAL=\\d\\s?/', '', $sql_line, 1); } } } $this->table_name = $matches[1]; echo '<strong>' . sprintf(__('Restoring table (%s)', 'updraftplus'), $engine) . ":</strong> " . htmlspecialchars($this->table_name); $logline = "Restoring table ({$engine}): " . $this->table_name; if ('' != $old_table_prefix && $import_table_prefix != $old_table_prefix) { echo ' - ' . __('will restore as:', 'updraftplus') . ' ' . htmlspecialchars($this->new_table_name); $logline .= " - will restore as: " . $this->new_table_name; $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line); } $updraftplus->log($logline); $restoring_table = $this->new_table_name; echo '<br>'; if ($engine_change_message) { echo $engine_change_message; } } elseif (preg_match('/^\\s*(insert into \\`?([^\\`]*)\\`?\\s+(values|\\())/i', $sql_line, $matches)) { $sql_type = 3; if ('' != $old_table_prefix && $import_table_prefix != $old_table_prefix) { $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line); } } elseif (preg_match('/^\\s*(\\/\\*\\!40000 )?(alter|lock) tables? \\`?([^\\`\\(]*)\\`?\\s+(write|disable|enable)/i', $sql_line, $matches)) { # Only binary mysqldump produces this pattern (LOCK TABLES `table` WRITE, ALTER TABLE `table` (DISABLE|ENABLE) KEYS) $sql_type = 4; if ('' != $old_table_prefix && $import_table_prefix != $old_table_prefix) { $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line); } } elseif (preg_match('/^(un)?lock tables/i', $sql_line)) { # BackWPup produces these $sql_type = 5; } elseif (preg_match('/^(create|drop) database /i', $sql_line)) { # WPB2D produces these, as do some phpMyAdmin dumps $sql_type = 6; } elseif (preg_match('/^use /i', $sql_line)) { # WPB2D produces these, as do some phpMyAdmin dumps $sql_type = 7; } elseif (preg_match('#/\\*\\!40\\d+ SET NAMES (\\S+)#', $sql_line, $smatches)) { $sql_type = 8; $this->set_names = $smatches[1]; } else { # Prevent the previous value of $sql_type being retained for an unknown type $sql_type = 0; } // if (5 !== $sql_type) { if ($sql_type != 6 && $sql_type != 7) { $do_exec = $this->sql_exec($sql_line, $sql_type); if (is_wp_error($do_exec)) { return $do_exec; } } else { $updraftplus->log("Skipped SQL statement (unwanted type={$sql_type}): {$sql_line}"); } # Reset $sql_line = ''; $sql_type = -1; } $updraftplus->log("Leaving maintenance mode"); $this->maintenance_mode(false); if ($restoring_table) { $this->restored_table($restoring_table, $import_table_prefix, $old_table_prefix); } $time_taken = microtime(true) - $this->start_time; $updraftplus->log_e('Finished: lines processed: %d in %.2f seconds', $this->line, $time_taken); if ($is_plain) { fclose($dbhandle); } elseif ($is_bz2) { bzclose($dbhandle); } else { gzclose($dbhandle); } global $wp_filesystem; $wp_filesystem->delete($working_dir . '/' . $db_basename, false, 'f'); return true; }
/** * Get size of contents of a file, for a compressed file the uncompressed size * Warning: reading uncompressed size of content of bz-files requires uncompressing * * @author Gerrit Uitslag <*****@*****.**> * * @param string $file filename path to file * @return int size of file */ function io_getSizeFile($file) { if (!file_exists($file)) { return 0; } if (substr($file, -3) == '.gz') { $fp = @fopen($file, "rb"); if ($fp === false) { return 0; } fseek($fp, -4, SEEK_END); $buffer = fread($fp, 4); fclose($fp); $array = unpack("V", $buffer); $uncompressedsize = end($array); } else { if (substr($file, -4) == '.bz2') { if (!DOKU_HAS_BZIP) { return 0; } $bz = bzopen($file, "r"); if ($bz === false) { return 0; } $uncompressedsize = 0; while (!feof($bz)) { //8192 seems to be the maximum buffersize? $buffer = bzread($bz, 8192); if ($buffer === false || bzerrno($bz) !== 0) { return 0; } $uncompressedsize += strlen($buffer); } } else { $uncompressedsize = filesize($file); } } return $uncompressedsize; }
$fd = bzopen(dirname(__FILE__) . "/004_1.txt.bz2", "r"); var_dump(bzerror($fd)); var_dump(bzerrstr($fd)); var_dump(bzerrno($fd)); $fd2 = bzopen(dirname(__FILE__) . "/004_2.txt.bz2", "r"); var_dump(bzerror($fd2)); var_dump(bzerrstr($fd2)); var_dump(bzerrno($fd2)); var_dump(bzread($fd, 10)); var_dump(bzerror($fd)); var_dump(bzerrstr($fd)); var_dump(bzerrno($fd)); var_dump(bzread($fd2, 10)); var_dump(bzerror($fd2)); var_dump(bzerrstr($fd2)); var_dump(bzerrno($fd2)); var_dump(bzread($fd)); var_dump(bzerror($fd)); var_dump(bzerrstr($fd)); var_dump(bzerrno($fd)); var_dump(bzread($fd2)); var_dump(bzerror($fd2)); var_dump(bzerrstr($fd2)); var_dump(bzerrno($fd2)); bzclose($fd2); var_dump(bzread($fd2)); var_dump(bzerror($fd2)); var_dump(bzerrstr($fd2)); var_dump(bzerrno($fd2)); echo "Done\n";
/** * Returns the content of a .bz2 compressed file as string * * @author marcel senf <*****@*****.**> * @author Andreas Gohr <*****@*****.**> * * @param string $file filename * @return string|bool content or false on error */ function bzfile($file) { $bz = bzopen($file, "r"); if ($bz === false) { return false; } $str = ''; while (!feof($bz)) { //8192 seems to be the maximum buffersize? $buffer = bzread($bz, 8192); if ($buffer === false || bzerrno($bz) !== 0) { return false; } $str = $str . $buffer; } bzclose($bz); return $str; }
/** * Returns the content of a .bz2 compressed file as string * * @author marcel senf <*****@*****.**> * @author Andreas Gohr <*****@*****.**> * * @param string $file filename * @param bool $array return array of lines * @return string|array|bool content or false on error */ function bzfile($file, $array = false) { $bz = bzopen($file, "r"); if ($bz === false) { return false; } if ($array) { $lines = array(); } $str = ''; while (!feof($bz)) { //8192 seems to be the maximum buffersize? $buffer = bzread($bz, 8192); if ($buffer === false || bzerrno($bz) !== 0) { return false; } $str = $str . $buffer; if ($array) { $pos = strpos($str, "\n"); while ($pos !== false) { $lines[] = substr($str, 0, $pos + 1); $str = substr($str, $pos + 1); $pos = strpos($str, "\n"); } } } bzclose($bz); if ($array) { if ($str !== '') { $lines[] = $str; } return $lines; } return $str; }