function unpack_player_archive($player_package)
{
    if (!class_exists("ZipArchive")) {
        return zip_fallback($player_package);
    }
    $zip = new ZipArchive();
    if ($zip->open($player_package)) {
        $contents = "";
        $dir = $zip->getNameIndex(0);
        $fp = $zip->getStream($dir . "player.swf");
        if (!$fp) {
            return READ_ERROR;
        }
        while (!feof($fp)) {
            $contents .= fread($fp, 2);
        }
        fclose($fp);
        $result = @file_put_contents(LongTailFramework::getPrimaryPlayerPath(), $contents);
        if (!$result) {
            return WRITE_ERROR;
        }
        chmod(LongTailFramework::getPrimaryPlayerPath(), 0777);
        $contents = "";
        $fp = $zip->getStream($dir . "yt.swf");
        if (!$fp) {
            return READ_ERROR;
        }
        while (!feof($fp)) {
            $contents .= fread($fp, 2);
        }
        fclose($fp);
        $result = @file_put_contents(str_replace("player.swf", "yt.swf", LongTailFramework::getPrimaryPlayerPath()), $contents);
        if (!$result) {
            return WRITE_ERROR;
        }
        chmod(str_replace("player.swf", "yt.swf", LongTailFramework::getPrimaryPlayerPath()), 0777);
        $fp = $zip->getStream($dir . "jwplayer.js");
        if ($fp) {
            $contents = "";
            while (!feof($fp)) {
                $contents .= fread($fp, 2);
            }
            fclose($fp);
            $result = @file_put_contents(LongTailFramework::getEmbedderPath(), $contents);
            if (!$result) {
                return WRITE_ERROR;
            }
            chmod(LongTailFramework::getEmbedderPath(), 0777);
        }
        $zip->close();
    }
    unlink($player_package);
    return SUCCESS;
}
Example #2
0
 protected function doCreate()
 {
     $result = true;
     $counter = 0;
     foreach ($this->metaData['createdFiles'] as $createdFile) {
         $fullName = "{$this->basePath}/{$createdFile}";
         if ($this->matchesTargetHash($createdFile)) {
             $counter++;
         } elseif (!is_dir(dirname($fullName)) && !mkdir(dirname($fullName), 0777, true)) {
             $this->messages[] = "Failed to create directories for {$createdFile}";
             $result = false;
         } elseif (file_exists($fullName)) {
             $this->messages[] = "File to be created: {$createdFile} already exists.";
             $result = false;
         } elseif (false === ($handle = @fopen($fullName, 'x'))) {
             $this->messages[] = "No write permission: {$createdFile}";
             $result = false;
         } else {
             $this->archive->getStream($createdFile);
             stream_copy_to_stream($this->archive->getStream($createdFile), $handle);
             fclose($handle);
             if (!$this->matchesTargetHash($createdFile)) {
                 $this->messages[] = "{$createdFile} was not successfully created.";
             } else {
                 $counter++;
             }
         }
     }
     $this->messages[] = "{$counter} files created.";
     return $result;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->georgiaVoterService->setConnectionName($input->getArgument('dbname'));
     if ($input->getOption('config')) {
         $this->georgiaVoterService->setConfigFolder($input->getOption('config'));
     }
     // setConfigFolder
     $zip = new \ZipArchive();
     $res = $zip->open($input->getArgument('zipFile'));
     if ($res === TRUE) {
         $this->georgiaVoterService->initializeGeorgiaVoterTable();
         $compressedfiles = [];
         for ($i = 0; $i < $zip->numFiles; $i++) {
             $compressedfiles[] = $zip->statIndex($i);
         }
         usort($compressedfiles, function ($a, $b) {
             if ($a['size'] == $b['size']) {
                 return 0;
             }
             return $a['size'] < $b['size'] ? -1 : 1;
         });
         $maxentry = array_pop($compressedfiles);
         $exportDate = \date("Y-m-d", $maxentry['mtime']);
         $fp = $zip->getStream($maxentry['name']);
         while (($buffer = fgets($fp, 4096)) !== false) {
             $output->writeln($buffer);
         }
     } else {
         $output->writeln("Zip File Problem");
     }
 }
 function import($inputFile, $targetDirectory = null)
 {
     if (!$targetDirectory) {
         $targetDirectory = '';
     }
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     $type = finfo_file($finfo, $inputFile);
     finfo_close($finfo);
     switch ($type) {
         case 'application/zip':
             $zip = new ZipArchive();
             $zip->open($inputFile);
             $i = 0;
             while ($i < $zip->numFiles) {
                 $file = $zip->statIndex($i);
                 $contents = '';
                 $fp = $zip->getStream($file['name']);
                 while (!feof($fp)) {
                     $contents .= fread($fp, 2);
                 }
                 SiteCollection::createFile($targetDirectory . $file['name'], $contents);
                 fclose($fp);
                 $i++;
             }
             break;
         default:
             throw new Exception('MIME type ' . $type . ' unsupported.');
     }
 }
Example #5
0
function processPluginsFolder($folder, $requiredMpsVersion, $pluginsVersion)
{
    $files = scandir($folder);
    foreach ($files as $zipfile) {
        if (pathinfo($zipfile, PATHINFO_EXTENSION) == 'zip') {
            $za = new ZipArchive();
            $za->open($folder . $zipfile);
            for ($i = 0; $i < $za->numFiles; $i++) {
                $stat = $za->statIndex($i);
                $pluginXmlFile = $stat['name'];
                if (endsWith($pluginXmlFile, "META-INF/plugin.xml")) {
                    $stream = $za->getStream($pluginXmlFile);
                    $content = stream_get_contents($stream);
                    $xml = simplexml_load_string($content);
                    if (fixPluginXml($xml, $requiredMpsVersion, $pluginsVersion)) {
                        $za->deleteName($pluginXmlFile);
                        $za->addFromString($pluginXmlFile, $xml->asXML());
                    }
                    printPluginXml($xml, $zipfile, $requiredMpsVersion, $pluginsVersion);
                    break;
                }
            }
        }
    }
}
Example #6
0
 /**
  * Get a file handler to the entry defined by its name.
  *
  * @param string $name The name of the entry to use.
  *
  * @return resource|bool File pointer (resource) on success or false on failure.
  * @throws Exception
  */
 public function getFileHandler($name)
 {
     if (!$this->open) {
         throw new \Exception('No archive has been opened');
     }
     return $this->zip->getStream($name);
 }
