Example #1
1
 /**
  * Render a response object.
  */
 function render($output_body = true)
 {
     $this->outputHeaders();
     if ($output_body) {
         $manifest = $this->stdio->exec(array('get_manifest_of', $this->revision));
         $stanzas = IDF_Scm_Monotone_BasicIO::parse($manifest);
         $zip = new ZipStream();
         foreach ($stanzas as $stanza) {
             if ($stanza[0]['key'] != 'file') {
                 continue;
             }
             $content = $this->stdio->exec(array('get_file', $stanza[1]['hash']));
             $zip->add_file($stanza[0]['values'][0], $content);
         }
         $zip->finish();
     }
 }
 public static function apiDownload(Request $r)
 {
     self::authenticateRequest($r);
     self::validateStats($r);
     // Get our runs
     $relevant_columns = array('run_id', 'guid', 'language', 'status', 'verdict', 'runtime', 'penalty', 'memory', 'score', 'contest_score', 'time', 'submit_delay', 'Users.username', 'Problems.alias');
     try {
         $runs = RunsDAO::search(new Runs(array('contest_id' => $r['contest']->getContestId())), 'time', 'DESC', $relevant_columns);
     } catch (Exception $e) {
         // Operation failed in the data layer
         throw new InvalidDatabaseOperationException($e);
     }
     $zip = new ZipStream($r['contest_alias'] . '.zip');
     // Add runs to zip
     $table = "guid,user,problem,verdict,points\n";
     foreach ($runs as $run) {
         $zip->add_file_from_path('runs/' . $run->getGuid(), RunController::getSubmissionPath($run));
         $columns[0] = 'username';
         $columns[1] = 'alias';
         $usernameProblemData = $run->asFilteredArray($columns);
         $table .= $run->getGuid() . ',' . $usernameProblemData['username'] . ',' . $usernameProblemData['alias'] . ',' . $run->getVerdict() . ',' . $run->getContestScore();
         $table .= "\n";
     }
     $zip->add_file('summary.csv', $table);
     // Add problem cases to zip
     $contest_problems = ContestProblemsDAO::GetRelevantProblems($r['contest']->getContestId());
     foreach ($contest_problems as $problem) {
         $zip->add_file_from_path($problem->getAlias() . '_cases.zip', PROBLEMS_PATH . '/' . $problem->getAlias() . '/cases.zip');
     }
     // Return zip
     $zip->finish();
     die;
 }
 static function downloadToZip($data)
 {
     // set cookie
     setcookie('fileLoading', true, time() + 10, '/');
     //Create ZipArchive using Stream
     $zipStream = new ZipStream('exams.zip');
     foreach ($data as $item) {
         //Add files
         $filesInDirectory = $item["value"];
         foreach ($filesInDirectory as $file) {
             //Download file
             $downloaded_file = file_get_contents($file);
             //Add to zip
             $zipStream->add_file($item["key"] . "/" . basename($file), $downloaded_file);
         }
     }
     $zipStream->finish();
     //Clean up
     ob_clean();
     flush();
 }
 /**
  * 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 other
  * objects in the same object hierarchy as the specified object. 
  */
 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->DownloadAttributeFile();
     }
     $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 = caEmbedMediaMetadataIntoFile($t_rep->getMediaPath('media', $ps_version), $t_subject->tableName(), $t_subject->getPrimaryKey(), $t_subject->getTypeCode(), $t_rep->getPrimaryKey(), $t_rep->getTypeCode()))) {
                 $vs_path = $t_rep->getMediaPath('media', $ps_version);
             }
             $va_file_paths[$vs_path] = $vs_file_name;
             $vn_c++;
         }
     }
     if (!($vn_limit = ini_get('max_execution_time'))) {
         $vn_limit = 30;
     }
     set_time_limit($vn_limit * 2);
     $o_zip = new ZipStream();
     foreach ($va_file_paths as $vs_path => $vs_name) {
         $o_zip->addFile($vs_path, $vs_name);
     }
     $o_view->setVar('zip_stream', $o_zip);
     $o_view->setVar('archive_name', preg_replace('![^A-Za-z0-9\\.\\-]+!', '_', $t_subject->get('idno')) . '.zip');
     $this->response->addContent($o_view->render('download_file_binary.php'));
     set_time_limit($vn_limit);
 }
