listContent() public method

--------------------------------------------------------------------------------
public listContent ( )
Exemplo n.º 1
0
 public function open($Path)
 {
     $this->PclZip = new PclZip($Path);
     $Result = $this->_Contents = $this->PclZip->listContent();
     if (!$Result) {
         return ZipArchive::ER_READ;
     }
     $this->_Names = array();
     foreach ($this->_Contents as $Content) {
         $this->_Names[$Content['filename']] = $Content;
     }
     $this->numFiles = count($this->_Contents);
     return TRUE;
 }
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>';
}
Exemplo n.º 3
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;"));
 }
function rex_a52_extract_archive($file, $msg = '', $path = '../files/tmp_')
{
    $archive = new PclZip($file);
    if ($archive->extract(PCLZIP_OPT_PATH, $path) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
    if (($list = $archive->listContent()) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
}
Exemplo n.º 5
0
 function checkZip()
 {
     include_once SERVER_ROOT . "core/inc/lib/pclzip.php";
     $zip = new PclZip(SERVER_ROOT . "cache/update.zip");
     $zip->listContent();
     if ($zip->errorName() != "PCLZIP_ERR_NO_ERROR") {
         return false;
     }
     return true;
 }
Exemplo n.º 6
0
 function on_submit()
 {
     if (isset($_FILES['zipfile']) && $_FILES['zipfile']['error'] == 0) {
         //$fileEXT=strtolower(substr($_FILES['zipfile']['name'],strlen($_FILES['zipfile']['name'])-4,4));
         $fileEXT = AZLib::getExtension($_FILES['zipfile']['name']);
         if ($fileEXT == '.zip') {
             $uploadPath = ROOT_PATH . 'promotion/';
             @chmod($uploadPath, 0777);
             $zipFilePath = $uploadPath . time() . $fileEXT;
             @chmod($zipFilePath, 0777);
             if (!move_uploaded_file($_FILES['zipfile']['tmp_name'], $zipFilePath)) {
                 $this->setFormError('zipfile', "Không Upload được file Zip !");
                 return;
             } else {
                 @chmod($zipFilePath, 0777);
                 require_once "includes/unzip.ncl.php";
                 if (file_exists($zipFilePath)) {
                     $txt = '';
                     //unzipping...
                     $zip = new PclZip($zipFilePath);
                     if (($list = $zip->listContent()) == 0) {
                         $this->setFormError('zipfile', "File Zip trống!");
                         @unlink($zipFilePath);
                         return;
                     }
                     //calculate statistics...
                     for ($i = 0; $i < sizeof($list); $i++) {
                         if ($list[$i]['folder'] == '1') {
                             $fold++;
                             $dirs[$fold] = $list[$i]['stored_filename'];
                             $dirname = $list[$i]['stored_filename'];
                             $dirname = substr($dirname, 0, strlen($dirname) - 1);
                             @mkdir($basedir . '/' . $dirname);
                             @chmod($basedir . '/' . $dirname, 0777);
                         }
                     }
                     if ($zip->extract('promotion/')) {
                         unset($zip);
                         @unlink($zipFilePath);
                     } else {
                         $this->setFormError('zipfile', "Không giải nén được!");
                         return;
                     }
                 }
             }
         } else {
             $this->setFormError('zipfile', "File Upload phải là file nén dạng .zip !");
             return;
         }
     }
     $this->setFormError('zipfile', "Bạn chưa chọn file up lên!");
     //Url::redirect_current();
 }
/**
 * Charger un zip à partir d'un tableau d'options descriptives
 *
 * @uses  http_deballe_recherche_racine()
 *
 * @param array $quoi
 *     Tableau d'options
 * @return array|bool|int|string
 *     En cas de réussite, Tableau décrivant le zip, avec les index suivant :
 *     - files : la liste des fichiers présents dans le zip,
 *     - size : la taille décompressée
 *     - compressed_size : la taille compressée
 *     - dirname : répertoire où les fichiers devront être décompréssés
 *     - tmpname : répertoire temporaire où les fichiers sont décompressés
 *     - target : cible sur laquelle décompresser les fichiers...
 */
function teleporter_http_charger_zip($quoi = array())
{
    if (!$quoi) {
        return false;
    }
    foreach (array('remove' => 'spip', 'rename' => array(), 'edit' => array(), 'root_extract' => false, 'tmp' => sous_repertoire(_DIR_CACHE, 'chargeur')) as $opt => $def) {
        isset($quoi[$opt]) || ($quoi[$opt] = $def);
    }
    if (!@file_exists($fichier = $quoi['fichier'])) {
        return 0;
    }
    include_spip('inc/pclzip');
    $zip = new PclZip($fichier);
    $list = $zip->listContent();
    $racine = http_deballe_recherche_racine($list);
    $quoi['remove'] = $racine;
    // si pas de racine commune, reprendre le nom du fichier zip
    // en lui enlevant la racine h+md5 qui le prefixe eventuellement
    // cf action/charger_plugin L74
    if (!strlen($nom = basename($racine))) {
        $nom = preg_replace(",^h[0-9a-f]{8}-,i", "", basename($fichier, '.zip'));
    }
    $dir_export = $quoi['root_extract'] ? $quoi['dest'] : $quoi['dest'] . $nom;
    $dir_export = rtrim($dir_export, '/') . '/';
    $tmpname = $quoi['tmp'] . $nom . '/';
    // choisir la cible selon si on veut vraiment extraire ou pas
    $target = $quoi['extract'] ? $dir_export : $tmpname;
    // ici, il faut vider le rep cible si il existe deja, non ?
    if (is_dir($target)) {
        supprimer_repertoire($target);
    }
    // et enfin on extrait
    $ok = $zip->extract(PCLZIP_OPT_PATH, $target, PCLZIP_OPT_SET_CHMOD, _SPIP_CHMOD, PCLZIP_OPT_REPLACE_NEWER, PCLZIP_OPT_REMOVE_PATH, $quoi['remove']);
    if ($zip->error_code < 0) {
        spip_log('charger_decompresser erreur zip ' . $zip->error_code . ' pour paquet: ' . $quoi['archive'], "teleport" . _LOG_ERREUR);
        return $zip->errorName(true);
    }
    spip_log('charger_decompresser OK pour paquet: ' . $quoi['archive'], "teleport");
    $size = $compressed_size = 0;
    $removex = ',^' . preg_quote($quoi['remove'], ',') . ',';
    foreach ($list as $a => $f) {
        $size += $f['size'];
        $compressed_size += $f['compressed_size'];
        $list[$a] = preg_replace($removex, '', $f['filename']);
    }
    // Indiquer par un fichier install.log
    // a la racine que c'est chargeur qui a installe ce plugin
    ecrire_fichier($target . 'install.log', "installation: charger_plugin\n" . "date: " . gmdate('Y-m-d\\TH:i:s\\Z', time()) . "\n" . "source: " . $quoi['archive'] . "\n");
    return array('files' => $list, 'size' => $size, 'compressed_size' => $compressed_size, 'dirname' => $dir_export, 'tmpname' => $tmpname, 'target' => $target);
}
function rex_a52_extract_archive($file, $msg = '', $path = null)
{
    global $REX;
    if (!$path) {
        $path = '../files/' . $REX['TEMP_PREFIX'];
    }
    $archive = new PclZip($file);
    if ($archive->extract(PCLZIP_OPT_PATH, $path) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
    if (($list = $archive->listContent()) == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
}
Exemplo n.º 9
0
 protected function execute()
 {
     $this->loadParams();
     $archive = new PclZip($this->zipFile->getFileName());
     $listContent = $archive->listContent();
     $allFilesCount = count($listContent);
     $processedFiles = -self::UNZIP_STEP;
     while ($processedFiles < $allFilesCount) {
         $processedFiles += self::UNZIP_STEP;
         if ($this->isDone($processedFiles, $this->_('%s%% files unzipped', round($processedFiles / $allFilesCount * 100, 0)))) {
             continue;
         }
         $this->changePermissions($archive->extractByIndex($processedFiles . '-' . ($processedFiles + self::UNZIP_STEP - 1), $this->outputDirectory->getFileName()));
         $this->setDone($processedFiles);
     }
 }
Exemplo n.º 10
0
function unZip($uid, $from_zip)
{
    $afety_tag = 'Safety first -- ts24';
    //
    require 'include/pclzip.lib.php';
    $to_dir = '../data/diamond/' . substr($uid, -1) . '/';
    //允许的非模板文件类型
    $file_type = array('jpg', 'gif', 'jpeg', 'js', 'css', 'mp3', 'wma');
    //解压文件条件判断
    $reg_type = '/^' . $uid . '\\/.+\\.(' . implode('|', $file_type) . ')$/i';
    //
    $reg_htm = '/^' . $uid . '\\/' . intval($uid) . '_.+\\.htm$/i';
    $zip = new PclZip($from_zip);
    //包内所有文件列表
    $all_list = $zip->listContent();
    //获取解压列表
    $out_index = array();
    $arr_ret = array();
    if (empty($all_list)) {
        $all_list = array();
    }
    foreach ($all_list as $k => $v) {
        if (substr($v['filename'], -1) != '/') {
            if ('htm' == substr($v['filename'], -3)) {
                $tmp = preg_match($reg_htm, $v['filename']);
            } else {
                $tmp = preg_match($reg_type, $v['filename']);
            }
            if ($tmp) {
                //合格文件,可解压
                $arr_ret[$v['filename']] = 1;
                $out_index[] = $k;
            } else {
                $arr_ret[$v['filename']] = 0;
            }
        }
    }
    //解压
    if (empty($out_index)) {
        return $arr_ret;
    }
    $ret = $zip->extract(PCLZIP_OPT_PATH, $to_dir, PCLZIP_OPT_BY_INDEX, $out_index);
    if ($ret == 0) {
        return array();
    }
    return $arr_ret;
}
Exemplo n.º 11
0
 function decompress($to)
 {
     if (!file_exists($this->zip)) {
         throw new \Fuse_Exception('File :file does not exist', array(':file' => $this->zip));
     }
     $zip = new PclZip($this->zip);
     if (($list = $zip->listContent()) == 0) {
         error_log($zip->errorInfo(true));
         throw new \Fuse_Exception('Invalid zip file');
     }
     $v_list = $zip->extract($to);
     if ($v_list == 0) {
         error_log($zip->errorInfo(true));
         throw new \Fuse_Exception('Zip extraction failed');
     }
     return true;
 }
Exemplo n.º 12
0
 public function install($id)
 {
     $entry = $this->getEntry($id);
     if ($entry && !empty($entry['url'])) {
         App::uses('File', 'Utility');
         copy($entry['url'], TMP . DS . $id);
         App::import('Vendor', 'PclZip', array('file' => 'pclzip-2-8-2/pclzip.lib.php'));
         $zip = new PclZip(TMP . DS . $id);
         $list = $zip->listContent();
         $zip->extract(TMP);
         unlink(TMP . DS . $id);
         rename(TMP . DS . $list[0]['filename'], APP . 'Plugin' . DS . Inflector::camelize($id));
         Cache::clear(false, '_cake_core_');
         CakePlugin::loadAll();
         return true;
     }
     return false;
 }
Exemplo n.º 13
0
/**
 * find the name of the first GEDCOM file in a zipfile
 * @param string $zipfile	the path and filename
 * @param boolean $extract  true = extract and return filename, false = return filename
 * @return string		the path and filename of the gedcom file
 */
function GetGEDFromZIP($zipfile, $extract = true)
{
    global $INDEX_DIRECTORY;
    require_once PGV_ROOT . 'includes/pclzip.lib.php';
    $zip = new PclZip($zipfile);
    // if it's not a valid zip, just return the filename
    if (($list = $zip->listContent()) == 0) {
        return $zipfile;
    }
    // Determine the extract directory
    $slpos = strrpos($zipfile, "/");
    if (!$slpos) {
        $slpos = strrpos($zipfile, "\\");
    }
    if ($slpos) {
        $path = substr($zipfile, 0, $slpos + 1);
    } else {
        $path = $INDEX_DIRECTORY;
    }
    // Scan the files and return the first .ged found
    foreach ($list as $key => $listitem) {
        if (($listitem["status"] = "ok") && strstr(strtolower($listitem["filename"]), ".") == ".ged") {
            $filename = basename($listitem["filename"]);
            if ($extract == false) {
                return $filename;
            }
            // if the gedcom exists, save the old one. NOT to bak as it will be overwritten on import
            if (file_exists($path . $filename)) {
                if (file_exists($path . $filename . ".old")) {
                    unlink($path . $filename . ".old");
                }
                copy($path . $filename, $path . $filename . ".old");
                unlink($path . $filename);
            }
            if ($zip->extract(PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $path, PCLZIP_OPT_BY_NAME, $listitem["filename"]) == 0) {
                print "ERROR cannot extract ZIP";
            }
            return $filename;
        }
    }
    return $zipfile;
}
Exemplo n.º 14
0
		private function useLibPcl(){

      require_once('../../lib/pclzip.lib.php');
      $zip = new PclZip($this->file);
      $aff_fichiers = $zip->listContent();


      if ($zip->content = $zip->extract(PCLZIP_OPT_BY_NAME, $aff_fichiers[9]['filename'],  //on extrait content.xml
	                       PCLZIP_OPT_PATH, $aff_fichiers[9]['stored_filename']) == 0) { //de l'archive dans le dossier archive (id unique)
      echo "ERROR : ".$zip->errorInfo(true);
     }

      /*
      echo '<pre>';
      print_r($aff_fichiers);
      echo '</pre>';
      exit();
      */

    }
Exemplo n.º 15
0
/**
 * 查询解压缩文件的内容
 * $path example './zips/' 文件路径后面的斜线也请写上
 * $file example 1.zip
 */
function getFileFromZip($path)
{
    $zip = new PclZip($path);
    $list = $zip->listContent();
    return $list;
}
Exemplo n.º 16
0
 function zipListing($zipPath, $localPath, &$filteredList)
 {
     require_once "server/classes/pclzip.lib.php";
     $crtZip = new PclZip($this->getPath() . "/" . $zipPath);
     $liste = $crtZip->listContent();
     $files = array();
     if ($localPath[strlen($localPath) - 1] != "/") {
         $localPath .= "/";
     }
     foreach ($liste as $item) {
         $stored = $item["stored_filename"];
         if ($stored[0] != "/") {
             $stored = "/" . $stored;
         }
         $pathPos = strpos($stored, $localPath);
         if ($pathPos !== false) {
             $afterPath = substr($stored, $pathPos + strlen($localPath));
             if ($afterPath != "" && strpos($afterPath, "/") === false || strpos($afterPath, "/") == strlen($afterPath) - 1) {
                 $item["filename"] = $zipPath . $localPath . $afterPath;
                 if ($item["folder"]) {
                     $filteredList[] = $item;
                 } else {
                     $files[] = $item;
                 }
             }
         }
     }
     $filteredList = array_merge($filteredList, $files);
     return $crtZip;
 }
Exemplo n.º 17
0
 /**
  * @param $galleryId
  * @param $file
  * @param $user
  * @return bool|int
  */
 function process_batch_image_upload($galleryId, $file, $user)
 {
     global $prefs;
     $numimages = 0;
     include_once 'vendor_extra/pclzip/pclzip.lib.php';
     $archive = new PclZip($file);
     // Read Archive contents
     $ziplist = $archive->listContent();
     if (!$ziplist) {
         return false;
     }
     // Archive invalid
     foreach ($ziplist as $zipfile) {
         $file = $zipfile["filename"];
         if (!$zipfile["folder"]) {
             //copied
             $gal_info = $this->get_gallery($galleryId);
             $upl = 1;
             if (!empty($prefs['gal_match_regex'])) {
                 if (!preg_match('/' . $prefs['gal_match_regex'] . '/', $file, $reqs)) {
                     $upl = 0;
                 }
             }
             if (!empty($prefs['gal_nmatch_regex'])) {
                 if (preg_match('/' . $prefs['gal_nmatch_regex'] . '/', $file, $reqs)) {
                     $upl = 0;
                 }
             }
             //extract file
             $archive->extractByIndex($zipfile["index"], $prefs['tmpDir'], dirname($file));
             //extract and remove (dangerous) pathname
             $file = basename($file);
             //unset variables
             unset($this->filetype);
             unset($this->xsize);
             unset($this->ysize);
             //determine filetype and dimensions
             $this->getfileinfo($prefs['tmpDir'] . "/" . $file);
             $foo = explode(".", $file);
             $exp = end($foo);
             // read image and delete it after
             $this->readimagefromfile($prefs['tmpDir'] . "/" . $file);
             unlink($prefs['tmpDir'] . "/" . $file);
             if ($this->issupported($exp)) {
                 // convert to handle
                 $this->readimagefromstring();
                 if ($this->validhandle()) {
                     $this->getimageinfo();
                 }
             }
             //if there is no mimetype, we don't got a image
             if (isset($this->filetype)) {
                 if (!isset($this->xsize)) {
                     $this->xsize = $this->ysize = 0;
                 }
                 $imageId = $this->insert_image($galleryId, $file, '', $file, $this->filetype, $this->image, $this->filesize, $this->xsize, $this->ysize, $user, '', '', NULL, NULL, $gal_info);
                 $numimages++;
             }
         }
     }
     return $numimages;
 }
';"><?php 
    echo $TEXT['CANCEL'];
    ?>
</button>
        </td>
    </tr>
    </table>
    <br />
<div class="cb-import" id="cb-droplets" >
<?php 
    if (is_readable($sArchiveFile)) {
        if (!class_exists('PclZip', false)) {
            require WB_PATH . '/include/pclzip/pclzip.lib.php';
        }
        $oArchive = new PclZip($sArchiveFile);
        $aFilesInArchiv = $oArchive->listContent();
        if ($aFilesInArchiv == 0) {
            msgQueue::add($Droplet_Message['GENERIC_MISSING_ARCHIVE_FILE']);
        } else {
            ?>
<table class="droplets_import" style="margin-bottom: 1.225em;">
  <thead>
    <tr>
      <th  style="width: 3%;">
          <label>
              <input name="select_all" id="select_all" type="checkbox" value="1"  />
          </label>
      </th>
      <th style="width: 3%;"></th>
      <th style="width: 3%;"></th>
      <th style="width: 30%;"><?php 
Exemplo n.º 19
0
 if (file_exists(NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . $filename)) {
     @nv_deletefile(NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . $filename);
 }
 $apidata = $NV_Http->post(NUKEVIET_STORE_APIURL, $args);
 if (!empty(NukeViet\Http\Http::$error)) {
     $error = nv_http_get_lang(NukeViet\Http\Http::$error);
 } elseif (empty($apidata['filename']) or !file_exists($apidata['filename'])) {
     $error = $lang_module['get_update_error_file_download'];
 }
 if (!empty($error)) {
     $xtpl->assign('ERROR', $error);
     $xtpl->parse('error');
     echo $xtpl->text('error');
 } else {
     $zip = new PclZip(NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . $filename);
     $ziplistContent = $zip->listContent();
     // Not exists (can not download)
     $warning = 2;
     if (!empty($ziplistContent)) {
         // Package ok
         $warning = 0;
         foreach ($ziplistContent as $zipContent) {
             if (!preg_match("/^install\\//is", $zipContent['filename'])) {
                 // Package invald
                 $warning = 1;
             }
         }
     }
     if ($warning == 1) {
         $xtpl->assign('MESSAGE', sprintf($lang_module['get_update_warning'], NV_BASE_ADMINURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&amp;' . NV_NAME_VARIABLE . '=webtools&amp;' . NV_OP_VARIABLE . '=' . $op . '&amp;version=' . $version . '&amp;package=' . $package . '&amp;checksess=' . md5('unzip' . $version . $package . NV_CHECK_SESSION)));
         $xtpl->parse('warning');
Exemplo n.º 20
0
if ($_GET['file'] == "") {
    echo "Не выбран файл<br/><a href='?'>К категориям</a><br/>";
    require_once '../incfiles/end.php';
    exit;
}
$file = intval(trim($_GET['file']));
$file1 = mysql_query("select * from `download` where type = 'file' and id = '" . $file . "';");
$file2 = mysql_num_rows($file1);
$adrfile = mysql_fetch_array($file1);
if ($file1 == 0 || !is_file("{$adrfile['adres']}/{$adrfile['name']}")) {
    echo "Ошибка при выборе файла<br/><a href='?'>К категориям</a><br/>";
    require_once '../incfiles/end.php';
    exit;
}
$zip = new PclZip("{$adrfile['adres']}/{$adrfile['name']}");
if (($list = $zip->listContent()) == 0) {
    die("Ошибка: " . $zip->errorInfo(true));
}
for ($i = 0; $i < sizeof($list); $i++) {
    for (reset($list[$i]); $key = key($list[$i]); next($list[$i])) {
        $listcontent = "[{$i}]--{$key}:" . $list[$i][$key] . "";
        $zfilesize = strstr($listcontent, "--size");
        $zfilesize = ereg_replace("--size:", "", $zfilesize);
        $zfilesize = @ereg_replace("{$zfilesize}", "{$zfilesize}|", $zfilesize);
        $sizelist .= "{$zfilesize}";
        $zfile = strstr($listcontent, "--filename");
        $zfile = ereg_replace("--filename:", "", $zfile);
        $zfile = @ereg_replace("{$zfile}", "{$zfile}|", $zfile);
        $savelist .= "{$zfile}";
    }
}
Exemplo n.º 21
0
 /**
  * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...)
  *
  * Generally, the package provided is in the form of a zip file, so the function
  * has been written to test a zip file. If not a zip, the function will return the
  * default return value: ''
  * @param    string    the path to the file
  * @param    string     the original name of the file
  * @return    string    'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  */
 public static function get_package_type($file_path, $file_name)
 {
     // Get name of the zip file without the extension.
     $file_info = pathinfo($file_name);
     $filename = $file_info['basename'];
     // Name including extension.
     $extension = $file_info['extension'];
     // Extension only.
     if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), array('dll', 'exe'))) {
         return 'oogie';
     }
     if (!empty($_POST['woogie']) && !in_array(strtolower($extension), array('dll', 'exe'))) {
         return 'woogie';
     }
     $file_base_name = str_replace('.' . $extension, '', $filename);
     // Filename without its extension.
     $zipFile = new PclZip($file_path);
     // Check the zip content (real size and file extension).
     $zipContentArray = $zipFile->listContent();
     $package_type = '';
     $at_root = false;
     $manifest = '';
     // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
     if (is_array($zipContentArray) && count($zipContentArray) > 0) {
         foreach ($zipContentArray as $thisContent) {
             if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                 // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
             } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
                 $manifest = $thisContent['filename'];
                 // Just the relative directory inside scorm/
                 $package_type = 'scorm';
                 break;
                 // Exit the foreach loop.
             } elseif (preg_match('/aicc\\//i', $thisContent['filename'])) {
                 // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
                 $package_type = 'aicc';
                 //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
             } else {
                 $package_type = '';
             }
         }
     }
     return $package_type;
 }
Exemplo n.º 22
0
 function find_working_bin_zip($logit = true, $cacheit = true)
 {
     if ($this->detect_safe_mode()) {
         return false;
     }
     // The hosting provider may have explicitly disabled the popen or proc_open functions
     if (!function_exists('popen') || !function_exists('proc_open') || !function_exists('escapeshellarg')) {
         if ($cacheit) {
             $this->jobdata_set('binzip', false);
         }
         return false;
     }
     $existing = $this->jobdata_get('binzip', null);
     # Theoretically, we could have moved machines, due to a migration
     if (null !== $existing && (!is_string($existing) || @is_executable($existing))) {
         return $existing;
     }
     $updraft_dir = $this->backups_dir_location();
     foreach (explode(',', UPDRAFTPLUS_ZIP_EXECUTABLE) as $potzip) {
         if (!@is_executable($potzip)) {
             continue;
         }
         if ($logit) {
             $this->log("Testing: {$potzip}");
         }
         # Test it, see if it is compatible with Info-ZIP
         # If you have another kind of zip, then feel free to tell me about it
         @mkdir($updraft_dir . '/binziptest/subdir1/subdir2', 0777, true);
         file_put_contents($updraft_dir . '/binziptest/subdir1/subdir2/test.html', '<html></body><a href="https://updraftplus.com">UpdraftPlus is a great backup and restoration plugin for WordPress.</body></html>');
         @unlink($updraft_dir . '/binziptest/test.zip');
         if (is_file($updraft_dir . '/binziptest/subdir1/subdir2/test.html')) {
             $exec = "cd " . escapeshellarg($updraft_dir) . "; {$potzip} -v -u -r binziptest/test.zip binziptest/subdir1";
             $all_ok = true;
             $handle = popen($exec, "r");
             if ($handle) {
                 while (!feof($handle)) {
                     $w = fgets($handle);
                     if ($w && $logit) {
                         $this->log("Output: " . trim($w));
                     }
                 }
                 $ret = pclose($handle);
                 if ($ret != 0) {
                     if ($logit) {
                         $this->log("Binary zip: error (code: {$ret})");
                     }
                     $all_ok = false;
                 }
             } else {
                 if ($logit) {
                     $this->log("Error: popen failed");
                 }
                 $all_ok = false;
             }
             # Now test -@
             if (true == $all_ok) {
                 file_put_contents($updraft_dir . '/binziptest/subdir1/subdir2/test2.html', '<html></body><a href="https://updraftplus.com">UpdraftPlus is a really great backup and restoration plugin for WordPress.</body></html>');
                 $exec = $potzip . " -v -@ binziptest/test.zip";
                 $all_ok = true;
                 $descriptorspec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
                 $handle = proc_open($exec, $descriptorspec, $pipes, $updraft_dir);
                 if (is_resource($handle)) {
                     if (!fwrite($pipes[0], "binziptest/subdir1/subdir2/test2.html\n")) {
                         @fclose($pipes[0]);
                         @fclose($pipes[1]);
                         @fclose($pipes[2]);
                         $all_ok = false;
                     } else {
                         fclose($pipes[0]);
                         while (!feof($pipes[1])) {
                             $w = fgets($pipes[1]);
                             if ($w && $logit) {
                                 $this->log("Output: " . trim($w));
                             }
                         }
                         fclose($pipes[1]);
                         while (!feof($pipes[2])) {
                             $last_error = fgets($pipes[2]);
                             if (!empty($last_error) && $logit) {
                                 $this->log("Stderr output: " . trim($w));
                             }
                         }
                         fclose($pipes[2]);
                         $ret = proc_close($handle);
                         if ($ret != 0) {
                             if ($logit) {
                                 $this->log("Binary zip: error (code: {$ret})");
                             }
                             $all_ok = false;
                         }
                     }
                 } else {
                     if ($logit) {
                         $this->log("Error: proc_open failed");
                     }
                     $all_ok = false;
                 }
             }
             // Do we now actually have a working zip? Need to test the created object using PclZip
             // If it passes, then remove dirs and then return $potzip;
             $found_first = false;
             $found_second = false;
             if ($all_ok && file_exists($updraft_dir . '/binziptest/test.zip')) {
                 if (!class_exists('PclZip')) {
                     require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
                 }
                 $zip = new PclZip($updraft_dir . '/binziptest/test.zip');
                 $foundit = 0;
                 if (($list = $zip->listContent()) != 0) {
                     foreach ($list as $obj) {
                         if ($obj['filename'] && !empty($obj['stored_filename']) && 'binziptest/subdir1/subdir2/test.html' == $obj['stored_filename'] && $obj['size'] == 128) {
                             $found_first = true;
                         }
                         if ($obj['filename'] && !empty($obj['stored_filename']) && 'binziptest/subdir1/subdir2/test2.html' == $obj['stored_filename'] && $obj['size'] == 135) {
                             $found_second = true;
                         }
                     }
                 }
             }
             $this->remove_binzip_test_files($updraft_dir);
             if ($found_first && $found_second) {
                 if ($logit) {
                     $this->log("Working binary zip found: {$potzip}");
                 }
                 if ($cacheit) {
                     $this->jobdata_set('binzip', $potzip);
                 }
                 return $potzip;
             }
         }
         $this->remove_binzip_test_files($updraft_dir);
     }
     if ($cacheit) {
         $this->jobdata_set('binzip', false);
     }
     return false;
 }
Exemplo n.º 23
0
                 $inserterrors[] = 'File (' . $file . ') does not exist.';
             }
         }
     }
     if ($my_uploader->upload_failed()) {
         array_push($inserterrors, $my_uploader->get_error());
     }
     if (count($inserterrors) > 0) {
         error('admin.php?action=db&job=query', $inserterrors);
     } else {
         $ext = get_extension($file);
         if (($ext == 'zip' || $ext == 'sql') && file_exists($file)) {
             if ($ext == 'zip') {
                 require_once 'classes/class.zip.php';
                 $archive = new PclZip($file);
                 if (($list = $archive->listContent()) == 0) {
                     error($archive->errorInfo(true));
                 }
                 $data = $archive->extractByIndex($list[0]['index'], PCLZIP_OPT_EXTRACT_AS_STRING);
                 $lines = $data[0]['content'];
                 unset($data);
             } elseif ($ext == 'sql') {
                 $lines = file_get_contents($file);
             }
         }
     }
 } else {
     $lines = $gpc->get('query', none);
 }
 $sql = str_replace('{:=DBPREFIX=:}', $db->pre, $lines);
 @exec_query_form($lines);
Exemplo n.º 24
0
 public function get_file_list($zip_file)
 {
     $file_list = array();
     // Use ZipArchive if available
     if (in_array('ziparchive', $this->_zip_methods)) {
         // Make doubly sure it is available
         if (class_exists('ZipArchive', false)) {
             $za = new ZipArchive();
             $result = $za->open($zip_file);
             // Make sure we opened the zip ok and it has content
             if ($result === true) {
                 if (($file_count = $za->numFiles) > 0) {
                     // Get each file in sequence by index and get the properties
                     for ($i = 0; $i < $file_count; $i++) {
                         $stat = $za->statIndex($i);
                         // Assume all these keys do exist (consider testing)
                         $file_list[] = array($stat['name'], $stat['size'], $stat['comp_size'], $stat['mtime']);
                     }
                 }
                 $za->close();
                 return $file_list;
             } else {
                 // Couldn't open archive - drop through as maybe other method will succeed?
                 $error_string = $this->ziparchive_error_info($result);
                 pb_backupbuddy::status('details', sprintf(__('ZipArchive failed to open file to list content in file %1$s - Error Info: %2$s.', 'it-l10n-backupbuddy'), $zip_file, $error_string));
             }
         } else {
             // Something fishy - the methods indicated ziparchive but we couldn't find the class
             pb_backupbuddy::status('details', __('ziparchive indicated as available method but ZipArchive class non-existent', 'it-l10n-backupbuddy'));
         }
     }
     // Dropped through because ZipArchive not available or failed to open file
     if (in_array('pclzip', $this->_zip_methods)) {
         // Make sure we have it
         if (!class_exists('PclZip', false)) {
             // It's not already loaded so try and find/load it from possible locations
             if (file_exists(ABSPATH . 'wp-admin/includes/class-pclzip.php')) {
                 // Running under WordPress
                 @(include_once ABSPATH . 'wp-admin/includes/class-pclzip.php');
             } elseif (file_exists(pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php')) {
                 // Running Standalone (importbuddy)
                 @(include_once pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php');
             }
         }
         // Make sure we did load it
         if (class_exists('PclZip', false)) {
             $za = new PclZip($zip_file);
             // Make sure we opened the zip ok and it has content
             if (($content_list = $za->listContent()) !== 0) {
                 $file_count = sizeof($content_list);
                 // Get each file in sequence by index and get the properties
                 for ($i = 0; $i < $file_count; $i++) {
                     $stat = $content_list[$i];
                     // Assume all these keys do exist (consider testing)
                     $file_list[] = array($stat['filename'], $stat['size'], $stat['compressed_size'], $stat['mtime']);
                 }
                 return $file_list;
             } else {
                 // Couldn't open archive - drop through as maybe other method will succeed?
                 $error_string = $za->errorInfo(true);
                 pb_backupbuddy::status('details', sprintf(__('PclZip failed to open file to list content in file %1$s - Error Info: %2$s.', 'it-l10n-backupbuddy'), $zip_file, $error_string));
             }
         } else {
             // Something fishy - the methods indicated pclzip but we couldn't find the class
             pb_backupbuddy::status('details', __('pclzip indicated as available method but class PclZip non-existent', 'it-l10n-backupbuddy'));
         }
     }
     // If we got this far then no method to list backup content was available or worked
     return false;
 }
Exemplo n.º 25
0
     }
     html_footer();
     break;
 case "listzip":
     html_header($course, $wdir);
     if (!empty($file) and confirm_sesskey()) {
         $strname = get_string("name");
         $strsize = get_string("size");
         $strmodified = get_string("modified");
         $strok = get_string("ok");
         $strlistfiles = get_string("listfiles", "", $file);
         echo "<p align=\"center\">{$strlistfiles}:</p>";
         $file = basename($file);
         require_once $CFG->libdir . '/pclzip/pclzip.lib.php';
         $archive = new PclZip("{$basedir}/{$wdir}/{$file}");
         if (!($list = $archive->listContent("{$basedir}/{$wdir}"))) {
             notify($archive->errorInfo(true));
         } else {
             echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\">\n";
             echo "<tr>\n<th align=\"left\" scope=\"col\">{$strname}</th><th align=\"right\" scope=\"col\">{$strsize}</th><th align=\"right\" scope=\"col\">{$strmodified}</th></tr>";
             foreach ($list as $item) {
                 echo "<tr>";
                 print_cell("left", $item['filename']);
                 if (!$item['folder']) {
                     print_cell("right", display_size($item['size']));
                 } else {
                     echo "<td>&nbsp;</td>\n";
                 }
                 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
                 print_cell("right", $filedate);
                 echo "</tr>\n";
Exemplo n.º 26
0
 function upload_zip($imagefile)
 {
     if (!mkdir($tmpdir = $this->config->pathto_cache . '/' . uniqid("ps"))) {
         $this->last_error = "Your cache directory is not writeable, please check the permissions.";
         return false;
     }
     $archive = $imagefile["tmp_name"];
     if (!is_uploaded_file($archive)) {
         $this->last_error = "Could not upload file";
         return false;
     }
     switch ($this->config->unzip_method) {
         case 'unzip':
             //decompress archive to temp
             $cmd = escapeshellcmd($this->config->pathto_unzip);
             $cmd .= ' -d "' . escapeshellcmd(realpath($tmpdir));
             $cmd .= '" "' . escapeshellcmd(realpath($archive)) . '"';
             if (!exec($cmd)) {
                 $this->last_error = "Could not decompress archive";
                 return false;
             }
             break;
         case 'pclzip':
             /* 
             				This uses the PclZip Library to extract the files of the zip-archive
             */
             $zip = new PclZip(realpath($archive));
             $archiveContents = $zip->listContent();
             foreach ($archiveContents as $file) {
                 if (preg_match("/\\.(" . $this->config->recognised_extensions . ")\$/i", $file['filename'])) {
                     //if(stristr($file['filename'],'/') === FALSE){
                     $imageIndex .= $file['index'] . ",";
                     //}
                 }
             }
             $imageIndex = substr($imageIndex, 0, strlen($imageIndex) - 1);
             $zip->extractByIndex($imageIndex, $tmpdir);
             break;
     }
     //start processing archive contents
     $wd = $tmpdir;
     $contents = $this->get_listing($wd, "images");
     //cope with archives contained within a directory
     if (empty($contents->files) && count($contents->dirs) == 1) {
         $contents = $this->get_listing($wd .= '/' . $contents->dirs[0], "images");
     }
     $success = true;
     //add any images to current gallery
     foreach ($contents->files as $image) {
         //make sure file has a recognised extension
         if (!preg_match("/\\.(" . $this->config->recognised_extensions . ")\$/i", $image)) {
             $image .= ".jpeg";
         }
         $path = $this->config->pathto_galleries . $this->gallery->id . "/" . $image;
         $srcImage = $image;
         if (file_exists($path)) {
             switch ($this->config->upload_overwrite) {
                 case 1:
                     //overwrite
                     $this->delete_image($image);
                     break;
                 case 2:
                     //generate unique
                     for ($i = 0; file_exists($path); $i++) {
                         $pivot = strrpos($srcImage, ".");
                         $image = substr($srcImage, 0, $pivot) . '-' . $i . substr($srcImage, $pivot, strlen($srcImage) - $pivot);
                         $path = $this->config->pathto_galleries . $this->gallery->id . "/" . $image;
                     }
                     break;
                 case 0:
                     //raise error
                 //raise error
                 default:
                     $this->last_error = "File already exists";
                     $success = false;
                     continue;
             }
         }
         copy($wd . '/' . $srcImage, $path);
         @chmod($path, octdec($this->config->chmod_value));
         $img = new image();
         $img->filename = $image;
         $img->name = strtr(substr($image, strrpos($image, "/"), strrpos($image, ".") - strlen($image)), "_", " ");
         list($img->width, $img->height, $img->type) = GetImageSize($path);
         $this->gallery->images[count($this->gallery->images)] = $img;
     }
     //add any directories as subgalleries, if allowed
     foreach ($contents->dirs as $gallery) {
         if ($gallery != '__MACOSX') {
             $path = $this->config->pathto_galleries . $this->gallery->id . "/" . $gallery;
             if (file_exists($path)) {
                 switch ($this->config->upload_overwrite) {
                     case 1:
                         //overwrite
                         $this->delete_gallery($this->gallery->id . '/' . $gallery);
                         break;
                     case 2:
                         //generate unique
                         for ($i = 0; file_exists($path); $i++) {
                             $path = $this->config->pathto_galleries . $this->gallery->id . "/" . $gallery . '-' . $i;
                         }
                         break;
                     case 0:
                         //raise error
                     //raise error
                     default:
                         $success = false;
                         continue;
                 }
             }
             rename($wd . '/' . $gallery, $path);
             chmod($path, octdec($this->config->chmod_value));
         }
     }
     //if images were added save metadata
     if (!empty($contents->files)) {
         $success &= $this->io->put_gallery($this->gallery);
     }
     //if subgalleries were added reload gallery data
     if (!empty($contents->dirs)) {
         $this->select_gallery();
     }
     //remove temporary directory
     $this->rmdir_all($tmpdir);
     if (!$success) {
         $this->last_error = "Some archive contents could not be added";
     }
     return $success;
 }
Exemplo n.º 27
0
function ftp_unziptransferfiles($archivesArray)
{
    // --------------
    // Extract the directories and files from the archive to a temporary directory on the web server, and
    // then create the directories and put the files on the FTP server
    // --------------
    // -------------------------------------------------------------------------
    // Global variables
    // -------------------------------------------------------------------------
    global $net2ftp_globals, $net2ftp_result, $net2ftp_output;
    // -------------------------------------------------------------------------
    // Open connection
    // -------------------------------------------------------------------------
    $conn_id = ftp_openconnection();
    if ($net2ftp_result["success"] == false) {
        for ($archive_nr = 1; $archive_nr <= sizeof($archivesArray); $archive_nr++) {
            @unlink($archivesArray[$archive_nr]["tmp_name"]);
        }
        return false;
    }
    // -------------------------------------------------------------------------
    // For each archive...
    // -------------------------------------------------------------------------
    for ($archive_nr = 1; $archive_nr <= sizeof($archivesArray); $archive_nr++) {
        // Set status
        setStatus($archive_nr, sizeof($archivesArray), __("Decompressing archives and transferring files"));
        // -------------------------------------------------------------------------
        // Determine the type of archive depending on the filename extension
        // -------------------------------------------------------------------------
        $archive_name = $archivesArray[$archive_nr]["name"];
        $archive_file = $archivesArray[$archive_nr]["tmp_name"];
        $archivename_without_dottext = substr($archivesArray[$archive_nr]["tmp_name"], 0, strlen($archive) - 4);
        $archive_type = get_filename_extension($archivename_without_dottext);
        $net2ftp_output["ftp_unziptransferfiles"][] = __("Processing archive nr %1\$s: <b>%2\$s</b>", $archive_nr, $archive_name);
        $net2ftp_output["ftp_unziptransferfiles"][] = "<ul>";
        if ($archive_type != "zip" && $archive_type != "tar" && $archive_type != "tgz" && $archive_type != "gz") {
            $net2ftp_output["ftp_unziptransferfiles"][] = __("Archive <b>%1\$s</b> was not processed because its filename extension was not recognized. Only zip, tar, tgz and gz archives are supported at the moment.", $archive_name);
            continue;
        }
        // -------------------------------------------------------------------------
        // Extract directories and files
        // -------------------------------------------------------------------------
        // ------------------------------
        // Check list of files to see if there are any malicious filenames
        // ------------------------------
        if ($archive_type == "zip") {
            $zip = new PclZip($archive_file);
            $list_to_check = $zip->listContent();
        } elseif ($archive_type == "tar" || $archive_type == "tgz" || $archive_type == "gz") {
            $list_to_check = PclTarList($archive_file);
        }
        if ($list_to_check <= 0) {
            $net2ftp_output["ftp_unziptransferfiles"][] = __("Unable to extract the files and directories from the archive");
            continue;
        }
        for ($i = 0; $i < sizeof($list_to_check); $i++) {
            $source = trim($list_to_check[$i]["filename"]);
            if (strpos($source, "../") !== false || strpos($source, "..\\") !== false) {
                $errormessage = __("Archive contains filenames with ../ or ..\\ - aborting the extraction");
                setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
                return false;
            }
        }
        // ------------------------------
        // Generate random directory
        // ------------------------------
        $tempdir = tempdir2($net2ftp_globals["application_tempdir"], "unzip__", "");
        if ($net2ftp_result["success"] == false) {
            return false;
        }
        registerTempfile("register", "{$tempdir}");
        // ------------------------------
        // Extract
        // ------------------------------
        if ($archive_type == "zip") {
            $zip = new PclZip($archive_file);
            $list = $zip->extract($p_path = $tempdir);
        } elseif ($archive_type == "tar" || $archive_type == "tgz" || $archive_type == "gz") {
            $list = PclTarExtract($archive_file, $tempdir);
        }
        // This code is not needed any more - see above: if ($list_to_check <= 0)
        if ($list <= 0) {
            //			$net2ftp_output["ftp_unziptransferfiles"][] = __("Unable to extract the files and directories from the archive");
            continue;
        }
        // ------------------------------
        // Create the directories and put the files on the FTP server
        // ------------------------------
        for ($i = 0; $i < sizeof($list); $i++) {
            $source = trim($list[$i]["filename"]);
            $unzip_status = trim($list[$i]["status"]);
            $target_relative = substr($source, strlen($tempdir));
            $target = $net2ftp_globals["directory"] . $target_relative;
            $ftpmode = ftpAsciiBinary($source);
            if ($unzip_status != "ok") {
                $net2ftp_output["ftp_unziptransferfiles"][] = __("Could not unzip entry %1\$s (error code %2\$s)", $target_relative, $unzip_status);
                setErrorVars(true, "", "", "", "");
                continue;
            }
            // Directory entry in the archive: create the directory
            if (is_dir($source) == true) {
                ftp_newdirectory($conn_id, $target);
                if ($net2ftp_result["success"] == true) {
                    $net2ftp_output["ftp_unziptransferfiles"][] = __("Created directory %1\$s", $target);
                } else {
                    $net2ftp_output["ftp_unziptransferfiles"][] = __("Could not create directory %1\$s", $target);
                    setErrorVars(true, "", "", "", "");
                }
            } elseif (is_file($source) == true) {
                ftp_putfile($conn_id, dirname($source), basename($source), dirname($target), basename($target), $ftpmode, "move");
                if ($net2ftp_result["success"] == true) {
                    $net2ftp_output["ftp_unziptransferfiles"][] = __("Copied file %1\$s", $target);
                } else {
                    setErrorVars(true, "", "", "", "");
                    $target_relative_parts = explode("/", str_replace("\\", "/", dirname($target_relative)));
                    $directory_to_create = $net2ftp_globals["directory"];
                    for ($j = 0; $j < sizeof($target_relative_parts); $j = $j + 1) {
                        $directory_to_create = $directory_to_create . "/" . $target_relative_parts[$j];
                        $ftp_chdir_result = @ftp_chdir($conn_id, $directory_to_create);
                        if ($ftp_chdir_result == false) {
                            ftp_newdirectory($conn_id, $directory_to_create);
                            if ($net2ftp_result["success"] == true) {
                                $net2ftp_output["ftp_unziptransferfiles"][] = __("Created directory %1\$s", $directory_to_create);
                            } else {
                                setErrorVars(true, "", "", "", "");
                            }
                        }
                        // end if
                    }
                    // end for
                    ftp_putfile($conn_id, dirname($source), basename($source), dirname($target), basename($target), $ftpmode, "copy");
                    if ($net2ftp_result["success"] == true) {
                        $net2ftp_output["ftp_unziptransferfiles"][] = __("Copied file %1\$s", $target);
                    } else {
                        setErrorVars(true, "", "", "", "");
                        $net2ftp_output["ftp_unziptransferfiles"][] = __("Could not copy file %1\$s", $target);
                    }
                }
            }
            // end elseif file
        }
        // end for
        // -------------------------------------------------------------------------
        // Delete the uploaded archive and the temporary files
        // -------------------------------------------------------------------------
        // Delete the temporary directory and its contents
        $delete_dirorfile_result = delete_dirorfile($tempdir);
        if ($delete_dirorfile_result == false) {
            $net2ftp_output["ftp_unziptransferfiles"][] = __("Unable to delete the temporary directory");
        } else {
            registerTempfile("unregister", "{$tempdir}");
        }
        // Delete the archive
        $unlink_result = @unlink($archive_file);
        if ($unlink_result == false) {
            $net2ftp_output["ftp_unziptransferfiles"][] = __("Unable to delete the temporary file %1\$s", $archive_file);
        } else {
            registerTempfile("unregister", "{$archive_file}");
        }
        $net2ftp_output["ftp_unziptransferfiles"][] = "</ul>";
    }
    // End for
    // -------------------------------------------------------------------------
    // Close connection
    // -------------------------------------------------------------------------
    ftp_closeconnection($conn_id);
}
Exemplo n.º 28
0
     }
     html_footer();
     break;
 case "listzip":
     html_header($course, $wdir);
     if ($file != '' and confirm_sesskey()) {
         $strname = get_string("name");
         $strsize = get_string("size");
         $strmodified = get_string("modified");
         $strok = get_string("ok");
         $strlistfiles = get_string("listfiles", "", $file);
         echo "<p align=\"center\">{$strlistfiles}:</p>";
         $file = basename($file);
         include_once "{$CFG->libdir}/pclzip/pclzip.lib.php";
         $archive = new PclZip(cleardoubleslashes("{$basedir}{$wdir}/{$file}"));
         if (!($list = $archive->listContent(cleardoubleslashes("{$basedir}{$wdir}")))) {
             notify($archive->errorInfo(true));
         } else {
             echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\" width=\"640\" class=\"files\">";
             echo "<tr class=\"file\"><th align=\"left\" class=\"header name\" scope=\"col\">{$strname}</th><th align=\"right\" class=\"header size\" scope=\"col\">{$strsize}</th><th align=\"right\" class=\"header date\" scope=\"col\">{$strmodified}</th></tr>";
             foreach ($list as $item) {
                 echo "<tr>";
                 print_cell("left", s($item['filename']), 'name');
                 if (!$item['folder']) {
                     print_cell("right", display_size($item['size']), 'size');
                 } else {
                     echo "<td>&nbsp;</td>";
                 }
                 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
                 print_cell("right", $filedate, 'date');
                 echo "</tr>";
Exemplo n.º 29
0
function importSurveyFile($sFullFilepath, $bTranslateLinksFields, $sNewSurveyName = NULL, $DestSurveyID = NULL)
{
    $aPathInfo = pathinfo($sFullFilepath);
    if (isset($aPathInfo['extension'])) {
        $sExtension = $aPathInfo['extension'];
    } else {
        $sExtension = "";
    }
    if (isset($sExtension) && strtolower($sExtension) == 'csv') {
        return CSVImportSurvey($sFullFilepath, $DestSurveyID, $bTranslateLinksFields);
    } elseif (isset($sExtension) && strtolower($sExtension) == 'lss') {
        return XMLImportSurvey($sFullFilepath, null, $sNewSurveyName, $DestSurveyID, $bTranslateLinksFields);
    } elseif (isset($sExtension) && strtolower($sExtension) == 'txt') {
        return TSVImportSurvey($sFullFilepath);
    } elseif (isset($sExtension) && strtolower($sExtension) == 'lsa') {
        Yii::import("application.libraries.admin.pclzip.pclzip", true);
        $pclzip = new PclZip(array('p_zipname' => $sFullFilepath));
        $aFiles = $pclzip->listContent();
        if ($pclzip->extract(PCLZIP_OPT_PATH, Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, PCLZIP_OPT_BY_EREG, '/(lss|lsr|lsi|lst)$/') == 0) {
            unset($pclzip);
        }
        // Step 1 - import the LSS file and activate the survey
        foreach ($aFiles as $aFile) {
            if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lss') {
                //Import the LSS file
                $aImportResults = XMLImportSurvey(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename'], null, null, null, true);
                // Activate the survey
                Yii::app()->loadHelper("admin/activate");
                $activateoutput = activateSurvey($aImportResults['newsid']);
                unlink(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename']);
                break;
            }
        }
        // Step 2 - import the responses file
        foreach ($aFiles as $aFile) {
            if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lsr') {
                //Import the LSS file
                $aResponseImportResults = XMLImportResponses(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename'], $aImportResults['newsid'], $aImportResults['FieldReMap']);
                $aImportResults = array_merge($aResponseImportResults, $aImportResults);
                unlink(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename']);
                break;
            }
        }
        // Step 3 - import the tokens file - if exists
        foreach ($aFiles as $aFile) {
            if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lst') {
                Yii::app()->loadHelper("admin/token");
                if (createTokenTable($aImportResults['newsid'])) {
                    $aTokenCreateResults = array('tokentablecreated' => true);
                }
                $aImportResults = array_merge($aTokenCreateResults, $aImportResults);
                $aTokenImportResults = XMLImportTokens(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename'], $aImportResults['newsid']);
                $aImportResults = array_merge($aTokenImportResults, $aImportResults);
                unlink(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename']);
                break;
            }
        }
        // Step 4 - import the timings file - if exists
        foreach ($aFiles as $aFile) {
            if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lsi' && tableExists("survey_{$aImportResults['newsid']}_timings")) {
                $aTimingsImportResults = XMLImportTimings(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename'], $aImportResults['newsid'], $aImportResults['FieldReMap']);
                $aImportResults = array_merge($aTimingsImportResults, $aImportResults);
                unlink(Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $aFile['filename']);
                break;
            }
        }
        return $aImportResults;
    } else {
        return null;
    }
}
Exemplo n.º 30
0
 /**
  * Imports a zip file into the Chamilo structure
  * @param    string    Zip file info as given by $_FILES['userFile']
  * @return    string    Absolute path to the imsmanifest.xml file or empty string on error
  */
 function import_package($zip_file_info, $current_dir = '')
 {
     if ($this->debug > 0) {
         error_log('In scorm::import_package(' . print_r($zip_file_info, true) . ',"' . $current_dir . '") method', 0);
     }
     $maxFilledSpace = DocumentManager::get_course_quota();
     $zip_file_path = $zip_file_info['tmp_name'];
     $zip_file_name = $zip_file_info['name'];
     if ($this->debug > 1) {
         error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0);
     }
     // scorm dir web path starting from /courses
     $course_rel_dir = api_get_course_path() . '/scorm';
     $course_sys_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir;
     // Absolute system path for this course.
     if (!is_dir($course_sys_dir)) {
         mkdir($course_sys_dir, api_get_permissions_for_new_directories());
     }
     $current_dir = api_replace_dangerous_char(trim($current_dir), 'strict');
     // Current dir we are in, inside scorm/
     if ($this->debug > 1) {
         error_log('New LP - import_package() - current_dir = ' . $current_dir, 0);
     }
     //$uploaded_filename = $_FILES['userFile']['name'];
     // Get name of the zip file without the extension.
     if ($this->debug > 1) {
         error_log('New LP - Received zip file name: ' . $zip_file_path, 0);
     }
     $file_info = pathinfo($zip_file_name);
     $filename = $file_info['basename'];
     $extension = $file_info['extension'];
     $file_base_name = str_replace('.' . $extension, '', $filename);
     // Filename without its extension.
     $this->zipname = $file_base_name;
     // Save for later in case we don't have a title.
     if ($this->debug > 1) {
         error_log("New LP - base file name is : " . $file_base_name, 0);
     }
     $new_dir = api_replace_dangerous_char(trim($file_base_name), 'strict');
     $this->subdir = $new_dir;
     if ($this->debug > 1) {
         error_log("New LP - subdir is first set to : " . $this->subdir, 0);
     }
     $zipFile = new PclZip($zip_file_path);
     // Check the zip content (real size and file extension).
     $zipContentArray = $zipFile->listContent();
     $package_type = '';
     $at_root = false;
     $manifest = '';
     $realFileSize = 0;
     $manifest_list = array();
     // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
     foreach ($zipContentArray as $thisContent) {
         $file = $thisContent['filename'];
         //error_log('Looking at  '.$thisContent['filename'], 0);
         if (preg_match('~.(php.*|phtml)$~i', $file)) {
             $this->set_error_msg("File {$file} contains a PHP script");
             //return api_failure::set_failure('php_file_in_zip_file');
         } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
             //error_log('Found imsmanifest at '.$thisContent['filename'], 0);
             if ($thisContent['filename'] == basename($thisContent['filename'])) {
                 $at_root = true;
             } else {
                 //$this->subdir .= '/'.dirname($thisContent['filename']);
                 if ($this->debug > 2) {
                     error_log("New LP - subdir is now " . $this->subdir, 0);
                 }
             }
             $package_type = 'scorm';
             $manifest_list[] = $thisContent['filename'];
             $manifest = $thisContent['filename'];
             //just the relative directory inside scorm/
         } else {
             // Do nothing, if it has not been set as scorm somewhere else, it stays as '' default.
         }
         $realFileSize += $thisContent['size'];
     }
     // Now get the shortest path (basically, the imsmanifest that is the closest to the root).
     $shortest_path = $manifest_list[0];
     $slash_count = substr_count($shortest_path, '/');
     foreach ($manifest_list as $manifest_path) {
         $tmp_slash_count = substr_count($manifest_path, '/');
         if ($tmp_slash_count < $slash_count) {
             $shortest_path = $manifest_path;
             $slash_count = $tmp_slash_count;
         }
     }
     $this->subdir .= '/' . dirname($shortest_path);
     // Do not concatenate because already done above.
     $manifest = $shortest_path;
     if ($this->debug > 1) {
         error_log('New LP - Package type is now ' . $package_type, 0);
     }
     // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
     if ($package_type == '') {
         if ($this->debug > 1) {
             error_log('New LP - Package type is empty', 0);
         }
         return api_failure::set_failure('not_scorm_content');
     }
     // It happens on Linux that $new_dir sometimes doesn't start with '/'
     if ($new_dir[0] != '/') {
         $new_dir = '/' . $new_dir;
     }
     if ($new_dir[strlen($new_dir) - 1] == '/') {
         $new_dir = substr($new_dir, 0, -1);
     }
     $isDir = is_dir($course_sys_dir . $new_dir);
     if ($isDir == false) {
         mkdir($course_sys_dir . $new_dir, api_get_permissions_for_new_directories());
         $isDir = is_dir($course_sys_dir . $new_dir);
     }
     /* Uncompressing phase */
     /*
         We need to process each individual file in the zip archive to
         - add it to the database
         - parse & change relative html links
         - make sure the filenames are secure (filter funny characters or php extensions)
     */
     if ($isDir) {
         if (!FileManager::enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
             if ($this->debug > 1) {
                 error_log('New LP - Not enough space to store package', 0);
             }
             return api_failure::set_failure('not_enough_space');
         }
         // PHP method - slower...
         if ($this->debug >= 1) {
             error_log('New LP - Changing dir to ' . $course_sys_dir . $new_dir, 0);
         }
         $saved_dir = getcwd();
         chdir($course_sys_dir . $new_dir);
         $unzippingState = $zipFile->extract();
         for ($j = 0; $j < count($unzippingState); $j++) {
             $state = $unzippingState[$j];
             // TODO: Fix relative links in html files (?)
             $extension = strrchr($state['stored_filename'], '.');
             if ($this->debug >= 1) {
                 error_log('New LP - found extension ' . $extension . ' in ' . $state['stored_filename'], 0);
             }
         }
         if (!empty($new_dir)) {
             $new_dir = $new_dir . '/';
         }
         // Rename files, for example with \\ in it.
         if ($this->debug >= 1) {
             error_log('New LP - try to open: ' . $course_sys_dir . $new_dir, 0);
         }
         if ($dir = @opendir($course_sys_dir . $new_dir)) {
             if ($this->debug >= 1) {
                 error_log('New LP - Opened dir ' . $course_sys_dir . $new_dir, 0);
             }
             while ($file = readdir($dir)) {
                 if ($file != '.' && $file != '..') {
                     $filetype = 'file';
                     if (is_dir($course_sys_dir . $new_dir . $file)) {
                         $filetype = 'folder';
                     }
                     // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
                     //$safe_file = replace_dangerous_char($file, 'strict');
                     $find_str = array('\\', '.php', '.phtml');
                     $repl_str = array('/', '.txt', '.txt');
                     $safe_file = str_replace($find_str, $repl_str, $file);
                     if ($this->debug >= 1) {
                         error_log('Comparing:  ' . $safe_file, 0);
                     }
                     if ($this->debug >= 1) {
                         error_log('and:  ' . $file, 0);
                     }
                     if ($safe_file != $file) {
                         $mydir = dirname($course_sys_dir . $new_dir . $safe_file);
                         if (!is_dir($mydir)) {
                             $mysubdirs = split('/', $mydir);
                             $mybasedir = '/';
                             foreach ($mysubdirs as $mysubdir) {
                                 if (!empty($mysubdir)) {
                                     $mybasedir = $mybasedir . $mysubdir . '/';
                                     if (!is_dir($mybasedir)) {
                                         @mkdir($mybasedir, api_get_permissions_for_new_directories());
                                         if ($this->debug >= 1) {
                                             error_log('New LP - Dir ' . $mybasedir . ' doesnt exist. Creating.', 0);
                                         }
                                     }
                                 }
                             }
                         }
                         @rename($course_sys_dir . $new_dir . $file, $course_sys_dir . $new_dir . $safe_file);
                         if ($this->debug >= 1) {
                             error_log('New LP - Renaming ' . $course_sys_dir . $new_dir . $file . ' to ' . $course_sys_dir . $new_dir . $safe_file, 0);
                         }
                     }
                 }
             }
             closedir($dir);
             chdir($saved_dir);
             api_chmod_R($course_sys_dir . $new_dir, api_get_permissions_for_new_directories());
             if ($this->debug > 1) {
                 error_log('New LP - changed back to init dir: ' . $course_sys_dir . $new_dir, 0);
             }
         }
     } else {
         return '';
     }
     return $course_sys_dir . $new_dir . $manifest;
 }