Example #7
0
 /** Returns an array of strings (for error messages) and image objects (for successful). */
 public static function createFromArchive($filename, $objAlbum)
 {
     if (!class_exists('ZipArchive')) {
         return "image_nozip";
     }
     $arrRet = array();
     $zipArchive = new ZipArchive();
     $zipArchive->open($filename);
     for ($i = 0; $i < $zipArchive->numFiles; $i++) {
         /* We stat the file, to get its name. */
         $stat = $zipArchive->statIndex($i);
         $strInName = $stat['name'];
         /* Open the temp output file. This is vulnerable to a race condition. TODO. */
         $filename = tempnam("/tmp", "OSPAP2");
         $out = fopen($filename, 'w');
         /* Get the file stream from the archive. */
         $in = $zipArchive->getStream($stat['name']);
         /* Read the file from the zip. It takes several iterations to get to the end, so we loop. */
         while (!feof($in)) {
             fputs($out, fgets($in));
         }
         /* Close the input and output files. */
         fclose($out);
         fclose($in);
         /* Determine the mimetype from the filename. None of php's built-in functions seem to work.. */
         if (preg_match("/\\.png\$/", $stat['name'])) {
             $mimetype = "image/png";
         } elseif (preg_match("/\\.gif\$/", $stat['name'])) {
             $mimetype = "image/gif";
         } elseif (preg_match("/\\.jpg\$/", $stat['name'])) {
             $mimetype = "image/jpeg";
         } elseif (preg_match("/\\.jpeg\$/", $stat['name'])) {
             $mimetype = "image/jpeg";
         } else {
             $mimetype = "unknown";
         }
         /* Create the new file. */
         $new = clsPicture::createFromFile($filename, $mimetype, $objAlbum);
         /* Delete the file. */
         unlink($filename);
         if (is_string($new)) {
             $strError = $new;
             $new = new clsDB('image');
             $new->set('error', $strError);
             $new->set('name', $stat['name']);
         } else {
             $new->set('original_name', $stat['name']);
             $new->set('original_mime', $mimetype);
             $new->set('original_size', $stat['size']);
         }
         /* Add it to the array (note that it can be a string (for an error) or an image object. */
         $arrRet[] = $new;
     }
     if (sizeof($arrRet) == 0) {
         return 'image_nofiles';
     }
     return $arrRet;
 }
Example #8
0
function getFileContentFromArchive(ZipArchive $archive, $filename)
{
    $fp = $archive->getStream($filename);
    $contents = '';
    while (!feof($fp)) {
        $contents .= fread($fp, 4096);
    }
    fclose($fp);
    return $contents;
}
Example #9
0
function getZipContentOfFile($zipFilePath, $name)
{
    $zip = new ZipArchive();
    $zip->open($zipFilePath);
    $fp = $zip->getStream($name);
    $contents = '';
    while (!feof($fp)) {
        $contents .= fread($fp, 1024);
    }
    fclose($fp);
    return $contents;
}
Example #10
0
function mergecitem($item, $t1, $c, $sc)
{
    $czip = 'D:\\Projects\\zhunei-wechat\\web\\bible\\b\\' . getHexStr($t1) . '\\' . getHexStr($c) . '.zip';
    echo $czip . '<br/>';
    $curitem = $item;
    $lastsitem = null;
    $zip = new ZipArchive();
    if ($zip->open($czip)) {
        $i = 0;
        while (true) {
            $fname = dechex($i);
            if (strlen($fname) < 2) {
                $fname = '0' . $fname;
            }
            $contents = '';
            $fp = $zip->getStream($fname);
            if (!$fp) {
                break;
            }
            while (!feof($fp)) {
                $contents .= fread($fp, 2);
            }
            fclose($fp);
            $sitem = null;
            while (true) {
                $curitem = $curitem->nextSibling->nextSibling;
                $class = $curitem->getAttribute('class');
                if ($class == 'c') {
                    break;
                } else {
                    if ($class == 's') {
                        $sitem = $curitem;
                        break;
                    }
                }
            }
            if ($sitem) {
                $sitem->removeChild($sitem->firstChild);
                $sitem->appendChild(new DOMText(zhconversion_hans($contents)));
                $sitem->setAttribute('value', $i + 1);
                $lastsitem = $sitem;
            } else {
                $sitem = $lastsitem->parentNode->insertBefore(new DOMElement('p'), $lastsitem->nextSibling->nextSibling);
                $sitem->setAttribute('class', 's');
                $sitem->setAttribute('value', $i + 1);
                $sitem->appendChild(new DOMText(zhconversion_hans($contents)));
            }
            //			echo(($i+1).'&nbsp;&nbsp;'.zhconversion_hans($contents).'&nbsp;'.$sitem->textContent.'<br/>');
            $i++;
        }
    }
    //	die();
}
Example #11
0
 /**
  * @inheritDoc
  */
 public function getContent($path)
 {
     $content = '';
     $fp = $this->zip->getStream($path);
     if (!$fp) {
         throw new FileException(sprintf('File "%s" not found in archive.', $path));
     }
     while (!feof($fp)) {
         $content .= fread($fp, 2);
     }
     fclose($fp);
     return $content;
 }
Example #12
0
 public function __construct($zipFilename)
 {
     $zip = new \ZipArchive();
     $zip->open($zipFilename);
     if ($zip->numFiles != 1) {
         throw new \Exception("Unknown source file structure");
     }
     $filename = $zip->getNameIndex(0);
     $this->handle = $zip->getStream($filename);
     if (!$this->handle) {
         throw new \Exception("Could not read source");
     }
 }
Example #13
0
 /**
  * @param  string                                     $pathToFile
  * @return null|string
  * @throws \Thelia\Exception\FileNotFoundException
  * @throws \Thelia\Exception\FileNotReadableException
  * @throws \ErrorException
  *
  * This method returns a file content
  */
 public function getFileContent($pathToFile)
 {
     $pathToFile = $this->formatFilePath($pathToFile);
     if (!$this->hasFile($pathToFile)) {
         $this->throwFileNotFound($pathToFile);
     }
     $stream = $this->zip->getStream($pathToFile);
     $content = "";
     while (!feof($stream)) {
         $content .= fread($stream, 2);
     }
     fclose($stream);
     return $content;
 }