Example #5
0
 function __construct($plgFile, $plgName, $domain = '')
 {
     $this->status = '';
     $this->error = '';
     if (empty($plgName)) {
         $plgName = basename($plgFile, '.php');
         $plgName = ucfirst(strtr($plgName, '-_', '  '));
     }
     $this->plgName = $plgName;
     $this->slug = strtolower(strtr($plgName, ' !.,', '----'));
     $this->slug = str_replace("--", "-", $this->slug);
     if (empty($domain)) {
         $domain = $this->slug;
     }
     $this->domain = $domain;
     $this->plgDir = dirname($plgFile);
     $this->plgURL = plugin_dir_url($plgFile);
     $locale = get_locale();
     $this->locale = str_replace('-', '_', $locale);
     $this->target = $this->locale;
     if (!is_admin()) {
         return;
     }
     if (!session_id()) {
         session_start();
     }
     if (!empty($_POST['ezt-savePot']) || !empty($_POST['ezt-download'])) {
         // saving cannot be done from handleSubmits
         // because it would be too late for the headers.
         $slug = $_POST['ezt-slug'];
         if ($slug == $this->slug) {
             if (!empty($_POST['ezt-savePot'])) {
                 $target = $_POST['ezt-target'];
                 $file = "{$slug}-{$target}.zip";
                 $potArray = unserialize(gzinflate(base64_decode($_POST['potArray'])));
                 $poName = $target;
             }
             if (!empty($_POST['ezt-download'])) {
                 require_once ABSPATH . WPINC . '/pluggable.php';
                 global $current_user;
                 get_currentuserinfo();
                 $msg = array();
                 $msg['name'] = $current_user->user_firstname . " " . $current_user->user_lastname;
                 $msg['email'] = $current_user->user_email;
                 $msg['blog'] = get_bloginfo('blog');
                 $msg['url'] = get_bloginfo('url');
                 $msg['charset'] = get_bloginfo('charset');
                 $msg['locale'] = $this->locale;
                 $msg['ezt-target'] = "POT File";
                 $file = "{$slug}.zip";
                 $s = $this->getFileContents();
                 $POs = $this->getTranPOs($s);
                 $potArray = $this->mkPotStr($POs, $msg);
                 $poName = $slug;
             }
             $zip = new ZipStream($file);
             if ($this->isEmbedded && $slug != 'easy-translator' && $slug != 'easy-translator-lite') {
                 $zip->add_file("readme.txt", "Please edit the included PO files using appropriate tools such as poedit (or any text editor) and email them to the plugin author. If you are translating one of my plugins, the email address is manoj@thulasidas.com.");
             }
             foreach ($potArray as $d => $str) {
                 if (empty($d)) {
                     // skip strings with no domain -- they are WP core ones
                     continue;
                 }
                 if ($d == $slug) {
                     $filePO = "{$poName}.po";
                 } else {
                     // d should be 'easy-common'
                     $filePO = "{$poName}_{$d}.po";
                 }
                 $zip->add_file($filePO, $str);
             }
             $zip->finish();
             $this->status .= '<div class="updated">Pot file: ' . $file . ' was saved.</div> ';
             exit(0);
         }
     }
 }
Example #6
0
/**
 * Outputs a file for zip download
 * @param string $zipname name of the zip file
 * @param string $file the file to zip
 */
function putZip($zipname, $file)
{
    //we are dealing with file system items, convert the names
    $fileFS = internalToFilesystem($file);
    if (class_exists('ZipArchive')) {
        $zipfileFS = tempnam('', 'zip');
        $zip = new ZipArchive();
        $zip->open($zipfileFS, ZipArchive::CREATE);
        $zip->addFile($fileFS, basename($fileFS));
        $zip->close();
        ob_get_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=" . basename($zipname) . ";");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($zipfileFS));
        readfile($zipfileFS);
        // remove zip file from temp path
        unlink($zipfileFS);
    } else {
        include_once SERVERPATH . '/' . ZENFOLDER . '/lib-zipStream.php';
        $zip = new ZipStream(internalToFilesystem($zipname));
        $zip->add_file_from_path(basename($fileFS), $fileFS);
        $zip->finish();
    }
}
<?php

