extract() public method

--------------------------------------------------------------------------------
public extract ( )
示例#1
1
 /**
  * Unzip a file into the specified directory. Throws a RuntimeException
  * if the extraction failed.
  */
 public static function unzip($file, $to = 'cache/zip')
 {
     @ini_set('memory_limit', '256M');
     if (!is_dir($to)) {
         mkdir($to);
         chmod($to, 0777);
     }
     if (class_exists('ZipArchive')) {
         // use ZipArchive
         $zip = new ZipArchive();
         $res = $zip->open($file);
         if ($res === true) {
             $zip->extractTo($to);
             $zip->close();
         } else {
             throw new RuntimeException('Could not open zip file [ZipArchive].');
         }
     } else {
         // use PclZip
         $zip = new PclZip($file);
         if ($zip->extract(PCLZIP_OPT_PATH, $to) === 0) {
             throw new RuntimeException('Could not extract zip file [PclZip].');
         }
     }
     return true;
 }
示例#2
0
 function unzip_file($zip_archive, $archive_file, $to_dir, $forceOverwrite = false)
 {
     if (!is_dir($to_dir)) {
         if (!defined('SUGAR_PHPUNIT_RUNNER')) {
             die("Specified directory '{$to_dir}' for zip file '{$zip_archive}' extraction does not exist.");
         }
         return false;
     }
     $archive = new PclZip($zip_archive);
     if ($forceOverwrite) {
         if ($archive->extract(PCLZIP_OPT_BY_NAME, $archive_file, PCLZIP_OPT_PATH, $to_dir, PCLZIP_OPT_REPLACE_NEWER) == 0) {
             if (!defined('SUGAR_PHPUNIT_RUNNER')) {
                 die("Error: " . $archive->errorInfo(true));
             }
             return false;
         }
     } else {
         if ($archive->extract(PCLZIP_OPT_BY_NAME, $archive_file, PCLZIP_OPT_PATH, $to_dir) == 0) {
             if (!defined('SUGAR_PHPUNIT_RUNNER')) {
                 die("Error: " . $archive->errorInfo(true));
             }
             return false;
         }
     }
 }
 function unzip($zipfile, $destination_dir = false, $delete_old_dir = false)
 {
     //We check if the previous folder needs to be removed. If so, we do it with deltree() function that recursively deletes all files and then the empty folders from the target folder. if no destination_dir, then ignore this section.
     if ($destination_dir && $delete_old_dir) {
         if (file_exists($destination_dir)) {
             if (!is_writable($destination_dir)) {
                 $this->create_error("Error in deleting the old directory. Missing write permissions in '" . $destination_dir . "'");
             } else {
                 $this->deltree($destination_dir);
             }
         }
     }
     //if destination url, we need to check if it's there and writable, if now, we are going to make it. This script is meant to make the final directory, it will not create the necessary tree up the the folder.
     if (!$this->error() && $destination_dir) {
         if (file_exists($destination_dir)) {
             if (!is_writable($destination_dir)) {
                 $this->create_error("Missing write permissions in '" . $destination_dir . "'");
             }
         } else {
             if (!mkdir($destination_dir, 0775)) {
                 $this->create_error("Unable to create directory '" . $destination_dir . "'. Check writing permissions.");
             }
         }
     }
     //check if the archive file exists and is readable, then depending on destination_dir either just unpack it or unpack it into the destination_dir folder.
     if (!$this->error) {
         if (file_exists($zipfile)) {
             if (is_readable($zipfile)) {
                 $archive = new PclZip($zipfile);
                 if ($destination_dir) {
                     if ($archive->extract(PCLZIP_OPT_REPLACE_NEWER, PCLZIP_OPT_PATH, $destination_dir, PCLZIP_OPT_SET_CHMOD, 0777) == 0) {
                         $this->create_error("Error : " . $archive->errorInfo(true));
                     } else {
                         return true;
                     }
                 } else {
                     if ($archive->extract(PCLZIP_OPT_SET_CHMOD, 0777) == 0) {
                         $this->create_error("Error : " . $archive->errorInfo(true));
                     } else {
                         return true;
                     }
                 }
             } else {
                 $this->create_error("Unable to read ZIP file '" . $zipfile . "'. Check reading permissions.");
             }
         } else {
             $this->create_error("Missing ZIP file '.{$zipfile}.'");
         }
     }
     return $error;
 }