Example #14
0
 /**
  * @param string $path
  * @param string $targetDir
  * @param string $root path without trailing slash
  * @return boolean
  */
 static function extractByRoot($path, $targetDir, $root)
 {
     //get items paths from within root
     $namesList = srokap_zip::getArchiveNameIndex($path);
     if ($namesList === false) {
         throw new IOException("Error while reading archive contents: {$path}");
     }
     foreach ($namesList as $key => $item) {
         //keep only items within root path
         if (strpos($item, $root) !== 0) {
             unset($namesList[$key]);
         }
     }
     if (empty($namesList)) {
         throw new IOException("Invalid archive root path privided: {$root}");
     }
     $targetDir .= '/';
     if (!srokap_files::createDir($targetDir)) {
         throw new IOException("Unable to create target dir: {$targetDir}");
     }
     $result = false;
     $zip = new ZipArchive();
     if ($zip->open($path)) {
         foreach ($namesList as $key => $item) {
             $sufix = substr($item, strlen($root) + 1);
             if ($sufix === false) {
                 continue;
             }
             $path = $targetDir . $sufix;
             $dirPath = dirname($path);
             if (!empty($dirPath) && !srokap_files::createDir($dirPath)) {
                 throw new IOException("Unable to create dir: " . dirname($path));
             }
             if ($item[strlen($item) - 1] == '/') {
                 //not a file
                 continue;
             }
             $content = stream_get_contents($zip->getStream($item));
             if ($content === false) {
                 throw new IOException("Error reading from archive path: {$item}");
             }
             if (file_put_contents($path, $content) === false) {
                 throw new IOException("Error extracting file from {$item} to {$path}");
             }
         }
         $result = true;
     }
     $zip->close();
     return $result;
 }
function ShowAllImageInZip($path, $filename)
{
    ignore_user_abort(true);
    set_time_limit(0);
    // disable the time limit for this script
    $dl_file = $filename;
    $fullPath = $path . $dl_file;
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "zip":
            break;
        default:
            exit;
    }
    //echo "this is zip ok <br/>";
    $zip = new ZipArchive();
    if ($zip->open($fullPath) === true) {
        for ($i = 0; $i < $zip->numFiles; $i++) {
            //$zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));
            // here you can run a custom function for the particular extracted file
            $cont_name = $zip->getNameIndex($i);
            $cont_path_parts = pathinfo($cont_name);
            $cont_ext = strtolower($cont_path_parts["extension"]);
            if ($cont_ext == "jpg") {
                $contents = '';
                //echo $cont_name."<br/>";
                $fp = $zip->getStream($cont_name);
                if (!$fp) {
                    exit("failed\n");
                }
                //echo "get stream...<br/>";
                while (!feof($fp)) {
                    $contents .= fread($fp, 2);
                }
                fclose($fp);
                $b64 = base64_encode($contents);
                list($w, $h) = getimagesizefromstring($contents);
                //echo $w." ".$h."<br/>";
                list($width, $height) = fixWidth(600, $w, $h);
                //echo $width." ".$height."<br/>";
                echo "<img src='data:image/jpeg;base64,{$b64}' width='" . $width . "' height='" . $height . "'><br/>";
            }
        }
        $zip->close();
    } else {
        echo "fail open file " . $filename . "<br/>";
    }
}
 function testRunPass()
 {
     // modify the request so we have a fake one
     $wb = new WidgetBuilder('helpers/widget_testcase_001');
     $filename = $wb->getFilename();
     $z = new ZipArchive();
     $z->open($filename);
     $fp = $z->getStream('widget.txt');
     $this->assertTrue($fp);
     while (!feof($fp)) {
         $contents .= fread($fp, 2);
     }
     fclose($fp);
     $this->assertEqual($contents, 'pass');
 }
 protected function openTemplate()
 {
     $zip = new ZipArchive();
     $res = $zip->open($this->fileTemplate, ZipArchive::CREATE);
     $fp = $zip->getStream("content.xml");
     if (!$fp) {
         exit("failed open " . $this->fileTemplate . " ");
     }
     while (!feof($fp)) {
         $contents .= fread($fp, 2);
     }
     fclose($fp);
     $zip->close();
     $this->dom = new DOMDocument();
     $this->dom->loadXML($contents);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->voterService->setConnectionName($input->getArgument('dbname'));
     if ($input->getOption('config')) {
         $this->voterService->setConfigFolder($input->getOption('config'));
     } else {
         $this->voterService->setConfigFolder('/usr/local/etc/votertools');
     }
     $this->voterService->setAttributes([\PDO::MYSQL_ATTR_LOCAL_INFILE => true]);
     $filePath = $input->getArgument('fileName');
     if ($input->getOption('tmp')) {
         $tempfile = \tempnam($input->getOption('tmp'), '');
     } else {
         $tempfile = \tempnam(\sys_get_temp_dir(), '');
     }
     $output->writeln("Creating temp file to store unzipped voter file: " . $tempfile);
     $op = \fopen($tempfile, 'a');
     $zip = new \ZipArchive();
     $info = [];
     $voterDate = '';
     if ($zip->open($filePath) === TRUE) {
         for ($i = 0; $i < $zip->numFiles; $i++) {
             if (empty($voterDate)) {
                 $info = $zip->statIndex($i);
                 $voterDate = date("Ymd", $info["mtime"]);
                 $output->writeln("Import Date: " . date("Ymd", $info["mtime"]));
             }
             $output->writeln("Reading Voter File: " . $zip->getNameIndex($i));
             $fp = $zip->getStream($zip->getNameIndex($i));
             while (!feof($fp)) {
                 \fwrite($op, fread($fp, 2));
             }
         }
         $output->writeln("Extraced to " . $tempfile);
         $zip->close();
         fclose($op);
         chmod($tempfile, 0644);
         $output->writeln("Importing " . $tempfile . " for " . $voterDate);
         $this->voterService->loadRawData($voterDate, $tempfile, "florida/VoterLoadImport");
         $output->writeln("Cleaned up " . $tempfile);
         $output->writeln("Starting append of Party Affiliation to PartyHistories table ");
         $this->voterService->appendFloridaPartyHistories();
         $output->writeln("Completed append of Party Affiliation to PartyHistories table ");
     }
 }
 /**
  * read an spreadsheet file.
  *
  * $sheets = read('~/example.ods');
  * $sheet = 0;
  * $row = 0;
  * $column = 0;
  * echo $sheets[$sheet][$row][$column];
  *
  * @param  $odsFilePath  File path of Open Document Sheet file.
  * @param  [$returnType]  how to store read data?
  *      READ_ARRAY  - Default. Return an numeric index array.
  *      READ_NUM    - Same as READ_ARRAY
  *      READ_ASSOC  - Return an associative array.
  *                    It will use values of first row to be field name.
  *                    Though the count of rows will less one than numeric index array.
  *      READ_HASH   - Same as READ_ASSOC
  *      READ_XMLSTRING - Return an XML String.
  *
  * @return  FALSE or array or string.
  */
 public function &read($odsFilePath, $returnType = self::READ_ARRAY)
 {
     $ReturnFalse = FALSE;
     if (!is_readable($odsFilePath)) {
         return $ReturnFalse;
     }
     if (strncmp(PHP_VERSION, '4', 1)) {
         $zip = new ZipArchive();
         // PHP5 or later.
         if ($zip->open($odsFilePath) !== TRUE) {
             return $ReturnFalse;
         }
         $fp = $zip->getStream('content.xml');
         //fpassthru($fp);
         $xmlString = '';
         while ($s = fgets($fp)) {
             $xmlString .= $s;
         }
         fclose($fp);
         $zip->close();
     } else {
         $zip = zip_open($odsFilePath);
         // PHP4
         if (!is_resource($zip)) {
             return $ReturnFalse;
         }
         while ($entry = zip_read($zip)) {
             if (zip_entry_name($entry) == 'content.xml') {
                 break;
             }
         }
         $xmlString = '';
         while ($s = zip_entry_read($entry)) {
             $xmlString .= $s;
         }
         zip_entry_close($entry);
         zip_close($zip);
     }
     $this->_odsXml->loadXML($xmlString);
     $xmlString = $this->_processor->transformToXML($this->_odsXml);
     if ($returnType == self::READ_XMLSTRING or $returnType === 'string') {
         return $xmlString;
     }
     return $this->_toArray($xmlString, $returnType);
 }
