Example #1
0
 function fgets($fp, $len = 8192)
 {
     if ($this->has_gzip()) {
         return gzgets($fp, $len);
     }
     return fgets($fp, $len);
 }
Example #2
0
function fgetcsvWrapper($fp)
{
    global $gzipEnabled;
    if ($gzipEnabled) {
        // FIXME エスケープが必要なデータが来ると壊れるよーー
        $r = gzgets($fp, 4000);
        //        $r = "";
        //        $r = "";
        //        do {
        //            $r .= gzgets($fp, 4000);
        //        } while(mb_substr_count($r,'"') % 2 == 1);
        if ($r !== FALSE) {
            // 行末の\r\nは消してから分割
            $r = mb_ereg_replace("\r?\n\$", "", $r);
            return explode("\t", $r);
        } else {
            return FALSE;
        }
    } else {
        //         return fgetcsv($fp, 4000, "\t", '"');
        $r = fgets($fp, 4000);
        if ($r !== FALSE) {
            // 行末の\r\nは消してから分割
            $r = mb_ereg_replace("\r?\n\$", "", $r);
            return explode("\t", $r);
        } else {
            return FALSE;
        }
    }
}
Example #3
0
function LoadBackUp()
{
    global $SAMSConf;
    global $USERConf;
    $DB = new SAMSDB();
    $lang = "./lang/lang.{$SAMSConf->LANG}";
    require $lang;
    if ($USERConf->ToWebInterfaceAccess("C") != 1) {
        exit;
    }
    PageTop("reark_48.jpg", "{$backupbuttom_2_loadbase_LoadBackUp_1}");
    if (($finp = gzopen($_FILES['userfile']['tmp_name'], "r")) != NULL) {
        while (gzeof($finp) == 0) {
            $string = gzgets($finp, 10000);
            $QUERY = strtok($string, ";");
            if (strstr($QUERY, "#") == FALSE) {
                echo "{$QUERY}<BR>";
                $num_rows = $DB->samsdb_query($QUERY . ";");
            }
            $count++;
        }
    }
    print "<SCRIPT>\n";
    print "  parent.lframe.location.href=\"lframe.php\"; \n";
    print "</SCRIPT> \n";
}
 public function import()
 {
     // It might not look like it, but it is actually compatible to
     // uncompressed files.
     $gzFileHandler = gzopen($this->file, 'r');
     Model\DownloadIntent::delete_all();
     Model\DownloadIntentClean::delete_all();
     $batchSize = 1000;
     $batch = array();
     while (!gzeof($gzFileHandler)) {
         $line = gzgets($gzFileHandler);
         list($id, $user_agent_id, $media_file_id, $request_id, $accessed_at, $source, $context, $geo_area_id, $lat, $lng) = explode(",", $line);
         $batch[] = array($user_agent_id, $media_file_id, $request_id, $accessed_at, $source, $context, $geo_area_id, $lat, $lng);
         if (count($batch) >= $batchSize) {
             self::save_batch_to_db($batch);
             $batch = [];
         }
     }
     gzclose($gzFileHandler);
     // save last batch to db
     self::save_batch_to_db($batch);
     \Podlove\Analytics\DownloadIntentCleanup::cleanup_download_intents();
     \Podlove\Cache\TemplateCache::get_instance()->setup_purge();
     wp_redirect(admin_url('admin.php?page=podlove_imexport_migration_handle&status=success'));
     exit;
 }
 /**
  * Read a line
  *
  * This function is identical to readLine except that trailing CR and LF characters
  * will be included in its return value
  *
  * @param   int bytes default 4096 Max. ammount of bytes to be read
  * @return  string Data read
  * @throws  io.IOException in case of an error
  */
 public function gets($bytes = 4096)
 {
     if (FALSE === ($result = gzgets($this->_fd, $bytes))) {
         throw new IOException('gets() cannot read ' . $bytes . ' bytes from ' . $this->uri);
     }
     return $result;
 }
Example #6
0
 function import_sql($filename)
 {
     $handle = @gzopen($filename, "r");
     // can open normal files, too.
     $query = "";
     $queries = 0;
     while ($handle && !feof($handle)) {
         $line = gzgets($handle, 1024);
         // keep string manipulations sane
         if ($line != "" && substr($line, 0, 2) != "--") {
             // line doesnt start with comment
             $query .= $line;
             if (substr(trim($line), -1, 1) == ";") {
                 if (!mysql_query($query)) {
                     if (defined("DEBUG")) {
                         echo "MYSQL Error: " . mysql_error() . "<Br><br>in query: {$query}";
                     } else {
                         echo "MYSQL Error: " . mysql_error();
                     }
                 }
                 $query = "";
                 $queries++;
             }
         }
     }
     return true;
 }
Example #7
0
 function restoreAction()
 {
     $backupFile = new UploadedFile("backupFile");
     if (!$backupFile->wasUploaded()) {
         return;
     }
     $gzipMode = $this->request->fileType == "gzip";
     $fileName = $backupFile->getTempName();
     $fp = $gzipMode ? gzopen($fileName, "r") : fopen($fileName, "r");
     $inString = false;
     $query = "";
     while (!feof($fp)) {
         $line = $gzipMode ? gzgets($fp) : fgets($fp);
         if (!$inString) {
             $isCommentLine = false;
             foreach (array("#", "--") as $commentTag) {
                 if (strpos($line, $commentTag) === 0) {
                     $isCommentLine = true;
                 }
             }
             if ($isCommentLine || trim($line) == "") {
                 continue;
             }
         }
         $deslashedLine = str_replace('\\', '', $line);
         if ((substr_count($deslashedLine, "'") - substr_count($deslashedLine, "\\'")) % 2) {
             $inString = !$inString;
         }
         $query .= $line;
         if (substr_compare(rtrim($line), ";", -1) == 0 && !$inString) {
             $this->database->sqlQuery($query);
             $query = "";
         }
     }
 }
Example #8
0
 /**
 * Open the file containing the backup data
 * @return String a String containing the DB Dump 
 * @access private
 */
 function _Open()
 {
     $fp = gzopen($this->filename, "rb") or die("Error. No se pudo abrir el archivo {$this->filename}");
     while (!gzeof($fp)) {
         $line = gzgets($fp, 1024);
         $SQL .= "{$line}";
     }
     gzclose($fp);
     return $SQL;
 }
Example #9
0
 function __getline()
 {
     switch ($this->type) {
         case 'gz':
             $this->line = trim(gzgets($this->handle));
             break;
         case 'file':
             $this->line = trim(fgets($this->handle));
             break;
     }
 }
 public function process($dumpFile)
 {
     $handle = gzopen($dumpFile, "r");
     while ($line = gzgets($handle, 100000000)) {
         $data = json_decode(rtrim($line, ",\n"), true);
         if ($data !== null) {
             $entity = $this->entityDeserializer->deserialize($data);
             $this->entityHandler->handleEntity($entity);
         }
     }
     gzclose($handle);
 }
Example #11
0
 /**
  * Reads a line from a stream. If the optional argument is provided,
  * the method terminates reading on raching the specified length.
  *
  * @throws Opl_Stream_Exception
  * @param integer $length The maximum line length to read.
  * @return string The returned string.
  */
 public function readLine($length = null)
 {
     if (!is_resource($this->_stream)) {
         throw new Opl_Stream_Exception('Input stream is not opened.');
     }
     $content = gzgets($this->_stream, (int) $length, "\r\n");
     if ($content === false) {
         throw new Opl_Stream_Exception('Unable to read a line from an input stream.');
     }
     $this->_readingPtr += strlen($content);
     return $content;
 }
Example #12
0
function gzgetcont($f)
{
    $d = "";
    $fo = gzopen($f, 'r');
    if ($fo) {
        while (!gzeof($fo)) {
            $d .= gzgets($fo);
        }
    }
    gzclose($fo);
    return $d;
}
Example #13
0
 /**
  * Uncompress a map file.
  *
  * @param string $path
  *
  * @return string
  */
 private static function uncompress($path)
 {
     if (!file_exists($path)) {
         throw new InvalidArgumentException('File does not exist');
     }
     $data = '';
     $gzo = gzopen($path, 'r');
     while ($line = gzgets($gzo, 1024)) {
         $data .= $line;
     }
     gzclose($gzo);
     return $data;
 }
Example #14
0
 function import_sql($filename)
 {
     global $mysql;
     $handle = @gzopen($filename, "r");
     // can open normal files, too.
     $query = "";
     $queries = 0;
     while ($handle && !feof($handle)) {
         $line = gzgets($handle, 4096);
         // keep string manipulations sane
         if ($line != "" && substr($line, 0, 2) != "--") {
             // line doesnt start with comment
             $query .= $line;
             if (substr(trim($line), -2, 2) == ");") {
                 $query = str_replace("NOT EXISTS `", "NOT EXISTS `" . DB_PREFIX, $query);
                 $query = str_replace("IF EXISTS `", "IF EXISTS `" . DB_PREFIX, $query);
                 $query = str_replace("TABLE `", "TABLE `" . DB_PREFIX, $query);
                 $query = str_replace("INTO `", "INTO `" . DB_PREFIX, $query);
                 $query = str_replace("TABLES `", "TABLES `" . DB_PREFIX, $query);
                 if (!$mysql->query($query)) {
                     if (defined("DEBUG")) {
                         die("MYSQL Error: " . $mysql->error . "<Br><br>in query: <textarea>{$query}</textarea><br>");
                     } else {
                         die("MYSQL Error: " . $mysql->error . "<br>");
                     }
                 }
                 $query = "";
                 $queries++;
             } elseif (substr(trim($line), -1, 1) == ";") {
                 $query = str_replace("NOT EXISTS `", "NOT EXISTS `" . DB_PREFIX, $query);
                 $query = str_replace("IF EXISTS `", "IF EXISTS `" . DB_PREFIX, $query);
                 $query = str_replace("TABLE `", "TABLE `" . DB_PREFIX, $query);
                 $query = str_replace("INTO `", "INTO `" . DB_PREFIX, $query);
                 $query = str_replace("TABLES `", "TABLES `" . DB_PREFIX, $query);
                 if (!$mysql->query($query)) {
                     if (defined("DEBUG")) {
                         die("MYSQL Error: " . $mysql->error . "<Br><br>in query: <textarea>{$query}</textarea><br>");
                     } else {
                         die("MYSQL Error: " . $mysql->error . "<br>");
                     }
                 }
                 $query = "";
                 $queries++;
             }
         }
     }
     if ($queries == 0) {
         die("NO QUERIES RUN<br>");
     }
     return true;
 }
 public function peekLine()
 {
     $line = false;
     if ($this->tResource !== false) {
         if ($this->tLine === false) {
             $this->tLine = gzgets($this->tResource, FileDecoder::BUFLEN);
         }
         if ($this->tLine !== false) {
             $line = $this->tLine;
         } else {
             bzclose($this->tResource);
             $this->tResource = false;
         }
     }
     return $line;
 }
