Ejemplo n.º 1
0
 /**
  * @inheritDoc
  */
 public function addFile($file, $local_name)
 {
     try {
         $this->phar->addFile($file, $local_name);
     } catch (\PharException $e) {
         return false;
     }
     return true;
 }
 public static function createArchive($arg, $origin_dir, $archive_file, $overwrite = false)
 {
     if (!extension_loaded('phar')) {
         throw new pakeException(__CLASS__ . ' module requires "phar" extension');
     }
     if (false === $overwrite and file_exists($archive_file)) {
         return true;
     }
     if (self::endsWith($archive_file, '.tar.gz')) {
         $archive_file = substr($archive_file, 0, -3);
         $compress = Phar::GZ;
         $extension = '.tar.gz';
         if (!extension_loaded('zlib')) {
             throw new pakeException('GZip compression method is not available on this system (install "zlib" extension)');
         }
     } elseif (self::endsWith($archive_file, '.tgz')) {
         $archive_file = substr($archive_file, 0, -3) . 'tar';
         $compress = Phar::GZ;
         $extension = '.tgz';
         if (!extension_loaded('zlib')) {
             throw new pakeException('GZip compression method is not available on this system (install "zlib" extension)');
         }
     } elseif (self::endsWith($archive_file, '.tar.bz2')) {
         $archive_file = substr($archive_file, 0, -4);
         $compress = Phar::BZ2;
         $extension = '.tar.bz2';
         if (!extension_loaded('bz2')) {
             throw new pakeException('BZip2 compression method is not available on this system (install "bzip2" extension)');
         }
     } elseif (self::endsWith($archive_file, '.tar') or self::endsWith($archive_file, '.zip')) {
         $compress = Phar::NONE;
     } else {
         throw new pakeException("Only .zip, .tar, .tar.gz and .tar.bz2 archives are supported");
     }
     $files = pakeFinder::get_files_from_argument($arg, $origin_dir, true);
     pake_echo_action('file+', $archive_file);
     try {
         $arc = new PharData($archive_file);
         foreach ($files as $file) {
             $full_path = $origin_dir . '/' . $file;
             pake_echo_action('archive', '-> ' . $file);
             if (is_dir($full_path)) {
                 $arc->addEmptyDir($file);
             } else {
                 $arc->addFile($full_path, $file);
             }
         }
         if (Phar::NONE !== $compress) {
             $new_name = substr($archive_file, 0, -4) . $extension;
             pake_echo_action('file+', $new_name);
             $arc->compress($compress, $extension);
             unset($arc);
             pake_remove($archive_file, '/');
         }
     } catch (PharException $e) {
         unset($arc);
         pake_remove($archive_file);
         throw $e;
     }
 }
Ejemplo n.º 3
0
 /**
  * @param  string                                     $filePath           It is the path to access the file.
  * @param  string                                     $directoryInArchive This is the directory where it will be stored in the archive
  * @param  null|string                                $name               The name of the file in the archive. if it null or empty, it keeps the same name
  * @param  bool                                       $isOnline
  * @return $this
  * @throws \Thelia\Exception\FileNotFoundException
  * @throws \Thelia\Exception\FileNotReadableException
  * @throws \ErrorException
  *
  * This methods adds a file in the archive.
  * If the file is local, $isOnline must be false,
  * If the file online, $filePath must be an URL.
  */
 public function addFile($filePath, $directoryInArchive = "/", $name = null, $isOnline = false)
 {
     if (!empty($name)) {
         $dirName = dirname($name);
         if ($dirName == ".") {
             $dirName = "";
         }
         $directoryInArchive .= '/' . $dirName;
     }
     if (empty($name) || !is_scalar($name)) {
         $name = basename($filePath);
     } else {
         $name = basename($name);
     }
     /**
      * Download the file if it is online
      * If it's local check if the file exists and if it is redable
      */
     $fileDownloadCache = $this->cacheDir . DS . md5(uniqid()) . ".tmp";
     $this->copyFile($filePath, $fileDownloadCache, $isOnline);
     /**
      * Then write the file in the archive
      */
     $directoryInArchive = $this->formatDirectoryPath($directoryInArchive);
     if (!empty($directoryInArchive)) {
         $name = $this->formatFilePath($directoryInArchive . $name);
     }
     $this->tar->addFile($filePath, $name);
     /**
      * And clear the download temp file
      */
     unlink($fileDownloadCache);
     return $this;
 }
Ejemplo n.º 4
0
 /**
  * Create package.
  */
 public function create(array $args = array())
 {
     $archBasename = $this->pkg->getSimpleName() . '-' . $this->pkg->getPrettyVersion();
     /* Work around bug  #67417 [NEW]: ::compress modifies archive basename
        creates temp file and rename it */
     $tempName = getcwd() . '/pkl-tmp.tar';
     if (file_exists($tempName)) {
         unlink($tempName);
     }
     $arch = new \PharData($tempName);
     $pkgDir = $this->pkg->getRootDir();
     foreach ($this->pkg->getFiles() as $file) {
         if (is_file($file)) {
             $name = str_replace($pkgDir, '', $file);
             $arch->addFile($file, $name);
         }
     }
     if (file_exists($tempName)) {
         @unlink($tempName . '.gz');
     }
     $arch->compress(\Phar::GZ);
     unset($arch);
     rename($tempName . '.gz', $archBasename . '.tgz');
     unlink($tempName);
     if ($this->cb) {
         $cb = $this->cb;
         $cb($this->pkg);
     }
 }
Ejemplo n.º 5
0
 public function imgCreate($tag, $dkFileData)
 {
     file_put_contents('Dockerfile', $dkFileData);
     $dkfiletar = new PharData('Dockerfile.tar');
     $dkfiletar->addFile('Dockerfile');
     //执行此行代码后生成Dockerfile.tar.gz文件
     $dkfiletar->compress(Phar::GZ);
     $this->cmObj->curlPostFile(DOCKER_URL . '/build?t=' . $tag . '&nocache=1', 'Dockerfile.tar.gz', array('Content-Type:application/tar'));
     return $this->cmObj->curlHttpCode();
 }
Ejemplo n.º 6
0
 /**
  * Create tgz archive.
  */
 public function compress()
 {
     $tarFile = $this->rootDir . '/' . $this->tmpName . '.tar';
     $tgzFile = $this->rootDir . '/' . $this->tmpName . '.tgz';
     $phar = new \PharData($tarFile);
     foreach ($this->files as $file) {
         $phar->addFile($file[0], $file[1]);
     }
     // Compress .tar file to .tgz
     $phar->compress(\Phar::GZ, '.tgz');
     rename($tgzFile, $this->rootDir . '/' . $this->name);
     // Both files (.tar and .tgz) exist. Remove the temporary .tar archive
     unlink($tarFile);
 }