function serveFileFromZIP($baseDir, $zipName, $fileName)
{
    $zip = new ZipArchive();
    if ($zip->open($baseDir . $zipName) !== TRUE) {
        handleError("Could not open ZIP file '{$zipName}'");
    }
    $contents = $zip->getStream($fileName);
    if ($contents === FALSE) {
        $zip->close();
        handleError("Could not find file '{$fileName}' in ZIP file '{$zipName}'");
    }
    $fileSize = $zip->statName($fileName)['size'];
    header('Content-Length: ' . $fileSize);
    header('Content-Type: text/plain');
    fpassthru($contents);
    fclose($contents);
    $zip->close();
    exit;
}
 /**
  * @param string $url
  * @return resource File handle
  */
 private function downloadAndOpen($url)
 {
     $zip_path = Yii::app()->runtimePath . '/hscic_data.zip';
     $f = fopen($zip_path, 'x');
     $c = curl_init($url);
     curl_setopt($c, CURLOPT_FILE, $f);
     curl_exec($c);
     curl_close($c);
     fclose($f);
     $z = new ZipArchive();
     if (($res = $z->open($zip_path)) !== true) {
         throw new Exception("Failed to open zip file at '{$zip_path}': " . $res);
     }
     $filename = str_replace('.zip', '.csv', basename($url));
     if (!($stream = $z->getStream($filename))) {
         throw new Exception("Failed to extract '{$filename}' from zip file at '{$zip_path}'");
     }
     unlink($zip_path);
     return $stream;
 }
function extractSubFolder($zipFile, $target = null, $subFolder = null)
{
    if (is_null($target)) {
        $target = dirname(__FILE__);
    }
    $zip = new ZipArchive();
    $res = $zip->open($zipFile);
    if ($res === TRUE) {
        if (is_null($subFolder)) {
            $zip->extractTo($target);
        } else {
            for ($i = 0, $c = $zip->numFiles; $i < $c; $i++) {
                $entry = $zip->getNameIndex($i);
                //Use strpos() to check if the entry name contains the directory we want to extract
                if ($entry != $subFolder . '/' && strpos($entry, $subFolder . '/') === 0) {
                    $stripped = substr($entry, 9);
                    if (substr($entry, -1) == '/') {
                        // Subdirectory
                        $subdir = $target . '/' . substr($stripped, 0, -1);
                        if (!is_dir($subdir)) {
                            mkdir($subdir);
                        }
                    } else {
                        $stream = $zip->getStream($entry);
                        $write = fopen($target . '/' . $stripped, 'w');
                        while ($data = fread($stream, 1024)) {
                            fwrite($write, $data);
                        }
                        fclose($write);
                        fclose($stream);
                    }
                }
            }
        }
        $zip->close();
        return true;
    }
    die('Unable to open ' . $zipFile);
    return false;
}
 private function retrieve()
 {
     $client = new Client();
     $response = $client->get($this->vendor->getUrl());
     $body = $response->getBody();
     // if zip, extract it and retrieve contents
     if ('application/zip' == $response->getHeader('Content-Type')) {
         $tmpFile = tmpfile();
         fwrite($tmpFile, $body->getContents());
         $contents = '';
         $z = new \ZipArchive();
         if ($z->open(stream_get_meta_data($tmpFile)['uri'])) {
             $fileToOpen = null;
             for ($i = 0; $i < $z->numFiles; $i++) {
                 if ($filename = $z->getNameIndex($i)) {
                     if (preg_match('/(\\.xml$)/', $filename)) {
                         $fileToOpen = $filename;
                         break;
                     }
                 }
             }
             if ($fileToOpen) {
                 $fp = $z->getStream($fileToOpen);
                 if ($fp) {
                     while (!feof($fp)) {
                         $contents .= fread($fp, 2);
                     }
                 }
                 fclose($fp);
             }
         }
         fclose($tmpFile);
         if (!$contents) {
             return false;
         }
     } else {
         $contents = $body->getContents();
     }
     return $contents;
 }