Example #16
0
 function loadStatus($path)
 {
     $gz = gzopen($path, "rb");
     while ($line = gzgets($gz)) {
         $a = json_decode($line, true);
         $s = new TwitterStatus($a);
         $this->listStatus[] = $s;
         if ($s->user) {
             $this->listUser[$s->user->screen_name] = $s->user;
         }
         if ($this->lastId < $s->id) {
             $this->lastId = $s->id;
         }
     }
     gzclose($gz);
 }
 /**
  * Returns the contents of the file as an array, split on PHP_EOL.
  *
  * @param string $file
  * @return array
  */
 protected static function _getFileContentsAsArray($file)
 {
     // Fortunately, gzopen() will handle reading uncompressed files too
     $fileContents = array();
     $fh = gzopen($file, 'r');
     $eolLen = strlen(PHP_EOL);
     while ($line = gzgets($fh)) {
         /* Here I'm not just doing an easy trimming of whitespace because I
            want to be sure that any trailing whitespace that was meant to be
            on this line of the file stays there. */
         if (substr($line, $eolLen * -1) == PHP_EOL) {
             $line = substr($line, 0, strlen($line) - $eolLen);
         }
         $fileContents[] = $line;
     }
     gzclose($fh);
     return $fileContents;
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $now = time();
     $file_csv = $this->getContainer()->getParameter('kernel.cache_dir') . '/' . $this->getContainer()->getParameter('anime_db.ani_db.titles_db');
     if (!file_exists($file_csv) || filemtime($file_csv) + self::CACHE_LIFE_TIME < $now) {
         try {
             $file = $this->getOriginDb($output, $now);
         } catch (\Exception $e) {
             $output->writeln(sprintf('<error>AniDB list titles is not downloaded: %s</error>', $e->getMessage()));
             return 0;
         }
         $output->writeln('Start assembling database');
         // clear list titles and add unified title
         $fp = gzopen($file, 'r');
         $fp_csv = gzopen($file_csv, 'w');
         while (!gzeof($fp)) {
             $line = trim(gzgets($fp, 4096));
             // ignore comments
             if ($line[0] == '#') {
                 continue;
             }
             list($aid, $type, $lang, $title) = explode('|', $line);
             $lang = substr($lang, 0, 2);
             // ignore not supported locales
             if ($lang == 'x-') {
                 continue;
             }
             gzwrite($fp_csv, $aid . '|' . $type . '|' . $lang . '|' . $this->getUnifiedTitle($title) . '|' . $title . "\n");
         }
         gzclose($fp);
         gzclose($fp_csv);
         touch($file, $now);
         touch($file_csv, $now);
         $output->writeln('The titles database is updated');
     } else {
         $output->writeln('Update is not needed');
     }
     return 0;
 }
Example #19
0
 public function analyse_db_file($timestamp, $res, $db_file = false, $header_only = false)
 {
     $mess = array();
     $warn = array();
     $err = array();
     $info = array();
     global $wp_version;
     include ABSPATH . WPINC . '/version.php';
     $updraft_dir = $this->backups_dir_location();
     if (false === $db_file) {
         # This attempts to raise the maximum packet size. This can't be done within the session, only globally. Therefore, it has to be done before the session starts; in our case, during the pre-analysis.
         $this->get_max_packet_size();
         $backup = $this->get_backup_history($timestamp);
         if (!isset($backup['nonce']) || !isset($backup['db'])) {
             return array($mess, $warn, $err, $info);
         }
         $db_file = is_string($backup['db']) ? $updraft_dir . '/' . $backup['db'] : $updraft_dir . '/' . $backup['db'][0];
     }
     if (!is_readable($db_file)) {
         return array($mess, $warn, $err, $info);
     }
     // Encrypted - decrypt it
     if ($this->is_db_encrypted($db_file)) {
         $encryption = empty($res['updraft_encryptionphrase']) ? UpdraftPlus_Options::get_updraft_option('updraft_encryptionphrase') : $res['updraft_encryptionphrase'];
         if (!$encryption) {
             if (class_exists('UpdraftPlus_Addon_MoreDatabase')) {
                 $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted, but you have no encryption key entered.', 'updraftplus'));
             } else {
                 $err[] = sprintf(__('Error: %s', 'updraftplus'), __('Decryption failed. The database file is encrypted.', 'updraftplus'));
             }
             return array($mess, $warn, $err, $info);
         }
         $ciphertext = $this->decrypt($db_file, $encryption);
         if ($ciphertext) {
             $new_db_file = $updraft_dir . '/' . basename($db_file, '.crypt');
             if (!file_put_contents($new_db_file, $ciphertext)) {
                 $err[] = __('Failed to write out the decrypted database to the filesystem.', 'updraftplus');
                 return array($mess, $warn, $err, $info);
             }
             $db_file = $new_db_file;
         } else {
             $err[] = __('Decryption failed. The most likely cause is that you used the wrong key.', 'updraftplus');
             return array($mess, $warn, $err, $info);
         }
     }
     # Even the empty schema when gzipped comes to 1565 bytes; a blank WP 3.6 install at 5158. But we go low, in case someone wants to share single tables.
     if (filesize($db_file) < 1000) {
         $err[] = sprintf(__('The database is too small to be a valid WordPress database (size: %s Kb).', 'updraftplus'), round(filesize($db_file) / 1024, 1));
         return array($mess, $warn, $err, $info);
     }
     $is_plain = '.gz' == substr($db_file, -3, 3) ? false : true;
     $dbhandle = $is_plain ? fopen($db_file, 'r') : $this->gzopen_for_read($db_file, $warn, $err);
     if (!is_resource($dbhandle)) {
         $err[] = __('Failed to open database file.', 'updraftplus');
         return array($mess, $warn, $err, $info);
     }
     # Analyse the file, print the results.
     $line = 0;
     $old_siteurl = '';
     $old_home = '';
     $old_table_prefix = '';
     $old_siteinfo = array();
     $gathering_siteinfo = true;
     $old_wp_version = '';
     $old_php_version = '';
     $tables_found = array();
     // TODO: If the backup is the right size/checksum, then we could restore the $line <= 100 in the 'while' condition and not bother scanning the whole thing? Or better: sort the core tables to be first so that this usually terminates early
     $wanted_tables = array('terms', 'term_taxonomy', 'term_relationships', 'commentmeta', 'comments', 'links', 'options', 'postmeta', 'posts', 'users', 'usermeta');
     $migration_warning = false;
     // Don't set too high - we want a timely response returned to the browser
     // Until April 2015, this was always 90. But we've seen a few people with ~1Gb databases (uncompressed), and 90s is not enough. Note that we don't bother checking here if it's compressed - having a too-large timeout when unexpected is harmless, as it won't be hit. On very large dbs, they're expecting it to take a while.
     // "120 or 240" is a first attempt at something more useful than just fixed at 90 - but should be sufficient (as 90 was for everyone without ~1Gb databases)
     $default_dbscan_timeout = filesize($db_file) < 31457280 ? 120 : 240;
     $dbscan_timeout = defined('UPDRAFTPLUS_DBSCAN_TIMEOUT') && is_numeric(UPDRAFTPLUS_DBSCAN_TIMEOUT) ? UPDRAFTPLUS_DBSCAN_TIMEOUT : $default_dbscan_timeout;
     @set_time_limit($dbscan_timeout);
     while (($is_plain && !feof($dbhandle) || !$is_plain && !gzeof($dbhandle)) && ($line < 100 || !$header_only && count($wanted_tables) > 0)) {
         $line++;
         // Up to 1Mb
         $buffer = $is_plain ? rtrim(fgets($dbhandle, 1048576)) : rtrim(gzgets($dbhandle, 1048576));
         // Comments are what we are interested in
         if (substr($buffer, 0, 1) == '#') {
             if ('' == $old_siteurl && preg_match('/^\\# Backup of: (http(.*))$/', $buffer, $matches)) {
                 $old_siteurl = untrailingslashit($matches[1]);
                 $mess[] = __('Backup of:', 'updraftplus') . ' ' . htmlspecialchars($old_siteurl) . (!empty($old_wp_version) ? ' ' . sprintf(__('(version: %s)', 'updraftplus'), $old_wp_version) : '');
                 // Check for should-be migration
                 if (!$migration_warning && $old_siteurl != untrailingslashit(site_url())) {
                     $migration_warning = true;
                     $powarn = apply_filters('updraftplus_dbscan_urlchange', sprintf(__('Warning: %s', 'updraftplus'), '<a href="https://updraftplus.com/shop/migrator/">' . __('This backup set is from a different site - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus') . '</a>'), $old_siteurl, $res);
                     if (!empty($powarn)) {
                         $warn[] = $powarn;
                     }
                 }
             } elseif ('' == $old_home && preg_match('/^\\# Home URL: (http(.*))$/', $buffer, $matches)) {
                 $old_home = untrailingslashit($matches[1]);
                 // Check for should-be migration
                 if (!$migration_warning && $old_home != home_url()) {
                     $migration_warning = true;
                     $powarn = apply_filters('updraftplus_dbscan_urlchange', sprintf(__('Warning: %s', 'updraftplus'), '<a href="https://updraftplus.com/shop/migrator/">' . __('This backup set is from a different site - this is not a restoration, but a migration. You need the Migrator add-on in order to make this work.', 'updraftplus') . '</a>'), $old_home, $res);
                     if (!empty($powarn)) {
                         $warn[] = $powarn;
                     }
                 }
             } elseif ('' == $old_wp_version && preg_match('/^\\# WordPress Version: ([0-9]+(\\.[0-9]+)+)(-[-a-z0-9]+,)?(.*)$/', $buffer, $matches)) {
                 $old_wp_version = $matches[1];
                 if (!empty($matches[3])) {
                     $old_wp_version .= substr($matches[3], 0, strlen($matches[3]) - 1);
                 }
                 if (version_compare($old_wp_version, $wp_version, '>')) {
                     //$mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version);
                     $warn[] = sprintf(__('You are importing from a newer version of WordPress (%s) into an older one (%s). There are no guarantees that WordPress can handle this.', 'updraftplus'), $old_wp_version, $wp_version);
                 }
                 if (preg_match('/running on PHP ([0-9]+\\.[0-9]+)(\\s|\\.)/', $matches[4], $nmatches) && preg_match('/^([0-9]+\\.[0-9]+)(\\s|\\.)/', PHP_VERSION, $cmatches)) {
                     $old_php_version = $nmatches[1];
                     $current_php_version = $cmatches[1];
                     if (version_compare($old_php_version, $current_php_version, '>')) {
                         //$mess[] = sprintf(__('%s version: %s', 'updraftplus'), 'WordPress', $old_wp_version);
                         $warn[] = sprintf(__('The site in this backup was running on a webserver with version %s of %s. ', 'updraftplus'), $old_php_version, 'PHP') . ' ' . sprintf(__('This is significantly newer than the server which you are now restoring onto (version %s).', 'updraftplus'), PHP_VERSION) . ' ' . sprintf(__('You should only proceed if you cannot update the current server and are confident (or willing to risk) that your plugins/themes/etc. are compatible with the older %s version.', 'updraftplus'), 'PHP') . ' ' . sprintf(__('Any support requests to do with %s should be raised with your web hosting company.', 'updraftplus'), 'PHP');
                     }
                 }
             } elseif ('' == $old_table_prefix && (preg_match('/^\\# Table prefix: (\\S+)$/', $buffer, $matches) || preg_match('/^-- Table prefix: (\\S+)$/i', $buffer, $matches))) {
                 $old_table_prefix = $matches[1];
                 // 					echo '<strong>'.__('Old table prefix:', 'updraftplus').'</strong> '.htmlspecialchars($old_table_prefix).'<br>';
             } elseif (empty($info['label']) && preg_match('/^\\# Label: (.*)$/', $buffer, $matches)) {
                 $info['label'] = $matches[1];
                 $mess[] = __('Backup label:', 'updraftplus') . ' ' . htmlspecialchars($info['label']);
             } 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) {
                             $err[] = sprintf(__('Error: %s', 'updraftplus'), __('You are running on WordPress multisite - but your backup is not of a multisite site.', 'updraftplus'));
                             return array($mess, $warn, $err, $info);
                         }
                         // Got the needed code?
                         if (!class_exists('UpdraftPlusAddOn_MultiSite') || !class_exists('UpdraftPlus_Addons_Migrator')) {
                             $err[] = sprintf(__('Error: %s', 'updraftplus'), __('To import an ordinary WordPress site into a multisite installation requires both the multisite and migrator add-ons.', 'updraftplus'));
                             return array($mess, $warn, $err, $info);
                         }
                     } elseif (isset($old_siteinfo['multisite']) && $old_siteinfo['multisite'] && !is_multisite()) {
                         $warn[] = __('Warning:', 'updraftplus') . ' ' . __('Your backup is of a WordPress multisite install; but this site is not. Only the first site of the network will be accessible.', 'updraftplus') . ' <a href="http://codex.wordpress.org/Create_A_Network">' . __('If you want to restore a multisite backup, you should first set up your WordPress installation as a multisite.', 'updraftplus') . '</a>';
                     }
                 } elseif (preg_match('/^([^=]+)=(.*)$/', $matches[1], $kvmatches)) {
                     $key = $kvmatches[1];
                     $val = $kvmatches[2];
                     if ('multisite' == $key && $val) {
                         $mess[] = '<strong>' . __('Site information:', 'updraftplus') . '</strong>' . ' is a WordPress Network';
                     }
                     $old_siteinfo[$key] = $val;
                 }
             }
         } elseif (preg_match('/^\\s*create table \\`?([^\\`\\(]*)\\`?\\s*\\(/i', $buffer, $matches)) {
             $table = $matches[1];
             $tables_found[] = $table;
             if ($old_table_prefix) {
                 // Remove prefix
                 $table = $this->str_replace_once($old_table_prefix, '', $table);
                 if (in_array($table, $wanted_tables)) {
                     $wanted_tables = array_diff($wanted_tables, array($table));
                 }
             }
         }
     }
     if ($is_plain) {
         @fclose($dbhandle);
     } else {
         @gzclose($dbhandle);
     }
     /*        $blog_tables = "CREATE TABLE $wpdb->terms (
     CREATE TABLE $wpdb->term_taxonomy (
     CREATE TABLE $wpdb->term_relationships (
     CREATE TABLE $wpdb->commentmeta (
     CREATE TABLE $wpdb->comments (
     CREATE TABLE $wpdb->links (
     CREATE TABLE $wpdb->options (
     CREATE TABLE $wpdb->postmeta (
     CREATE TABLE $wpdb->posts (
             $users_single_table = "CREATE TABLE $wpdb->users (
             $users_multi_table = "CREATE TABLE $wpdb->users (
             $usermeta_table = "CREATE TABLE $wpdb->usermeta (
             $ms_global_tables = "CREATE TABLE $wpdb->blogs (
     CREATE TABLE $wpdb->blog_versions (
     CREATE TABLE $wpdb->registration_log (
     CREATE TABLE $wpdb->site (
     CREATE TABLE $wpdb->sitemeta (
     CREATE TABLE $wpdb->signups (
     */
     $missing_tables = array();
     if ($old_table_prefix) {
         if (!$header_only) {
             foreach ($wanted_tables as $table) {
                 if (!in_array($old_table_prefix . $table, $tables_found)) {
                     $missing_tables[] = $table;
                 }
             }
             if (count($missing_tables) > 0) {
                 $warn[] = sprintf(__('This database backup is missing core WordPress tables: %s', 'updraftplus'), implode(', ', $missing_tables));
             }
         }
     } else {
         if (empty($backup['meta_foreign'])) {
             $warn[] = __('UpdraftPlus was unable to find the table prefix when scanning the database backup.', 'updraftplus');
         }
     }
     return array($mess, $warn, $err, $info);
 }