Ejemplo n.º 7
0
 public function create($execution, $format, $hrefs)
 {
     $this->dirs = array();
     $this->files = array();
     $this->sc401 = false;
     $this->add_hrefs($hrefs);
     if ($this->sc401) {
         return 401;
     } else {
         if (count($this->dirs) === 0 && count($this->files) === 0) {
             return 404;
         }
     }
     $target = H5ai::normalize_path(sys_get_temp_dir(), true) . "h5ai-selection-" . microtime(true) . rand() . "." . $format;
     try {
         if ($execution === "shell") {
             if ($format === "tar") {
                 $cmd = Archive::$TAR_CMD;
             } else {
                 if ($format === "zip") {
                     $cmd = Archive::$ZIP_CMD;
                 } else {
                     return null;
                 }
             }
             $cmd = str_replace("[ROOTDIR]", "\"" . $this->h5ai->getRootAbsPath() . "\"", $cmd);
             $cmd = str_replace("[TARGET]", "\"" . $target . "\"", $cmd);
             $cmd = str_replace("[DIRS]", count($this->dirs) ? "\"" . implode("\"  \"", array_values($this->dirs)) . "\"" : "", $cmd);
             $cmd = str_replace("[FILES]", count($this->files) ? "\"" . implode("\"  \"", array_values($this->files)) . "\"" : "", $cmd);
             `{$cmd}`;
         } else {
             if ($execution === "php") {
                 $archive = new PharData($target);
                 foreach ($this->dirs as $archivedDir) {
                     $archive->addEmptyDir($archivedDir);
                 }
                 foreach ($this->files as $realFile => $archivedFile) {
                     $archive->addFile($realFile, $archivedFile);
                     // very, very slow :/
                 }
             }
         }
     } catch (Exeption $err) {
         return 500;
     }
     return @filesize($target) ? $target : null;
 }
Ejemplo n.º 8
0
 /**
  * Archiving the file
  *
  * @param unknown $filePath
  * @param string $preFix
  * @param string $debug
  * @throws Exception
  */
 private static function _zipFile($files, $preFix = '', $debug = false)
 {
     $tarFilePath = self::$_outputFileDir . '/' . self::FILE_NAME . '.tar';
     $start = self::_log('== Archiving the file: ' . $tarFilePath, __CLASS__ . '::' . __FUNCTION__, $preFix);
     $csvFilePath = '/tmp/' . md5('ProductToMagento_CSV_' . trim(UDate::now())) . '.csv';
     $tarFile = new PharData($tarFilePath);
     //add csv file
     self::_log('Generating the CSV file: ' . $csvFilePath, '', $preFix . self::TAB);
     $objWriter = PHPExcel_IOFactory::createWriter($files['phpExcel'], 'CSV');
     $objWriter->save($csvFilePath);
     self::_log('Adding the CSV file to: ' . $tarFilePath, '', $preFix . self::TAB);
     $tarFile->addFile($csvFilePath, self::FILE_NAME . '.csv');
     //add image files
     if (isset($files['imageFiles']) && count($files['imageFiles']) > 0) {
         $imageDir = self::$_imageDirName;
         $tarFile->addEmptyDir($imageDir);
         foreach ($files['imageFiles'] as $index => $imageFile) {
             self::_log('Processing file: ' . $index, '', $preFix . self::TAB . self::TAB);
             if (!isset($imageFile['filePath'])) {
                 self::_log('No File Path SET. SKIP ', '', $preFix . self::TAB . self::TAB . self::TAB);
                 continue;
             }
             if (!is_file($imageFile['filePath'])) {
                 self::_log('File NOT FOUND: ' . $imageFile['filePath'], '', $preFix . self::TAB . self::TAB . self::TAB);
                 continue;
             }
             $tarFile->addFile($imageFile['filePath'], $imageDir . '/' . $imageFile['fileName']);
             self::_log('Added File:' . $imageFile['fileName'] . ', from path: ' . $imageFile['filePath'], '', $preFix . self::TAB . self::TAB . self::TAB);
         }
     } else {
         self::_log('No image files to add.', '', $preFix . self::TAB);
     }
     // COMPRESS archive.tar FILE. COMPRESSED FILE WILL BE archive.tar.gz
     self::_log('Compressing file: ' . $tarFilePath, '', $preFix . self::TAB . self::TAB . self::TAB);
     $tarFile->compress(Phar::GZ);
     // NOTE THAT BOTH FILES WILL EXISTS. SO IF YOU WANT YOU CAN UNLINK archive.tar
     self::_log('REMOVING the orginal file: ' . $tarFilePath, '', $preFix . self::TAB);
     unlink($tarFilePath);
     self::_log('REMOVED', '', $preFix . self::TAB . self::TAB);
     //remving temp csv file
     self::_log('REMOVING the tmp csv file: ' . $csvFilePath, '', $preFix . self::TAB);
     unlink($csvFilePath);
     self::_log('REMOVED', '', $preFix . self::TAB . self::TAB);
     self::_log('== Archived', __CLASS__ . '::' . __FUNCTION__, $preFix, $start);
 }
Ejemplo n.º 9
0
 /**
  * Create an empty.box in the temp dir that we can use to test
  * compression/decompression and adding metadata.json to it.
  *
  * PHP's PharData does NOT work with vfsStream so we're required
  * to put this on the actual filesystem.
  */
 public static function setUpBeforeClass()
 {
     $fixturesPath = $GLOBALS['PHPUNIT_FIXTURES_DIR'] . DIRECTORY_SEPARATOR . 'empty.box';
     $p = new \PharData("tmp.tar");
     $emptyBoxFiles = array('box.ovf', 'box-disk1.vmdk', 'metadata.json', 'Vagrantfile');
     foreach ($emptyBoxFiles as $file) {
         $p->addFile("{$fixturesPath}/{$file}", basename($file));
     }
     $p->compress(\Phar::GZ);
     unset($p);
     // Windows: make $p release the tmp.tar file
     if (!unlink("tmp.tar")) {
         fwrite(STDERR, "unlink('tmp.tar') failed in " . getcwd() . "\n");
         system('ls -la');
     }
     rename("tmp.tar.gz", "empty.box");
     self::$emptyPackageBox = file_get_contents("empty.box");
 }
Ejemplo n.º 10
0
 public function clean()
 {
     # Maximum size of log file allowed, in bytes ( 100000000 = 100 MB)
     $max_size = 100000000;
     chdir(LOG_PATH);
     foreach (glob("*.log") as $_file) {
         if (filesize($_file) >= $max_size) {
             $tar = new \PharData(basename($_file, ".log") . '-error-log-archive.tar');
             $tar->addFile($_file);
             $tar->compress(\Phar::GZ);
             # Move tarball to archives folder once complete
             if (is_readable('archive/' . $_file . '-error-log-archive.tar')) {
                 rename($_file . '-error-log-archive.tar', 'archive/' . $_file . '-error-log-archive.tar');
             } else {
                 rename($_file . '-error-log-archive.tar', 'archive/' . $_file . '_' . time() . '-error-log-archive.tar');
             }
         }
     }
 }
Ejemplo n.º 11
0
 public function create($execution, $format, $hrefs)
 {
     $this->dirs = array();
     $this->files = array();
     $this->add_hrefs($hrefs);
     if (count($this->dirs) === 0 && count($this->files) === 0) {
         return 404;
     }
     $target = $this->app->get_cache_abs_path() . "/package-" . sha1(microtime(true) . rand()) . "." . $format;
     try {
         if ($execution === "shell") {
             if ($format === "tar") {
                 $cmd = Archive::$TAR_CMD;
             } else {
                 if ($format === "zip") {
                     $cmd = Archive::$ZIP_CMD;
                 } else {
                     return null;
                 }
             }
             // $cmd = str_replace("[ROOTDIR]", "\"" . $this->app->get_root_abs_path() . "\"", $cmd);
             $cmd = str_replace("[ROOTDIR]", "\"" . $this->app->get_abs_path() . "\"", $cmd);
             $cmd = str_replace("[TARGET]", "\"" . $target . "\"", $cmd);
             $cmd = str_replace("[DIRS]", count($this->dirs) ? "\"" . implode("\"  \"", array_values($this->dirs)) . "\"" : "", $cmd);
             $cmd = str_replace("[FILES]", count($this->files) ? "\"" . implode("\"  \"", array_values($this->files)) . "\"" : "", $cmd);
             shell_exec($cmd);
         } else {
             if ($execution === "php") {
                 $archive = new PharData($target);
                 foreach ($this->dirs as $archived_dir) {
                     $archive->addEmptyDir($archived_dir);
                 }
                 foreach ($this->files as $real_file => $archived_file) {
                     $archive->addFile($real_file, $archived_file);
                     // very, very slow :/
                 }
             }
         }
     } catch (Exeption $err) {
         return 500;
     }
     return @filesize($target) ? $target : null;
 }