// Example. Zip all .html files in the current directory and save to current directory.
// Make a copy, also to the current dir, for good measure.
//$mem = ini_get('memory_limit');
//$extime = ini_get('max_execution_time');
//
////ini_set('memory_limit', '512M');
//ini_set('max_execution_time', 120);
include_once "ZipStream.php";
//print_r(ini_get_all());
$fileTime = date("D, d M Y H:i:s T");
$chapter1 = "Chapter 1\n" . "Lorem ipsum\n" . "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n";
$zip = new ZipStream("ZipStreamExample1s.zip");
$zip->setComment("Example Zip file for Large file sets.\nCreated on " . date('l jS \\of F Y h:i:s A'));
$zip->openStream("big one3.txt");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->closeStream();
$zip->addDirectory("Empty Dir");
$zip->finalize();
// Mandatory, needed to send the Zip files central directory structure.
 /**
  * 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) {
         $o_zip = new ZipStream();
         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_zip->addFile($vs_path, $vs_filename);
                 $vn_c++;
             }
         }
         $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
         // send files
         $o_view->setVar('zip_stream', $o_zip);
         $o_view->setVar('archive_name', 'media_for_' . mb_substr(preg_replace('![^A-Za-z0-9]+!u', '_', ($vs_set_code = $t_set->get('set_code')) ? $vs_set_code : $t_set->getPrimaryKey()), 0, 20) . '.zip');
         $this->response->addContent($o_view->render('download_file_binary.php'));
         return;
     } else {
         $this->notification->addNotification(_t('No files to download'), __NOTIFICATION_TYPE_ERROR__);
         $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_sets', $t_set->getPrimaryKey()));
         return;
     }
     return $this->Edit();
 }
 public function getLotMedia()
 {
     //if ((bool)$this->request->config->get('allow_download_of_all_object_media_in_a_lot')) {	// DO WE NEED TO REINSTATE THIS OPTIN?
     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));
     $o_media_metadata_conf = Configuration::load($t_lot->getAppConfig()->get('media_metadata'));
     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'), 'type_code' => caGetListItemIdno($qr_res->get('type_id')), 'paths' => $va_original_paths, 'representation_ids' => $qr_res->get('ca_object_representations.representation_id', array('returnAsArray' => true)), 'representation_types' => $qr_res->get('ca_object_representations.type_id', array('returnAsArray' => true)));
             }
         }
         if (sizeof($va_paths) > 0) {
             $o_zip = new ZipStream();
             foreach ($va_paths as $vn_object_id => $va_path_info) {
                 // make sure we don't download representations the user isn't allowed to read
                 if (!caCanRead($this->request->user->getPrimaryKey(), 'ca_objects', $vn_object_id)) {
                     continue;
                 }
                 $vn_c = 1;
                 foreach ($va_path_info['paths'] as $vn_i => $vs_media_path) {
                     if (!file_exists($vs_media_path)) {
                         continue;
                     }
                     if ($o_media_metadata_conf->get('do_metadata_embedding_for_lot_media_download')) {
                         if (!($vs_path = caEmbedMediaMetadataIntoFile($vs_media_path, 'ca_objects', $vn_object_id, $va_path_info['type_code'], $va_path_info['representation_ids'][$vn_i], $va_path_info['representation_types'][$vn_i]))) {
                             $vs_path = $vs_media_path;
                         }
                     } else {
                         $vs_path = $vs_media_path;
                     }
                     $vs_filename = $va_path_info['idno'] ? $va_path_info['idno'] : $vn_object_id;
                     $vs_filename .= "_{$vn_c}";
                     if ($vs_ext = pathinfo($vs_media_path, PATHINFO_EXTENSION)) {
                         $vs_filename .= ".{$vs_ext}";
                     }
                     $o_zip->addFile($vs_path, $vs_filename);
                     $vn_c++;
                 }
             }
             $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
             // send files
             $o_view->setVar('zip_stream', $o_zip);
             $o_view->setVar('archive_name', 'media_for_' . mb_substr(preg_replace('![^A-Za-z0-9]+!u', '_', ($vs_idno = $t_lot->get('idno_stub')) ? $vs_idno : $t_lot->getPrimaryKey()), 0, 20) . '.zip');
             $this->response->addContent($o_view->render('download_file_binary.php'));
             return;
         } else {
             $this->notification->addNotification(_t('No files to download'), __NOTIFICATION_TYPE_ERROR__);
             $this->opo_response->setRedirect(caEditorUrl($this->opo_request, 'ca_object_lots', $t_lot->getPrimaryKey()));
             return;
         }
     }
     //}
     return $this->Edit();
 }
Example #10
0
@(include_once '../conf/configuration.php') or die("Strip It isn't configured yet: conf/configuration.php file is missing.<br/>See README for details.");
@(require_once "zipstream.php");
/**
 * generate the metadata conf
 */
function getMetadataContent($conf)
{
    return "[Desktop Entry]\n" . "Name=" . $conf->title . "\n" . "Comment=" . $conf->title . "\n" . "Type=Service\n" . "X-KDE-ServiceTypes=Plasma/Comic\n" . "Icon=favicon.png\n" . "\n" . "X-KDE-Library=plasma_comic_krossprovider\n" . "X-KDE-PluginInfo-Author=Frederic Forjan\n" . "X-KDE-PluginInfo-Email=fforjab@free.fr\n" . "X-KDE-PluginInfo-Name=" . $conf->title . "\n" . "X-KDE-PluginInfo-Version=0.2\n" . "X-KDE-PluginInfo-Website=http://stripit.sf.net\n" . "X-KDE-PluginInfo-License=GPLv2\n" . "X-KDE-PluginInfo-EnabledByDefault=true\n" . "X-KDE-PlasmaComicProvider-SuffixType=Number";
}
/**
 * return the favicon content
 */