Example #24
0
function openZipNew($icvInfo)
{
    global $context;
    echo 'Retrieving zip from ICEcoder site...<br>';
    $source = 'ICEcoder v' . $icvInfo;
    $target = '../';
    $remoteFile = 'https://icecoder.net/ICEcoder-v' . str_replace(" beta", "-beta", $icvInfo) . '.zip';
    $file = "../tmp/new-version.zip";
    if (ini_get('allow_url_fopen')) {
        $fileData = @file_get_contents($remoteFile, false, $context);
        if (!$fileData) {
            $fileData = file_get_contents(str_replace("https:", "http:", $remoteFile), false, $context);
        }
    } elseif (function_exists('curl_init')) {
        $client = curl_init($remoteFile);
        curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
        //fixed this line
        $fileData = curl_exec($client);
    } else {
        die('Sorry, couldn\'t get latest version zip file.');
    }
    echo 'Storing zip file...<br>';
    file_put_contents($file, $fileData);
    $zip = new ZipArchive();
    $zip->open($file);
    echo 'Copying over zip dirs & files...<br>';
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $name = $zip->getNameIndex($i);
        // Skip files not in $source
        if (strpos($name, "{$source}/") !== 0) {
            continue;
        }
        // Determine output filename (removing the $source prefix and trimming traiing slashes)
        $file = $target . substr($name, strlen($source) + 1);
        // Create the directories if necessary
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        // Read from Zip and write to disk
        $fpr = $zip->getStream($name);
        if (!is_dir($file)) {
            $fpw = fopen($file, 'w');
            while ($data = fread($fpr, 1024)) {
                fwrite($fpw, $data);
            }
            fclose($fpw);
        }
        fclose($fpr);
    }
    echo 'Finished copying over zip dirs & files...<br>';
    copyOverSettings($icvInfo);
}
Example #25
0
 /**
  * Import locations
  * @param mix $type
  * @return null
  */
 public function GetLocationsAll($type = false)
 {
     if (!$this->WS()) {
         return null;
     }
     try {
         $params = array('sid' => $this->_sid);
         $result = $this->WS()->getSC()->__soapCall("GetLocationsAll", array($params));
         $buf = $result->GetLocationsAllResult->ByteZip;
         $f = fopen(self::TMP_LOCATIONSALL_ZIP_FILE, "w");
         fwrite($f, $buf);
         fclose($f);
         //unzip XML file with lists
         $zip = new ZipArchive();
         if ($zip->open(self::TMP_LOCATIONSALL_ZIP_FILE)) {
             $fp = $zip->getStream('locationsall.xml');
             if (!$fp) {
                 exit("failed reading xml file (" . getcwd() . ")\n");
             }
             $contents = '';
             while (!feof($fp)) {
                 $contents .= fread($fp, 2);
             }
             fclose($fp);
             $zip->close();
             file_put_contents(self::TMP_XML_LOCATIONSALL_FILE, $contents);
             if (file_exists(self::TMP_LOCATIONSALL_ZIP_FILE)) {
                 unlink(self::TMP_LOCATIONSALL_ZIP_FILE);
             }
             $db = DataBase::GetDbInstance();
             $xml = simplexml_load_file(self::TMP_XML_LOCATIONSALL_FILE);
             $listsNode = null;
             //read main nodes
             if ($type === false || $type == 1) {
                 $query = "DELETE FROM powiaty";
                 $db->ExecuteQuery($query);
                 foreach ($xml->Powiaty->children() as $child) {
                     $query = "INSERT INTO powiaty VALUES(?, ?, ?)";
                     $params = array((int) $child['Id'], $child['Nazwa'], (int) $child['WojewodztwoId']);
                     $r = $db->ExecuteQueryWithParams($query, $params);
                 }
             }
             if ($type === false || $type == 2) {
                 $query = "DELETE FROM lokalizacje";
                 $db->ExecuteQuery($query);
                 foreach ($xml->Lokalizacje->children() as $child) {
                     $query = "INSERT INTO lokalizacje VALUES(?, ?, ?, ?, ?)";
                     $params = array((int) $child['Id'], $child['Nazwa'], (int) $child['PowiatId'], (int) $child['WojewodztwoId'], $child['Gmina'] == 'True' ? 1 : 0);
                     $r = $db->ExecuteQueryWithParams($query, $params);
                 }
             }
             if ($type === false || $type == 3) {
                 $query = "DELETE FROM dzielnice";
                 $db->ExecuteQuery($query);
                 foreach ($xml->Dzielnice->children() as $child) {
                     $query = "INSERT INTO dzielnice VALUES(?, ?, ?)";
                     $params = array((int) $child['Id'], $child['Nazwa'], (int) $child['LokalizacjaId']);
                     $r = $db->ExecuteQueryWithParams($query, $params);
                 }
             }
             if ($type === false || $type == 4) {
                 $query = "DELETE FROM rejony";
                 $db->ExecuteQuery($query);
                 foreach ($xml->Regiony->children() as $child) {
                     $query = "INSERT INTO rejony VALUES(?, ?, ?)";
                     $params = array((int) $child['Id'], $child['Nazwa'], (int) $child['DzielnicaId']);
                     $r = $db->ExecuteQueryWithParams($query, $params);
                 }
             }
             if (file_exists(self::TMP_XML_LOCATIONSALL_FILE)) {
                 unlink(self::TMP_XML_LOCATIONSALL_FILE);
             }
         }
     } catch (Exception $ex) {
         Errors::LogError("WebService:GetLists", $ex->getMessage());
     }
 }