Ejemplo n.º 12
0
 private function getTar($filesToInclude, $docId, $filesPath, $tempPath)
 {
     $tarball = $tempPath . uniqid($docId, true) . '.tar';
     $phar = null;
     try {
         $phar = new PharData($tarball);
     } catch (UnexpectedValueException $e) {
         $this->logErrorMessage('could not create tarball archive file ' . $tarball . ' due to insufficient file system permissions: ' . $e->getMessage());
         throw new Oai_Model_Exception('error while creating tarball container: could not open tarball');
     }
     foreach ($filesToInclude as $file) {
         $filePath = $filesPath . $docId . DIRECTORY_SEPARATOR;
         try {
             $phar->addFile($filePath . $file->getPathName(), $file->getPathName());
         } catch (Exception $e) {
             $this->logErrorMessage('could not add ' . $file->getPathName() . ' to tarball archive file: ' . $e->getMessage());
             throw new Oai_Model_Exception('error while creating tarball container: could not add file to tarball');
         }
     }
     return $tarball;
 }
Ejemplo n.º 13
0
 /**
  * Download Folder
  *
  * @param array $params
  *
  * @return void
  * @throws \Exception
  */
 public function downloadFolder(array $params)
 {
     try {
         if (extension_loaded('Phar')) {
             /**
              * Decode Path
              */
             $base64 = base64_decode($params['dir']);
             /**
              * Path to File on Disk
              */
             $path = $this->getSearchPath() . '/' . $base64;
             clearstatcache();
             if (is_dir($path)) {
                 $array = $this->directoryListing($base64);
                 if (is_array($array) && count($array) > '0') {
                     unset($array['totalLength']);
                     unset($array['totalFileSize']);
                     $filename = $path . '.' . $params['format'];
                     $phar = new \PharData($filename);
                     foreach ($array as $value) {
                         $phar->addFile($value['fullPath'], $value['name']);
                     }
                     switch ($params['format']) {
                         case 'tar':
                             header('Content-Type: application/x-tar');
                             break;
                         case 'zip':
                             header('Content-Type: application/zip');
                             break;
                         case 'bz2':
                             header('Content-Type: application/x-bzip2');
                             break;
                         case 'rar':
                             header('Content-Type: x-rar-compressed');
                             break;
                     }
                     header('Content-disposition: attachment; filename=' . basename($filename));
                     header('Content-Length: ' . filesize($filename));
                     readfile($filename);
                     unlink($filename);
                     exit;
                 } else {
                     throw new \Exception($this->translate->translate('Something went wrong and we cannot download this folder', 'mp3'));
                 }
             } else {
                 throw new \Exception($path . ' ' . $this->translate->translate('was not found', 'mp3'));
             }
         } else {
             throw new \Exception($this->translate->translate('Phar Extension is not loaded'));
         }
     } catch (\Exception $e) {
         throw $e;
     }
 }
Ejemplo n.º 14
0
function caZipDirectory($ps_directory, $ps_name, $ps_output_file)
{
    $va_files_to_zip = caGetDirectoryContentsAsList($ps_directory);
    $vs_tmp_name = caGetTempFileName('caZipDirectory', 'zip');
    $o_phar = new PharData($vs_tmp_name, null, null, Phar::ZIP);
    foreach ($va_files_to_zip as $vs_file) {
        $vs_name = str_replace($ps_directory, $ps_name, $vs_file);
        $o_phar->addFile($vs_file, $vs_name);
    }
    copy($vs_tmp_name, $ps_output_file);
    unlink($vs_tmp_name);
    return true;
}
 /**
  * Add the extra files to the package.
  * @throws HttpDeployerException
  */
 private function addExtraFiles()
 {
     $this->logger->info("Adding the extra files into the package.");
     try {
         $phar = new \PharData($this->package);
         foreach ($this->getExtraFiles() as $from => $to) {
             $phar->addFile($from, $to);
         }
     } catch (\Exception $e) {
         throw new HttpDeployerException("An error ocurred while adding the extra files to the package.", 0, $e);
     }
 }
 public function getLotMedia()
 {
     //if ((bool)$this->request->config->get('allow_download_of_all_object_media_in_a_lot')) {
     set_time_limit(600);
     // allow a lot of time for this because the sets can be potentially large
     $t_lot = new ca_object_lots($this->request->getParameter('lot_id', pInteger));
     if ($t_lot->getPrimaryKey()) {
         $va_object_ids = $t_lot->get('ca_objects.object_id', array('returnAsArray' => true, 'limit' => 100000));
         if (!is_array($va_object_ids) || !sizeof($va_object_ids)) {
             $this->notification->addNotification(_t('No media is available for download'), __NOTIFICATION_TYPE_ERROR__);
             $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_object_lots', $t_lot->getPrimaryKey()));
             return;
         }
         $qr_res = ca_objects::createResultSet($va_object_ids);
         $qr_res->filterNonPrimaryRepresentations(false);
         $va_paths = array();
         while ($qr_res->nextHit()) {
             $va_original_paths = $qr_res->getMediaPaths('ca_object_representations.media', 'original');
             if (sizeof($va_original_paths) > 0) {
                 $va_paths[$qr_res->get('object_id')] = array('idno' => $qr_res->get('idno'), 'paths' => $va_original_paths);
             }
         }
         if (sizeof($va_paths) > 0) {
             $vs_tmp_name = caGetTempFileName('DownloadLotMedia', 'zip');
             $o_phar = new PharData($vs_tmp_name, null, null, Phar::ZIP);
             foreach ($va_paths as $vn_object_id => $va_path_info) {
                 $vn_c = 1;
                 foreach ($va_path_info['paths'] as $vs_path) {
                     if (!file_exists($vs_path)) {
                         continue;
                     }
                     $vs_filename = $va_path_info['idno'] ? $va_path_info['idno'] : $vn_object_id;
                     $vs_filename .= "_{$vn_c}";
                     if ($vs_ext = pathinfo($vs_path, PATHINFO_EXTENSION)) {
                         $vs_filename .= ".{$vs_ext}";
                     }
                     $o_phar->addFile($vs_path, $vs_filename);
                     $vn_c++;
                 }
             }
             $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
             // send download
             $vs_idno = $t_lot->get('idno_stub');
             $o_view->setVar('tmp_file', $vs_tmp_name);
             $o_view->setVar('download_name', 'media_for_' . mb_substr(preg_replace('![^A-Za-z0-9]+!u', '_', $vs_idno ? $vs_idno : $t_lot->getPrimaryKey()), 0, 20) . '.zip');
             $this->response->addContent($o_view->render('ca_object_lots_download_media.php'));
             return;
         } else {
             $this->notification->addNotification(_t('No media is available for download'), __NOTIFICATION_TYPE_ERROR__);
             $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_object_lots', $t_lot->getPrimaryKey()));
             return;
         }
     }
     //}
     return $this->Edit();
 }