function getFaviconContent()
{
    return implode("", file("../favicon.png"));
}
/**
 * generate the main.es file
 */
function getMainEsContent($conf)
{
    return "//auto-generated URL\nvar URL =  \"" . $conf->url . "/\"\n" . implode("", file("main.es.template"));
}
# create a new stream object
$conf = new configuration();
$zipfile = new ZipStream($conf->title . ".comic", array('content_type' => 'application/octet-stream'));
$conf = new configuration();
$zipfile->add_file("favicon.png", getFaviconContent());
$zipfile->add_file("metadata.desktop", getMetadataContent($conf));
$zipfile->add_file("contents/code/main.es", getMainEsContent($conf));
$zipfile->finish();
Example #11
0
        throw new Exception('Permission denied');
    }
    $app['zadania_service']->delete($id);
    return new RedirectResponse($app['url_generator']->generate('home'));
})->before($checkUser)->bind('zadanie.delete')->convert('id', function ($id) {
    return (int) $id;
});
/**
 * Stahovanie zadani
 */
$app->get('/zadanie/{id}/zip', function (Silex\Application $app, $id) {
    error_reporting(0);
    $filelist = $app['zadania_service']->getFileList($id);
    $notelist = $app['zadania_service']->getNotes($id);
    $stream = function () use($filelist, $notelist, $id) {
        $zip = new ZipStream('zadanie_' . $id . '.zip');
        foreach ($notelist as $note) {
            if (empty($note['poznamka'])) {
                continue;
            }
            $zip->add_file('zadanie_' . $id . '/' . $note['login'] . '/poznamka.txt', $note['poznamka']);
        }
        foreach ($filelist as $subor) {
            $zip->add_file_from_path('zadanie_' . $id . '/' . $subor['login'] . '/' . $subor['nazov'], __DIR__ . '/uploads/' . $subor['cesta']);
        }
        $zip->finish();
    };
    return $app->stream($stream, 200, array('Content-Type' => 'application/zip'));
})->before($checkUser)->bind('zadanie.zip')->convert('id', function ($id) {
    return (int) $id;
});
Example #12
0
    }
    $i = 0;
    $filesString = "";
    foreach ($frames as $frame) {
        $i++;
        $filesName = sprintf("%0" . ZM_EVENT_IMAGE_DIGITS . "d-capture.jpg", $i);
        $filesString .= "\nframes.push(\"events/" . $mid . "/" . $eid . "/" . $filesName . "\");";
        $zip->addLargeFile($frame, "events/" . $mid . "/" . $eid . "/" . $filesName);
    }
    return $filesString;
}
if (isset($_REQUEST['exportevents'])) {
    require 'skins/' . $skin . '/includes/ZipStream.php';
    if ($_REQUEST['exportevents'] === "single") {
        if (isset($_REQUEST['eid']) && ctype_digit($_REQUEST['eid'])) {
            $zip = new ZipStream("event-" . $_REQUEST['eid'] . ".zip");
            $zip->addDirectory("events");
            $zip->addDirectory("assets");
            $filesString = addEventToZip($_REQUEST['eid'], $_REQUEST['mid'], $zip);
            $zip->addFile(file_get_contents("skins/{$skin}/views/assets/images/onerror.png"), "assets/playback-placeholder.png");
            $playerFile = file_get_contents("skins/{$skin}/views/includes/standalone-event-player.html");
            $playerFile = str_replace("###files###", $filesString, $playerFile);
            $zip->addFile($playerFile, "player.html");
            return $zip->finalize();
        } else {
            die("ERROR: Invalid event ID!");
        }
    } else {
        die("ERROR: Invalid export option!");
    }
}
Example #13
0
<?php

# load zipstream class
require '../zipstream.php';
# get path to current file
$pwd = dirname(__FILE__);
# add some random files
$files = array('../extras/zip-appnote-6.3.1-20070411.txt', '../zipstream.php');
# create new zip stream object
$zip = new ZipStream('test.zip', array('comment' => 'this is a zip file comment.  hello?'));
# common file options
$file_opt = array('time' => time() - 2 * 3600, 'comment' => 'this is a file comment. hi!');
# add files under folder 'asdf'
foreach ($files as $file) {
    # build absolute path and get file data
    $path = $file[0] == '/' ? $file : "{$pwd}/{$file}";
    $data = file_get_contents($path);
    # add file to archive
    $zip->add_file('asdf/' . basename($file), $data, $file_opt);
}
# add same files again wihtout a folder
foreach ($files as $file) {
    # build absolute path and get file data
    $path = $file[0] == '/' ? $file : "{$pwd}/{$file}";
    $data = file_get_contents($path);
    # add file to archive
    $zip->add_file(basename($file), $data, $file_opt);
}
# finish archive
$zip->finish();
 public function __construct($name, $opts = array())
 {
     parent::__construct($name, $opts);
 }
