Example #1
0
 private static function extractZip($file, $destDir)
 {
     $za = new ZipArchive();
     $za->open($file);
     $entries = array();
     for ($i = 0, $max = $za->numFiles; $i < $max; $i++) {
         $stat = $za->statIndex($i);
         // Skip files not at the top level
         if ($stat['name'] != basename($stat['name'])) {
             continue;
         }
         // Skip dot files or ztmp (which we use as temp dir)
         if ($stat['name'][0] == '.' || $stat['name'] == 'ztmp') {
             continue;
         }
         if (preg_match("/%ZB64\$/", $stat['name'])) {
             $filename = Z_Base64::decode(substr($stat['name'], 0, -5));
             $filename = self::decodeRelativeDescriptorString($filename);
             $za->renameIndex($i, $filename);
         } else {
             $filename = $stat['name'];
         }
         $entries[] = $filename;
     }
     $success = $za->extractTo($destDir, $entries);
     $za->close();
     if (!$success) {
         Z_Core::logError($za->getStatusString());
     }
     return $success;
 }
Example #2
0
 function _pbboard_updates_start()
 {
     global $PowerBB;
     // get main dir
     $To = $PowerBB->functions->GetMianDir();
     $To = str_ireplace("index.php/", '', $To);
     $pbboard_last_time_updates = 'http://www.pbboard.info/check_updates/pbboard_last_time_updates.txt';
     $last_time_updates = @file_get_contents($pbboard_last_time_updates);
     if (!$last_time_updates) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $pbboard_last_time_updates);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $last_time_updates = curl_exec($ch);
     }
     $arr = explode('-', $last_time_updates);
     $url = trim($arr[2]);
     $file_get = fopen($url, 'r');
     file_put_contents($To . "Tmpfile.zip", $file_get);
     $zip = new ZipArchive();
     $file = $To . 'Tmpfile.zip';
     //$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
     if ($zip->open($file) === TRUE) {
         $zip->extractTo($To);
         $ziped = 1;
     } else {
         $ziped = 0;
     }
     if ($ziped) {
         if ($PowerBB->admincpdir != 'admincp') {
             for ($i = 0; $i < $zip->numFiles; $i++) {
                 if (strstr($zip->getNameIndex($i), 'admincp')) {
                     $zip->renameIndex($i, str_replace("admincp", $PowerBB->admincpdir, $zip->getNameIndex($i)));
                     $zip->extractTo($To, $zip->getNameIndex($i));
                 }
             }
         }
         $zip->close();
         $PowerBB->info->UpdateInfo(array('value' => $PowerBB->_CONF['now'], 'var_name' => 'last_time_updates'));
         unlink($file);
         echo $PowerBB->_CONF['template']['_CONF']['lang']['pbboard_updated'];
     } else {
         echo $PowerBB->_CONF['template']['_CONF']['lang']['automatic_update_fails'];
     }
 }
Example #3
0
 /**
  * Creates the backup with given name and description
  *
  * @param string $name filename
  * @param string $description
  * @return bool true on success, false on error
  */
 private function createBackup($name, $description = '')
 {
     $zip = new ZipArchive();
     // create empty array
     if ($zip->open(__DIR__ . '/data/' . $name, ZipArchive::CREATE) !== true) {
         return false;
     }
     // add all files
     if (!isset($this->CONFIG['backup_list']) || !is_array($this->CONFIG['backup_list'])) {
         return false;
     }
     foreach ($this->CONFIG['backup_list'] as $item) {
         $zip->addGlob($item);
     }
     // rename files as zip thinks there are CP866 filenames but they are in 1251
     // so all cyrillic names are unreadable
     for ($i = 0; $i < $zip->numFiles; $i++) {
         if ($zip->getNameIndex($i) > '') {
             $zip->renameIndex($i, iconv(filesystem_encoding(), 'CP866', $zip->getNameIndex($i)));
         }
     }
     // ok, finished
     $zip->setArchiveComment($description);
     $zip->close();
     return true;
 }