Ejemplo n.º 17
0
 /**
  * @param string $format      The algorithm used for the archive.
  * @param string $destination The path to the new archive.
  * @param array  $contents    The files and/or directories that should be included in the archive.
  *
  * @return \PharData
  *
  * @throws ArchivalException If the archive could not be created.
  */
 protected function createArchive($format, $destination, array $contents = [])
 {
     try {
         $archive = new \PharData($destination, null, null, $format);
         foreach ($contents as $pathInArchive => $path) {
             if (is_integer($pathInArchive)) {
                 $pathInArchive = null;
             }
             if (!is_readable($path)) {
                 throw new ArchivalException(sprintf('Could not add the given file/dir to the archive: %s, it doesn\'t exist', $path));
             }
             if (is_dir($path)) {
                 $archive->buildFromDirectory($path);
             } else {
                 if ($pathInArchive !== null) {
                     $archive->addFile($path, $pathInArchive);
                 } else {
                     $archive->addFile($path);
                 }
             }
         }
     } catch (\Exception $e) {
         throw new ArchivalException(sprintf('Failed to create archive with destination: %s', $destination), null, $e);
     }
     return $archive;
 }
 /**
  * Download all media attached to specified object (not necessarily open for editing)
  * Includes all representation media attached to the specified object + any media attached to oter
  * objects in the same object hierarchy as the specified object. Used by the book viewer interfacce to
  * initiate a download.
  */
 public function DownloadMedia($pa_options = null)
 {
     list($vn_subject_id, $t_subject) = $this->_initView();
     $pn_representation_id = $this->request->getParameter('representation_id', pInteger);
     $pn_value_id = $this->request->getParameter('value_id', pInteger);
     if ($pn_value_id) {
         return $this->DownloadAttributeMedia();
     }
     $ps_version = $this->request->getParameter('version', pString);
     if (!$vn_subject_id) {
         return;
     }
     $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
     if (!$ps_version) {
         $ps_version = 'original';
     }
     $o_view->setVar('version', $ps_version);
     $va_ancestor_ids = $t_subject->isHierarchical() ? $t_subject->getHierarchyAncestors(null, array('idsOnly' => true, 'includeSelf' => true)) : array($vn_subject_id);
     if ($vn_parent_id = array_pop($va_ancestor_ids)) {
         $t_subject->load($vn_parent_id);
         array_unshift($va_ancestor_ids, $vn_parent_id);
     }
     $va_child_ids = $t_subject->isHierarchical() ? $t_subject->getHierarchyChildren(null, array('idsOnly' => true)) : array($vn_subject_id);
     foreach ($va_ancestor_ids as $vn_id) {
         array_unshift($va_child_ids, $vn_id);
     }
     $vn_c = 1;
     $va_file_names = array();
     $va_file_paths = array();
     foreach ($va_child_ids as $vn_child_id) {
         if (!$t_subject->load($vn_child_id)) {
             continue;
         }
         if ($t_subject->tableName() == 'ca_object_representations') {
             $va_reps = array($vn_child_id => array('representation_id' => $vn_child_id, 'info' => array($ps_version => $t_subject->getMediaInfo('media', $ps_version))));
         } else {
             $va_reps = $t_subject->getRepresentations(array($ps_version));
         }
         $vs_idno = $t_subject->get('idno');
         foreach ($va_reps as $vn_representation_id => $va_rep) {
             if ($pn_representation_id && $pn_representation_id != $vn_representation_id) {
                 continue;
             }
             $va_rep_info = $va_rep['info'][$ps_version];
             $vs_idno_proc = preg_replace('![^A-Za-z0-9_\\-]+!', '_', $vs_idno);
             switch ($this->request->user->getPreference('downloaded_file_naming')) {
                 case 'idno':
                     $vs_file_name = $vs_idno_proc . '_' . $vn_c . '.' . $va_rep_info['EXTENSION'];
                     break;
                 case 'idno_and_version':
                     $vs_file_name = $vs_idno_proc . '_' . $ps_version . '_' . $vn_c . '.' . $va_rep_info['EXTENSION'];
                     break;
                 case 'idno_and_rep_id_and_version':
                     $vs_file_name = $vs_idno_proc . '_representation_' . $vn_representation_id . '_' . $ps_version . '.' . $va_rep_info['EXTENSION'];
                     break;
                 case 'original_name':
                 default:
                     if ($va_rep['info']['original_filename']) {
                         $va_tmp = explode('.', $va_rep['info']['original_filename']);
                         if (sizeof($va_tmp) > 1) {
                             if (strlen($vs_ext = array_pop($va_tmp)) < 3) {
                                 $va_tmp[] = $vs_ext;
                             }
                         }
                         $vs_file_name = join('_', $va_tmp);
                     } else {
                         $vs_file_name = $vs_idno_proc . '_representation_' . $vn_representation_id . '_' . $ps_version;
                     }
                     if (isset($va_file_names[$vs_file_name . '.' . $va_rep_info['EXTENSION']])) {
                         $vs_file_name .= "_{$vn_c}";
                     }
                     $vs_file_name .= '.' . $va_rep_info['EXTENSION'];
                     break;
             }
             $va_file_names[$vs_file_name] = true;
             $o_view->setVar('version_download_name', $vs_file_name);
             //
             // Perform metadata embedding
             $t_rep = new ca_object_representations($va_rep['representation_id']);
             if (!($vs_path = caEmbedMetadataIntoRepresentation($t_subject, $t_rep, $ps_version))) {
                 $vs_path = $t_rep->getMediaPath('media', $ps_version);
             }
             $va_file_paths[$vs_path] = $vs_file_name;
             $vn_c++;
         }
     }
     if (sizeof($va_file_paths) > 1) {
         if (!($vn_limit = ini_get('max_execution_time'))) {
             $vn_limit = 30;
         }
         set_time_limit($vn_limit * 2);
         $vs_tmp_name = caGetTempFileName('DownloadMedia', 'zip');
         $o_phar = new PharData($vs_tmp_name, null, null, Phar::ZIP);
         foreach ($va_file_paths as $vs_path => $vs_name) {
             $o_phar->addFile($vs_path, $vs_name);
         }
         $o_view->setVar('archive_path', $vs_tmp_name);
         $o_view->setVar('archive_name', preg_replace('![^A-Za-z0-9\\.\\-]+!', '_', $t_subject->get('idno')) . '.zip');
         $this->response->addContent($o_view->render('download_media_binary.php'));
         if ($vs_tmp_name) {
             @unlink($vs_tmp_name);
         }
     } else {
         foreach ($va_file_paths as $vs_path => $vs_name) {
             $o_view->setVar('archive_path', $vs_path);
             $o_view->setVar('archive_name', $vs_name);
         }
         $this->response->addContent($o_view->render('download_media_binary.php'));
     }
 }
Ejemplo n.º 19
0
 public function tarData($tarFile, $cron)
 {
     $log = vglobal('log');
     $log->info('BackUp - Start ZipArchive');
     $dbFiles = $this->getFilesStructure();
     $destination = $this->tempDir . '/' . $tarFile . '.tar';
     $tar = new PharData($destination);
     $count = 0;
     foreach ($dbFiles as $id => $path) {
         if (is_dir($path)) {
             $tar->addEmptyDir($path . '/');
         } elseif (is_file($path)) {
             $tar->addFile($path, $path);
         }
         $this->markFile($id);
         if ($count == $this->ajaxFilesLimit && $cron == FALSE) {
             $percentage = $this->getPercentage();
             exit(json_encode(['percentage' => $percentage]));
         }
         $count++;
     }
     //$tar->compress(Phar::GZ);
 }