Example #15
0
 public static function apiDownload(Request $r)
 {
     self::authenticateRequest($r);
     self::validateStats($r);
     // Get our runs
     $relevant_columns = array("run_id", "guid", "language", "status", "verdict", "runtime", "penalty", "memory", "score", "contest_score", "time", "submit_delay", "Users.username", "Problems.alias");
     try {
         $runs = RunsDAO::search(new Runs(array("contest_id" => $r["contest"]->getContestId())), "time", "DESC", $relevant_columns);
     } catch (Exception $e) {
         // Operation failed in the data layer
         throw new InvalidDatabaseOperationException($e);
     }
     $zip = new ZipStream($r["contest_alias"] . '.zip');
     // Add runs to zip
     $table = "guid,user,problem,verdict,points\n";
     foreach ($runs as $run) {
         $zip->add_file_from_path("runs/" . $run->getGuid(), RunController::getSubmissionPath($run));
         $columns[0] = 'username';
         $columns[1] = 'alias';
         $usernameProblemData = $run->asFilteredArray($columns);
         $table .= $run->getGuid() . "," . $usernameProblemData['username'] . "," . $usernameProblemData['alias'] . "," . $run->getVerdict() . "," . $run->getContestScore();
         $table .= "\n";
     }
     $zip->add_file("summary.csv", $table);
     // Add problem cases to zip
     $contest_problems = ContestProblemsDAO::GetRelevantProblems($r["contest"]->getContestId());
     foreach ($contest_problems as $problem) {
         $zip->add_file_from_path($problem->getAlias() . "_cases.zip", PROBLEMS_PATH . "/" . $problem->getAlias() . "/cases.zip");
     }
     // Return zip
     $zip->finish();
     die;
 }
Example #16
0
 /**
  * Creates a zip file of the album
  *
  * @param string $albumname album folder
  * @param bool fromcache if true, images will be the "sized" image in the cache file
  */
 static function create($albumname, $fromcache)
 {
     global $_zp_zip_list, $_zp_gallery, $defaultSize;
     $album = newAlbum($albumname);
     if (!$album->isMyItem(LIST_RIGHTS) && !checkAlbumPassword($albumname)) {
         self::pageError(403, gettext("Forbidden"));
     }
     if (!$album->exists) {
         self::pageError(404, gettext('Album not found'));
     }
     $_zp_zip_list = array();
     if ($fromcache) {
         $opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from cached images of %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
         loadLocalOptions(false, $_zp_gallery->getCurrentTheme());
         $defaultSize = getOption('image_size');
         self::AddAlbumCache($album, strlen($albumname), SERVERPATH . '/' . CACHEFOLDER . '/' . $albumname);
     } else {
         $opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from images in %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
         self::AddAlbum($album, strlen($albumname), SERVERPATH . '/' . ALBUMFOLDER . '/' . $albumname);
     }
     $zip = new ZipStream($albumname . '.zip', $opt);
     foreach ($_zp_zip_list as $path => $file) {
         @set_time_limit(6000);
         $zip->add_file_from_path(internalToFilesystem($file), internalToFilesystem($path));
     }
     $zip->finish();
 }
Example #17
0
<?php

/*
 * A test to see if it was possible to recreate the result of
 *  Issue #7, if not the cause.
 * And a demnostration why the author of the script calling zip
 *  needs to be dilligent not to add extra characters to the output.
 */
include_once "ZipStream.php";
$zip = new ZipStream("test.zip");
/*
 * As seen in the output, the above construct with a PHP end and start tag after
 * creating the ZipStream is a bad idea. The Zip file will be starting with a
 * space followed by the newline characters.
 */
$zip->addDirectory("test");
$zip->addDirectoryContent("testData/test", "test");
return $zip->finalize();
<?php