Example #26
0
 file_put_contents($zipFile, $fileData);
 // Now unpack the zip
 $zip = new ZipArchive();
 $zip->open($zipFile);
 // Create all files & dirs, in 1kb chunks
 for ($i = 0; $i < $zip->numFiles; $i++) {
     $name = $zip->getNameIndex($i);
     // Determine output filename
     $file = $target . $name;
     // Create the directories if necessary
     $dir = dirname($file);
     if (!is_dir($dir)) {
         mkdir($dir, 0777, true);
     }
     // Read from zip and write to disk
     $fpr = $zip->getStream($name);
     if (!is_dir($file)) {
         $fpw = fopen($file, 'w');
         while ($data = fread($fpr, 1024)) {
             fwrite($fpw, $data);
         }
         fclose($fpw);
     }
     fclose($fpr);
 }
 $zip->close();
 // Remove the tmp zip file
 unlink($zipFile);
 // Start creating a new chunk for the plugins settings
 $settingsNew = '"plugins"		=> array(';
 // Set all the old plugins
 function do_icons_archive($zip)
 {
     /*
     	Not needed actually. WP already sets the memory limit to 256
     	\wp-admin\admin.php
     	\wp-includes\default-constants.php
     */
     // @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', '256M' ) );
     $return = array();
     $zipper = new ZipArchive();
     $extensions = array('eot', 'svg', 'ttf', 'woff', 'json');
     $tempdir = zn_create_folder($this->paths['tempdir'], false);
     if (!$tempdir) {
         $return['error'] = 'The temp folder could not be created !';
         return $return;
     }
     if ($zipper->open($zip) === true) {
         for ($i = 0; $i < $zipper->numFiles; $i++) {
             $filename = $zipper->getNameIndex($i);
             $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
             if (!in_array($file_extension, $extensions) || substr($filename, -1) == '/') {
                 continue;
             }
             $fp = $zipper->getStream($filename);
             $ofp = fopen($this->paths['tempdir'] . '/' . basename($filename), 'w');
             while (!feof($fp)) {
                 fwrite($ofp, fread($fp, 8192));
             }
             fclose($fp);
             fclose($ofp);
         }
         $zipper->close();
     } else {
         $return['error'] = 'The zip file could not be extracted !';
     }
     return $return;
 }
 /**
  * 
  * import slider from multipart form
  */
 public function importSliderFromPost($updateAnim = true, $updateStatic = true)
 {
     try {
         $sliderID = UniteFunctionsRev::getPostVariable("sliderid");
         $sliderExists = !empty($sliderID);
         if ($sliderExists) {
             $this->initByID($sliderID);
         }
         $filepath = $_FILES["import_file"]["tmp_name"];
         if (file_exists($filepath) == false) {
             UniteFunctionsRev::throwError("Import file not found!!!");
         }
         //check if zip file or fallback to old, if zip, check if all files exist
         $zip = new ZipArchive();
         $importZip = $zip->open($filepath, ZIPARCHIVE::CREATE);
         if ($importZip === true) {
             //true or integer. If integer, its not a correct zip file
             //check if files all exist in zip
             $slider_export = $zip->getStream('slider_export.txt');
             $custom_animations = $zip->getStream('custom_animations.txt');
             $dynamic_captions = $zip->getStream('dynamic-captions.css');
             $static_captions = $zip->getStream('static-captions.css');
             if (!$slider_export) {
                 UniteFunctionsRev::throwError("slider_export.txt does not exist!");
             }
             //if(!$custom_animations)  UniteFunctionsRev::throwError("custom_animations.txt does not exist!");
             //if(!$dynamic_captions) UniteFunctionsRev::throwError("dynamic-captions.css does not exist!");
             //if(!$static_captions)  UniteFunctionsRev::throwError("static-captions.css does not exist!");
             $content = '';
             $animations = '';
             $dynamic = '';
             $static = '';
             while (!feof($slider_export)) {
                 $content .= fread($slider_export, 1024);
             }
             if ($custom_animations) {
                 while (!feof($custom_animations)) {
                     $animations .= fread($custom_animations, 1024);
                 }
             }
             if ($dynamic_captions) {
                 while (!feof($dynamic_captions)) {
                     $dynamic .= fread($dynamic_captions, 1024);
                 }
             }
             if ($static_captions) {
                 while (!feof($static_captions)) {
                     $static .= fread($static_captions, 1024);
                 }
             }
             fclose($slider_export);
             if ($custom_animations) {
                 fclose($custom_animations);
             }
             if ($dynamic_captions) {
                 fclose($dynamic_captions);
             }
             if ($static_captions) {
                 fclose($static_captions);
             }
             //check for images!
         } else {
             //check if fallback
             //get content array
             $content = @file_get_contents($filepath);
         }
         if ($importZip === true) {
             //we have a zip
             $db = new UniteDBRev();
             //update/insert custom animations
             $animations = @unserialize($animations);
             if (!empty($animations)) {
                 foreach ($animations as $key => $animation) {
                     //$animation['id'], $animation['handle'], $animation['params']
                     $exist = $db->fetch(GlobalsRevSlider::$table_layer_anims, "handle = '" . $animation['handle'] . "'");
                     if (!empty($exist)) {
                         //update the animation, get the ID
                         if ($updateAnim == "true") {
                             //overwrite animation if exists
                             $arrUpdate = array();
                             $arrUpdate['params'] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
                             $db->update(GlobalsRevSlider::$table_layer_anims, $arrUpdate, array('handle' => $animation['handle']));
                             $id = $exist['0']['id'];
                         } else {
                             //insert with new handle
                             $arrInsert = array();
                             $arrInsert["handle"] = 'copy_' . $animation['handle'];
                             $arrInsert["params"] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
                             $id = $db->insert(GlobalsRevSlider::$table_layer_anims, $arrInsert);
                         }
                     } else {
                         //insert the animation, get the ID
                         $arrInsert = array();
                         $arrInsert["handle"] = $animation['handle'];
                         $arrInsert["params"] = stripslashes(json_encode(str_replace("'", '"', $animation['params'])));
                         $id = $db->insert(GlobalsRevSlider::$table_layer_anims, $arrInsert);
                     }
                     //and set the current customin-oldID and customout-oldID in slider params to new ID from $id
                     $content = str_replace(array('customin-' . $animation['id'], 'customout-' . $animation['id']), array('customin-' . $id, 'customout-' . $id), $content);
                 }
                 dmp(__("animations imported!", REVSLIDER_TEXTDOMAIN));
             } else {
                 dmp(__("no custom animations found, if slider uses custom animations, the provided export may be broken...", REVSLIDER_TEXTDOMAIN));
             }
             //overwrite/append static-captions.css
             if (!empty($static)) {
                 if ($updateStatic == "true") {
                     //overwrite file
                     RevOperations::updateStaticCss($static);
                 } else {
                     //append
                     $static_cur = RevOperations::getStaticCss();
                     $static = $static_cur . "\n" . $static;
                     RevOperations::updateStaticCss($static);
                 }
             }
             //overwrite/create dynamic-captions.css
             //parse css to classes
             $dynamicCss = UniteCssParserRev::parseCssToArray($dynamic);
             if (is_array($dynamicCss) && $dynamicCss !== false && count($dynamicCss) > 0) {
                 foreach ($dynamicCss as $class => $styles) {
                     //check if static style or dynamic style
                     $class = trim($class);
                     if (strpos($class, ':hover') === false && strpos($class, ':') !== false || strpos($class, " ") !== false || strpos($class, ".tp-caption") === false || (strpos($class, ".") === false || strpos($class, "#") !== false) || strpos($class, ">") !== false) {
                         //.tp-caption>.imageclass or .tp-caption.imageclass>img or .tp-caption.imageclass .img
                         continue;
                     }
                     //is a dynamic style
                     if (strpos($class, ':hover') !== false) {
                         $class = trim(str_replace(':hover', '', $class));
                         $arrInsert = array();
                         $arrInsert["hover"] = json_encode($styles);
                         $arrInsert["settings"] = json_encode(array('hover' => 'true'));
                     } else {
                         $arrInsert = array();
                         $arrInsert["params"] = json_encode($styles);
                     }
                     //check if class exists
                     $result = $db->fetch(GlobalsRevSlider::$table_css, "handle = '" . $class . "'");
                     if (!empty($result)) {
                         //update
                         $db->update(GlobalsRevSlider::$table_css, $arrInsert, array('handle' => $class));
                     } else {
                         //insert
                         $arrInsert["handle"] = $class;
                         $db->insert(GlobalsRevSlider::$table_css, $arrInsert);
                     }
                 }
                 dmp(__("dynamic styles imported!", REVSLIDER_TEXTDOMAIN));
             } else {
                 dmp(__("no dynamic styles found, if slider uses dynamic styles, the provided export may be broken...", REVSLIDER_TEXTDOMAIN));
             }
         }
         $content = preg_replace('!s:(\\d+):"(.*?)";!e', "'s:'.strlen('\$2').':\"\$2\";'", $content);
         //clear errors in string
         $arrSlider = @unserialize($content);
         if (empty($arrSlider)) {
             UniteFunctionsRev::throwError("Wrong export slider file format!");
         }
         //update slider params
         $sliderParams = $arrSlider["params"];
         if ($sliderExists) {
             $sliderParams["title"] = $this->arrParams["title"];
             $sliderParams["alias"] = $this->arrParams["alias"];
             $sliderParams["shortcode"] = $this->arrParams["shortcode"];
         }
         if (isset($sliderParams["background_image"])) {
             $sliderParams["background_image"] = UniteFunctionsWPRev::getImageUrlFromPath($sliderParams["background_image"]);
         }
         $json_params = json_encode($sliderParams);
         //update slider or craete new
         if ($sliderExists) {
             $arrUpdate = array("params" => $json_params);
             $this->db->update(GlobalsRevSlider::$table_sliders, $arrUpdate, array("id" => $sliderID));
         } else {
             //new slider
             $arrInsert = array();
             $arrInsert["params"] = $json_params;
             $arrInsert["title"] = UniteFunctionsRev::getVal($sliderParams, "title", "Slider1");
             $arrInsert["alias"] = UniteFunctionsRev::getVal($sliderParams, "alias", "slider1");
             $sliderID = $this->db->insert(GlobalsRevSlider::$table_sliders, $arrInsert);
         }
         //-------- Slides Handle -----------
         //delete current slides
         if ($sliderExists) {
             $this->deleteAllSlides();
         }
         //create all slides
         $arrSlides = $arrSlider["slides"];
         $alreadyImported = array();
         foreach ($arrSlides as $slide) {
             $params = $slide["params"];
             $layers = $slide["layers"];
             //convert params images:
             if (isset($params["image"])) {
                 //import if exists in zip folder
                 if (trim($params["image"]) !== '') {
                     if ($importZip === true) {
                         //we have a zip, check if exists
                         $image = $zip->getStream('images/' . $params["image"]);
                         if (!$image) {
                             echo $params["image"] . ' not found!<br>';
                         } else {
                             if (!isset($alreadyImported['zip://' . $filepath . "#" . 'images/' . $params["image"]])) {
                                 $importImage = UniteFunctionsWPRev::import_media('zip://' . $filepath . "#" . 'images/' . $params["image"], $sliderParams["alias"] . '/');
                                 if ($importImage !== false) {
                                     $alreadyImported['zip://' . $filepath . "#" . 'images/' . $params["image"]] = $importImage['path'];
                                     $params["image"] = $importImage['path'];
                                 }
                             } else {
                                 $params["image"] = $alreadyImported['zip://' . $filepath . "#" . 'images/' . $params["image"]];
                             }
                         }
                     }
                 }
                 $params["image"] = UniteFunctionsWPRev::getImageUrlFromPath($params["image"]);
             }
             //convert layers images:
             foreach ($layers as $key => $layer) {
                 if (isset($layer["image_url"])) {
                     //import if exists in zip folder
                     if (trim($layer["image_url"]) !== '') {
                         if ($importZip === true) {
                             //we have a zip, check if exists
                             $image_url = $zip->getStream('images/' . $layer["image_url"]);
                             if (!$image_url) {
                                 echo $layer["image_url"] . ' not found!<br>';
                             } else {
                                 if (!isset($alreadyImported['zip://' . $filepath . "#" . 'images/' . $layer["image_url"]])) {
                                     $importImage = UniteFunctionsWPRev::import_media('zip://' . $filepath . "#" . 'images/' . $layer["image_url"], $sliderParams["alias"] . '/');
                                     if ($importImage !== false) {
                                         $alreadyImported['zip://' . $filepath . "#" . 'images/' . $layer["image_url"]] = $importImage['path'];
                                         $layer["image_url"] = $importImage['path'];
                                     }
                                 } else {
                                     $layer["image_url"] = $alreadyImported['zip://' . $filepath . "#" . 'images/' . $layer["image_url"]];
                                 }
                             }
                         }
                     }
                     $layer["image_url"] = UniteFunctionsWPRev::getImageUrlFromPath($layer["image_url"]);
                     $layers[$key] = $layer;
                 }
             }
             //create new slide
             $arrCreate = array();
             $arrCreate["slider_id"] = $sliderID;
             $arrCreate["slide_order"] = $slide["slide_order"];
             $arrCreate["layers"] = json_encode($layers);
             $arrCreate["params"] = json_encode($params);
             $this->db->insert(GlobalsRevSlider::$table_slides, $arrCreate);
         }
     } catch (Exception $e) {
         $errorMessage = $e->getMessage();
         return array("success" => false, "error" => $errorMessage, "sliderID" => $sliderID);
     }
     //update dynamic-captions.css
     RevOperations::updateDynamicCaptions();
     return array("success" => true, "sliderID" => $sliderID);
 }
 protected function _extract(\lib\AvailablePackage $package, $zipPath, LocalRepositoryManager $localRepo)
 {
     $pkgFiles = $package->files();
     //Get the package's files
     //Check if the package is already installed
     $isUpgrade = false;
     if (($localPkg = $localRepo->getPackage($package->metadata()->name())) !== null) {
         $isUpgrade = true;
     }
     $zip = new \ZipArchive();
     $result = $zip->open($zipPath);
     //Open the package's source
     if ($result !== true) {
         throw new \RuntimeException('Cannot open package\'s contents from temporary file "' . $zipPath . '" : ZipArchive error #' . $result);
     }
     $root = __DIR__ . '/../../';
     //Root folder
     $filesToCopy = array();
     //Check if everything goes the right way, and store files to copy in an array
     for ($i = 0; $i < $zip->numFiles; $i++) {
         //For each file
         //Get info about it
         $itemStat = $zip->statIndex($i);
         //From the archive
         if (strpos($itemStat['name'], 'src/') !== 0) {
             //Not in "src/" directory
             continue;
         }
         $itemName = preg_replace('#^src/#', '', $itemStat['name']);
         if (empty($itemName) || substr($itemName, -1) == '/') {
             //Is this a directory ?
             continue;
         }
         if (!isset($pkgFiles[$itemName])) {
             //Is this in files list ?
             continue;
         }
         $itemPkgData = $pkgFiles[$itemName];
         //From the package
         //Pre-check
         if ($itemPkgData['noextract']) {
             continue;
         }
         //Skip this item
         $itemDestPath = $root . '/' . $itemName;
         //Here is the final file's destination
         //Add this file in the list
         $filesToCopy[$itemName] = array('sourcePath' => $itemStat['name'], 'name' => $itemName, 'destPath' => $itemDestPath, 'md5sum' => $itemPkgData['md5sum']);
     }
     //Now, extract files
     foreach ($filesToCopy as $item) {
         //Re-create parent dirs if they are not
         $parentDir = dirname($item['destPath']);
         if (!is_dir($parentDir)) {
             if (!mkdir($parentDir, 0777, true)) {
                 throw new \RuntimeException('Cannot create directory "' . $parentDir . '"');
             }
             chmod($parentDir, 0777);
         }
         //If the file already exists, do not overwrite it
         if (file_exists($item['destPath'])) {
             //Is the file owned by another package ?
             $fileData = $localRepo->getPackageFile($item['name']);
             if (!empty($fileData)) {
                 //Collision
                 if ($fileData['pkg'] != $package->metadata()->name()) {
                     throw new \RuntimeException('File collision detected : "' . $item['name'] . '" is already provided by "' . $fileData['pkg'] . '"');
                 }
                 //Check if the file must be upgraded
                 if (!empty($item['md5sum']) && isset($fileData['md5sum']) && !empty($fileData['md5sum']) && $fileData['md5sum'] == $item['md5sum']) {
                     continue;
                     //Skip this file : not changed
                 }
                 //Check if the file was manually modified
                 $destMd5 = md5_file($item['destPath']);
                 //Calculate the MD5 sum of the destination file
                 if (!empty($fileData['md5sum']) && $fileData['md5sum'] != $destMd5) {
                     continue;
                     //Skip this file : manually modified
                 }
             } else {
                 //File not provided by another pkg, maybe manually modified
                 continue;
                 //Skip this file
             }
         }
         $itemSource = $zip->getStream($item['sourcePath']);
         //Get the file's stream
         $itemDest = fopen($item['destPath'], 'w');
         //Destination file
         $copiedBits = stream_copy_to_stream($itemSource, $itemDest);
         //Extract current file...
         fclose($itemDest);
         if ($copiedBits == 0) {
             //Nothing copied -> error ?
             throw new \RuntimeException('Cannot extract file "' . $item['sourcePath'] . '" from "' . $zipPath . '" to "' . $item['destPath'] . '"');
         }
         //Post-check
         if (!empty($item['md5sum'])) {
             //If a md5 checksum is specified
             $destMd5 = md5_file($item['destPath']);
             //Calculate the MD5 sum of the extracted file
             if ($item['md5sum'] != $destMd5) {
                 //If checksums are different
                 unlink($item['destPath']);
                 //Delete copied file
                 throw new \RuntimeException('Bad file checksum : "' . $item['destPath'] . '". This file is corrupted. Please try to install this package again.');
             }
         }
         chmod($item['destPath'], 0777);
         //Allow read-write-execute for all users - better for maintaining the framework
     }
     //If it is an upgrade, remove newly deleted files
     if ($isUpgrade) {
         foreach ($localPkg->files() as $fileData) {
             $oldFilePath = preg_replace('#^\\./#', '', $fileData['path']);
             //Was this file already processed ?
             if (!isset($filesToCopy[$oldFilePath])) {
                 //Delete old file
                 if (!unlink($oldFilePath)) {
                     //Delete this file
                     throw new \RuntimeException('Cannot delete file "' . $oldFilePath . '"');
                 }
                 //Delete parent folders while they are empty
                 do {
                     $parentDirPath = dirname(isset($parentDirPath) ? $parentDirPath : $oldFilePath);
                     $parentDir = opendir($parentDirPath);
                     $isEmpty = true;
                     if ($parentDir === false) {
                         continue;
                     }
                     while (false !== ($entry = readdir($parentDir))) {
                         if ($entry == '.' || $entry == '..') {
                             continue;
                         }
                         $isEmpty = false;
                         break;
                     }
                     closedir($parentDir);
                     if ($isEmpty) {
                         rmdir($parentDirPath);
                     }
                 } while ($isEmpty);
             }
         }
     }
     $zip->close();
     //Close the package's source
 }