Ejemplo n.º 20
0
function create_archive($archive_name, $path, $extension, $files, $multiple)
{
    if (!empty($archive_name) && !empty($path) && !empty($extension) && !empty($files)) {
        $accepted_extension = false;
        $array_files = array();
        $array_path_files = array();
        $array_path_folders = array();
        $array_all = array();
        $array_extension = array(".zip", ".tar", ".tar.gz", ".tar.bz2");
        foreach ($array_extension as $archive_extension) {
            if ($archive_extension === $extension) {
                $accepted_extension = true;
                break;
            }
        }
        if ($accepted_extension === false) {
            send_json("Archive extension is not supported !!", null);
        }
        $max_size = 4294967296;
        foreach ($files as $file) {
            if (is_file($path . $file)) {
                if (filesize($path . $file) > $max_size || filesize($path . $file) < 1) {
                } else {
                    array_push($array_path_files, $path . $file);
                    array_push($array_files, substr($path . $file, strlen($path)));
                }
            } else {
                array_push($array_path_folders, $path . $file);
            }
        }
        if ($extension === ".zip") {
            $tmp_archive = tempnam("tmp", "zip");
            $archive = new ZipArchive();
            $create_archive = $archive->open($tmp_archive, ZipArchive::OVERWRITE);
            if ($create_archive !== true) {
                unlink($tmp_archive);
                send_json("Can't create zip archive !!", null);
                throw new Exception("Can't create zip archive !!");
            }
            foreach ($array_path_folders as $folder) {
                $list_folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder));
                foreach ($list_folder as $file_in_folder) {
                    if ($file_in_folder->isDir()) {
                        continue;
                    }
                    array_push($array_path_files, $file_in_folder->getPathname());
                    array_push($array_files, substr($file_in_folder->getPathname(), strlen($path)));
                }
            }
            $array_all = array_combine($array_path_files, $array_files);
            foreach ($array_all as $full_path => $file_name) {
                if (file_exists($full_path)) {
                    if (is_readable($full_path)) {
                        $archive->addFile($full_path, $file_name);
                    }
                }
            }
            $archive->close();
        } else {
            $tmp_archive = tempnam("tmp", "tar") . ".tar";
            $archive = new PharData($tmp_archive);
            if (count($array_path_folders) > 0) {
                $tmp_archive = tempnam("tmp", "tar") . ".tar";
                $archive = new PharData($tmp_archive);
                if ($multiple === "false") {
                    foreach ($array_path_folders as $folder) {
                        try {
                            $archive->buildFromDirectory($folder);
                        } catch (Exception $e) {
                            send_json($e->getMessage(), null);
                            throw new Exception($e->getMessage());
                        }
                    }
                } else {
                    foreach ($array_path_folders as $folder) {
                        $list_folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS));
                        foreach ($list_folder as $file) {
                            try {
                                if (is_readable($file->getPathname())) {
                                    array_push($array_files, substr($file->getPathname(), strlen($path)));
                                    array_push($array_path_files, $file->getPathname());
                                }
                            } catch (Exception $e) {
                                send_json($e->getMessage(), null);
                                throw new Exception($e->getMessage());
                            }
                        }
                    }
                }
            }
            if (count($array_path_files) > 0 && count($array_files) > 0) {
                $array_all = array_combine($array_path_files, $array_files);
                foreach ($array_all as $full_path => $file_name) {
                    $archive->addFile($full_path, $file_name);
                }
            }
        }
        if ($extension !== ".tar" && $extension !== ".zip") {
            $archive_type_compress = substr(strrchr($extension, "."), 1);
            if ($archive_type_compress == "gz") {
                $archive->compress(Phar::GZ);
            } elseif ($archive_type_compress == "bz2") {
                $archive->compress(Phar::BZ2);
            }
            $tmp_archive = $tmp_archive . "." . $archive_type_compress;
        }
        rename($tmp_archive, $path . $archive_name . $extension);
        send_json(null, $archive_name . $extension);
    }
}
Ejemplo n.º 21
0
 /**
  * @inheritdoc
  */
 public function run(&$cmdParams, &$params)
 {
     $res = true;
     $taskRunner = $this->taskRunner;
     $toBeAdded = [];
     $srcList = !empty($cmdParams[0]) ? $cmdParams[0] : [];
     $destFile = !empty($cmdParams[1]) ? $taskRunner->parsePath($cmdParams[1]) : '';
     $srcBaseDir = !empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : '';
     $format = !empty($cmdParams[3]) ? strtolower($cmdParams[3]) : self::CMP_GZ;
     $options = !empty($cmdParams[4]) ? $cmdParams[4] : [];
     if (!empty($srcBaseDir) && !is_dir($srcBaseDir)) {
         Log::throwException('compress: srcBaseDir has to be a directory');
     }
     if (empty($destFile) || file_exists($destFile) && is_dir($destFile)) {
         Log::throwException('compress: Destination has to be a file');
     }
     switch ($format) {
         case self::CMP_NONE:
             $extension = '.tar';
             $compression = \Phar::NONE;
             $doCompress = false;
             break;
         case self::CMP_GZ:
             $extension = '.tar.gz';
             $compression = \Phar::GZ;
             $doCompress = true;
             break;
         case self::CMP_BZ2:
             $extension = '.tar.bz2';
             $compression = \Phar::BZ2;
             $doCompress = true;
             break;
         default:
             $extension = '';
             $compression = false;
             $doCompress = false;
             Log::throwException('compress: Invalid format specified: ' . $format);
             break;
     }
     // if $srcList is specified but it is a string, we convert it to an array
     if (!empty($srcList) && is_string($srcList)) {
         $srcList = explode(',', $srcList);
     }
     foreach ($srcList as $srcPath) {
         $parsedPath = $taskRunner->parseStringAliases(trim($srcPath));
         if (!empty($srcBaseDir)) {
             $toBeAdded[$parsedPath] = $srcBaseDir . DIRECTORY_SEPARATOR . $parsedPath;
         } else {
             $toBeAdded[] = $parsedPath;
         }
     }
     $this->controller->stdout("Creating archive: ");
     $this->controller->stdout($destFile, Console::FG_BLUE);
     $archive = null;
     $destDir = dirname($destFile);
     $destBaseFile = $destDir . DIRECTORY_SEPARATOR . basename($destFile, '.tar');
     if (!$this->controller->dryRun) {
         if (!is_dir($destDir)) {
             FileHelper::createDirectory($destDir);
         }
         @unlink($destFile);
         @unlink($destBaseFile);
         try {
             $archive = new \PharData($destFile);
         } catch (\Exception $e) {
             Log::throwException($e->getMessage());
         }
     } else {
         $this->controller->stdout(' [dry run]', Console::FG_YELLOW);
     }
     $this->controller->stdout("\n");
     $this->controller->stdout("Adding to archive: ");
     foreach ($toBeAdded as $srcRelPath => $srcFullPath) {
         if (file_exists($srcFullPath)) {
             $this->controller->stdout("\n - " . $srcFullPath);
             if (!$this->controller->dryRun) {
                 if (is_dir($srcFullPath)) {
                     $files = FileHelper::findFiles($srcFullPath, $options);
                     $archive->buildFromIterator(new ArrayIterator($files), !empty($srcBaseDir) ? $srcBaseDir : $srcFullPath);
                 } elseif (FileHelper::filterPath($srcFullPath, $options)) {
                     $archive->addFile($srcFullPath, !empty($srcBaseDir) ? $srcRelPath : basename($srcFullPath));
                 }
             } else {
                 $this->controller->stdout(' [dry run]', Console::FG_YELLOW);
             }
         } else {
             $this->controller->stderr("\n{$srcFullPath} does not exists!\n", Console::FG_RED);
         }
     }
     $this->controller->stdout("\n");
     if ($doCompress) {
         $this->controller->stdout("Compressing archive: ");
         $this->controller->stdout($destBaseFile . $extension, Console::FG_CYAN);
         if (!$this->controller->dryRun) {
             @unlink($destBaseFile . $extension);
             try {
                 $archive->compress($compression, $extension);
             } catch (\Exception $e) {
                 Log::throwException($e->getMessage());
             }
             @unlink($destFile);
         } else {
             $this->controller->stdout(' [dry run]', Console::FG_YELLOW);
         }
         $this->controller->stdout("\n");
     }
     return $res;
 }