require_once "../lib/init.php";
protectPage(12);
// Profile pictures privileges
// Get a list of all current members
$q = "SELECT ID FROM Members WHERE WardID={$MEMBER->WardID} AND PictureFile != '' ORDER BY FirstName ASC, LastName ASC";
$r = DB::Run($q);
if (mysql_num_rows($r) == 0) {
    fail("No pictures to export; no members have a profile picture.");
}
$zip = new ZipStream("profile_pics.zip");
while ($row = mysql_fetch_array($r)) {
    $member = Member::Load($row['ID']);
    $file = $member->PictureFile;
    if (file_exists("../uploads/{$file}")) {
        $zip->addLargeFile("../uploads/" . $file, "profile_pictures/" . $file);
    }
}
$zip->finalize();
Example #19
0
 /**
  * Sends all files from a set of rows of a users table to the client.
  * @param string $name name of the database table
  * @param string $rowIds ids of the rows
  */
 public function row($table, array $rowIds)
 {
     // look for the files in the table
     $rowFiles = $this->_getFilesInRow($table, $rowIds);
     if (empty($rowFiles)) {
         throw new Daiquiri_Exception_NotFound();
     }
     // leave some time for the file to be transferred
     ini_set('max_execution_time', 3600);
     // setup zipped transfer
     $fileName = $table . ".zip";
     $zip = new ZipStream($fileName);
     $comment = "All files connected to rows " . implode(", ", $rowIds) . " of table " . $table . " downloaded on " . date('l jS \\of F Y h:i:s A');
     $zip->setComment($comment);
     // look for the files in the file system and stream files
     foreach ($rowFiles as $rowFile) {
         // look for file
         $file = $this->_findFile($rowFile);
         if (empty($file)) {
             continue;
         }
         // zip and stream
         $fhandle = fopen($file, "rb");
         $zip->addLargeFile($fhandle, $rowFile);
         fclose($fhandle);
     }
     $zip->finalize();
 }
Example #20
0
 public function zip()
 {
     if (!CONFIG()->pool_zips) {
         throw new Rails\ActiveRecord\Exception\RecordNotFoundException();
     }
     $pool = Pool::find($this->params()->id);
     $files = $pool->get_zip_data($this->params()->all());
     $zip = new ZipStream($pool->pretty_name() . '.zip');
     foreach ($files as $file) {
         list($path, $filename) = $file;
         $zip->addLargeFile($path, $filename);
     }
     $zip->finalize();
     $this->render(['nothing' => true]);
 }
 /**
  * 
  * 
  */
 public function DownloadRepresentations()
 {
     if ($t_subject = $this->opo_datamodel->getInstanceByTableName($this->ops_tablename, true)) {
         $o_media_metadata_conf = Configuration::load($t_subject->getAppConfig()->get('media_metadata'));
         $pa_ids = null;
         if ($vs_ids = trim($this->request->getParameter($t_subject->tableName(), pString))) {
             if ($vs_ids != 'all') {
                 $pa_ids = explode(';', $vs_ids);
                 foreach ($pa_ids as $vn_i => $vs_id) {
                     if (!trim($vs_id) || !(int) $vs_id) {
                         unset($pa_ids[$vn_i]);
                     }
                 }
             }
         }
         if (!is_array($pa_ids) || !sizeof($pa_ids)) {
             $pa_ids = $this->opo_result_context->getResultList();
         }
         $vn_file_count = 0;
         $o_view = new View($this->request, $this->request->getViewsDirectoryPath() . '/bundles/');
         if (is_array($pa_ids) && sizeof($pa_ids)) {
             $ps_version = $this->request->getParameter('version', pString);
             if ($qr_res = $t_subject->makeSearchResult($t_subject->tableName(), $pa_ids, array('filterNonPrimaryRepresentations' => false))) {
                 if (!($vn_limit = ini_get('max_execution_time'))) {
                     $vn_limit = 30;
                 }
                 set_time_limit($vn_limit * 10);
                 $o_zip = new ZipStream();
                 while ($qr_res->nextHit()) {
                     if (!is_array($va_version_list = $qr_res->getMediaVersions('ca_object_representations.media')) || !in_array($ps_version, $va_version_list)) {
                         $vs_version = 'original';
                     } else {
                         $vs_version = $ps_version;
                     }
                     $va_paths = $qr_res->getMediaPaths('ca_object_representations.media', $vs_version);
                     $va_infos = $qr_res->getMediaInfos('ca_object_representations.media');
                     $va_representation_ids = $qr_res->get('ca_object_representations.representation_id', array('returnAsArray' => true));
                     $va_representation_types = $qr_res->get('ca_object_representations.type_id', array('returnAsArray' => true));
                     foreach ($va_paths as $vn_i => $vs_path) {
                         $vs_ext = array_pop(explode(".", $vs_path));
                         $vs_idno_proc = preg_replace('![^A-Za-z0-9_\\-]+!', '_', $qr_res->get($t_subject->tableName() . '.idno'));
                         $vs_original_name = $va_infos[$vn_i]['ORIGINAL_FILENAME'];
                         $vn_index = sizeof($va_paths) > 1 ? "_" . ($vn_i + 1) : '';
                         $vn_representation_id = $va_representation_ids[$vn_i];
                         $vs_representation_type = caGetListItemIdno($va_representation_types[$vn_i]);
                         // make sure we don't download representations the user isn't allowed to read
                         if (!caCanRead($this->request->user->getPrimaryKey(), 'ca_object_representations', $vn_representation_id)) {
                             continue;
                         }
                         switch ($this->request->user->getPreference('downloaded_file_naming')) {
                             case 'idno':
                                 $vs_filename = "{$vs_idno_proc}{$vn_index}.{$vs_ext}";
                                 break;
                             case 'idno_and_version':
                                 $vs_filename = "{$vs_idno_proc}_{$vs_version}{$vn_index}.{$vs_ext}";
                                 break;
                             case 'idno_and_rep_id_and_version':
                                 $vs_filename = "{$vs_idno_proc}_representation_{$vn_representation_id}_{$vs_version}{$vn_index}.{$vs_ext}";
                                 break;
                             case 'original_name':
                             default:
                                 if ($vs_original_name) {
                                     $va_tmp = explode('.', $vs_original_name);
                                     if (sizeof($va_tmp) > 1) {
                                         if (strlen($vs_ext = array_pop($va_tmp)) < 3) {
                                             $va_tmp[] = $vs_ext;
                                         }
                                     }
                                     $vs_filename = join('_', $va_tmp) . "{$vn_index}.{$vs_ext}";
                                 } else {
                                     $vs_filename = "{$vs_idno_proc}_representation_{$vn_representation_id}_{$vs_version}{$vn_index}.{$vs_ext}";
                                 }
                                 break;
                         }
                         if ($o_media_metadata_conf->get('do_metadata_embedding_for_search_result_media_download')) {
                             if ($vs_path_with_embedding = caEmbedMediaMetadataIntoFile($vs_path, 'ca_objects', $qr_res->get('ca_objects.object_id'), caGetListItemIdno($qr_res->get('ca_objects.type_id')), $vn_representation_id, $vs_representation_type)) {
                                 $vs_path = $vs_path_with_embedding;
                             }
                         }
                         if (!file_exists($vs_path)) {
                             continue;
                         }
                         $o_zip->addFile($vs_path, $vs_filename);
                         $vn_file_count++;
                     }
                 }
             }
         }
         if ($o_zip && $vn_file_count > 0) {
             $o_view->setVar('zip_stream', $o_zip);
             $o_view->setVar('archive_name', 'media_for_' . mb_substr(preg_replace('![^A-Za-z0-9]+!u', '_', $this->getCriteriaForDisplay()), 0, 20) . '.zip');
             $this->response->addContent($o_view->render('download_file_binary.php'));
             set_time_limit($vn_limit);
             //$this->render('Results/object_representation_download_binary.php');
         } else {
             $this->response->setHTTPResponseCode(204, _t('No files to download'));
         }
         return;
     }
     // post error
     $this->postError(3100, _t("Could not generate ZIP file for download"), "BaseFindController->DownloadRepresentation()");
 }