Example #20
0
 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/>";
         return false;
     }
     // 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 (!is_readable($working_dir_localpath . '/backup.db.gz')) {
         return new WP_Error('gzopen_failed', __('Failed to find database file', 'updraftplus') . " ({$working_dir}/backup.db.gz)");
     }
     global $wpdb, $updraftplus;
     $this->skin->feedback('restore_database');
     // Read-only access: don't need to go through WP_Filesystem
     $dbhandle = gzopen($working_dir_localpath . '/backup.db.gz', 'r');
     if (!$dbhandle) {
         return new WP_Error('gzopen_failed', __('Failed to open database file', 'updraftplus'));
     }
     $this->line = 0;
     // Line up a wpdb-like object to use
     // mysql_query will throw E_DEPRECATED from PHP 5.5, so we expect WordPress to have switched to something else by then
     // 			$use_wpdb = (version_compare(phpversion(), '5.5', '>=') || !function_exists('mysql_query') || !$wpdb->is_mysql || !$wpdb->ready) ? true : false;
     // Seems not - PHP 5.5 is immanent for release
     $this->use_wpdb = !function_exists('mysql_query') || !$wpdb->is_mysql || !$wpdb->ready ? true : false;
     if (false == $this->use_wpdb) {
         // We have our own extension which drops lots of the overhead on the query
         $wpdb_obj = new UpdraftPlus_WPDB(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
         // Was that successful?
         if (!$wpdb_obj->is_mysql || !$wpdb_obj->ready) {
             $this->use_wpdb = true;
         } else {
             $this->mysql_dbh = $wpdb_obj->updraftplus_getdbh();
         }
     }
     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 {
         @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->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 = '';
     $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));
     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 {
         $req = mysql_unbuffered_query("CREATE TABLE {$random_table_name}", $this->mysql_dbh);
         if (!$req) {
             $this->last_error = mysql_error($this->mysql_dbh);
             $this->last_error_no = mysql_errno($this->mysql_dbh);
         }
     }
     if (!$req && ($this->use_wpdb || $this->last_error_no === 1142)) {
         $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 {
             $req = mysql_unbuffered_query("DROP TABLE {$random_table_name}", $this->mysql_dbh);
             if (!$req) {
                 $this->last_error = mysql_error($this->mysql_dbh);
                 $this->last_error_no = 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 = '';
     $max_allowed_packet = $updraftplus->get_max_packet_size();
     while (!gzeof($dbhandle)) {
         // Up to 1Mb
         $buffer = rtrim(gzgets($dbhandle, 1048576));
         // Discard comments
         if (empty($buffer) || substr($buffer, 0, 1) == '#') {
             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);
             } 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)) {
                 $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 ($sql_line && preg_match('/^\\s*(insert into \\`?([^\\`]*)\\`?\\s+values)/i', $sql_line, $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) > $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) . " : {$max_allowed_packet})<br>";
             $updraftplus->log("Split line to avoid exceeding maximum packet size (" . strlen($sql_line) . " + " . strlen($buffer) . " : {$max_allowed_packet})");
             $do_exec = $this->sql_exec($sql_line, $sql_type);
             # Reset, then carry on
             $sql_line = $insert_prefix . " ";
             if (is_wp_error($do_exec)) {
                 return $do_exec;
             }
         }
         $sql_line .= $buffer;
         # Do we have a complete line yet?
         if (';' != 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 . $buffer) > $max_allowed_packet) {
             $logit = substr($sql_line . $buffer, 0, 100);
             $updraftplus->log(sprintf("An SQL line that is larger than the maximum packet size and cannot be split was found: %s", '(' . strlen($sql_line) . ', ' . strlen($buffer) . ', ' . $logit . ' ...)'));
             echo '<strong>' . __('Warning:', 'updraftplus') . '</strong> ' . sprintf(__("An SQL line that is larger than the maximum packet size and cannot be split was found; this line will not be processed, but will be dropped: %s", 'updraftplus'), '(' . strlen($sql_line) . ', ' . strlen($buffer) . ', ' . $logit . ' ...)') . "<br>";
             # Reset
             $sql_line = '';
             $sql_type = -1;
             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: {$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);
             }
         } elseif (preg_match('/^\\s*create table \\`?([^\\`\\(]*)\\`?\\s*\\(/i', $sql_line, $matches)) {
             $sql_type = 2;
             // MySQL 4.1 outputs TYPE=, but accepts ENGINE=; 5.1 onwards accept *only* ENGINE=
             $sql_line = $updraftplus->str_lreplace('TYPE=', 'ENGINE=', $sql_line);
             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 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) {
                 // 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();
                         }
                     }
                 }
                 $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) {
                 $new_table_name = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $this->table_name);
                 echo ' - ' . __('will restore as:', 'updraftplus') . ' ' . htmlspecialchars($new_table_name);
                 $logline .= " - will restore as: " . $new_table_name;
                 $sql_line = $updraftplus->str_replace_once($old_table_prefix, $import_table_prefix, $sql_line);
             } else {
                 $new_table_name = $this->table_name;
             }
             $updraftplus->log($logline);
             $restoring_table = $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);
             }
         }
         $do_exec = $this->sql_exec($sql_line, $sql_type);
         if (is_wp_error($do_exec)) {
             return $do_exec;
         }
         # Reset
         $sql_line = '';
         $sql_type = -1;
     }
     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);
     gzclose($dbhandle);
     global $wp_filesystem;
     $wp_filesystem->delete($working_dir . '/backup.db.gz', false, true);
     return true;
 }