Ejemplo n.º 22
0
/**
 * Compress files with Tar archiver
 *
 * @param string $archive_name - archive name (zip, tgz, gz and tar.gz supported)
 * @param string $file_list - list of files to place into archive
 * @param string $dirname - directory, where the files should be get from
 * @return bool true
 */
function fn_compress_files($archive_name, $file_list, $dirname = '')
{
    if (!class_exists('PharData')) {
        fn_set_notification('E', __('error'), __('error_class_phar_data_not_found'));
        return false;
    }
    if (empty($dirname)) {
        $dirname = Registry::get('config.dir.files');
    }
    if (!is_array($file_list)) {
        $file_list = array($file_list);
    }
    $ext = fn_get_file_ext($archive_name);
    $_exts = explode('.', $archive_name);
    array_shift($_exts);
    $first_dot_ext = '.' . implode('.', $_exts);
    // https://bugs.php.net/bug.php?id=58852. Phar gets ext from the first dot: 'test.1.2.3.tgz' -> ext = 1.2.3.tgz
    $arch = fn_normalize_path($dirname . '/' . $archive_name);
    fn_rm($arch);
    if ($ext != 'zip') {
        $arch = fn_normalize_path($dirname . '/' . $archive_name . '.tmp');
        fn_rm($arch);
    }
    if ($ext == 'gz' && strpos($archive_name, '.tar.gz') !== false) {
        $ext = 'tar.gz';
    }
    try {
        $phar = new PharData($arch);
        foreach ($file_list as $file) {
            $path = fn_normalize_path($dirname . '/' . $file);
            if (is_file($path)) {
                $phar->addFile($path, basename($path));
            } elseif (is_dir($path)) {
                $phar->buildFromDirectory($path);
            }
        }
        if ($ext == 'zip') {
            $phar->compressFiles(Phar::GZ);
        } else {
            $phar->compress(Phar::GZ, $first_dot_ext);
            // We need to unset Phar because the PharData class still has the file "open".
            // Windows servers cannot delete the files with the "open" handlers.
            unset($phar);
            fn_rm($arch);
        }
    } catch (Exception $e) {
        fn_set_notification('E', __('error'), $e->getMessage());
        return false;
    }
    return true;
}
Ejemplo n.º 23
0
 /**
  * Handles the archiving of faxes. Modifies the filesystem by creating new archive files,
  * and remove existing fax files. Has many opportunities to throw exceptions.
  * 
  * Only accessible by URL of form:
  * .../index.php?module=faxmaster&op=archive&start_date=(UNIX TIMESTAMP)[&end_date=(UNIX TIMESTAMP)]
  */
 private function archiveFaxes()
 {
     PHPWS_Core::initModClass('faxmaster', 'Fax.php');
     // Get date range for archive. Use NOW for end date if one is not supplied.
     $startDate = $_REQUEST['start_date'];
     $endDate = isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] : time();
     // Check user's permissions
     if (!Current_User::allow('faxmaster', 'archive')) {
         PHPWS_Core::initModClass('faxmaster', 'exception/PermissionException.php');
         throw new PermissionException('Permission denied');
     }
     // SELECT id FROM faxmaster_fax WHERE dateReceived >= start_date AND dateReceived < end_date AND archived=0;
     $db = new PHPWS_DB('faxmaster_fax');
     $db->addColumn('id');
     $db->addWhere('archived', 0);
     // only grab unarchived files
     $db->addWhere('dateReceived', $startDate, '>=', 'AND');
     // startDate is inclusive
     $db->addWhere('dateReceived', $endDate, '<', 'AND');
     // endDate is exclusive
     $results = $db->select();
     // Make archive
     $path = PHPWS_Settings::get('faxmaster', 'archive_path');
     $archiveName = strftime('%m%d%Y', $startDate) . 'to' . strftime('%m%d%Y', $endDate) . '.tar';
     try {
         $archive = new PharData($path . $archiveName);
     } catch (UnexpectedValueException $e) {
         die('Could not open .tar file' . $e->getMessage());
     } catch (BadMethodCallException $e) {
         die('Bad method call' . $e->getMessage());
     }
     // Fill the archive
     foreach ($results as $result) {
         $fax = new Fax($result['id']);
         try {
             $archive->addFile($fax->getFullPath(), $fax->getFileName());
         } catch (PharException $e) {
             die($e->getMessage());
         }
     }
     // Compress the archive
     try {
         $archive = $archive->compress(Phar::GZ);
     } catch (BadMethodCallException $e) {
         die($e->getMessage());
     }
     // Remove .tar, leaving only the .tar.gz
     unlink($path . $archiveName);
     // Update each fax in the database, then remove it from the fax directory
     foreach ($results as $result) {
         $fax = new Fax($result['id']);
         $fax->setArchived(1, $archiveName . '.gz');
         $fax->save();
         unlink($fax->getFullPath());
     }
 }
Ejemplo n.º 24
0
 /**
  * Creates a backup and sends it to the cloud
  * @return bool
  * @access public
  * @final
  */
 public final function backup()
 {
     $folder = $this->request(self::$url . self::REMOTEDIR, array('Depth: 0'), 'PROPFIND');
     if ($folder->code == 404) {
         $folder = $this->request(self::$url . self::REMOTEDIR, array(), 'MKCOL');
     }
     if (in_array($folder->code, array(201, 207)) === false) {
         throw new RuntimeException('Failed to create remote directory', $folder->code);
     }
     try {
         $archive = new PharData(__DIR__ . '/' . self::TMPPATH . '/' . self::$time . '.tar');
         if (is_null(self::$path) == false) {
             $archive->buildFromDirectory(self::$path);
         }
         if (file_exists(__DIR__ . '/' . self::TMPPATH . '/' . self::$time . '.sql')) {
             $archive->addFile(__DIR__ . '/' . self::TMPPATH . '/' . self::$time . '.sql', 'sql/' . self::$time . '.sql');
             unlink(__DIR__ . '/' . self::TMPPATH . '/' . self::$time . '.sql');
         }
         if ($this->compression == true) {
             $archive->compress(Phar::GZ);
             unlink(__DIR__ . '/' . self::TMPPATH . '/' . self::$time . '.tar');
         }
     } catch (Exception $e) {
         throw new RuntimeException("Failed to create the archive: {$e}");
     }
     $realName = self::$time . '.tar' . ($this->compression == true ? '.gz' : '');
     if (file_exists(__DIR__ . '/' . self::TMPPATH . '/' . $realName)) {
         $send = $this->request(self::$url . self::REMOTEDIR . '/' . $realName, array('Content-type: application/octet-stream'), 'PUT', __DIR__ . '/' . self::TMPPATH . '/' . $realName);
         unlink(__DIR__ . '/' . self::TMPPATH . '/' . $realName);
         return $send->code == 201 ? true : false;
     }
 }
 /**
  * Download (accessible) media for all records in this set
  */
 public function getSetMedia()
 {
     set_time_limit(600);
     // allow a lot of time for this because the sets can be potentially large
     $o_dm = Datamodel::load();
     $t_set = new ca_sets($this->request->getParameter('set_id', pInteger));
     if (!$t_set->getPrimaryKey()) {
         $this->notification->addNotification(_t('No set defined'), __NOTIFICATION_TYPE_ERROR__);
         $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_sets', $t_set->getPrimaryKey()));
         return false;
     }
     $va_record_ids = array_keys($t_set->getItemRowIDs(array('limit' => 100000)));
     if (!is_array($va_record_ids) || !sizeof($va_record_ids)) {
         $this->notification->addNotification(_t('No media is available for download'), __NOTIFICATION_TYPE_ERROR__);
         $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_sets', $t_set->getPrimaryKey()));
         return false;
     }
     $vs_subject_table = $o_dm->getTableName($t_set->get('table_num'));
     $t_instance = $o_dm->getInstanceByTableName($vs_subject_table);
     $qr_res = $vs_subject_table::createResultSet($va_record_ids);
     $qr_res->filterNonPrimaryRepresentations(false);
     $va_paths = array();
     while ($qr_res->nextHit()) {
         $va_original_paths = $qr_res->getMediaPaths('ca_object_representations.media', 'original');
         if (sizeof($va_original_paths) > 0) {
             $va_paths[$qr_res->get($t_instance->primaryKey())] = array('idno' => $qr_res->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'paths' => $va_original_paths);
         }
     }
     if (sizeof($va_paths) > 0) {
         $vs_tmp_name = caGetTempFileName('DownloadSetMedia', 'zip');
         $o_phar = new PharData($vs_tmp_name, null, null, Phar::ZIP);
         foreach ($va_paths as $vn_pk => $va_path_info) {
             $vn_c = 1;
             foreach ($va_path_info['paths'] as $vs_path) {
                 if (!file_exists($vs_path)) {
                     continue;
                 }
                 $vs_filename = $va_path_info['idno'] ? $va_path_info['idno'] : $vn_pk;
                 $vs_filename .= "_{$vn_c}";
                 if ($vs_ext = pathinfo($vs_path, PATHINFO_EXTENSION)) {
                     $vs_filename .= ".{$vs_ext}";
                 }
                 $o_phar->addFile($vs_path, $vs_filename);
                 $vn_c++;
             }
         }
         $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
         // send download
         $vs_set_code = $t_set->get('set_code');
         $o_view->setVar('tmp_file', $vs_tmp_name);
         $o_view->setVar('download_name', 'media_for_' . mb_substr(preg_replace('![^A-Za-z0-9]+!u', '_', $vs_set_code ? $vs_set_code : $t_set->getPrimaryKey()), 0, 20) . '.zip');
         $this->response->addContent($o_view->render('ca_sets_download_media.php'));
         return;
     } else {
         $this->notification->addNotification(_t('No media is available for download'), __NOTIFICATION_TYPE_ERROR__);
         $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_sets', $t_set->getPrimaryKey()));
         return;
     }
     return $this->Edit();
 }