Example #22
0
 /**
  *Export an entire collection as a zip file filled with METS xml 
  *files for each item.
  *
  *@param int $collectionID The ID of the omeka collection to export
  *@return void
  */
 public function exportCollectionZip($collectionID)
 {
     include_once dirname(dirname(__FILE__)) . '/libraries/zipstream-php-0.2.2/zipstream.php';
     $collection = get_record_by_id("collection", $collectionID);
     $items = get_records('Item', array('collection' => $collectionID), 999);
     error_reporting(0);
     $zip = new ZipStream('Collection_' . $collection->id . '.zip');
     foreach ($items as $item) {
         ob_start();
         $this->_generateMETS($item->id, false);
         $zip->add_file("Item_" . $item->id . ".mets.xml", ob_get_clean());
     }
     $zip->finish();
 }
Example #23
0
                        ob_get_clean();
                        header("Pragma: public");
                        header("Expires: 0");
                        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                        header("Cache-Control: private", false);
                        header("Content-Type: application/zip");
                        header("Content-Disposition: attachment; filename=" . basename($zipname) . ";");
                        header("Content-Transfer-Encoding: binary");
                        header("Content-Length: " . filesize($zipname));
                        readfile($zipname);
                        // remove zip file from temp path
                        unlink($zipname);
                        exit;
                    } else {
                        include_once SERVERPATH . '/' . ZENFOLDER . '/lib-zipStream.php';
                        $zip = new ZipStream($zipname);
                        $zip->add_file_from_path(internalToFilesystem(basename($file)), internalToFilesystem($file));
                        $zip->finish();
                    }
                }
                break;
        }
    }
}
list($subtabs, $default) = getLogTabs();
$zenphoto_tabs['logs'] = array('text' => gettext("logs"), 'link' => WEBPATH . "/" . ZENFOLDER . '/admin-logs.php?page=logs', 'subtabs' => $subtabs, 'default' => $default);
printAdminHeader('logs', $default);
echo "\n</head>";
?>