示例#4
0
function extract_files($archive, $dir, $type)
{
    if ($type != "zip") {
        switch ($type) {
            case "targz":
            case "tgz":
                $cmd = which("tar") . " xfz " . escapeshellarg($archive) . " -C " . escapeshellarg($dir);
                break;
            case "tarbz2":
                $cmd = which("tar") . " xfj " . escapeshellarg($archive) . " -C " . escapeshellarg($dir);
                break;
            case "tar":
                $cmd = which("tar") . " xf " . escapeshellarg($archive) . " -C " . escapeshellarg($dir);
                break;
            case "gz":
                $cmd = which("gzip") . " -dq " . escapeshellarg($archive);
                break;
            case "bz2":
                $cmd = which("bzip2") . " -dq " . escapeshellarg($archive);
                break;
            default:
                exit;
        }
        exec($cmd . " 2>&1", $res);
        return $res;
    }
    if ($type == "zip") {
        require_once "../../lib/pclzip/pclzip.lib.php";
        $ar = new PclZip($archive);
        return $ar->extract(PCLZIP_OPT_PATH, $dir);
    }
}
示例#5
0
 public function restore($filename)
 {
     if (!file_exists($filename)) {
         $this->pushError(sprintf(langBup::_('Filesystem backup %s does not exists'), basename($filename)));
         return false;
     }
     if (!class_exists('PclZip', false)) {
         /** @var backupBup $backup */
         $backup = $this->getModule();
         $backup->loadLibrary('pcl');
     }
     $pcl = new PclZip($filename);
     if ($files = $pcl->extract(PCLZIP_OPT_PATH, ABSPATH, PCLZIP_OPT_REPLACE_NEWER) === 0) {
         $this->pushError(langBup::_('An error has occurred while unpacking the archive'));
         return false;
     }
     unset($pcl);
     // Unpack stacks
     $stacks = glob(realpath(ABSPATH) . '/BUP*');
     if (empty($stacks)) {
         return true;
     }
     foreach ($stacks as $stack) {
         if (file_exists($stack)) {
             $pcl = new PclZip($stack);
             $pcl->extract(PCLZIP_OPT_PATH, ABSPATH, PCLZIP_OPT_REPLACE_NEWER);
             unlink($stack);
             unset($pcl);
         }
     }
     return true;
 }
示例#6
0
 /**
  * 数据库还原
  */
 public function restore()
 {
     set_time_limit(0);
     $data = array();
     if ($_POST) {
         if (!$_FILES['db_file']) {
             message('请上传文件!');
         }
         /**
          * 上传文件
          */
         $upload_path = BASEPATH . '/../cache/backup/';
         $txt = strtolower(end(explode('.', $_FILES['db_file']['name'])));
         if (!in_array($txt, array('sql', 'zip'))) {
             message('数据文件格式不符合要求!');
         }
         $file_name = microtime(true) . '.' . $txt;
         $upload_file = $upload_path . $file_name;
         if (!is_dir($upload_path)) {
             mkdir($upload_path, '0777', true);
         }
         if (!@move_uploaded_file($_FILES['db_file']['tmp_name'], $upload_file)) {
             message('文件处理失败,请重新上传文件!');
         } else {
             if ($txt == 'zip') {
                 require_once APPPATH . 'libraries/Pclzip.php';
                 $archive = new PclZip($upload_file);
                 $list = $archive->extract(PCLZIP_OPT_BY_NAME, $upload_file . "zmte.sql", PCLZIP_OPT_EXTRACT_AS_STRING);
                 pr($list, 1);
             }
         }
     }
     $this->load->view('dbmanage/restore', $data);
 }
 function _extract($package, $target)
 {
     // First extract files
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     jimport('joomla.filesystem.archive');
     jimport('joomla.filesystem.path');
     $adapter =& JArchive::getAdapter('zip');
     $result = $adapter->extract($package, $target);
     if (!is_dir($target)) {
         require_once PATH_ROOT . 'administrator' . DS . 'includes' . DS . 'pcl' . DS . 'pclzip.lib.php';
         require_once PATH_ROOT . 'administrator' . DS . 'includes' . DS . 'pcl' . DS . 'pclerror.lib.php';
         $extract = new PclZip($package);
         if (substr(PHP_OS, 0, 3) == 'WIN') {
             if (!defined('OS_WINDOWS')) {
                 define('OS_WINDOWS', 1);
             }
         } else {
             if (!defined('OS_WINDOWS')) {
                 define('OS_WINDOWS', 0);
             }
         }
         $result = $extract->extract(PCLZIP_OPT_PATH, $target);
     }
     return $result;
 }
示例#8
0
 function unzip($fn, $to, $suffix = false)
 {
     @set_time_limit(0);
     // Unzip uses a lot of memory
     @ini_set('memory_limit', '256M');
     require_once iPATH . 'include/pclzip.class.php';
     $files = array();
     $zip = new PclZip($fn);
     // Is the archive valid?
     if (false == ($archive_files = $zip->extract(PCLZIP_OPT_EXTRACT_AS_STRING))) {
         exit("ZIP包错误");
     }
     if (0 == count($archive_files)) {
         exit("空的ZIP文件");
     }
     $path = self::path($to);
     self::mkdir($path);
     foreach ($archive_files as $file) {
         $files[] = array('filename' => $file['filename'], 'isdir' => $file['folder']);
         $folder = $file['folder'] ? $file['filename'] : dirname($file['filename']);
         self::mkdir($path . '/' . $folder);
         if (empty($file['folder'])) {
             $fp = $path . '/' . $file['filename'];
             $suffix && ($fp = $fp . '.' . $suffix);
             self::write($fp, $file['content']);
         }
     }
     return $files;
 }