Example #21
0
if (isset($_REQUEST['restore'])) {
    if (isset($_FILES["thefile"]) && $_FILES["thefile"]["tmp_name"] != "" && $_FILES["thefile"]["error"] == 0) {
        $handle = gzopen($_FILES["thefile"]["tmp_name"], "r");
        if ($handle === FALSE) {
            $message = "Error: Restore file could not be opened";
        } else {
            // $handle OK
            $lines = 0;
            $ok = 0;
            $errors = 0;
            $drops = 0;
            $inserts = 0;
            $creates = 0;
            $start = 1;
            while (!gzeof($handle)) {
                $sql_line = trim(str_replace("\r", "", str_replace("\n", "", gzgets($handle, 99999))));
                if ($sql_line != "") {
                    if ($start) {
                        if (strpos($sql_line, "-- lwt-backup-") === false) {
                            $message = "Error: Invalid Restore file (possibly not created by LWT backup)";
                            break;
                        }
                        $start = 0;
                    }
                    if (strpos($sql_line, "--") === false) {
                        //echo tohtml($sql_line) . "<br />"; $res=TRUE;
                        $res = mysql_query($sql_line);
                        $lines++;
                        if ($res == FALSE) {
                            $errors++;
                        } else {
function get_sqlbefehl()
{
    global $restore, $config, $databases, $lang;
    //Init
    $restore['fileEOF'] = false;
    $restore['EOB'] = false;
    $complete_sql = '';
    $sqlparser_status = 0;
    if (!isset($restore['eintraege_ready'])) {
        $restore['eintraege_ready'] = 0;
    }
    //Parsen
    while ($sqlparser_status != 100 && !$restore['fileEOF'] && !$restore['EOB']) {
        //nächste Zeile lesen
        $zeile = $restore['compressed'] ? gzgets($restore['filehandle']) : fgets($restore['filehandle']);
        if (DEBUG) {
            echo "<br><br>Zeile: " . htmlspecialchars($zeile);
        }
        /******************* Setzen des Parserstatus *******************/
        // herausfinden um was für einen Befehl es sich handelt
        if ($sqlparser_status == 0) {
            //Vergleichszeile, um nicht bei jedem Vergleich strtoupper ausführen zu müssen
            $zeile2 = strtoupper(trim($zeile));
            // pre-built compare strings - so we need the CPU power only once :)
            $sub9 = substr($zeile2, 0, 9);
            $sub7 = substr($sub9, 0, 7);
            $sub6 = substr($sub7, 0, 6);
            $sub4 = substr($sub6, 0, 4);
            $sub3 = substr($sub4, 0, 3);
            $sub2 = substr($sub3, 0, 2);
            $sub1 = substr($sub2, 0, 1);
            if ($sub7 == 'INSERT ') {
                $sqlparser_status = 3;
                //Datensatzaktion
                $restore['actual_table'] = get_tablename($zeile);
            } elseif ($sub7 == 'LOCK TA') {
                $sqlparser_status = 4;
            } elseif ($sub6 == 'COMMIT') {
                $sqlparser_status = 7;
            } elseif (substr($sub6, 0, 5) == 'BEGIN') {
                $sqlparser_status = 7;
            } elseif ($sub9 == 'UNLOCK TA') {
                $sqlparser_status = 4;
            } elseif ($sub3 == 'SET') {
                $sqlparser_status = 4;
            } elseif ($sub6 == 'START ') {
                $sqlparser_status = 4;
            } elseif ($sub3 == '/*!') {
                $sqlparser_status = 5;
            } elseif ($sub9 == 'ALTER TAB') {
                $sqlparser_status = 4;
            } elseif ($sub9 == 'CREATE TA') {
                $sqlparser_status = 2;
            } elseif ($sub9 == 'CREATE AL') {
                $sqlparser_status = 2;
            } elseif ($sub9 == 'CREATE IN') {
                $sqlparser_status = 4;
            } elseif ($sqlparser_status != 5 && substr($zeile2, 0, 2) == '/*') {
                $sqlparser_status = 6;
            } elseif ($sub9 == 'DROP TABL') {
                $sqlparser_status = 1;
            } elseif ($sub9 == 'DROP VIEW') {
                $sqlparser_status = 1;
            } elseif ($sub9 == 'CREATE DA') {
                $sqlparser_status = 7;
            } elseif ($sub9 == 'DROP DATA ') {
                $sqlparser_status = 7;
            } elseif ($sub3 == 'USE') {
                $sqlparser_status = 7;
            } elseif ($sub6 == '-- EOB' || $sub4 == '# EO') {
                $restore['EOB'] = true;
                $restore['fileEOF'] = true;
                $zeile = '';
                $zeile2 = '';
                $sqlparser_status = 100;
            } elseif ($sub2 == '--' || $sub1 == '#') {
                $zeile = '';
                $zeile2 = '';
                $sqlparser_status = 0;
            }
            // Fortsetzung von erweiterten Inserts
            if ($restore['flag'] == 1) {
                $sqlparser_status = 3;
            }
            if ($sqlparser_status == 0 && trim($complete_sql) > '' && $restore['flag'] == -1) {
                // Unbekannten Befehl entdeckt
                v($restore);
                echo "<br>Sql: " . htmlspecialchars($complete_sql);
                echo "<br>Erweiterte Inserts: " . $restore['erweiterte_inserts'];
                die('<br>' . $lang['L_UNKNOWN_SQLCOMMAND'] . ': ' . $zeile . '<br><br>' . $complete_sql);
            }
            /******************* Ende von Setzen des Parserstatus *******************/
        }
        $last_char = substr(rtrim($zeile), -1);
        // Zeilenumbrüche erhalten - sonst werden Schlüsselwörter zusammengefügt
        // z.B. 'null' und in der nächsten Zeile 'check' wird zu 'nullcheck'
        $complete_sql .= $zeile . "\n";
        if ($sqlparser_status == 3) {
            //INSERT
            if (SQL_Is_Complete($complete_sql)) {
                $sqlparser_status = 100;
                $complete_sql = trim($complete_sql);
                if (substr($complete_sql, -2) == '*/') {
                    $complete_sql = remove_comment_at_eol($complete_sql);
                }
                // letzter Ausdruck des erweiterten Inserts erreicht?
                if (substr($complete_sql, -2) == ');') {
                    $restore['flag'] = -1;
                } else {
                    if (substr($complete_sql, -2) == '),') {
                        // letztes Komme gegen Semikolon tauschen
                        $complete_sql = substr($complete_sql, 0, -1) . ';';
                        $restore['erweiterte_inserts'] = 1;
                        $restore['flag'] = 1;
                    }
                }
                if (substr(strtoupper($complete_sql), 0, 7) != 'INSERT ') {
                    // wenn der Syntax aufgrund eines Reloads verloren ging - neu ermitteln
                    if (!isset($restore['insert_syntax'])) {
                        $restore['insert_syntax'] = get_insert_syntax($restore['actual_table']);
                    }
                    $complete_sql = $restore['insert_syntax'] . ' VALUES ' . $complete_sql . ';';
                } else {
                    // INSERT Syntax ermitteln und merken
                    $ipos = strpos(strtoupper($complete_sql), ' VALUES');
                    if (!$ipos === false) {
                        $restore['insert_syntax'] = substr($complete_sql, 0, $ipos);
                    } else {
                        $restore['insert_syntax'] = 'INSERT INTO `' . $restore['actual_table'] . '`';
                    }
                }
            }
        } else {
            if ($sqlparser_status == 1) {
                //Löschaktion
                if ($last_char == ';') {
                    $sqlparser_status = 100;
                }
                //Befehl komplett
                $restore['actual_table'] = get_tablename($complete_sql);
            } else {
                if ($sqlparser_status == 2) {
                    // Createanweisung ist beim Finden eines ; beendet
                    if ($last_char == ';') {
                        if ($config['minspeed'] > 0) {
                            $restore['anzahl_zeilen'] = $config['minspeed'];
                        }
                        // Soll die Tabelle hergestellt werden?
                        $do_it = true;
                        if (is_array($restore['tables_to_restore'])) {
                            $do_it = false;
                            if (in_array($restore['actual_table'], $restore['tables_to_restore'])) {
                                $do_it = true;
                            }
                        }
                        if ($do_it) {
                            $tablename = submit_create_action($complete_sql);
                            $restore['actual_table'] = $tablename;
                            $restore['table_ready']++;
                        }
                        // Zeile verwerfen, da CREATE jetzt bereits ausgefuehrt wurde und naechsten Befehl suchen
                        $complete_sql = '';
                        $sqlparser_status = 0;
                    }
                } else {
                    if ($sqlparser_status == 4) {
                        //Createindex
                        if ($last_char == ';') {
                            if ($config['minspeed'] > 0) {
                                $restore['anzahl_zeilen'] = $config['minspeed'];
                            }
                            $complete_sql = del_inline_comments($complete_sql);
                            $sqlparser_status = 100;
                        }
                    } else {
                        if ($sqlparser_status == 5) {
                            //Anweisung
                            $t = strrpos($zeile, '*/;');
                            if (!$t === false) {
                                $restore['anzahl_zeilen'] = $config['minspeed'];
                                $sqlparser_status = 100;
                                if ($config['ignore_enable_keys'] && strrpos($zeile, 'ENABLE KEYS ') !== false) {
                                    $sqlparser_status = 100;
                                    $complete_sql = '';
                                }
                            }
                        } else {
                            if ($sqlparser_status == 6) {
                                $t = strrpos($zeile, '*/');
                                if (!$t === false) {
                                    $complete_sql = '';
                                    $sqlparser_status = 0;
                                }
                            } else {
                                if ($sqlparser_status == 7) {
                                    //Anweisung
                                    if ($last_char == ';') {
                                        if ($config['minspeed'] > 0) {
                                            $restore['anzahl_zeilen'] = $config['minspeed'];
                                        }
                                        $complete_sql = '';
                                        $sqlparser_status = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($restore['compressed'] && gzeof($restore['filehandle'])) {
            $restore['fileEOF'] = true;
        }
        if (!$restore['compressed'] && feof($restore['filehandle'])) {
            $restore['fileEOF'] = true;
        }
    }
    // wenn bestimmte Tabellen wiederhergestellt werden sollen -> pruefen
    if (is_array($restore['tables_to_restore']) && !in_array($restore['actual_table'], $restore['tables_to_restore'])) {
        $complete_sql = '';
    }
    return trim($complete_sql);
}
Example #23
0
 public function backup_db($already_done = 'begun', $whichdb = 'wp', $dbinfo = array())
 {
     global $updraftplus, $wpdb;
     $this->whichdb = $whichdb;
     $this->whichdb_suffix = 'wp' == $whichdb ? '' : $whichdb;
     if (!$updraftplus->backup_time) {
         $updraftplus->backup_time_nonce();
     }
     if (!$updraftplus->opened_log_time) {
         $updraftplus->logfile_open($updraftplus->nonce);
     }
     if ('wp' == $this->whichdb) {
         $this->wpdb_obj = $wpdb;
         # The table prefix after being filtered - i.e. what filters what we'll actually back up
         $this->table_prefix = $updraftplus->get_table_prefix(true);
         # The unfiltered table prefix - i.e. the real prefix that things are relative to
         $this->table_prefix_raw = $updraftplus->get_table_prefix(false);
         $dbinfo['host'] = DB_HOST;
         $dbinfo['name'] = DB_NAME;
         $dbinfo['user'] = DB_USER;
         $dbinfo['pass'] = DB_PASSWORD;
     } else {
         if (!is_array($dbinfo) || empty($dbinfo['host'])) {
             return false;
         }
         # The methods that we may use: check_connection (WP>=3.9), get_results, get_row, query
         $this->wpdb_obj = new UpdraftPlus_WPDB_OtherDB($dbinfo['user'], $dbinfo['pass'], $dbinfo['name'], $dbinfo['host']);
         if (!empty($this->wpdb_obj->error)) {
             $updraftplus->log($dbinfo['user'] . '@' . $dbinfo['host'] . '/' . $dbinfo['name'] . ' : database connection attempt failed');
             $updraftplus->log($dbinfo['user'] . '@' . $dbinfo['host'] . '/' . $dbinfo['name'] . ' : ' . __('database connection attempt failed.', 'updraftplus') . ' ' . __('Connection failed: check your access details, that the database server is up, and that the network connection is not firewalled.', 'updraftplus'), 'error');
             return $updraftplus->log_wp_error($this->wpdb_obj->error);
         }
         $this->table_prefix = $dbinfo['prefix'];
         $this->table_prefix_raw = $dbinfo['prefix'];
     }
     $this->dbinfo = $dbinfo;
     $errors = 0;
     $use_time = apply_filters('updraftplus_backup_time_thisrun', $updraftplus->backup_time);
     $file_base = $this->get_backup_file_basename_from_time($use_time);
     $backup_file_base = $this->updraft_dir . '/' . $file_base;
     if ('finished' == $already_done) {
         return basename($backup_file_base) . '-db' . ('wp' == $whichdb ? '' : $whichdb) . '.gz';
     }
     if ('encrypted' == $already_done) {
         return basename($backup_file_base) . '-db' . ('wp' == $whichdb ? '' : $whichdb) . '.gz.crypt';
     }
     $updraftplus->jobdata_set('jobstatus', 'dbcreating' . $this->whichdb_suffix);
     $binsqldump = $updraftplus->find_working_sqldump();
     $total_tables = 0;
     # WP 3.9 onwards - https://core.trac.wordpress.org/browser/trunk/src/wp-includes/wp-db.php?rev=27925 - check_connection() allows us to get the database connection back if it had dropped
     if ('wp' == $whichdb && method_exists($this->wpdb_obj, 'check_connection')) {
         if (!$this->wpdb_obj->check_connection(false)) {
             $updraftplus->reschedule(60);
             $updraftplus->log("It seems the database went away; scheduling a resumption and terminating for now");
             $updraftplus->record_still_alive();
             die;
         }
     }
     // SHOW FULL - so that we get to know whether it's a BASE TABLE or a VIEW
     $all_tables = $this->wpdb_obj->get_results("SHOW FULL TABLES", ARRAY_N);
     if (empty($all_tables) && !empty($this->wpdb_obj->last_error)) {
         $all_tables = $this->wpdb_obj->get_results("SHOW TABLES", ARRAY_N);
         $all_tables = array_map(create_function('$a', 'return array("name" => $a[0], "type" => "BASE TABLE");'), $all_tables);
     } else {
         $all_tables = array_map(create_function('$a', 'return array("name" => $a[0], "type" => $a[1]);'), $all_tables);
     }
     # If this is not the WP database, then we do not consider it a fatal error if there are no tables
     if ('wp' == $whichdb && 0 == count($all_tables)) {
         $extra = $updraftplus->newresumption_scheduled ? ' - ' . __('please wait for the rescheduled attempt', 'updraftplus') : '';
         $updraftplus->log("Error: No WordPress database tables found (SHOW TABLES returned nothing)" . $extra);
         $updraftplus->log(__("No database tables found", 'updraftplus') . $extra, 'error');
         die;
     }
     // Put the options table first
     usort($all_tables, array($this, 'backup_db_sorttables'));
     $all_table_names = array_map(create_function('$a', 'return $a["name"];'), $all_tables);
     if (!$updraftplus->really_is_writable($this->updraft_dir)) {
         $updraftplus->log("The backup directory (" . $this->updraft_dir . ") could not be written to (could be account/disk space full, or wrong permissions).");
         $updraftplus->log($this->updraft_dir . ": " . __('The backup directory is not writable (or disk space is full) - the database backup is expected to shortly fail.', 'updraftplus'), 'warning');
         # Why not just fail now? We saw a bizarre case when the results of really_is_writable() changed during the run.
     }
     # This check doesn't strictly get all possible duplicates; it's only designed for the case that can happen when moving between deprecated Windows setups and Linux
     $this->duplicate_tables_exist = false;
     foreach ($all_table_names as $table) {
         if (strtolower($table) != $table && in_array(strtolower($table), $all_table_names)) {
             $this->duplicate_tables_exist = true;
             $updraftplus->log("Tables with names differing only based on case-sensitivity exist in the MySQL database: {$table} / " . strtolower($table));
         }
     }
     $how_many_tables = count($all_tables);
     $stitch_files = array();
     $found_options_table = false;
     $is_multisite = is_multisite();
     foreach ($all_tables as $ti) {
         $table = $ti['name'];
         $table_type = $ti['type'];
         $manyrows_warning = false;
         $total_tables++;
         // Increase script execution time-limit to 15 min for every table.
         @set_time_limit(UPDRAFTPLUS_SET_TIME_LIMIT);
         // The table file may already exist if we have produced it on a previous run
         $table_file_prefix = $file_base . '-db' . $this->whichdb_suffix . '-table-' . $table . '.table';
         if ('wp' == $whichdb && (strtolower($this->table_prefix_raw . 'options') == strtolower($table) || $is_multisite && (strtolower($this->table_prefix_raw . 'sitemeta') == strtolower($table) || strtolower($this->table_prefix_raw . '1_options') == strtolower($table)))) {
             $found_options_table = true;
         }
         if (file_exists($this->updraft_dir . '/' . $table_file_prefix . '.gz')) {
             $updraftplus->log("Table {$table}: corresponding file already exists; moving on");
             $stitch_files[] = $table_file_prefix;
         } else {
             # === is needed, otherwise 'false' matches (i.e. prefix does not match)
             if (empty($this->table_prefix) || $this->duplicate_tables_exist == false && stripos($table, $this->table_prefix) === 0 || $this->duplicate_tables_exist == true && strpos($table, $this->table_prefix) === 0) {
                 if (!apply_filters('updraftplus_backup_table', true, $table, $this->table_prefix, $whichdb, $dbinfo)) {
                     $updraftplus->log("Skipping table (filtered): {$table}");
                 } else {
                     $db_temp_file = $this->updraft_dir . '/' . $table_file_prefix . '.tmp.gz';
                     $updraftplus->check_recent_modification($db_temp_file);
                     // Open file, store the handle
                     $opened = $this->backup_db_open($db_temp_file, true);
                     if (false === $opened) {
                         return false;
                     }
                     // Create the SQL statements
                     $this->stow("# " . sprintf('Table: %s', $updraftplus->backquote($table)) . "\n");
                     $updraftplus->jobdata_set('dbcreating_substatus', array('t' => $table, 'i' => $total_tables, 'a' => $how_many_tables));
                     $table_status = $this->wpdb_obj->get_row("SHOW TABLE STATUS WHERE Name='{$table}'");
                     if (isset($table_status->Rows)) {
                         $rows = $table_status->Rows;
                         $updraftplus->log("Table {$table}: Total expected rows (approximate): " . $rows);
                         $this->stow("# Approximate rows expected in table: {$rows}\n");
                         if ($rows > UPDRAFTPLUS_WARN_DB_ROWS) {
                             $manyrows_warning = true;
                             $updraftplus->log(sprintf(__("Table %s has very many rows (%s) - we hope your web hosting company gives you enough resources to dump out that table in the backup", 'updraftplus'), $table, $rows), 'warning', 'manyrows_' . $this->whichdb_suffix . $table);
                         }
                     }
                     # Don't include the job data for any backups - so that when the database is restored, it doesn't continue an apparently incomplete backup
                     if ('wp' == $this->whichdb && (!empty($this->table_prefix) && strtolower($this->table_prefix . 'sitemeta') == strtolower($table))) {
                         $where = 'meta_key NOT LIKE "updraft_jobdata_%"';
                     } elseif ('wp' == $this->whichdb && (!empty($this->table_prefix) && strtolower($this->table_prefix . 'options') == strtolower($table))) {
                         $where = 'option_name NOT LIKE "updraft_jobdata_%" AND option_name NOT LIKE "_site_transient_update_%"';
                     } else {
                         $where = '';
                     }
                     # If no check-in last time, then we could in future try the other method (but - any point in retrying slow method on large tables??)
                     # New Jul 2014: This attempt to use bindump instead at a lower threshold is quite conservative - only if the last successful run was exactly two resumptions ago - may be useful to expand
                     $bindump_threshold = !$updraftplus->something_useful_happened && !empty($updraftplus->current_resumption) && $updraftplus->current_resumption - $updraftplus->last_successful_resumption == 2 ? 1000 : 8000;
                     $bindump = isset($rows) && ($rows > $bindump_threshold || defined('UPDRAFTPLUS_ALWAYS_TRY_MYSQLDUMP') && UPDRAFTPLUS_ALWAYS_TRY_MYSQLDUMP) && is_string($binsqldump) ? $this->backup_table_bindump($binsqldump, $table, $where) : false;
                     if (true !== $bindump) {
                         $this->backup_table($table, $where, 'none', $table_type);
                     }
                     if (!empty($manyrows_warning)) {
                         $updraftplus->log_removewarning('manyrows_' . $this->whichdb_suffix . $table);
                     }
                     $this->close();
                     $updraftplus->log("Table {$table}: finishing file ({$table_file_prefix}.gz - " . round(filesize($this->updraft_dir . '/' . $table_file_prefix . '.tmp.gz') / 1024, 1) . " KB)");
                     rename($db_temp_file, $this->updraft_dir . '/' . $table_file_prefix . '.gz');
                     $updraftplus->something_useful_happened();
                     $stitch_files[] = $table_file_prefix;
                 }
             } else {
                 $total_tables--;
                 $updraftplus->log("Skipping table (lacks our prefix (" . $this->table_prefix . ")): {$table}");
             }
         }
     }
     if ('wp' == $whichdb) {
         if (!$found_options_table) {
             if ($is_multisite) {
                 $updraftplus->log(__('The database backup appears to have failed', 'updraftplus') . ' - ' . __('no options or sitemeta table was found', 'updraftplus'), 'warning', 'optstablenotfound');
             } else {
                 $updraftplus->log(__('The database backup appears to have failed', 'updraftplus') . ' - ' . __('the options table was not found', 'updraftplus'), 'warning', 'optstablenotfound');
             }
             $time_this_run = time() - $updraftplus->opened_log_time;
             if ($time_this_run > 2000) {
                 # Have seen this happen; not sure how, but it was apparently deterministic; if the current process had been running for a long time, then apparently all database commands silently failed.
                 # If we have been running that long, then the resumption may be far off; bring it closer
                 $updraftplus->reschedule(60);
                 $updraftplus->log("Have been running very long, and it seems the database went away; scheduling a resumption and terminating for now");
                 $updraftplus->record_still_alive();
                 die;
             }
         } else {
             $updraftplus->log_removewarning('optstablenotfound');
         }
     }
     // Race detection - with zip files now being resumable, these can more easily occur, with two running side-by-side
     $backup_final_file_name = $backup_file_base . '-db' . $this->whichdb_suffix . '.gz';
     $time_now = time();
     $time_mod = (int) @filemtime($backup_final_file_name);
     if (file_exists($backup_final_file_name) && $time_mod > 100 && $time_now - $time_mod < 30) {
         $updraftplus->terminate_due_to_activity($backup_final_file_name, $time_now, $time_mod);
     }
     if (file_exists($backup_final_file_name)) {
         $updraftplus->log("The final database file ({$backup_final_file_name}) exists, but was apparently not modified within the last 30 seconds (time_mod={$time_mod}, time_now={$time_now}, diff=" . ($time_now - $time_mod) . "). Thus we assume that another UpdraftPlus terminated; thus we will continue.");
     }
     // Finally, stitch the files together
     if (!function_exists('gzopen')) {
         if (function_exists('gzopen64')) {
             $updraftplus->log("PHP function is disabled; abort expected: gzopen - buggy Ubuntu PHP version; try this plugin to help: https://wordpress.org/plugins/wp-ubuntu-gzopen-fix/");
         } else {
             $updraftplus->log("PHP function is disabled; abort expected: gzopen");
         }
     }
     if (false === $this->backup_db_open($backup_final_file_name, true)) {
         return false;
     }
     $this->backup_db_header();
     // We delay the unlinking because if two runs go concurrently and fail to detect each other (should not happen, but there's no harm in assuming the detection failed) then that leads to files missing from the db dump
     $unlink_files = array();
     $sind = 1;
     foreach ($stitch_files as $table_file) {
         $updraftplus->log("{$table_file}.gz ({$sind}/{$how_many_tables}): adding to final database dump");
         if (!($handle = gzopen($this->updraft_dir . '/' . $table_file . '.gz', "r"))) {
             $updraftplus->log("Error: Failed to open database file for reading: {$table_file}.gz");
             $updraftplus->log(__("Failed to open database file for reading:", 'updraftplus') . ' ' . $table_file . '.gz', 'error');
             $errors++;
         } else {
             while ($line = gzgets($handle, 65536)) {
                 $this->stow($line);
             }
             gzclose($handle);
             $unlink_files[] = $this->updraft_dir . '/' . $table_file . '.gz';
         }
         $sind++;
         // Came across a database with 7600 tables... adding them all took over 500 seconds; and so when the resumption started up, no activity was detected
         if ($sind % 100 == 0) {
             $updraftplus->something_useful_happened();
         }
     }
     if (@constant("DB_CHARSET")) {
         $this->stow("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
     }
     $updraftplus->log($file_base . '-db' . $this->whichdb_suffix . '.gz: finished writing out complete database file (' . round(filesize($backup_final_file_name) / 1024, 1) . ' KB)');
     if (!$this->close()) {
         $updraftplus->log('An error occurred whilst closing the final database file');
         $updraftplus->log(__('An error occurred whilst closing the final database file', 'updraftplus'), 'error');
         $errors++;
     }
     foreach ($unlink_files as $unlink_file) {
         @unlink($unlink_file);
     }
     if ($errors > 0) {
         return false;
     } else {
         # We no longer encrypt here - because the operation can take long, we made it resumable and moved it to the upload loop
         $updraftplus->jobdata_set('jobstatus', 'dbcreated' . $this->whichdb_suffix);
         $sha = sha1_file($backup_final_file_name);
         $updraftplus->jobdata_set('sha1-db' . ('wp' == $whichdb ? '0' : $whichdb . '0'), $sha);
         $updraftplus->log("Total database tables backed up: {$total_tables} (" . basename($backup_final_file_name) . ", size: " . filesize($backup_final_file_name) . ", checksum (SHA1): {$sha})");
         return basename($backup_final_file_name);
     }
 }
Example #24
0
function tep_update_all_shops($products_types_id = '')
{
    global $temp_tables, $in_shops, $currencies, $languages_id;
    $products_types_default_status = $products_types_id == 1 ? 1 : 0;
    if (!is_array($in_shops)) {
        $in_shops = array();
    }
    $temp_currencies = array();
    $filename_currencies_gz = UPLOAD_DIR . 'CSV/kurs.csv.gz';
    $filename_currencies = str_replace('.gz', '', $filename_currencies_gz);
    if (file_exists($filename_currencies_gz)) {
        $gz = @gzopen($filename_currencies_gz, 'r');
        $ff = @fopen($filename_currencies, 'w');
        if ($gz && $ff) {
            while ($string = gzgets($gz, 1024)) {
                fwrite($ff, $string);
            }
            fclose($ff);
            gzclose($gz);
        } elseif (file_exists($filename_currencies)) {
            @unlink($filename_currencies);
        }
    }
    if (file_exists($filename_currencies)) {
        $fp = fopen($filename_currencies, 'r');
        while ((list($currency_code, $currency_value) = fgetcsv($fp, 64, ';')) !== FALSE) {
            if ((double) $currency_value > 0) {
                $temp_currencies[$currency_code] = str_replace(',', '.', trim($currency_value));
            }
        }
        fclose($fp);
        unlink($filename_currencies);
    }
    if (sizeof($temp_currencies) == 0) {
        reset($currencies);
        while (list($currency_code, $currency_info) = each($currencies)) {
            $temp_currencies[$currency_code] = $currency_info['value'];
        }
    }
    $deleted_products = array();
    $filename_deleted_gz = UPLOAD_DIR . 'CSV/Deleted.csv.gz';
    $filename_deleted = str_replace('.gz', '', $filename_deleted_gz);
    if (file_exists($filename_deleted_gz)) {
        $gz = @gzopen($filename_deleted_gz, 'r');
        $ff = @fopen($filename_deleted, 'w');
        if ($gz && $ff) {
            while ($string = gzgets($gz, 1024)) {
                fwrite($ff, $string);
            }
            fclose($ff);
            gzclose($gz);
        } elseif (file_exists($filename_deleted)) {
            @unlink($filename_deleted);
        }
    }
    if (file_exists($filename_deleted)) {
        $fp = fopen($filename_deleted, 'r');
        while ((list($deleted_code, $deleted_type_id) = fgetcsv($fp, 64, ';')) !== FALSE) {
            if ((int) $deleted_code > 0) {
                $deleted_product_info_query = tep_db_query("select products_id from " . TABLE_TEMP_PRODUCTS . " where products_code = 'bbk" . sprintf('%010d', $deleted_code) . "' and products_types_id = '" . (int) $deleted_type_id . "'");
                $deleted_product_info = tep_db_fetch_array($deleted_product_info_query);
                $deleted_products[] = $deleted_product_info['products_id'];
            }
        }
        fclose($fp);
        unlink($filename_deleted);
    }
    $shops_query = tep_db_query("select * from " . TABLE_SHOPS . " where shops_database <> ''" . (sizeof($in_shops) > 0 ? " and (shops_default_status = '1' or shops_id in ('" . implode("', '", $in_shops) . "'))" : "") . " order by shops_default_status");
    while ($shops = tep_db_fetch_array($shops_query)) {
        list($shop_currency) = explode(',', $shops['shops_currency']);
        $shop_db = tep_db_input($shops['shops_database']);
        if (tep_not_null($shop_db)) {
            tep_db_select_db($shop_db);
            reset($temp_tables);
            while (list($step, $temp_table) = each($temp_tables)) {
                if ($shops['shops_default_status'] == '0') {
                    tep_db_query("drop table if exists " . $shop_db . ".temp_" . $temp_table);
                    if (tep_db_table_exists(DB_DATABASE, 'temp_' . $temp_table)) {
                        tep_db_query("create table " . $shop_db . ".temp_" . $temp_table . " like " . DB_DATABASE . ".temp_" . $temp_table);
                        tep_db_query("insert into " . $shop_db . ".temp_" . $temp_table . " select * from " . DB_DATABASE . ".temp_" . $temp_table);
                    } else {
                        tep_db_query("create table " . $shop_db . "." . $temp_table . " like " . DB_DATABASE . "." . $temp_table);
                        tep_db_query("insert into " . $shop_db . "." . $temp_table . " select * from " . DB_DATABASE . "." . $temp_table);
                    }
                }
            }
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_status = '1' where products_types_id > '1' and products_id in (select products_id from " . DB_DATABASE . "." . TABLE_PRODUCTS_TO_SHOPS . " where shops_id = '" . (int) $shops['shops_id'] . "' and products_status = '1')");
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_status = '0' where products_id in (select products_id from " . DB_DATABASE . "." . TABLE_PRODUCTS_TO_SHOPS . " where shops_id = '" . (int) $shops['shops_id'] . "' and products_status = '0')");
            /*
            		if ((int)$products_types_default_status==0) {
            		  $unused_categories_array = array();
            		  $unused_categories_query = tep_db_query("select categories_id from " . $shop_db . "." . TABLE_CATEGORIES . " where products_types_id = '" . (int)$products_types_id . "' and categories_status = '1'");
            	 	  while ($unused_categories = tep_db_fetch_array($unused_categories_query)) {
            			$subcategories_array = $unused_categories['categories_id'];
            			tep_get_subcategories($subcategories_array, $unused_categories['categories_id']);
            			$products_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " p where p.products_types_id = '" . (int)$products_types_id . "' and p2c.products_id = p.products_id and p.products_status = '1'");
            			$products_check = tep_db_fetch_array($products_check_query);
            			if ($products_check['total']==0) $unused_categories_array[] = (int)$unused_categories['categories_id'];
            		  }
            		  if (sizeof($unused_categories_array) > 0) tep_db_query("update " . $shop_db . "." . TABLE_CATEGORIES . " set categories_status = '0' where categories_id in ('" . implode("', '", $unused_categories_array) . "'))");
            		}
            */
            $unused_categories_array = array();
            $unused_categories_query = tep_db_query("select categories_id from " . $shop_db . "." . TABLE_CATEGORIES . " where categories_status = '0' and products_types_id in (select products_types_id from " . $shop_db . "." . TABLE_PRODUCTS_TYPES . " where products_types_status = '1')");
            while ($unused_categories = tep_db_fetch_array($unused_categories_query)) {
                $unused_categories_array[] = $unused_categories['categories_id'];
                tep_get_subcategories($unused_categories_array, $unused_categories['categories_id']);
            }
            if (sizeof($unused_categories_array) > 0) {
                tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_status = '0' where products_id in (select products_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where categories_id in ('" . implode("', '", $unused_categories_array) . "'))");
            }
            tep_update_shops_prices($shops['shops_id'], '', 'temp');
            reset($deleted_products);
            while (list(, $deleted_product_id) = each($deleted_products)) {
                tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_status = '0' where products_id = '" . (int) $deleted_product_id . "'");
            }
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_listing_status = '0', products_xml_status = '0' where products_price = '0'");
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_price = '0' where products_listing_status = '0'");
            if ($shops['shops_default_status'] == '0') {
                tep_db_query("delete from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_types_id = '5'");
            } else {
                tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_available_in = '1' where products_id in (select products_id from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_types_id = '5' and status = '1')");
            }
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " set products_available_in = '0' where products_filename is not null");
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_SPECIALS . " s, " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " p set s.status = p.products_status, s.products_image_exists = p.products_image_exists, s.specials_first_page = if((p.products_image_exists and p.products_listing_status), '1', '0') where s.products_id = p.products_id");
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_SPECIALS . " set specials_first_page = if((products_image_exists and status), '1', '0') where specials_types_id = '4'");
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " p, " . $shop_db . "." . TABLE_TEMP_PRODUCTS_INFO . " pi set pi.products_code = p.products_code, pi.products_model = p.products_model, pi.products_image = p.products_image, pi.products_filename = p.products_filename, pi.products_price = p.products_price, pi.products_last_modified = p.products_last_modified, pi.products_available_in = p.products_available_in, pi.products_weight = p.products_weight, pi.products_year = p.products_year, pi.products_pages_count = p.products_pages_count, pi.products_copies = p.products_copies, pi.products_status = p.products_status, pi.products_listing_status = p.products_listing_status, pi.products_types_id = p.products_types_id where pi.products_id = p.products_id");
            //		tep_db_query("delete from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where status = '1' and now() >= expires_date and expires_date > 0");
            $specials_query = tep_db_query("select specials_id, products_id, specials_new_products_price from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_new_products_price > '0'");
            while ($specials = tep_db_fetch_array($specials_query)) {
                $product_info_query = tep_db_query("select products_price, products_status from " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " where products_id = '" . (int) $specials['products_id'] . "'");
                $product_info = tep_db_fetch_array($product_info_query);
                if ($product_info['products_price'] <= $specials['specials_new_products_price'] || $product_info['products_status'] == '0') {
                    tep_db_query("delete from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_id = '" . (int) $specials['specials_id'] . "'");
                }
            }
            $specials_query = tep_db_query("select specials_id, products_id from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_types_id = '4'");
            while ($specials = tep_db_fetch_array($specials_query)) {
                $product_info_query = tep_db_query("select products_listing_status, products_price from " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " where products_id = '" . (int) $specials['products_id'] . "'");
                $product_info = tep_db_fetch_array($product_info_query);
                if ($product_info['products_price'] > '0' && $product_info['products_listing_status'] == '1') {
                    tep_db_query("delete from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where specials_id = '" . (int) $specials['specials_id'] . "'");
                }
            }
            // сортировка по умолчанию (сначала спецпредложения с картинками, потом спецпредложения без картинок, потом книги с картинками, потом все остальное)
            $max_specials_date_query = tep_db_query("select max(specials_date_added) as specials_date_added from " . $shop_db . "." . TABLE_TEMP_SPECIALS . " where status = '1'");
            $max_specials_date_row = tep_db_fetch_array($max_specials_date_query);
            $max_specials_date = strtotime($max_specials_date_row['specials_date_added']);
            $min_specials_date_added = date('Y-m-d', $max_specials_date - 60 * 60 * 24 * 7);
            tep_db_query("update " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " p left join " . $shop_db . "." . TABLE_TEMP_SPECIALS . " s on (s.products_id = p.products_id and s.specials_types_id in ('1', '2') and s.specials_date_added >= '" . tep_db_input($min_specials_date_added) . "') set p.sort_order = (if(p.products_listing_status=1, 8, 0) + if(s.specials_types_id, if(s.specials_types_id=1, 4, if(s.specials_types_id=2, 3, 0)), 0) + if(p.products_image_exists=1, 2, 0))");
            reset($temp_tables);
            while (list($step, $temp_table) = each($temp_tables)) {
                if (tep_db_table_exists($shop_db, 'temp_' . $temp_table)) {
                    if ($temp_table == TABLE_PRODUCTS && $products_types_default_status == 1) {
                        /*
                        			  $basket_products_query = tep_db_query("select products_id from " . TABLE_CUSTOMERS_BASKET . " where shops_id = '" . (int)$shops['shops_id'] . "'");
                        			  while ($basket_products = tep_db_fetch_array($basket_products_query)) {
                        				$check_old_status_query = tep_db_query("slect products_status, products_listing_status from " . $shop_db . "." . TABLE_PRODUCTS . " where products_id = '" . (int)$basket_products['products_id'] . "'");
                        				$check_old_status = tep_db_fetch_array($check_old_status_query);
                        
                        				$check_new_status_query = tep_db_query("slect products_status, products_listing_status from " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " where products_id = '" . (int)$basket_products['products_id'] . "'");
                        				$check_new_status = tep_db_fetch_array($check_new_status_query);
                        
                        				if ($check_new_status['products_status'] == '0') {
                        				  // удаляем из корзин товары, которых нет на сайте
                        				  tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where shops_id = '" . (int)$shops['shops_id'] . "' and products_id = '" . (int)$basket_products['products_id'] . "'");
                        				} elseif ($check_old_status['products_listing_status'] == '1' && $check_new_status['products_listing_status'] == '0') {
                        				  // переносим из корзин в отложенные товары
                        				  tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_basket_quantity = '1', customers_basket_type = 'postpone' where shops_id = '" . (int)$shops['shops_id'] . "' and products_id = '" . (int)$basket_products['products_id'] . "'");
                        				}
                        			  }
                        */
                        $lang_id = $languages_id;
                        if ($shop_db == 'setbook_org' || $shop_db == 'easternowl' || $shop_db == 'insellbooks') {
                            $lang_id = 1;
                        }
                        $shop_name_info_query = tep_db_query("select configuration_value from " . $shop_db . "." . TABLE_CONFIGURATION . " where configuration_key = 'STORE_NAME'");
                        $shop_name_info = tep_db_fetch_array($shop_name_info_query);
                        $shop_name = $shop_name_info['configuration_value'];
                        $shop_email_info_query = tep_db_query("select configuration_value from " . $shop_db . "." . TABLE_CONFIGURATION . " where configuration_key = 'STORE_OWNER_EMAIL_ADDRESS'");
                        $shop_email_info = tep_db_fetch_array($shop_email_info_query);
                        $shop_email = $shop_email_info['configuration_value'];
                        $shop_phone_info_query = tep_db_query("select configuration_value from " . $shop_db . "." . TABLE_CONFIGURATION . " where configuration_key = 'STORE_OWNER_PHONE_NUMBER'");
                        $shop_phone_info = tep_db_fetch_array($shop_phone_info_query);
                        $shop_phone = $shop_phone_info['configuration_value'];
                        $notify_products_query = tep_db_query("select customers_basket_id, products_id, customers_id, customers_basket_notify_url, customers_basket_notify from " . TABLE_CUSTOMERS_BASKET . " where shops_id = '" . (int) $shops['shops_id'] . "' and customers_basket_notify > '0'");
                        while ($notify_products = tep_db_fetch_array($notify_products_query)) {
                            $new_info_query = tep_db_query("select products_status, products_listing_status, products_price, authors_id from " . $shop_db . "." . TABLE_TEMP_PRODUCTS . " where products_id = '" . (int) $notify_products['products_id'] . "'");
                            $new_info = tep_db_fetch_array($new_info_query);
                            $old_info_query = tep_db_query("select products_status, products_listing_status, products_price, authors_id from " . $shop_db . "." . TABLE_PRODUCTS . " where products_id = '" . (int) $notify_products['products_id'] . "'");
                            $old_info = tep_db_fetch_array($old_info_query);
                            $product_name_info_query = tep_db_query("select products_name from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int) $notify_products['products_id'] . "' and language_id = '" . (int) $lang_id . "'");
                            $product_name_info = tep_db_fetch_array($product_name_info_query);
                            if (!is_array($product_name_info)) {
                                $product_name_info = array();
                            }
                            $author_info_query = tep_db_query("select authors_name from " . TABLE_AUTHORS . " where authors_id = '" . (int) $new_info['authors_id'] . "' and language_id = '" . (int) $lang_id . "'");
                            $author_info = tep_db_fetch_array($author_info_query);
                            if (!is_array($author_info)) {
                                $author_info = array();
                            }
                            if ($lang_id == 1) {
                                $product_email_name = $product_name_info['products_name'] . (tep_not_null($author_info['authors_name']) ? ' by ' . $author_info['authors_name'] : '');
                            } else {
                                $product_email_name = (tep_not_null($author_info['authors_name']) ? $author_info['authors_name'] . ': ' : '') . $product_name_info['products_name'];
                            }
                            $new_status = $new_info['products_listing_status'];
                            $new_price = $new_info['products_price'];
                            $old_status = $old_info['products_listing_status'];
                            $old_price = $old_info['products_price'];
                            $customer_info_query = tep_db_query("select customers_firstname, customers_email_address from " . TABLE_CUSTOMERS . " where customers_id = '" . (int) $notify_products['customers_id'] . "'");
                            $customer_info = tep_db_fetch_array($customer_info_query);
                            $notification_body = '';
                            $notification_subject = '';
                            $notification_warning = '';
                            if ($notify_products['customers_basket_notify'] == '1') {
                                // о появлении в продаже
                                if ($new_status == '1') {
                                    if ($lang_id == 1) {
                                        $notification_body = EMAIL_NOTIFICATION_BODY_EN_1;
                                        $notification_subject = EMAIL_NOTIFICATION_SUBJECT_EN_1;
                                        $notification_warning = EMAIL_NOTIFICATION_WARNING_EN_1;
                                    } else {
                                        $notification_body = EMAIL_NOTIFICATION_BODY_1;
                                        $notification_subject = EMAIL_NOTIFICATION_SUBJECT_1;
                                        $notification_warning = EMAIL_NOTIFICATION_WARNING_1;
                                    }
                                }
                            } elseif ($notify_products['customers_basket_notify'] == '2') {
                                // о снижении цены
                                if ($new_price > 0 && $new_price < $old_price) {
                                    if ($lang_id == 1) {
                                        $notification_body = EMAIL_NOTIFICATION_BODY_EN_2;
                                        $notification_subject = EMAIL_NOTIFICATION_SUBJECT_EN_2;
                                        $notification_warning = EMAIL_NOTIFICATION_WARNING_EN_2;
                                    } else {
                                        $notification_body = EMAIL_NOTIFICATION_BODY_2;
                                        $notification_subject = EMAIL_NOTIFICATION_SUBJECT_2;
                                        $notification_warning = EMAIL_NOTIFICATION_WARNING_2;
                                    }
                                }
                            }
                            if (tep_not_null($notification_body)) {
                                $email_notification_body = str_replace('{{product_link}}', $notify_products['customers_basket_notify_url'], sprintf($notification_body, $customer_info['customers_firstname'], $product_email_name)) . "\n\n" . EMAIL_NOTIFICATION_SEPARATOR . "\n" . sprintf($notification_warning, $shop_name);
                                $message = new email(array('X-Mailer: ' . $shop_name));
                                $text = strip_tags($email_notification_body);
                                if ($shops['shops_email_use_html'] < 1) {
                                    $message->add_text($text);
                                } else {
                                    ob_start();
                                    include DIR_FS_CATALOG . 'images/mail/email_header_1.php';
                                    echo trim($email_notification_body);
                                    include DIR_FS_CATALOG . 'images/mail/email_footer_1.php';
                                    $email_text_html = ob_get_clean();
                                    $email_text_html = str_replace(array('<title></title>', '{{HTTP_SERVER}}', '{{STORE_NAME}}', '{{STORE_OWNER_PHONE_NUMBER}}'), array('<title>' . sprintf($notification_subject, $shop_name) . '</title>', $shops['shops_url'], $shop_name, $shop_phone), $email_text_html);
                                    $message->add_html($email_text_html, $text);
                                }
                                $message->build_message();
                                $message->send($customer_info['customers_firstname'], $customer_info['customers_email_address'], $shop_name, $shop_email, sprintf($notification_subject, $shop_name));
                                tep_db_query("update " . TABLE_CUSTOMERS_BASKET . " set customers_basket_notify = '0', customers_basket_notify_url = null where customers_basket_id = '" . (int) $notify_products['customers_basket_id'] . "'");
                            }
                        }
                    }
                    tep_db_query("drop table " . $shop_db . "." . $temp_table . "");
                    tep_db_query("alter table " . $shop_db . ".temp_" . $temp_table . " rename as " . $shop_db . "." . $temp_table . "");
                    if ($shop_db == 'setbook_ua') {
                        tep_db_query("update " . $shop_db . "." . TABLE_CURRENCIES . " set value = '" . tep_db_input($temp_currencies[$shop_currency]) . "', last_updated = now() where code = '" . tep_db_input($shop_currency) . "'");
                    }
                }
            }
            if ($shops['shops_default_status'] == '1') {
                tep_db_query("delete from " . TABLE_SEARCH_KEYWORDS_TO_PRODUCTS . "");
                tep_db_query("delete from " . TABLE_SEARCH_KEYWORDS . "");
                tep_db_query("update " . TABLE_SPECIALS_TYPES . " set specials_last_modified = now()");
            }
            if ($products_types_default_status == 1) {
                tep_db_query("update " . $shop_db . "." . TABLE_PRODUCTS_TYPES . " set products_last_modified = now() where products_types_id = '1'");
            } else {
                tep_db_query("update " . $shop_db . "." . TABLE_PRODUCTS_TYPES . " set products_last_modified = now() where products_types_id > '1'");
            }
            if ($shop_db == 'setbook_us' || $shop_db == 'setbook_biz') {
                tep_db_query("replace into " . $shop_db . "." . TABLE_METATAGS . " (metatags_page_title, metatags_title, metatags_keywords, metatags_description, language_id, content_type, content_id) select concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_page_title, ' Russian books.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_title, '. Russian books.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_keywords, ' Russian books.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_description, ' Russian books.'), " . DB_DATABASE . "." . TABLE_METATAGS . ".language_id, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_id from " . DB_DATABASE . "." . TABLE_METATAGS . " where " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type in ('author', 'category', 'manufacturer',  'product', 'serie', 'type');");
                tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books', 'Russian magazines'), mt.metatags_title = replace(mt.metatags_title, 'Russian books', 'Russian magazines'), mt.metatags_keywords = replace(mt.metatags_keywords, 'Russian books', 'Russian magazines'), mt.metatags_description = replace(mt.metatags_description, 'Russian books', 'Russian magazines') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '2'");
                tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books', 'Russian magazines'), mt.metatags_title = replace(mt.metatags_title, 'Russian books', 'Russian souvenirs. Matreshka'), mt.metatags_keywords = replace(mt.metatags_keywords, 'Russian books', 'Russian magazines'), mt.metatags_description = replace(mt.metatags_description, 'Russian books', 'Russian souvenirs') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '5'");
            } elseif ($shop_db == 'setbook_eu' || $shop_db == 'setbook_net') {
                tep_db_query("replace into " . $shop_db . "." . TABLE_METATAGS . " (metatags_page_title, metatags_title, metatags_keywords, metatags_description, language_id, content_type, content_id) select concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_page_title, ' Russian books. Russische b&uuml;cher'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_title, '. Russian books.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_keywords, ' Russian books. Russische b&uuml;cher'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_description, ' Russian books. Russische b&uuml;cher'), " . DB_DATABASE . "." . TABLE_METATAGS . ".language_id, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_id from " . DB_DATABASE . "." . TABLE_METATAGS . " where " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type in ('author', 'category', 'manufacturer',  'product', 'serie', 'type');");
                tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books. Russische b&uuml;cher', 'Russian magazines. Russische Zeitschriften'), mt.metatags_title = replace(mt.metatags_title, 'Russian books', 'Russian magazines'), mt.metatags_keywords = replace(mt.metatags_keywords, 'Russian books', 'Russian magazines'), mt.metatags_description = replace(mt.metatags_description, 'Russian books', 'Russian magazines') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '2'");
            } elseif ($shop_db == 'setbook_ua') {
                tep_db_query("replace into " . $shop_db . "." . TABLE_METATAGS . " (metatags_page_title, metatags_title, metatags_keywords, metatags_description, language_id, content_type, content_id) select replace(" . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_page_title, 'Интернет-магазин Setbook', 'Книжный интернет-магазин в Украине Setbook'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_title, '. Книжный интернет-магазин в Украине Setbook.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_keywords, ' Украина, книги в Киеве.'),\nconcat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_description, ' Украина, книги в Киеве.'), " . DB_DATABASE . "." . TABLE_METATAGS . ".language_id, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_id from " . DB_DATABASE . "." . TABLE_METATAGS . " where " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type in ('author', 'category', 'manufacturer',  'product', 'serie', 'type');");
                //		  tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books', ''), mt.metatags_title = replace(mt.metatags_title, '', ''), mt.metatags_keywords = replace(mt.metatags_keywords, '', ''), mt.metatags_description = replace(mt.metatags_description, '', '') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '2'");
            } elseif ($shop_db == 'setbook_kz') {
                tep_db_query("replace into " . $shop_db . "." . TABLE_METATAGS . " (metatags_page_title, metatags_title, metatags_keywords, metatags_description, language_id, content_type, content_id) select replace(" . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_page_title, 'Интернет-магазин Setbook', 'Книжный интернет-магазин в Казахстане Setbook'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_title, '. Книжный интернет-магазин в Казахстане Setbook.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_keywords, ' Казахстан, книги в Алматы, Астане, Караганде.'),\nconcat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_description, ' Казахстан, книги в Алматы, Астане, Караганде.'), " . DB_DATABASE . "." . TABLE_METATAGS . ".language_id, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_id from " . DB_DATABASE . "." . TABLE_METATAGS . " where " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type in ('author', 'category', 'manufacturer',  'product', 'serie', 'type');");
                //		  tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books', ''), mt.metatags_title = replace(mt.metatags_title, '', ''), mt.metatags_keywords = replace(mt.metatags_keywords, '', ''), mt.metatags_description = replace(mt.metatags_description, '', '') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '2'");
            } elseif ($shop_db == 'setbook_by' || $shop_db == 'bookva_by') {
                if ($shop_db == 'setbook_by') {
                    tep_db_query("replace into " . $shop_db . "." . TABLE_METATAGS . " (metatags_page_title, metatags_title, metatags_keywords, metatags_description, language_id, content_type, content_id) select replace(" . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_page_title, 'Интернет-магазин Setbook', 'Интернет-магазин книг в Белоруссии Setbook'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_title, '. Интернет-магазин книг Белоруссии Setbook.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_keywords, ' Белоруссия, книги в Минске.'), concat_ws('', " . DB_DATABASE . "." . TABLE_METATAGS . ".metatags_description, ' Белоруссия, книги в Минске.'), " . DB_DATABASE . "." . TABLE_METATAGS . ".language_id, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type, " . DB_DATABASE . "." . TABLE_METATAGS . ".content_id from " . DB_DATABASE . "." . TABLE_METATAGS . " where " . DB_DATABASE . "." . TABLE_METATAGS . ".content_type in ('author', 'category', 'manufacturer',  'product', 'serie', 'type');");
                    //			tep_db_query("update " . $shop_db . "." . TABLE_METATAGS . " mt, " . $shop_db . "." . TABLE_PRODUCTS . " p set mt.metatags_page_title = replace(mt.metatags_page_title, 'Russian books', ''), mt.metatags_title = replace(mt.metatags_title, '', ''), mt.metatags_keywords = replace(mt.metatags_keywords, '', ''), mt.metatags_description = replace(mt.metatags_description, '', '') where mt.content_type = 'product' and mt.content_id = p.products_id and p.products_types_id = '2'");
                }
            }
        }
    }
    tep_db_select_db(DB_DATABASE);
}
Example #25
0
 if ($dh = opendir($dir)) {
     $delilength = strlen($delimiter);
     while (($dbfile = readdir($dh)) !== false) {
         if (eregi("\\.gz\$", $dbfile)) {
             $zp = @gzopen("{$dir}/{$dbfile}", "rb");
             //open backup-file of one table
             if (!$zp) {
                 die("Cannot read backup-file: {$dbfile}");
             }
             flush();
             //clear buffer
             set_time_limit(1800);
             //the rest of this backup-file should be done in 30 minutes (increase timeout)
             $temp = '';
             while (!gzeof($zp)) {
                 $temp = $temp . gzgets($zp, '8192');
                 //get  one row from current backup-file
                 if ($endoff = strpos($temp, $delimiter)) {
                     //find end of sql insert
                     $temp = substr($temp, 0, $endoff);
                     //delete delimiter
                     $temp = str_replace("\n\n", "\n", $temp);
                     //delete blank rows
                     $query = substr($temp, 0, $endoff);
                     //this part of tempfile is the current query
                     mysql_db_query($database, $query) or die(mysql_error());
                     //insert into table
                     $temp = '';
                 }
             }
             gzclose($zp);
 /**
  * Get a line from the stream source.
  *
  * @param   integer  $length  The number of bytes (optional) to read.
  *
  * @return  mixed
  *
  * @since   11.1
  */
 public function gets($length = 0)
 {
     if (!$this->_fh) {
         $this->setError(JText::_('JLIB_FILESYSTEM_ERROR_STREAMS_FILE_NOT_OPEN'));
         return false;
     }
     $retval = false;
     // Capture PHP errors
     $php_errormsg = 'Error Unknown';
     $track_errors = ini_get('track_errors');
     ini_set('track_errors', true);
     switch ($this->processingmethod) {
         case 'gz':
             $res = $length ? gzgets($this->_fh, $length) : gzgets($this->_fh);
             break;
         case 'bz':
         case 'f':
         default:
             $res = $length ? fgets($this->_fh, $length) : fgets($this->_fh);
             break;
     }
     if (!$res) {
         $this->setError($php_errormsg);
     } else {
         $retval = $res;
     }
     // Restore error tracking to what it was before
     ini_set('track_errors', $track_errors);
     // return the result
     return $retval;
 }
Example #27
0
/**
 * Uncompress GZip file
 * @param string $srcName 
 * @param string $dstName 
 */
function themify_uncompress_gzip($srcName, $dstName)
{
    $sfp = gzopen($srcName, "rb");
    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    WP_Filesystem();
    global $wp_filesystem;
    $string = '';
    while (!gzeof($sfp)) {
        $string .= gzgets($sfp, 8192);
    }
    $wp_filesystem->put_contents($dstName, $string, FS_CHMOD_FILE);
    gzclose($sfp);
}
Example #28
0
 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;
 }
Example #29
0
 if (!$error) {
     $query = "";
     $queries = 0;
     $totalqueries = $_REQUEST["totalqueries"];
     $linenumber = $_REQUEST["start"];
     $querylines = 0;
     $inparents = false;
     // Stay processing as long as the $linespersession is not reached or the query is still incomplete
     while ($linenumber < $_REQUEST["start"] + $linespersession || $query != "") {
         // Read the whole next line
         $dumpline = "";
         while (!feof($file) && substr($dumpline, -1) != "\n" && substr($dumpline, -1) != "\r") {
             if (!$gzipmode) {
                 $dumpline .= fgets($file, DATA_CHUNK_LENGTH);
             } else {
                 $dumpline .= gzgets($file, DATA_CHUNK_LENGTH);
             }
         }
         if ($dumpline === "") {
             break;
         }
         // Remove UTF8 Byte Order Mark at the file beginning if any
         if ($_REQUEST["foffset"] == 0) {
             $dumpline = preg_replace('|^\\xEF\\xBB\\xBF|', '', $dumpline);
         }
         // Create an SQL query from CSV line
         if ($csv_insert_table != "" && preg_match("/(\\.csv)\$/i", $curfilename)) {
             if ($csv_add_slashes) {
                 $dumpline = addslashes($dumpline);
             }
             $dumpline = explode($csv_delimiter, $dumpline);
Example #30
0
 $rows = array();
 if ($gz = substr($_REQUEST['file'], -2) == 'gz') {
     $file = gzopen(VIVVO_FS_ROOT . 'backup/' . $_REQUEST['file'], "r");
 } else {
     $file = fopen(VIVVO_FS_ROOT . 'backup/' . $_REQUEST['file'], "r");
 }
 $qc = 0;
 $success_no = 0;
 $queries_no = 0;
 $break_point = 0;
 $read_line = 0;
 $queries = '';
 $debug_mode = true;
 do {
     if ($gz) {
         $buffer = gzgets($file, 4096);
     } else {
         $buffer = fgets($file, 4096);
     }
     $read_line++;
     if (strlen($buffer) > 0 and substr($buffer, 0, 1) != '#' or substr($buffer, 0, 2) == '##') {
         $queries .= $buffer;
         if (substr(trim($buffer), -19) == "##VIVVO_END_OF_LINE") {
             $queries = str_replace("##VIVVO_END_OF_LINE", "", $queries);
             $queries_no++;
             if (!mysql_query($queries)) {
                 if ($debug_mode) {
                     $messages[] = array('message' => mysql_error() . "({$queries})", 'type' => 'error');
                 }
             } else {
                 $success_no++;