<body>
Example #24
0
<?php

// Example. Zip all .html files in the current directory and save to current directory.
// Make a copy, also to the current dir, for good measure.
//$mem = ini_get('memory_limit');
$extime = ini_get('max_execution_time');
//
////ini_set('memory_limit', '512M');
ini_set('max_execution_time', 600);
include_once "ZipStream.php";
//print_r(ini_get_all());
$fileTime = date("D, d M Y H:i:s T");
$chapter1 = "Chapter 1\n" . "Lorem ipsum\n" . "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna lorem, mattis sit amet porta vitae, consectetur ut eros. Nullam id mattis lacus. In eget neque magna, congue imperdiet nulla. Aenean erat lacus, imperdiet a adipiscing non, dignissim eget felis. Nulla facilisi. Vivamus sit amet lorem eget mauris dictum pharetra. In mauris nulla, placerat a accumsan ac, mollis sit amet ligula. Donec eget facilisis dui. Cras elit quam, imperdiet at malesuada vitae, luctus id orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque eu libero in leo ultrices tristique. Etiam quis ornare massa. Donec in velit leo. Sed eu ante tortor.\n";
$zip = new ZipStream("ZipStreamExample1.zip");
$zip->setComment("Example Zip file for Large file sets.\nCreated on " . date('l jS \\of F Y h:i:s A'));
$zip->addFile("Hello World!\r\n", "Hello.txt");
$zip->openStream("big one3.txt");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->addStreamData($chapter1 . "\n\n\n");
$zip->closeStream();
// For this test you need to create a large text file called "big one1.txt"
if (file_exists("big one1.txt")) {
    $zip->addLargeFile("big one1.txt", "big one2a.txt");
    $fhandle = fopen("big one1.txt", "rb");
    $zip->addLargeFile($fhandle, "big one2b.txt");
    fclose($fhandle);
}
$zip->addDirectory("Empty Dir");
//Dir test, using the stream option on $zip->addLargeFile
$fileDir = './';
Example #25
0
 /**
  * Creates a zip file of the album
  *
  * @param object $album album folder
  * @param string $zipname name of zip file
  * @param bool fromcache if true, images will be the "sized" image in the cache file
  */
 static function create($album, $zipname, $fromcache)
 {
     global $_zp_zip_list, $_zp_albums_visited_albumMenu, $_zp_gallery, $defaultSize;
     if (!$album->exists) {
         self::pageError(404, gettext('Album not found'));
     }
     if (!$album->checkAccess()) {
         self::pageError(403, gettext("Forbidden"));
     }
     $_zp_albums_visited_albumMenu = $_zp_zip_list = array();
     if ($fromcache) {
         $opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from cached images of %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
         $defaultSize = getThemeOption('image_size', NULL, $_zp_gallery->getCurrentTheme());
     } else {
         $defaultSize = NULL;
         $opt = array('large_file_size' => 5 * 1024 * 1024, 'comment' => sprintf(gettext('Created from images in %1$s on %2$s.'), $album->name, zpFormattedDate(DATE_FORMAT, time())));
     }
     self::AddAlbum($album, $fromcache);
     if (class_exists('ZipArchive')) {
         $zipfileFS = tempnam('', 'zip');
         $zip = new ZipArchive();
         $zip->open($zipfileFS, ZipArchive::CREATE);
         foreach ($_zp_zip_list as $path => $file) {
             @set_time_limit(6000);
             $zip->addFile($path, internalToFilesystem(trim($file, '/')));
         }
         $zip->close();
         ob_get_clean();
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Cache-Control: private", false);
         header("Content-Type: application/zip");
         header("Content-Disposition: attachment; filename=" . basename($zipname . '.zip') . ";");
         header("Content-Transfer-Encoding: binary");
         header("Content-Length: " . filesize($zipfileFS));
         readfile($zipfileFS);
         // remove zip file from temp path
         unlink($zipfileFS);
     } else {
         require_once SERVERPATH . '/' . ZENFOLDER . '/lib-zipStream.php';
         $zip = new ZipStream(internalToFilesystem($zipname) . '.zip', $opt);
         foreach ($_zp_zip_list as $path => $file) {
             @set_time_limit(6000);
             $zip->add_file_from_path(internalToFilesystem($file), $path);
         }
         $zip->finish();
     }
 }