function com_install()
{
    $database =& JFactory::getDBO();
    $path = JPATH_SITE;
    @ini_set('max_execution_time', '180');
    if (!defined('DS')) {
        define('DS', DIRECTORY_SEPARATOR);
    }
    if (file_exists($path . DS . "administrator" . DS . "includes" . DS . "pcl" . DS . "pclzip.lib.php")) {
        require_once $path . DS . "administrator" . DS . "includes" . DS . "pcl" . DS . "pclzip.lib.php";
    }
    $archivename = $path . DS . "administrator" . DS . "components" . DS . "com_sobi2" . DS . "includes" . DS . "install" . DS . "crystalsvg.zip";
    $zipfile = new PclZip($archivename);
    $zipfile->extract(PCLZIP_OPT_PATH, $path . DS . "images" . DS . "stories" . DS);
    $archivename = $path . DS . "administrator" . DS . "components" . DS . "com_sobi2" . DS . "includes" . DS . "install" . DS . "langs.zip";
    $zipfile = new PclZip($archivename);
    $zipfile->extract(PCLZIP_OPT_PATH, $path . DS . "administrator" . DS . "components" . DS . "com_sobi2" . DS . "languages" . DS);
    @unlink($path . DS . "images" . DS . "stories" . DS . "folder_add_f2.png");
    @unlink($path . DS . "images" . DS . "stories" . DS . "properties_f2.png");
    @chdir($path . DS . "images" . DS);
    @mkdir("com_sobi2", 0777);
    @chdir($path . DS . images . DS . "com_sobi2" . DS);
    @mkdir("clients", 0777);
    $m = JFactory::getApplication('site');
    $m->redirect('index2.php?option=com_sobi2&sinstall=screen', 'A instalação do SOBI2 não está concluída. Por favor terminar a primeira instalação.');
}
示例#10
0
 function packageUnzip($file, $target)
 {
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     jimport('joomla.filesystem.archive');
     jimport('joomla.filesystem.path');
     $extract1 =& JArchive::getAdapter('zip');
     $result = @$extract1->extract($file, $target);
     if ($result != true) {
         require_once PATH_ROOT . DS . 'administrator' . DS . 'includes' . DS . 'pcl' . DS . 'pclzip.lib.php';
         require_once PATH_ROOT . DS . 'administrator' . DS . 'includes' . DS . 'pcl' . DS . 'pclerror.lib.php';
         if (substr(PHP_OS, 0, 3) == 'WIN') {
             if (!defined('OS_WINDOWS')) {
                 define('OS_WINDOWS', 1);
             }
         } else {
             if (!defined('OS_WINDOWS')) {
                 define('OS_WINDOWS', 0);
             }
         }
         $extract2 = new PclZip($file);
         $result = @$extract2->extract(PCLZIP_OPT_PATH, $target);
     }
     unset($extract1, $extract2);
     return $result;
 }
示例#11
0
function zip_fallback($player_package) {
  $player_found = false;
  require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
  $zip = new PclZip($player_package);
  $archive_files = $zip->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
  $dir = $archive_files[0]["filename"];
  foreach($archive_files as $file) {
    $result = true;
    if ($file["filename"] == $dir . "player.swf" || $file["filename"] == $dir . "player-licensed.swf") {
      $result = @file_put_contents(LongTailFramework::getPrimaryPlayerPath(), $file["content"]);
      if (!$result) {
        return WRITE_ERROR;
      }
      $player_found = true;
    } else if ($file["filename"] == $dir . "yt.swf") {
      $result = @file_put_contents(str_replace("player.swf", "yt.swf", LongTailFramework::getPrimaryPlayerPath()), $file["content"]);
      if (!$result) {
        return WRITE_ERROR;
      }
    } else if ($file["filename"] == $dir . "jwplayer.js") {
      $result = @file_put_contents(LongTailFramework::getEmbedderPath(), $file["content"]);
      if (!$result) {
         return WRITE_ERROR;
      }
    }
  }
  if ($player_found) {
    unlink($player_package);
    return SUCCESS;
  }
  return ZIP_ERROR;
}
示例#12
0
 public function remoteinstall()
 {
     //安全验证 $this->checksafeauth();
     $url = $this->_get('url');
     $ext = strtolower(strrchr($url, '.'));
     $filepath = ltrim(strrchr($url, '/'), '/');
     if ($ext != '.zip') {
         //兼容旧版本
         $url = xbase64_decode($url);
         $ext = strtolower(strrchr($url, '.'));
         $filepath = ltrim(strrchr($url, '/'), '/');
         if ($ext != '.zip') {
             $this->error('远程文件格式必须为.zip');
         }
     }
     $content = fopen_url($url);
     if (empty($content)) {
         $this->error('远程获取文件失败!');
     }
     $filename = substr($filepath, 0, -4);
     File::write_file($filepath, $content);
     import('ORG.PclZip');
     $zip = new PclZip($filepath);
     $zip->extract(PCLZIP_OPT_PATH, './');
     @unlink($filepath);
     //删除安装文件
     $this->success('操作成功!', U('App/index'));
 }
