/** * Repacks exported document from Google.Drive, which has wrong order files in archive to show preview * in Google.Viewer. In Google.Viewer document should have file '[Content_Types].xml' on first position in archive. * @param FileData $fileData * @return FileData * @throws IO\FileNotFoundException * @throws IO\InvalidPathException * @internal */ public function repackDocument(FileData $fileData) { if (!extension_loaded('zip')) { return null; } if (!TypeFile::isDocument($fileData->getName())) { return null; } $file = new IO\File($fileData->getSrc()); if (!$file->isExists() || $file->getSize() > 15 * 1024 * 1024) { return null; } unset($file); $ds = DIRECTORY_SEPARATOR; $targetDir = \CTempFile::getDirectoryName(2, 'disk_repack' . $ds . md5(uniqid('di', true))); checkDirPath($targetDir); $targetDir = IO\Path::normalize($targetDir) . $ds; $zipOrigin = new \ZipArchive(); if (!$zipOrigin->open($fileData->getSrc())) { return null; } if ($zipOrigin->getNameIndex(0) === '[Content_Types].xml') { $zipOrigin->close(); return null; } if (!$zipOrigin->extractTo($targetDir)) { $zipOrigin->close(); return null; } $zipOrigin->close(); unset($zipOrigin); if (is_dir($targetDir) !== true) { return null; } $newName = md5(uniqid('di', true)); $newFilepath = $targetDir . '..' . $ds . $newName; $repackedZip = new \ZipArchive(); if (!$repackedZip->open($newFilepath, \ZipArchive::CREATE)) { return null; } $source = realpath($targetDir); $repackedZip->addFile($source . $ds . '[Content_Types].xml', '[Content_Types].xml'); $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { if ($file->getBasename() === '[Content_Types].xml') { continue; } $file = str_replace('\\', '/', $file); $file = realpath($file); if (is_dir($file) === true) { $repackedZip->addEmptyDir(str_replace('\\', '/', str_replace($source . $ds, '', $file . $ds))); } elseif (is_file($file) === true) { $repackedZip->addFile($file, str_replace('\\', '/', str_replace($source . $ds, '', $file))); } } $repackedZip->close(); $newFileData = new FileData(); $newFileData->setSrc($newFilepath); return $newFileData; }