Example #30
0
 function zip_flatten($zipfile, $filter)
 {
     if (is_dir($this->paths['tempdir'])) {
         $this->delete_folder($this->paths['tempdir']);
         $tempdir = smile_backend_create_folder($this->paths['tempdir'], false);
     } else {
         $tempdir = smile_backend_create_folder($this->paths['tempdir'], false);
     }
     if (!$tempdir) {
         die('Wasn\'t able to create temp folder');
     }
     $zip = new ZipArchive();
     if ($zip->open($zipfile)) {
         for ($i = 0; $i < $zip->numFiles; $i++) {
             $entry = $zip->getNameIndex($i);
             if (!empty($filter)) {
                 $delete = true;
                 $matches = array();
                 foreach ($filter as $regex) {
                     preg_match("!" . $regex . "!", $entry, $matches);
                     if (!empty($matches)) {
                         $delete = false;
                         break;
                     }
                 }
             }
             if (substr($entry, -1) == '/' || !empty($delete)) {
                 continue;
             }
             // skip directories and non matching files
             $fp = $zip->getStream($entry);
             $ofp = fopen($this->paths['tempdir'] . '/' . basename($entry), 'w');
             if (!$fp) {
                 die('Unable to extract the file.');
             }
             while (!feof($fp)) {
                 fwrite($ofp, fread($fp, 8192));
             }
             fclose($fp);
             fclose($ofp);
         }
         $zip->close();
     } else {
         die('Wasn\'t able to work with Zip Archive');
     }
     return true;
 }