Example #4
0
     }
 }
 if ($uploadfilename) {
     // Check ZIP file contents for extra directory at the top
     $za = new ZipArchive();
     $za->open($uploadfilename);
     for ($i = 0; $i < $za->numFiles; $i++) {
         $entryName = $za->getNameIndex($i);
         $firstSlash = strpos($entryName, '/');
         if ($entryName === 'manifest.xml' || $entryName === './manifest.xml' || $firstSlash === false) {
             $za->unchangeAll();
             break;
         }
         $newEntryName = substr($entryName, $firstSlash + 1);
         if ($newEntryName !== false) {
             $za->renameIndex($i, $newEntryName);
         } else {
             $za->deleteIndex($i);
         }
     }
     $za->close();
     $package = new Vtiger_Package();
     $moduleimport_name = $package->getModuleNameFromZip($uploadfilename);
     if ($moduleimport_name == null) {
         $smarty->assign("MODULEIMPORT_FAILED", "true");
         $smarty->assign("MODULEIMPORT_FILE_INVALID", "true");
     } else {
         if (!$package->isLanguageType() && !$package->isModuleBundle()) {
             $moduleInstance = Vtiger_Module::getInstance($moduleimport_name);
             $moduleimport_exists = $moduleInstance ? "true" : "false";
             $moduleimport_dir_name = "modules/{$moduleimport_name}";
 /**
  * Execute the action.
  * @param array command line parameters specific for this command
  */
 public function run($args)
 {
     echo PHP_EOL;
     if (!isset($args[0])) {
         $this->usageError('A language pack archive file must be specified.');
     }
     // Start
     $msg_file = INSTANCE_ROOT . DIRECTORY_SEPARATOR . 'protected' . DIRECTORY_SEPARATOR . 'commands' . DIRECTORY_SEPARATOR . $args[0];
     if (!file_exists($msg_file)) {
         $this->usageError('The provided filename does not exist.');
     }
     $zip = new ZipArchive();
     if ($zip->open($msg_file) === true) {
         if ($zip->numFiles > 0) {
             $overwriteAll = false;
             $locales = CLocale::getLocaleIDs();
             for ($i = 0; $i < $zip->numFiles; $i++) {
                 $zip->renameIndex($i, substr($zip->getNameIndex($i), strpos($zip->getNameIndex($i), 'app/')));
                 $entry = $zip->getNameIndex($i);
                 if (preg_match('#(__MACOSX)#i', $entry)) {
                     continue;
                 }
                 if (preg_match('#\\.(php)$#i', $entry)) {
                     $extractPath = substr(INSTANCE_ROOT, 0, -strlen('app/')) . DIRECTORY_SEPARATOR;
                     $file = $extractPath . $entry;
                     if (is_file($file)) {
                         preg_match('#(.*)\\/messages\\/(.*)\\/(.*)#i', $entry, $matches);
                         if (is_array($matches)) {
                             $lang = $matches[2];
                         }
                         if (!in_array($lang, $locales)) {
                             echo ' Message-file `' . $entry . '` ignored. Language `' . $lang . '` is not a supported language/locale.' . PHP_EOL;
                             continue;
                         }
                         if ($overwriteAll) {
                             echo ' Message-file `' . $entry . '` overwritten.' . PHP_EOL;
                         } else {
                             echo '  Message-file `' . $entry . '` already exists but different.' . PHP_EOL;
                             $answer = $this->prompt('    ...Overwrite? [Yes|No|All|Quit] ');
                             if (!strncasecmp($answer, 'q', 1)) {
                                 return;
                             } elseif (!strncasecmp($answer, 'y', 1)) {
                                 echo ' Message-file `' . $entry . '` overwritten.' . PHP_EOL;
                             } elseif (!strncasecmp($answer, 'a', 1)) {
                                 echo ' Message-file `' . $entry . '` overwritten.' . PHP_EOL;
                                 $overwriteAll = true;
                             } else {
                                 echo ' Message-file `' . $entry . '` skipped.' . PHP_EOL;
                                 continue;
                             }
                         }
                     }
                     $res = $zip->extractTo($extractPath, array($entry));
                     if ($res) {
                         echo ' Message-file `' . $entry . '` successfully extracted.' . PHP_EOL;
                     }
                 }
             }
         } else {
             $this->usageError('The ZIP archive contains no files.');
         }
         $zip->close();
         if (!is_writable($msg_file)) {
             echo 'Unable to remove ZIP Archive file. Please verify the file permissions.';
         } else {
             unlink($msg_file);
         }
     } else {
         $this->usageError('Error opening the ZIP archive.');
     }
 }
date_default_timezone_set('Asia/Irkutsk');
mb_regex_encoding('utf-8');
mb_internal_encoding('utf-8');
$uploaddir = dirname(__FILE__) . '/price/';
$pricedir = dirname(__FILE__) . '/files/';
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
    if ($_FILES['file']['type'] == 'application/zip') {
        $zip = new ZipArchive();
        $res = $zip->open($uploaddir . $_FILES['file']['name']);
        if ($res === TRUE) {
            for ($i = 0; $i <= $zip->numFiles; $i++) {
                if (preg_match("/теплиц/ui", $zip->getNameIndex($i))) {
                    debug('Найден прайс теплиц.');
                    $new_name = 'price-teplizy.pdf';
                    debug('Переименование файла "' . $zip->getNameIndex($i) . '" в "' . $new_name . '"');
                    $zip->renameIndex($i, $new_name);
                    $files[] = $new_name;
                } elseif (preg_match("/спк/ui", $zip->getNameIndex($i))) {
                    debug('Найден прайс СПК.');
                    $new_name = 'price-SPK.pdf';
                    debug('Переименование файла "' . $zip->getNameIndex($i) . '" в "' . $new_name . '"');
                    $zip->renameIndex($i, $new_name);
                    $files[] = $new_name;
                } elseif (preg_match('/удск/ui', $zip->getNameIndex($i))) {
                    debug('Найден прайс уличных ДСК.');
                    $new_name = 'price-udsk.pdf';
                    debug('Переивание файла "' . $zip->getNameIndex($i) . '" в "' . $new_name . '"');
                    $zip->renameIndex($i, $new_name);
                    $files[] = $new_name;
                } elseif (preg_match('/козырьк/ui', $zip->getNameIndex($i))) {
                    debug('Найден прайс козырьки.');
 $res = $zip->open($tmp_folder . $newpmazipfilename, ZipArchive::CHECKCONS);
 // ZipArchive::CHECKCONS will enforce additional consistency checks
 if ($res === true) {
     echo "ZIP OK\n";
     $listzip = "";
     for ($i = 0; $i < $zip->numFiles; $i++) {
         $listzip = $listzip . ($zip->getNameIndex($i) . "\n");
     }
     file_put_contents($tmp_folder . $newpmazipfilename . ".filelist.log", $listzip);
     //log filelist
     unset($listzip);
     //clear mem
     //rename folder
     $i = 0;
     while ($item_name = $zip->getNameIndex($i)) {
         $zip->renameIndex($i, str_replace($newpmaname . "/", "", $item_name));
         $i++;
     }
     $zip->deleteName($newpmaname . "/");
     //delete last empty dir
     $zip->close();
     //synch updated folder structure
     //extract ZIP
     $res = $zip->open($tmp_folder . $newpmazipfilename);
     echo 'Extraction ' . ($zip->extractTo($target_folder) ? "OK\n" : "Error\n");
     //modifies archive file modification times
     $zip->close();
     //send mail
     $mail_body = "PMA auto update executed to target ver " . $version->version . " released on " . $version->date;
     //mail body
     $subject = "PMA Update executed to " . $version->version;
Example #8
0
 function _rename_zip_path($file, $original_path, $replacement_path)
 {
     $original_path = preg_replace('|^[/\\\\]+|', '', $original_path);
     $original_path = preg_replace('|([/\\\\])+$|', '', $original_path);
     $original_path .= '/';
     $replacement_path = preg_replace('|^[/\\\\]+|', '', $replacement_path);
     $replacement_path = preg_replace('|[/\\\\]+$|', '', $replacement_path);
     if (!empty($replacement_path)) {
         $replacement_path .= '/';
     }
     $zip = new ZipArchive();
     echo $file;
     $open_status = $zip->open($file);
     if (true !== $open_status) {
         //				return array( 'error' => $this->get_zip_archive_error_message( $open_status ) );
         return array('error' => 'Unable to rename path');
     }
     $status = array('removed' => 0, 'renamed' => 0);
     for ($index = 0; $index < $zip->numFiles; $index++) {
         $name = $zip->getNameIndex($index);
         if ($name === $original_path) {
             // Remove original container directory
             $zip->deleteIndex($index);
             $status['removed']++;
         } else {
             if (preg_match('/^' . preg_quote($original_path, '/') . '(.+)/', $name, $matches)) {
                 // Rename paths
                 $zip->renameIndex($index, "{$replacement_path}{$matches[1]}");
                 $status['renamed']++;
             }
         }
     }
     $zip->close();
     return $status;
 }
Example #9
0
 /**
  * Processes an array of files
  */
 protected static function getArchivedFiles($file_path, $type)
 {
     $za = new ZipArchive();
     if ($za->open($file_path) !== true) {
         throw new SwatException(sprintf('Error opening file archive “%s”', $file_path));
     }
     $dir = dirname($file_path);
     $files = array();
     for ($i = 0; $i < $za->numFiles; $i++) {
         $stat = $za->statIndex($i);
         $original_filename = self::normalizeArchiveFileFilename($stat['name']);
         // ignore hidden files
         if (preg_match('@(^\\.|/\\.)@', $original_filename) === 1) {
             continue;
         }
         // ignore directories
         if (preg_match('@/$@', $original_filename) === 1) {
             continue;
         }
         // build temp filename
         $filename = self::getTempFilename($original_filename);
         // ignore certain common extensions
         if (strpos($filename, '.') !== false) {
             $ext = end(explode('.', $filename));
             $ignore_extensions = array('db', 'exe', 'torrent');
             if (in_array($ext, $ignore_extensions)) {
                 continue;
             }
         }
         $files[$filename] = $original_filename;
         // extract the file to the queue directory
         $za->renameIndex($i, $filename);
         $za->extractTo($dir, $filename);
         // set file permissions
         chmod($dir . '/' . $filename, 0664);
         // recurse into contained archives
         $archive_path = $dir . '/' . $filename;
         $archive_type = self::getArchiveType($archive_path);
         if ($archive_type !== false) {
             $files = array_merge($files, self::getArchivedFiles($archive_path, $archive_type));
             // do not include the recursed archive in results
             unset($files[$filename]);
         }
     }
     $za->close();
     // remove the zip file
     unlink($file_path);
     return $files;
 }
 /**
  * Decode ZIP filenames.
  *
  * Zotero stores web snapshots in ZIP files containing base64 encoded
  * filenames
  *
  * @param File $file
  */
 public static function beforeSaveFile($args)
 {
     if (!$args['insert']) {
         return;
     }
     $file = $args['record'];
     // Return if the file does not have a ".zip" file extension. This is
     // needed because ZipArchive::open() sometimes opens files that are not
     // ZIP archives.
     if (!preg_match('/\\.zip$/', $file->filename)) {
         return;
     }
     $za = new ZipArchive();
     // Skip this file if an error occurs. ZipArchive::open() will return
     // true if valid, error codes otherwise.
     if (true !== $za->open($file->getPath())) {
         return;
     }
     // Base64 decode each file in the archive if needed.
     for ($i = 0; $i < $za->numFiles; $i++) {
         $stat = $za->statIndex($i);
         // Filenames that end with "%ZB64" are Base64 encoded.
         if (preg_match('/%ZB64$/', $stat['name'])) {
             // Remove "%ZB64" prior to decoding.
             $name = preg_replace('/%ZB64$/', '', $stat['name']);
             // Base64 decode the filename and rename the file.
             $name = base64_decode($name);
             $za->renameIndex($i, $name);
         }
     }
     $za->close();
 }
Example #11
0
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, 'curl/' . $vers['version']);
    curl_setopt($ch, CURLOPT_URL, $url);
    // grab URL and pass it to the browser
    $data = curl_exec($ch);
    $file = $xerte_toolkits_site->import_path . time() . ".zip";
    file_put_contents($file, $data);
    $zip = new ZipArchive();
    $data = $zip->open($file);
    $extract_files = array();
    $language_files = array();
    for ($i = 0; $i < $zip->numFiles; $i++) {
        if (strpos($zip->getNameIndex($i), "/languagesXOT/")) {
            $zip->renameIndex($i, str_replace($_POST['name'] . "-master/", "", $zip->getNameIndex($i)));
            $name = explode("/", $zip->getNameIndex($i));
            $zip->renameIndex($i, $name[2] . "/modules/" . $name[0] . "/" . $name[3]);
            array_push($language_files, $zip->getNameIndex($i));
        } else {
            $zip->renameIndex($i, str_replace($_POST['name'] . "-master/", "", $zip->getNameIndex($i)));
            array_push($extract_files, $zip->getNameIndex($i));
        }
    }
    array_shift($language_files);
    array_shift($extract_files);
    $zip->extractTo($xerte_toolkits_site->root_file_path . "modules/", $extract_files);
    $zip->extractTo($xerte_toolkits_site->root_file_path . "languages/", $language_files);
    echo "<p>" . $_POST['name'] . "  " . EXTEND_INSTALLED . " : <a onclick='module_activate(\"" . str_replace("XOT-", "", $_POST['name']) . "\")'>" . EXTEND_ACTIVATE . "</a></p>";
    echo "<p><a onclick='list_modules(\"" . str_replace("XOT-", "", $_POST['name']) . "\")'>" . EXTEND_LIST . "</a></p>";
}
 public function RawInputFile($FileName, $FileType, $Fields, $SkipLines, $FileCategory, $MergeFieldNumber, $UPCFieldName, $OuterJoin, $TrimData = FALSE, $FileToExtract = NULL, $KeepOldFile = FALSE)
 {
     // Error Checking of parameters
     if (!is_readable($FileName)) {
         trigger_error("Filename {$FileName} does not exist or cannot be read", E_USER_ERROR);
     }
     if (in_array($FileType, $this->ValidFileTypes) === FALSE) {
         trigger_error("Invalid file type passed, {$FileType}", E_USER_ERROR);
     }
     if (!is_array($Fields)) {
         trigger_error("The fields parameter must be an array, {$Fields} passed", E_USER_ERROR);
     }
     if (!is_numeric($SkipLines)) {
         trigger_error("SkipLines must be numeric, {$SkipFirst} passed", E_USER_ERROR);
     }
     if (strlen($FileCategory) == 0) {
         trigger_error("FileType parameter is required", E_USER_ERROR);
     }
     // Erase the supplier errors table
     $sqlStmt = "delete from Supplier_Errors where Supplier_Party_ID = '{$this->PartyID}'";
     $this->FeedsDbObj->DeleteRow($sqlStmt);
     echo "Input file for {$FileCategory} is {$FileName}\n";
     // Store the file specifications
     if (is_null($this->UPCFieldName)) {
         $this->UPCFieldName = $UPCFieldName;
     }
     if (isset($this->FileCategories[$FileCategory])) {
         $this->FileCategories[$FileCategory]++;
     } else {
         $this->FileCategories[$FileCategory] = 1;
     }
     $newFile = tempnam(Config::getTmpDir(), "{$this->PartyID}-");
     if (asort($Fields) === FALSE) {
         trigger_error("Unable to sort fields array", E_USER_ERROR);
     }
     if ($this->IsMiniMSRP === FALSE && $this->GenericFeed === FALSE && $this->MiniFeed === FALSE && $KeepOldFile === FALSE) {
         $this->FilesToPurge[$FileName] = NULL;
     }
     $this->FilesToPurge[$newFile] = NULL;
     if (substr($FileType, 0, 3) == "ZIP") {
         $zip = new ZipArchive();
         if ($zip->open($FileName, ZipArchive::CREATE) !== TRUE) {
             trigger_error("Could not open the Zip File Archive {$FileName}", E_USER_ERROR);
         }
         // Get filename only, ignore rest of path
         $newFileName = pathinfo($newFile, PATHINFO_BASENAME);
         if (is_numeric($FileToExtract)) {
             $zip->renameIndex($FileToExtract, $newFileName);
         } else {
             $zip->renameName($FileToExtract, $newFileName);
         }
         $UnZipDir = Config::getTmpDir() . "/";
         if ($zip->extractTo($UnZipDir, $newFileName) === FALSE) {
             trigger_error("Could not unzip the Zip File Archive {$FileName} file {$newFileName}", E_USER_ERROR);
         }
         $zip->close();
         $FileName = $newFile;
         $newFile = tempnam(Config::getTmpDir(), "{$this->PartyID}-");
         $this->FilesToPurge[$newFile] = NULL;
     }
     // Based on the file type, we will convert to CSV and remove headers.
     switch ($FileType) {
         case "XLS":
             $newFile = $this->HandleXLSFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "ZIPCSV":
         case "CSV":
             $newFile = $this->HandleCSVFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "DBF":
         case "ZIPDBF":
             $newFile = $this->HandleDBFFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
             break;
         case "TAB":
         case "ZIPTAB":
             $newFile = $this->HandleTabFile($FileName, $newFile, $Fields, $SkipLines, $TrimData, FALSE);
             break;
         case "TABQ":
         case "ZIPTABQ":
             $newFile = $this->HandleTabFile($FileName, $newFile, $Fields, $SkipLines, $TrimData, TRUE);
             break;
         case "BAR":
         case "ZIPBAR":
             $newFile = $this->HandleDelimitedFile($FileName, $newFile, $Fields, $SkipLines, "|", $TrimData);
             break;
         case "TIL":
         case "ZIPTIL":
             $newFile = $this->HandleDelimitedFile($FileName, $newFile, $Fields, $SkipLines, "~", $TrimData);
             break;
         case "FIXED":
         case "ZIPFIXED":
             $newFile = $this->HandleFixedFile($FileName, $newFile, $Fields, $SkipLines, $TrimData);
     }
     // Re-sequence the columns
     // For fixed file format, we have to redo the fields array since it is not a list of fields. It's a list of starting positions:length
     $i = 1;
     foreach ($Fields as $Key => $Value) {
         if ($FileType == "FIXED" || $FileType == "ZIPFIXED") {
             if ($i == $MergeFieldNumber) {
                 $MergeFieldNumber = $i;
             }
         } else {
             if ($Value == $MergeFieldNumber) {
                 $MergeFieldNumber = $i;
             }
         }
         $Fields[$Key] = $i;
         $i++;
     }
     echo "New file for {$FileCategory} is {$newFile}\n";
     $SpecsArray = array();
     $SpecsArray["FileName"] = $newFile;
     $SpecsArray["Fields"] = $Fields;
     $SpecsArray["FileCategory"] = $FileCategory;
     $SpecsArray["MergeFieldNumber"] = $MergeFieldNumber;
     $SpecsArray["OuterJoin"] = $OuterJoin;
     $this->FileSpecs[] = $SpecsArray;
 }