function rex_a22_extract_archive($file, $destFolder = null)
{
    global $REX;
    if (!$destFolder) {
        $destFolder = '../files/' . $REX['TEMP_PREFIX'] . '/addon_framework';
    }
    $archive = new PclZip($file);
    if ($archive->extract(PCLZIP_OPT_PATH, $destFolder) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
    if (($list = $archive->listContent()) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
    echo '<div style="height:200px;width:770px;overflow:auto;margin-bottom:10px;text-align:center;">';
    echo '<h3>Archiv wird extrahiert...</h3>';
    echo '<table border="1" style="margin:0 auto 0 auto;">';
    echo '<tr><th>Datei</th><th>Gr&ouml;&szlig;e</th>';
    for ($i = 0; $i < count($list); $i++) {
        echo '<tr>';
        echo '<td>' . $list[$i]['filename'] . '</td><td>' . $list[$i]['size'] . ' bytes</td>';
        echo '</tr>';
    }
    echo '</table>';
    echo '</div>';
}
示例#14
0
 /**
  * Unzip a file into the specified directory. Throws a RuntimeException
  * if the extraction failed.
  */
 public static function unzip($source, $base = null)
 {
     $base = $base ? $base : self::$folder;
     @ini_set('memory_limit', '256M');
     if (!is_dir($base)) {
         mkdir($base);
         chmod($base, 0777);
     }
     if (class_exists('ZipArchive')) {
         // use ZipArchive
         $zip = new ZipArchive();
         $res = $zip->open($source);
         if ($res === true) {
             $zip->extractTo($base);
             $zip->close();
         } else {
             throw new RuntimeException('Could not open zip file [ZipArchive].');
         }
     } else {
         // use PclZip
         $zip = new PclZip($source);
         if ($zip->extract(PCLZIP_OPT_PATH, $base) === 0) {
             throw new RuntimeException('Could not extract zip file [PclZip].');
         }
     }
     return true;
 }
示例#15
0
    protected function saveUploadedFile() {
        
        $file = new Gpf_Db_File();
        $file->set('filename', $this->name);
        $file->set('filesize', $this->size);
        $file->set('filetype', $this->type);
        $file->save();
             
        $dir = new Gpf_Io_File($this->getZipFolderUrl().$file->getFileId().'/');
        if ($dir->isExists()) {
            $dir->delete();
        }
        $dir->mkdir();
        $tmpZip = new Gpf_Io_File($this->getZipFolderUrl().$file->getFileId().'/'.$file->getFileId().".zip");
        $dir->copy(new Gpf_Io_File($this->tmpName),$tmpZip);
        
        $archive = new PclZip($this->getZipFolderUrl().$file->getFileId().'/'.$file->getFileId().".zip");
        $err = $archive->extract($this->getZipFolderUrl().$file->getFileId().'/');
        if ($err <= 0) {
            throw new Gpf_Exception("code: ".$err);
        }

        $tmpZip->delete();
 
        return $file;
    }
 public function extractTextContent()
 {
     $config = KTConfig::getSingleton();
     $temp_dir = $config->get('urls/tmpDirectory');
     $docid = $this->document->getId();
     $time = 'ktindexer_openoffice_' . time() . '-' . $docid;
     $this->openxml_dir = $temp_dir . '/' . $time;
     $this->sourcefile = str_replace('\\', '/', $this->sourcefile);
     $this->openxml_dir = str_replace('\\', '/', $this->openxml_dir);
     $archive = new PclZip($this->sourcefile);
     if ($archive->extract(PCLZIP_OPT_PATH, $this->openxml_dir) == 0) {
         $this->output = _kt('Failed to extract content');
         return false;
     }
     /* *** Original code using the unzip binary ***
     		$cmd = '"' . $this->unzip . '"' . ' ' . str_replace(
     			array('{source}','{part}', '{target_dir}'),
     			array($this->sourcefile, 'content.xml',$this->openxml_dir), $this->unzip_params);
     
     		$cmd = str_replace('\\','/', $cmd);
     
      		if (!$this->exec($cmd))
     		{
     			$this->output = _kt('Failed to execute command: ') . $cmd;
     			return false;
     		}
     		*** End unzip code *** */
     $filename = $this->openxml_dir . '/content.xml';
     if (!file_exists($filename)) {
         $this->output = _kt('Failed to find file: ') . $filename;
         return false;
     }
     $result = file_put_contents($this->targetfile, $this->filter(file_get_contents($filename)));
     return $result !== false;
 }
示例#17
0
 function guardarArchivo()
 {
     global $db, $t;
     // Copia el archivo del usuario al directorio ../files
     $tipoArchivo = $_FILES['userfile']['type'];
     //if( $tipoArchivo=="application/zip" ){
     if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
         copy($_FILES['userfile']['tmp_name'], "../facturas/facturas.zip");
         $msg[] = "<font color=green>El archivo fue cargado correctamente.</font>";
         // -------------------------------------------
         // Descomprimir los zip
         require_once '../include/pclzip.lib.php';
         $archive = new PclZip('../facturas/facturas.zip');
         //Ejecutamos la funcion extract
         //if ( $archive->extract(PCLZIP_OPT_PATH, ' ../files/facturas/',PCLZIP_OPT_REMOVE_PATH, '../files/facturas/') == 0) {
         if ($archive->extract(PCLZIP_OPT_PATH, '../facturas/', PCLZIP_OPT_REMOVE_PATH, '../facturas/') == 0) {
             die("Error : " . $archive->errorInfo(true));
         }
         // -------------------------------------------
         // Eliminar zip, ya no es necesario.
         unlink("../facturas/facturas.zip");
     } else {
         $msg[] = "<font color=red>ERROR : Possible file upload attack. Filename: " . $_FILES['userfile']['name'];
     }
     //}
     //else{
     //    $archivo = $_FILES['userfile']['name'];
     //    $msg[]= "<font color=red>ERROR : El archivo (<i>$archivo</i>) es incorrecto, debe cargar un formato ZIP, y dentro de él todas las facturas.";
     //}
     return $msg;
 }
function themedrive_unzip($file, $dir)
{
    if (!current_user_can('edit_files')) {
        echo 'Oops, sorry you are not authorized to do this';
        return false;
    }
    if (!class_exists('PclZip')) {
        require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
    }
    $unzipArchive = new PclZip($file);
    $list = $unzipArchive->properties();
    if (!$list['nb']) {
        return false;
    }
    //echo "Number of files in archive : ".$list['nb']."<br>";
    echo "Copying the files<br>";
    $result = $unzipArchive->extract(PCLZIP_OPT_PATH, $dir);
    if ($result == 0) {
        echo 'Could not unarchive the file: ' . $unzipArchive->errorInfo(true) . ' <br />';
        return false;
    } else {
        //print_r($result);
        foreach ($result as $item) {
            if ($item['status'] != 'ok') {
                echo $item['stored_filename'] . ' ... ' . $item['status'] . '<br>';
            }
        }
        return true;
    }
}
示例#19
0
 public function restore_backup_file()
 {
     $data = $this->input->stream();
     if (isset($data['filename']) && !empty($data['filename'])) {
         $back_file_path = './backup/' . $data['filename'];
         if (file_exists($back_file_path)) {
             $archive = new PclZip($back_file_path);
             $row = $archive->extract(PCLZIP_OPT_PATH, "./backup/zycms");
             $row = array_shift($row);
             $extract_file_path = './' . $row['filename'];
             if (($sql_content = file_get_contents($filename = $extract_file_path)) !== false) {
                 $sql = explode("\n\n", $sql_content);
                 foreach ($sql as $key => $s) {
                     if (trim($s)) {
                         $result = $this->db->query($s);
                     }
                 }
                 unlink($extract_file_path);
                 rmdir('./backup/zycms');
                 die(json_encode(array('code' => 200, 'message' => '还原成功')));
             } else {
                 unlink($extract_file_path);
                 rmdir('./backup/zycms');
                 die(json_encode(array('code' => 403, 'message' => '还原失败')));
             }
         }
     }
 }
示例#20
0
 function getHeight($lat, $lon)
 {
     global $openDEMfiles, $CONF_DEMpath;
     if ($lat >= 0) {
         $latSouth = floor($lat);
         //$latNorth=$latSouth+1;
         $latD = 1 - $lat + $latSouth;
         $latStr = "N";
     } else {
         $latSouth = ceil(abs($lat));
         // $latNorth=$latSouth-1;
         $latD = -$lat - $latSouth + 1;
         $latStr = "S";
     }
     if ($lon >= 0) {
         $lonWest = floor($lon);
         //$lonEast=$lonWest+1;
         $lonD = $lon - $lonWest;
         $lonStr = "E";
     } else {
         $lonWest = ceil(abs($lon));
         //$lonEast=$lonWest-1;
         $lonD = $lonWest + $lon;
         $lonStr = "W";
     }
     // find the file to use!
     $demFile = sprintf("%s%02d%s%03d.hgt.zip", $latStr, $latSouth, $lonStr, $lonWest);
     if (!isset($openDEMfiles[$demFile])) {
         // echo "Getting DEM file: $demFile<BR>";
         if (!is_file($CONF_DEMpath . '/' . $demFile)) {
             // echo "#not found ".$CONF_DEMpath.'/'.$demFile."#";
             return 0;
         }
         require_once dirname(__FILE__) . '/lib/pclzip/pclzip.lib.php';
         $archive = new PclZip($CONF_DEMpath . '/' . $demFile);
         $list = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
         if ($list == 0) {
             //
             // echo "unzip error<br>";
             return 0;
             // die("Error : ".$archive->errorInfo(true));
         } else {
             //	echo $list[0]['content'];
         }
         $openDEMfiles[$demFile] = $list[0]['content'];
     }
     // find x,y inside the file
     // 1 degree is 1201 points
     $x = floor($lonD * 1201);
     $y = floor($latD * 1201);
     // point offeset in file
     $pointOffset = ($x + $y * 1201) * 2;
     // echo "$latD $lonD $x $y  $pointOffset<BR>";
     $alt = ord($openDEMfiles[$demFile][$pointOffset]) * 256 + ord($openDEMfiles[$demFile][$pointOffset + 1]);
     if ($alt > 10000) {
         $alt = 0;
     }
     return $alt;
 }
示例#21
0
 public function upgradecoreAction()
 {
     global $log;
     @ini_set('memory_limit', '256M');
     // Must set timeout !!!!!
     if (file_exists(APPLICATION_DIRECTORY . "/Joobsbox/Temp/Core_Upgrade_Log")) {
         $log = unserialize(file_get_contents(APPLICATION_DIRECTORY . "/Joobsbox/Temp/Core_Upgrade_Log"));
     } else {
         $log = array('lastActionMessage' => $this->view->translate("Starting file download"), 'actions' => array(), 'messageLog' => array());
         $this->updateLogFile($log);
     }
     /******************* LATEST FILE DOWNLAD *******************/
     /***********************************************************/
     if (!isset($log['actions']['downloaded'])) {
         // Download file from our repository
         $client = new Zend_Http_Client($this->requestBase . '/download/core');
         try {
             $response = $client->request();
             $file = $response->getBody();
             file_put_contents(APPLICATION_DIRECTORY . '/Joobsbox/Temp/latest.zip', $file);
             $log['messageLog'][] = $this->view->translate("Downloaded latest JoobsBox archive.");
             $log['actions']['downloaded'] = true;
             $this->updateLogFile($log);
         } catch (Exception $e) {
             $this->view->coreUpgrade = false;
             $log['messageLog'][] = $this->view->translate("Couldn't connect to the JoobsBox download server. Please check connection or contact your system's administrator.");
             $log['actions']['FAILED'] = true;
             $this->updateLogFile($log);
         }
     }
     /*************************** UNZIP *************************/
     /***********************************************************/
     require_once APPLICATION_DIRECTORY . "/Joobsbox/Filesystem/Zip.php";
     if (file_exists(APPLICATION_DIRECTORY . "/Joobsbox/Temp/joobsbox")) {
         // Move to trash
         @rename(APPLICATION_DIRECTORY . "/Joobsbox/Temp/joobsbox", APPLICATION_DIRECTORY . "/Joobsbox/Temp/.Trash/joobsbox");
     }
     $archive = new PclZip(APPLICATION_DIRECTORY . '/Joobsbox/Temp/latest.zip');
     $files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
     if ($files) {
         $log['messageLog'][] = $this->view->translate("Unzipped latest archive.");
     } else {
         $log['messageLog'][] = $this->view->translate("An error occured while unpacking the zip file. Please try again.");
         $log['actions']['FAILED'] = true;
     }
     $this->updateLogFile($log);
     /************************ UPDATE FILES *********************/
     /***********************************************************/
     $log['messageLog'][] = $this->view->translate("Updating files...");
     if (file_exists(APPLICATION_DIRECTORY . '/Joobsbox/Temp/backup/')) {
         rename(APPLICATION_DIRECTORY . '/Joobsbox/Temp/backup/', APPLICATION_DIRECTORY . '/Joobsbox/Temp/.Trash/backup/');
     }
     mkdir(APPLICATION_DIRECTORY . '/Joobsbox/Temp/backup/');
     $log['messageLog'][] = $this->view->translate("Created main application backup location Joobsbox/Temp/backup/");
     $log['messageLog'][] = $this->view->translate("Backing up and upgrading files as needed");
     $this->updateLogFile($log);
     $this->recurseAndUpgrade(0, $files);
     die;
 }
示例#22
0
 public function upload()
 {
     if (!MRights::can("upload")) {
         return $this->_noAuth("upload");
     }
     global $dir;
     $maxSize = MRoots::getMaxUploadSize();
     $maxSizeFormatted = MRoots::getMaxUploadSize(1);
     $files = $_FILES['files'];
     if (!$files) {
         $this->iframe(MText::_("up_too_large"));
         return null;
     }
     // Get the number of upload fields
     $rows = (int) MConfig::instance()->get("max_upload_fields", 6);
     // Check if empty
     $isEmpty = true;
     for ($t = 0; $t < $rows; $t++) {
         if (!empty($files["name"][$t])) {
             $isEmpty = false;
             break;
         }
     }
     $error = !$isEmpty ? null : MText::_("nouploadfilesselected");
     for ($t = 0; $t < $rows; $t++) {
         if (!empty($files["name"][$t])) {
             if ($files['size'][$t] <= $maxSize) {
                 $fileName = $dir . DS . $files['name'][$t];
                 $upload = move_uploaded_file($files['tmp_name'][$t], $fileName);
                 if (!$upload) {
                     $error .= MText::_("couldntupload") . ": " . $files['name'][$t] . "<br>";
                 } else {
                     if (isset($_REQUEST["unzip"][$t]) && !empty($_REQUEST["unzip"][$t])) {
                         $archive = new PclZip($fileName);
                         $status = $archive->extract(PCLZIP_OPT_PATH, $dir);
                         foreach ($status as $item) {
                             if ($item['status'] != "ok") {
                                 $error .= ' - <b>' . $item['stored_filename'] . ":</b> " . MText::_($item['status']) . '<br>';
                             }
                         }
                         //EOF foreach status
                         //Remove archive
                         MFile::remove($fileName);
                     }
                 }
             } else {
                 $error .= MText::_("couldntupload") . ": " . $files['name'][$t] . " -> " . MText::_("filetoolarge") . " " . $maxSizeFormatted . "<br>";
             }
         }
     }
     $template = null;
     if (file_exists(_FM_HOME_DIR . DS . 'templates' . DS . "afterupload.php")) {
         $template = _FM_HOME_DIR . DS . 'templates' . DS . "afterupload.php";
         $arg = array("dir" => $dir, "error" => $error);
         $this->view->add2Content(MTemplater::get($template, $arg));
     } else {
         $this->view->add2Content("Error: No after upload template!");
     }
 }
示例#23
0
 function install($package)
 {
     $this->init();
     $this->install_strings();
     global $wp_filesystem;
     //add_filter('upgrader_source_selection', array($this, 'check_package') );
     // $package is the path to zip file, so unzip it
     $destination = OP_LIB . 'content_layouts/working';
     // clear destination
     foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($destination, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
         $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
     }
     if (class_exists('ZipArchive')) {
         $zip = new ZipArchive();
         if ($zip->open($package) === true) {
             $zip->extractTo($destination);
             $zip->close();
             echo $this->strings['process_success'];
             // install the template
             require_once OP_LIB . 'admin/install.php';
             $ins = new OptimizePress_Install();
             $this->result = $ins->add_content_templates($destination, '', '', true, false);
             // refresh everything
             $GLOBALS['op_layout_uploaded'] = true;
             echo '<script type="text/javascript">var win = window.dialogArguments || opener || parent || top; win.op_refresh_content_layouts();</script>';
         } else {
             echo $this->strings['process_failed'];
         }
     } else {
         require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
         $zip = new PclZip($package);
         $zip->extract(PCLZIP_OPT_PATH, $destination);
         echo $this->strings['process_success'];
         // install the template
         require_once OP_LIB . 'admin/install.php';
         $ins = new OptimizePress_Install();
         $this->result = $ins->add_content_templates($destination, '', '', true, false);
         // refresh everything
         $GLOBALS['op_layout_uploaded'] = true;
         echo '<script type="text/javascript">var win = window.dialogArguments || opener || parent || top; win.op_refresh_content_layouts();</script>';
     }
     /*$this->run(array(
     					'package' => $package,
     					'destination' => OP_LIB.'content_layouts/working',//rtrim(OP_ASSETS,'/'),
     					'clear_destination' => true, //Do not overwrite files.
     					'clear_working' => true,
     					//'hook_extra' => array($this,'install_content_layout')
     					));
     
     		remove_filter('upgrader_source_selection', array($this, 'check_package') );
     
     		if ( ! $this->result || is_wp_error($this->result) )
     			return $this->result;
     		*/
     // Force refresh of plugin update information
     //delete_site_transient('update_plugins');
     //remove_filter('upgrader_source_selection', array($this, 'check_package') );
     return true;
 }
示例#24
0
/**
 * this function may be called by modules to install a droplet 
 **/
function droplet_install($temp_file, $temp_unzip)
{
    global $admin, $database;
    // Include the PclZip class file
    if (!function_exists("PclZipUtilPathReduction")) {
        require_once LEPTON_PATH . '/modules/lib_lepton/pclzip/pclzip.lib.php';
    }
    $errors = array();
    $count = 0;
    $archive = new PclZip($temp_file);
    $list = $archive->extract(PCLZIP_OPT_PATH, $temp_unzip);
    // now, open all *.php files and search for the header;
    // an exported droplet starts with "//:"
    if ($dh = opendir($temp_unzip)) {
        while (false !== ($file = readdir($dh))) {
            if ($file != "." && $file != "..") {
                if (preg_match('/^(.*)\\.php$/i', $file, $name_match)) {
                    // Name of the Droplet = Filename
                    $name = $name_match[1];
                    // Slurp file contents
                    $lines = file($temp_unzip . '/' . $file);
                    // First line: Description
                    if (preg_match('#^//\\:(.*)$#', $lines[0], $match)) {
                        $description = $match[1];
                    }
                    // Second line: Usage instructions
                    if (preg_match('#^//\\:(.*)$#', $lines[1], $match)) {
                        $usage = addslashes($match[1]);
                    }
                    // Remaining: Droplet code
                    $code = implode('', array_slice($lines, 2));
                    // replace 'evil' chars in code
                    $tags = array('<?php', '?>', '<?');
                    $code = addslashes(str_replace($tags, '', $code));
                    // Already in the DB?
                    $stmt = 'INSERT';
                    $id = NULL;
                    $found = $database->get_one("SELECT * FROM " . TABLE_PREFIX . "mod_droplets WHERE name='{$name}'");
                    if ($found && $found > 0) {
                        $stmt = 'REPLACE';
                        $id = $found;
                    }
                    // execute
                    $result = $database->query("{$stmt} INTO " . TABLE_PREFIX . "mod_droplets VALUES(" . ($id !== NULL ? "'" . $id . "'" : 'NULL') . ",'{$name}','{$code}','{$description}','" . time() . "','" . (isset($_SESSION['USER_ID']) ? $_SESSION['USER_ID'] : '1') . "',1,0,0,0,'{$usage}')");
                    if (!$database->is_error()) {
                        $count++;
                        $imports[$name] = 1;
                    } else {
                        $errors[$name] = $database->get_error();
                    }
                    // try to remove the temp file
                    unlink($temp_unzip . '/' . $file);
                }
            }
        }
        closedir($dh);
    }
    return array('count' => $count, 'errors' => $errors, 'imported' => $imports);
}
 /**
  * Extract the archive contents
  *
  * @param string $destination Location where to extract the files.
  * @param mixed  $entities    The entries to extract. It accepts either a single entry name or an array of names.
  *
  * @return boolean
  */
 public function extractTo($destination, $entities = null)
 {
     if ($entities) {
         return $this->pclZip->extract(PCLZIP_OPT_PATH, $destination, PCLZIP_OPT_BY_NAME, $entities);
     } else {
         return $this->pclZip->extract(PCLZIP_OPT_PATH, $destination);
     }
 }
示例#26
0
 /**
  * Extract files from archive to target directory
  *
  * @param string  $pathExtracted  Absolute path of target directory
  * @return mixed  Array of filenames if successful; or 0 if an error occurred
  */
 public function extract($pathExtracted)
 {
     $pathExtracted = str_replace('\\', '/', $pathExtracted);
     $list = $this->pclzip->listContent();
     if (empty($list)) {
         return 0;
     }
     foreach ($list as $entry) {
         $filename = str_replace('\\', '/', $entry['stored_filename']);
         $parts = explode('/', $filename);
         if (!strncmp($filename, '/', 1) || array_search('..', $parts) !== false || strpos($filename, ':') !== false) {
             return 0;
         }
     }
     // PCLZIP_CB_PRE_EXTRACT callback returns 0 to skip, 1 to resume, or 2 to abort
     return $this->pclzip->extract(PCLZIP_OPT_PATH, $pathExtracted, PCLZIP_OPT_STOP_ON_ERROR, PCLZIP_OPT_REPLACE_NEWER, PCLZIP_CB_PRE_EXTRACT, create_function('$p_event, &$p_header', "return strncmp(\$p_header['filename'], '{$pathExtracted}', strlen('{$pathExtracted}')) ? 0 : 1;"));
 }
示例#27
0
 /**
  * Extract zip file 
  * @param string $path path to extract files
  * @param string $input input zip file to extract
  * @example  $com->ZipExtract('newlibs', './sample.zip');
  */
 public function ZipExtract($path, $input)
 {
     include_once 'external/pclzip.lib.php';
     $archive = new PclZip($input);
     if ($archive->extract(PCLZIP_OPT_PATH, $path) == 0) {
         die("Error : " . $archive->errorInfo(true));
     }
 }
示例#28
0
function cherry_unzip_backup($file, $themes_folder)
{
    $zip = new PclZip($file);
    if ($zip->extract(PCLZIP_OPT_PATH, $themes_folder) == 0) {
        die("Error : " . $zip->errorInfo(true));
    }
    echo get_option(PARENT_NAME . "_version_backup");
}
示例#29
0
function extractEditor()
{
    $handle = new PclZip('./editor/jar/pluginwiris.zip');
    if ($handle->extract(PCLZIP_OPT_PATH, "./editor/jar/") === false) {
        return false;
    }
    return true;
}
 /**
  * 패키지 파일의 압축을 풀고 설치한다.
  * @param string $package
  * @param string $version
  * @param string $plugins_dir
  * @return boolean
  */
 public function install($package, $version, $plugins_dir)
 {
     $download_file = download_url("{$this->server}/download-{$package}?version={$version}");
     if (is_wp_error($download_file)) {
         unlink($download_file);
         echo '<script>alert("다운로드에 실패 했습니다. 다시 시도해 주세요.");</script>';
         return false;
     }
     // See #15789 - PclZip uses string functions on binary data, If it's overloaded with Multibyte safe functions the results are incorrect.
     if (ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding')) {
         $previous_encoding = mb_internal_encoding();
         mb_internal_encoding('ISO-8859-1');
     }
     require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
     $archive = new PclZip($download_file);
     $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
     unlink($download_file);
     if ($archive_files) {
         if (is_writable($plugins_dir)) {
             foreach ($archive_files as $file) {
                 if ($file['folder']) {
                     $extract_result = wp_mkdir_p($plugins_dir . '/' . $file['filename']);
                 } else {
                     $extract_result = file_put_contents($plugins_dir . '/' . $file['filename'], $file['content']);
                 }
                 if (!$extract_result) {
                     break;
                 }
             }
             if (!$extract_result) {
                 echo '<script>alert("FTP로 파일 쓰기에 실패했습니다. 서버 관리자에게 문의하시기 바랍니다.");</script>';
                 return false;
             }
         } else {
             global $wp_filesystem;
             $target_dir = trailingslashit($wp_filesystem->find_folder($plugins_dir));
             foreach ($archive_files as $file) {
                 if ($file['folder']) {
                     if ($wp_filesystem->is_dir($target_dir . $file['filename'])) {
                         continue;
                     } else {
                         $extract_result = $wp_filesystem->mkdir($target_dir . $file['filename'], FS_CHMOD_DIR);
                     }
                 } else {
                     $extract_result = $wp_filesystem->put_contents($target_dir . $file['filename'], $file['content'], FS_CHMOD_FILE);
                 }
                 if (!$extract_result) {
                     break;
                 }
             }
             if (!$extract_result) {
                 echo '<script>alert("FTP로 파일 쓰기에 실패했습니다. 서버 관리자에게 문의하시기 바랍니다.");</script>';
                 return false;
             }
         }
     }
     return true;
 }