Ejemplo n.º 26
0
 private function _tarball($id)
 {
     if ($this->mmultipaste->id_exists($id)) {
         $seen = array();
         $path = $this->mmultipaste->get_tarball_path($id);
         $archive = new \service\storage($path);
         if (!$archive->exists()) {
             $files = $this->mmultipaste->get_files($id);
             $total_size = 0;
             foreach ($files as $filedata) {
                 $total_size += $filedata["filesize"];
             }
             if ($total_size > $this->config->item("tarball_max_size")) {
                 throw new \exceptions\PublicApiException("file/tarball/tarball-filesize-limit", "Tarball too large, refusing to create.");
             }
             $tmpfile = $archive->begin();
             // create empty tar archive so PharData has something to open
             file_put_contents($tmpfile, str_repeat("", 1024 * 10));
             $a = new PharData($tmpfile);
             foreach ($files as $filedata) {
                 $filename = $filedata["filename"];
                 if (isset($seen[$filename]) && $seen[$filename]) {
                     $filename = $filedata["id"] . "-" . $filedata["filename"];
                 }
                 assert(!isset($seen[$filename]));
                 $a->addFile($this->mfile->file($filedata["data_id"]), $filename);
                 $seen[$filename] = true;
             }
             $archive->gzip_compress();
             $archive->commit();
         }
         // update mtime so the cronjob will keep the file for longer
         $lock = fopen($archive->get_file(), "r+");
         flock($lock, LOCK_SH);
         touch($archive->get_file());
         flock($lock, LOCK_UN);
         assert(filesize($archive->get_file()) > 0);
         $this->load->driver("ddownload");
         $this->ddownload->serveFile($archive->get_file(), "{$id}.tar.gz", "application/x-gzip");
     }
 }
Ejemplo n.º 27
0
 function _mtzmap($type)
 {
     $types = array('MrBUMP' => array('root' => 'auto_mrbump/', 'files' => array('PostMRRefine.pdb', 'PostMRRefine.mtz'), 'log' => 'MRBUMP.log'), 'Dimple' => array('root' => 'fast_dp/dimple/', 'files' => array('final.pdb', 'final.mtz'), 'log' => 'dimple.log'), 'FastEP' => array('root' => 'fast_ep/', 'files' => array('sad.mtz', 'sad_fa.pdb'), 'log' => 'fast_ep.log'));
     if (!array_key_exists($type, $types)) {
         $this->_error('No such downstream type');
     } else {
         $t = $types[$type];
     }
     $info = $this->db->pq('SELECT dc.imageprefix as imp, dc.datacollectionnumber as run, dc.imagedirectory as dir, p.proposalcode || p.proposalnumber || \'-\' || s.visit_number as vis FROM datacollection dc INNER JOIN blsession s ON s.sessionid=dc.sessionid INNER JOIN proposal p ON (p.proposalid = s.proposalid) WHERE dc.datacollectionid=:1', array($this->arg('id')));
     if (!sizeof($info)) {
         $this->_error('No such data collection', 'The specified data collection does not exist');
     } else {
         $info = $info[0];
     }
     $this->db->close();
     $info['DIR'] = $this->ads($info['DIR']);
     $root = str_replace($info['VIS'], $info['VIS'] . '/processed', $info['DIR']) . $info['IMP'] . '_' . $info['RUN'] . '_/' . $t['root'];
     $file = $root . $t['files'][0];
     if (file_exists($file)) {
         if ($this->has_arg('log')) {
             if (file_exists($root . $t['log'])) {
                 $this->app->contentType("text/plain");
                 readfile($root . $t['log']);
             } else {
                 $this->_error('Not found', 'That file couldnt be found');
             }
         } else {
             if (!file_exists('/tmp/' . $this->arg('id') . '_' . $type . '.tar.gz')) {
                 $a = new PharData('/tmp/' . $this->arg('id') . '_' . $type . '.tar');
                 $a->addFile($file, $t['files'][0]);
                 $a->addFile($root . $t['files'][1], $t['files'][1]);
                 $a->compress(Phar::GZ);
                 unlink('/tmp/' . $this->arg('id') . '_' . $type . '.tar');
             }
             $this->_header($this->arg('id') . '_' . $type . '.tar.gz');
             readfile('/tmp/' . $this->arg('id') . '_' . $type . '.tar.gz');
             exit;
         }
     } else {
         $this->_error('File not found', $type . ' files were not found');
     }
 }
Ejemplo n.º 28
0
 /**
  * Adding files to the archive.
  *
  * @param PharData|ZipArchive $archive
  * @return PharData|ZipArchive
  * @access private
  * @final
  */
 private final function addFiles($archive)
 {
     switch ($this->type) {
         case self::RAR:
         case self::TAR:
             $archive->buildFromDirectory($this->path);
             break;
         case self::ZIP:
             $this->backupDir = str_replace('\\', '/', realpath($this->path));
             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path), RecursiveIteratorIterator::SELF_FIRST);
             foreach ($files as $file) {
                 $file = str_replace('\\', '/', $file);
                 if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
                     continue;
                 }
                 $file = realpath($file);
                 if (is_file($file)) {
                     $archive->addFile($file, trim(str_replace($this->path, '', $file), '/'));
                 }
             }
             break;
     }
     return $archive;
 }
Ejemplo n.º 29
0
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @throws Exception
  */
 public function receiveAction($action, $httpVars, $fileVars)
 {
     //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !!
     $messages = ConfService::getMessages();
     $repository = ConfService::getRepository();
     $userSelection = new UserSelection($repository, $httpVars);
     $nodes = $userSelection->buildNodes();
     $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath());
     $currentDirPath = rtrim($currentDirPath, "/") . "/";
     $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath;
     if (empty($httpVars["compression_id"])) {
         $compressionId = sha1(rand());
         $httpVars["compression_id"] = $compressionId;
     } else {
         $compressionId = $httpVars["compression_id"];
     }
     $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt";
     if (empty($httpVars["extraction_id"])) {
         $extractId = sha1(rand());
         $httpVars["extraction_id"] = $extractId;
     } else {
         $extractId = $httpVars["extraction_id"];
     }
     $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt";
     if ($action == "compression") {
         $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
         $archiveFormat = $httpVars["type_archive"];
         $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2");
         $acceptedExtension = false;
         foreach ($tabTypeArchive as $extensionArchive) {
             if ($extensionArchive == $archiveFormat) {
                 $acceptedExtension = true;
                 break;
             }
         }
         if ($acceptedExtension == false) {
             file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]);
             throw new AJXP_Exception($messages["compression.16"]);
         }
         $typeArchive = $httpVars["type_archive"];
         //if we can run in background we do it
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             $archivePath = $currentDirPath . $archiveName;
             file_put_contents($progressCompressionFileName, $messages["compression.5"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         } else {
             $maxAuthorizedSize = 4294967296;
             $currentDirUrlLength = strlen($currentDirUrl);
             $tabFolders = array();
             $tabAllRecursiveFiles = array();
             $tabFilesNames = array();
             foreach ($nodes as $node) {
                 $nodeUrl = $node->getUrl();
                 if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) {
                     array_push($tabAllRecursiveFiles, $nodeUrl);
                     array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength));
                 }
                 if (is_dir($nodeUrl)) {
                     array_push($tabFolders, $nodeUrl);
                 }
             }
             //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES
             foreach ($tabFolders as $value) {
                 $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value));
                 foreach ($dossiers as $file) {
                     if ($file->isDir()) {
                         continue;
                     }
                     array_push($tabAllRecursiveFiles, $file->getPathname());
                     array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength));
                 }
             }
             //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES
             if (empty($tabFilesNames)) {
                 file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]);
                 throw new AJXP_Exception($messages["compression.17"]);
             }
             try {
                 $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar";
                 $archive = new PharData($tmpArchiveName);
             } catch (Exception $e) {
                 file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                 throw $e;
             }
             $counterCompression = 0;
             //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP
             $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames);
             foreach ($tabAllFiles as $fullPath => $fileName) {
                 try {
                     $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName);
                     $counterCompression++;
                     file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
                 } catch (Exception $e) {
                     unlink($tmpArchiveName);
                     file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                     throw $e;
                 }
             }
             $finalArchive = $tmpArchiveName;
             if ($typeArchive != ".tar") {
                 $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1);
                 file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress)));
                 if ($archiveTypeCompress == "gz") {
                     $archive->compress(Phar::GZ);
                 } elseif ($archiveTypeCompress == "bz2") {
                     $archive->compress(Phar::BZ2);
                 }
                 $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress;
             }
             $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName);
             rename($finalArchive, $destArchive);
             AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive)));
             if (file_exists($tmpArchiveName)) {
                 unlink($tmpArchiveName);
                 unlink(substr($tmpArchiveName, 0, -4));
             }
             $newNode = new AJXP_Node($currentDirUrl . $archiveName);
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             file_put_contents($progressCompressionFileName, "SUCCESS");
         }
     } elseif ($action == "check_compression_status") {
         $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]);
         $progressCompression = file_get_contents($progressCompressionFileName);
         $substrProgressCompression = substr($progressCompression, 0, 5);
         if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5);
             AJXP_XMLWriter::close();
         } elseif ($progressCompression == "SUCCESS") {
             $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($messages["compression.8"], null);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         } elseif ($substrProgressCompression == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressCompression);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         }
     } elseif ($action == "extraction") {
         $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME);
         $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1);
         $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8);
         $acceptedArchive = false;
         $extensionLength = 0;
         $counterExtract = 0;
         $currentAllPydioPath = $currentDirUrl . $fileArchive;
         $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath);
         $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION);
         //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES
         foreach ($authorizedExtension as $extension => $strlenExtension) {
             if ($pathInfoCurrentAllPydioPath == $extension) {
                 $acceptedArchive = true;
                 $extensionLength = $strlenExtension;
                 break;
             }
         }
         if ($acceptedArchive == false) {
             file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]);
             throw new AJXP_Exception($messages["compression.15"]);
         }
         $onlyFileName = substr($fileArchive, 0, -$extensionLength);
         $lastPosOnlyFileName = strrpos($onlyFileName, "-");
         $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName);
         $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1);
         if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) {
             $tmpOnlyFileName = $onlyFileName;
             $counterDuplicate = 1;
         }
         while (file_exists($currentDirUrl . $onlyFileName)) {
             $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate;
             $counterDuplicate++;
         }
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             file_put_contents($progressExtractFileName, $messages["compression.12"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         }
         mkdir($currentDirUrl . $onlyFileName, 0777, true);
         chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777);
         try {
             $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath));
             $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath));
             foreach ($fichiersArchive as $file) {
                 $fileGetPathName = $file->getPathname();
                 if ($file->isDir()) {
                     continue;
                 }
                 $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1);
                 try {
                     $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false);
                 } catch (Exception $e) {
                     file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
                     throw new AJXP_Exception($e);
                 }
                 $counterExtract++;
                 file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
             }
         } catch (Exception $e) {
             file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
             throw new AJXP_Exception($e);
         }
         file_put_contents($progressExtractFileName, "SUCCESS");
         $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
         AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
     } elseif ($action == "check_extraction_status") {
         $currentDirUrl = $httpVars["currentDirUrl"];
         $onlyFileName = $httpVars["onlyFileName"];
         $progressExtract = file_get_contents($progressExtractFileName);
         $substrProgressExtract = substr($progressExtract, 0, 5);
         if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4);
             AJXP_XMLWriter::close();
         } elseif ($progressExtract == "SUCCESS") {
             $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null);
             AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         } elseif ($substrProgressExtract == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressExtract);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         }
     }
 }
Ejemplo n.º 30
0
        }
        if ($pDefine) {
            $phar->addFromString('/processor.php', $pDefine);
        }
        if ($rDefine) {
            $phar->addFromString('/receiver.php', $rDefine);
        }
        if ($sDefine) {
            $phar->addFromString('/site.php', $sDefine);
        }
        $phar->addEmptyDir('/template');
        if ($m['application']['setting']) {
            $phar->addFromString("/template/setting.html", "{template 'common/header'}\r\n这里定义页面内容\r\n{template 'common/footer'}");
        }
        if ($m['icon']) {
            $phar->addFile($m['icon'], '/icon.jpg');
            @unlink($m['icon']);
        }
        if ($m['preview']) {
            $phar->addFile($m['preview'], '/preview.jpg');
            @unlink($m['preview']);
        }
        header('content-type: application/tar');
        header('content-disposition: attachment; filename="' . $ident . '.tar"');
        readfile($fname);
        unset($phar);
        Phar::unlinkArchive($fname);
    }
}
template('setting/designer');
function manifest($m)