add() public méthode

--------------------------------------------------------------------------------
public add ( $p_filelist )
function wpd_download()
{
    if (!class_exists('PclZip')) {
        include ABSPATH . 'wp-admin/includes/class-pclzip.php';
    }
    $what = $_GET['wpd'];
    $object = $_GET['object'];
    switch ($what) {
        case 'plugin':
            if (strpos($object, '/')) {
                $object = dirname($object);
            }
            $root = WP_PLUGIN_DIR;
            break;
        case 'theme':
            $root = get_theme_root($object);
            break;
    }
    $path = $root . '/' . $object;
    $fileName = $object . '.zip';
    $archive = new PclZip($fileName);
    $archive->add($path, PCLZIP_OPT_REMOVE_PATH, $root);
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    readfile($fileName);
    // remove tmp zip file
    unlink($fileName);
    exit;
}
 public function add($file)
 {
     if (empty($this->remove_path)) {
         $this->archive->add($file);
     } else {
         $this->archive->add($file, PCLZIP_OPT_REMOVE_PATH, $this->remove_path);
     }
     $this->saveMd5($file);
 }
 public function packed($file)
 {
     ini_set("memory_limit", "256M");
     if (empty($this->remove_path)) {
         $this->archive->add($file);
     } else {
         $this->archive->add($file, PCLZIP_OPT_REMOVE_PATH, $this->remove_path);
     }
     $this->saveMd5($file);
 }
Exemple #4
0
function zip_go()
{
    global $list, $options, $L;
    $saveTo = realpath($options['download_dir']) . '/';
    $_POST["archive"] = strlen(trim(urldecode($_POST["archive"]))) > 4 && substr(trim(urldecode($_POST["archive"])), -4) == ".zip" ? trim(urldecode($_POST["archive"])) : "archive.zip";
    $_POST["archive"] = $saveTo . basename($_POST["archive"]);
    for ($i = 0; $i < count($_POST["files"]); $i++) {
        $files[] = $list[$_POST["files"][$i]];
    }
    foreach ($files as $file) {
        $CurrDir = ROOT_DIR;
        $inCurrDir = stristr(dirname($file["name"]), $CurrDir) ? TRUE : FALSE;
        if ($inCurrDir) {
            $add_files[] = substr($file["name"], strlen($CurrDir));
        }
    }
    require_once CLASS_DIR . "pclzip.php";
    $archive = new PclZip($_POST["archive"]);
    $no_compression = $options['disable_to']['act_archive_compression'] || isset($_POST["no_compression"]);
    if (file_exists($_POST["archive"])) {
        if ($no_compression) {
            $v_list = $archive->add($add_files, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_NO_COMPRESSION);
        } else {
            $v_list = $archive->add($add_files, PCLZIP_OPT_REMOVE_ALL_PATH);
        }
    } else {
        if ($no_compression) {
            $v_list = $archive->create($add_files, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_NO_COMPRESSION);
        } else {
            $v_list = $archive->create($add_files, PCLZIP_OPT_REMOVE_ALL_PATH);
        }
    }
    if ($v_list == 0) {
        echo $L->say['_error'] . ": " . $archive->errorInfo(true) . "<br /><br />";
        return;
    } else {
        echo $L->say['_arcv'] . " <b>" . $_POST["archive"] . "</b> " . $L->say['success_created'] . "<br /><br />";
    }
    if (is_file($_POST['archive'])) {
        $time = getNowzone(@filemtime($_POST['archive']));
        while (isset($list[$time])) {
            $time++;
        }
        $list[$time] = array("name" => $_POST['archive'], "size" => bytesToKbOrMbOrGb(filesize($_POST['archive'])), "date" => $time);
        if (!updateListInFile($list)) {
            echo $L->say['couldnt_upd_list'] . "<br /><br />";
        }
    }
}
/**
 * Creates an archive of the given files.
 *
 * @param	array	$files		Array of files to archive
 * @param	string	$ommit_path	Path to ommit
 * @param	integer	$id			To prevent overwriting archives created in the same second
 * @return	string  $filename	Filename of the archive created
 */
function wpmove_create_archive($files, $ommit_path = '', $id = 0)
{
    $filename = trailingslashit(WPMOVE_BACKUP_DIR) . 'Backup-' . time() . $id . '.zip';
    $archive = new PclZip($filename);
    $archive->add($files, PCLZIP_OPT_REMOVE_PATH, $ommit_path);
    return basename($filename);
}
 /**
  * Creates zip of data directory.
  */
 public function zipRequest($messages = true)
 {
     $data = "";
     date_default_timezone_set("GMT");
     if ($messages) {
         $data = "<p>" . $this->localize("Please wait while the zip is being archived...") . "</p>";
     }
     $name = 'modules/Backup/zips/archive' . date("c") . '-id-' . $this->generateRandStr(20) . '.zip';
     include_once 'modules/Backup/pclzip.lib.php';
     $archive = new PclZip($name);
     $v_list = $archive->add('data/');
     if ($v_list == 0) {
         $data .= "<p><b>" . $this->localize("Error") . " Zipping:</b> " . $archive->errorInfo(true) . "</p>";
     } else {
         if ($messages) {
             $data .= "<p class='success'><strong>" . $this->localize("Success") . ":</strong> " . $this->localize("Your backup has been successfully prepared") . ".</p><p><strong>" . $this->localize("Download Zip of Backup") . ": <a href='" . $name . "'>" . $this->localize("Here") . "</a></strong></p>";
         } else {
             $data .= "<p class='error msg'>" . $this->localize("If an 'PCLZIP_ERR_READ_OPEN_FAIL' error has occured, this indicates that the permissions for the backup folder are sit incorrectly - if so please chmod 'modules/Backup/zips' to 777.") . "</p>";
         }
     }
     if ($messages) {
         $this->setContent($data);
     } else {
         return $data;
     }
 }
 function toSCO()
 {
     $deck_id = $_GET['deck_id'];
     if (isset($_GET['format'])) {
         $format = $_GET['format'];
     } else {
         $format = 'scorm2004_3rd';
     }
     $scorm = new Scorm();
     $scorm->create($deck_id, $format);
     $deck_name = $scorm->root_deck_name;
     $archive = new PclZip($deck_name . '.zip');
     //adding sco universal metadata
     $v_list = $archive->create(ROOT . DS . 'libraries' . DS . 'backend' . DS . $format, PCLZIP_OPT_REMOVE_PATH, ROOT . DS . 'libraries' . DS . 'backend' . DS . $format, PCLZIP_OPT_ADD_TEMP_FILE_ON);
     if ($v_list == 0) {
         die("Error : " . $archive->errorInfo(true));
     }
     //adding sco from tmp
     $v_list = $archive->add(ROOT . DS . 'tmp' . DS . $deck_name, PCLZIP_OPT_REMOVE_PATH, ROOT . DS . 'tmp' . DS . $deck_name, PCLZIP_OPT_ADD_TEMP_FILE_ON);
     if ($v_list == 0) {
         die("Error : " . $archive->errorInfo(true));
     }
     $archive->force_download();
     chmod(ROOT . DS . $deck_name . '.zip', 0777);
     unlink(ROOT . DS . $deck_name . '.zip');
     $this->RemoveDir(ROOT . DS . 'tmp' . DS . $deck_name);
 }
function cherry_plugin_export_content()
{
    $exclude_files = array('xml', 'json');
    /**
     * Filters folders to exclude from export parser
     * @var array
     */
    $exclude_folder = apply_filters('cherry_export_exclude_folders', array('woocommerce_uploads', 'wc-logs'));
    $response = array('what' => 'status', 'action' => 'export_content', 'id' => '1', 'data' => __('Export content done', CHERRY_PLUGIN_DOMAIN));
    $response_file = array('what' => 'file', 'action' => 'export_content', 'id' => '2');
    $zip_name = UPLOAD_BASE_DIR . '/sample_data.zip';
    cherry_plugin_delete_file($zip_name);
    if (is_dir(UPLOAD_BASE_DIR)) {
        $file_string = cherry_plugin_scan_dir(UPLOAD_BASE_DIR, $exclude_folder, $exclude_files);
    }
    $zip = new PclZip($zip_name);
    $result = $zip->create($file_string, PCLZIP_OPT_REMOVE_ALL_PATH);
    //export json
    $json_file = cherry_plugin_export_json();
    if (is_wp_error($json_file)) {
        $response['data'] = "Error : " . $json_file->get_error_message();
    } else {
        $zip->add($json_file, PCLZIP_OPT_REMOVE_ALL_PATH);
        cherry_plugin_delete_file($json_file);
    }
    //export xml
    $xml_file = cherry_plugin_export_xml();
    if (is_wp_error($xml_file)) {
        $response['data'] = "Error : " . $xml_file->get_error_message();
    } else {
        $zip->add($xml_file, PCLZIP_OPT_REMOVE_ALL_PATH);
        cherry_plugin_delete_file($xml_file);
    }
    $nonce = wp_create_nonce('cherry_plugin_download_content');
    $file_url = add_query_arg(array('action' => 'cherry_plugin_get_export_file', 'file' => $zip_name, '_wpnonce' => $nonce), admin_url('admin-ajax.php'));
    if ($result == 0) {
        $response['data'] = "Error : " . $zip->errorInfo(true);
    } else {
        $response_file['data'] = $file_url;
    }
    $xmlResponse = new WP_Ajax_Response($response);
    $xmlResponse->add($response_file);
    $xmlResponse->send();
    exit;
}
Exemple #9
0
 public function run()
 {
     try {
         main::log(lang::get('Start Backup process...', false));
         $this->init();
         $db_param = $this->getDBParams();
         $mysql = $this->incMysql();
         if (isset($this->params['optimize'])) {
             main::log(lang::get('Optimize Database Tables', false));
             $mysql->optimize();
         }
         $mysql->backup($this->db_file);
         if (filesize($this->db_file) == 0) {
             throw new Exception(lang::get('Error in create dump Database: Chance of a lack of rights for the backup.', fale));
         } else {
             $size_dump = round(filesize($this->db_file) / 1024 / 1024, 2);
             main::log(str_replace('%s', $size_dump, lang::get('Database Dump was successfully created( %s Mb):', false)) . str_replace(ABSPATH, '', $this->db_file));
         }
         $files = $this->createListFiles();
         $files[] = $this->db_file;
         if (($n = count($files)) > 0) {
             include main::getPluginDir() . "/libs/pclzip.lib.php";
             $archive = $this->dir_backup . '/' . $this->getArchive($this->name);
             $zip = new PclZip($archive);
             main::log(lang::get('Add files to Backup', false));
             main::log(lang::get('Create part ', false) . basename($archive));
             for ($i = 0; $i < $n; $i++) {
                 if (file_exists($archive) && filesize($archive) > $this->max_size_archive) {
                     unset($zip);
                     $archive = $this->dir_backup . '/' . $this->getNextArchive($this->name);
                     main::log(lang::get('Create part ', false) . basename($archive));
                     $zip = new PclZip($archive);
                 }
                 $zip->add($files[$i], PCLZIP_OPT_REMOVE_PATH, ABSPATH);
                 $this->saveMd5($files[$i], $archive);
             }
             // delete dump db
             main::log(lang::get('Remove dump Database with folder', false));
             main::remove($this->db_file);
             $dirs = readDirectrory($this->dir_backup, array('.zip', '.md5'));
             $size = 0;
             if (($n = count($dirs)) > 0) {
                 for ($i = 0; $i < $n; $i++) {
                     $size += filesize($dirs[$i]);
                     $dirs[$i] = basename($dirs[$i]);
                 }
             }
             $sizeMb = round($size / 1024 / 1024, 2);
             // MB
             main::log(str_replace('%s', $sizeMb, lang::get('Backup created is finish ( %s Mb)', false)));
             $this->dirs = $dirs;
             $this->size = $size;
         }
     } catch (Exception $e) {
         $this->setError($e->message);
     }
 }
Exemple #10
0
 /**
  * Send a zipped theme
  *
  * @author Samuele Tognini <*****@*****.**>
  */
 function send_theme($file)
 {
     require_once DOKU_PLUGIN . 'indexmenu/syntax/indexmenu.php';
     $idxm = new syntax_plugin_indexmenu_indexmenu();
     //clean the file name
     $file = cleanID($file);
     //check config
     if (!$idxm->getConf('be_repo') || empty($file)) {
         return false;
     }
     $repodir = INDEXMENU_IMG_ABSDIR . "/repository";
     $zipfile = $repodir . "/{$file}.zip";
     $localtheme = INDEXMENU_IMG_ABSDIR . "/{$file}/";
     //theme does not exists
     if (!file_exists($localtheme)) {
         return false;
     }
     if (!io_mkdir_p($repodir)) {
         return false;
     }
     $lm = @filemtime($zipfile);
     //no cached zip or older than 1 day
     if ($lm < time() - 60 * 60 * 24) {
         //create the zip
         require_once DOKU_PLUGIN . "indexmenu/inc/pclzip.lib.php";
         @unlink($zipfile);
         $zip = new PclZip($zipfile);
         $status = $zip->add($localtheme, PCLZIP_OPT_REMOVE_ALL_PATH);
         //error
         if ($status == 0) {
             return false;
         }
     }
     $len = (int) filesize($zipfile);
     //don't send large zips
     if ($len > 2 * 1024 * 1024) {
         return false;
     }
     //headers
     header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
     header('Pragma: public');
     header('Content-Type: application/zip');
     header('Content-Disposition: attachment; filename="' . basename($zipfile) . '";');
     header("Content-Transfer-Encoding: binary");
     //send zip
     $fp = @fopen($zipfile, 'rb');
     if ($fp) {
         $ct = @fread($fp, $len);
         print $ct;
     }
     @fclose($fp);
     return true;
 }
function cherry_plugin_export_content()
{
    $exclude_files = array('xml', 'json');
    $exclude_folder = array('woocommerce_uploads');
    $response = array('what' => 'status', 'action' => 'export_content', 'id' => '1', 'data' => __('Export content done', CHERRY_PLUGIN_DOMAIN));
    $response_file = array('what' => 'file', 'action' => 'export_content', 'id' => '2');
    $zip_name = UPLOAD_BASE_DIR . '/sample_data.zip';
    cherry_plugin_delete_file($zip_name);
    if (is_dir(UPLOAD_BASE_DIR)) {
        $file_string = cherry_plugin_scan_dir(UPLOAD_BASE_DIR, $exclude_folder, $exclude_files);
    }
    $zip = new PclZip($zip_name);
    $result = $zip->create($file_string, PCLZIP_OPT_REMOVE_ALL_PATH);
    //export json
    $json_file = cherry_plugin_export_json();
    if (is_wp_error($json_file)) {
        $response['data'] = "Error : " . $json_file->get_error_message();
    } else {
        $zip->add($json_file, PCLZIP_OPT_REMOVE_ALL_PATH);
        cherry_plugin_delete_file($json_file);
    }
    //export xml
    $xml_file = cherry_plugin_export_xml();
    if (is_wp_error($xml_file)) {
        $response['data'] = "Error : " . $xml_file->get_error_message();
    } else {
        $zip->add($xml_file, PCLZIP_OPT_REMOVE_ALL_PATH);
        cherry_plugin_delete_file($xml_file);
    }
    if ($result == 0) {
        $response['data'] = "Error : " . $zip->errorInfo(true);
    } else {
        $response_file['data'] = $zip_name;
    }
    $xmlResponse = new WP_Ajax_Response($response);
    $xmlResponse->add($response_file);
    $xmlResponse->send();
    exit;
}
Exemple #12
0
 /**
  * Serve files to browser - one file can be served directly, multiple files must be served as a ZIP file.
  */
 protected function _prepareFileDownload($fileArray)
 {
     if (count($fileArray) > 1) {
         // We need to zip multiple files and return a ZIP file to browser
         if (!@class_exists('ZipArchive') && !function_exists('gzopen')) {
             $this->_getSession()->addError(Mage::helper('xtento_orderexport')->__('PHP ZIP extension not found. Please download files manually from the server, or install the ZIP extension, or export just one file with each profile.'));
             return $this->_redirectReferer();
         }
         // ZIP creation
         $zipFile = false;
         if (@class_exists('ZipArchive')) {
             // Try creating it using the PHP ZIP functions
             $zipArchive = new ZipArchive();
             $zipFile = tempnam(sys_get_temp_dir(), 'zip');
             if ($zipArchive->open($zipFile, ZIPARCHIVE::CREATE) !== TRUE) {
                 $this->_getSession()->addError(Mage::helper('xtento_orderexport')->__('Could not open file ' . $zipFile . '. ZIP creation failed.'));
                 return $this->_redirectReferer();
             }
             foreach ($fileArray as $filename => $content) {
                 $zipArchive->addFromString($filename, $content);
             }
             $zipArchive->close();
         } else {
             if (function_exists('gzopen')) {
                 // Try creating it using the PclZip class
                 require_once Mage::getModuleDir('', 'Xtento_OrderExport') . DS . 'lib' . DS . 'PclZip.php';
                 $zipFile = tempnam(sys_get_temp_dir(), 'zip');
                 $zipArchive = new PclZip($zipFile);
                 if (!$zipArchive) {
                     $this->_getSession()->addError(Mage::helper('xtento_orderexport')->__('Could not open file ' . $zipFile . '. ZIP creation failed.'));
                     return $this->_redirectReferer();
                 }
                 foreach ($fileArray as $filename => $content) {
                     $zipArchive->add(array(array(PCLZIP_ATT_FILE_NAME => $filename, PCLZIP_ATT_FILE_CONTENT => $content)));
                 }
             }
         }
         if (!$zipFile) {
             $this->_getSession()->addError(Mage::helper('xtento_orderexport')->__('ZIP file couldn\'t be created.'));
             return $this->_redirectReferer();
         }
         $this->_prepareDownloadResponse("export_" . time() . ".zip", file_get_contents($zipFile));
         @unlink($zipFile);
         return $this;
     } else {
         // Just one file, output to browser
         foreach ($fileArray as $filename => $content) {
             return $this->_prepareDownloadResponse($filename, $content);
         }
     }
 }
/**
 * Do the main task of archiving a course.
 * 
 * @param int $course_id
 * @param string $course_code
 * @return boolean $success
 */
function doArchive($course_id, $course_code)
{
    global $webDir, $urlServer, $urlAppend, $siteName;
    if (extension_loaded('zlib')) {
        include 'include/pclzip/pclzip.lib.php';
    }
    $basedir = "{$webDir}/courses/archive/{$course_code}";
    mkpath($basedir);
    // Remove previous back-ups older than 10 minutes
    cleanup("{$webDir}/courses/archive", 600);
    $backup_date = date('Ymd-His');
    $backup_date_short = date('Ymd');
    $archivedir = $basedir . '/' . $backup_date;
    mkpath($archivedir);
    $zipfile = $basedir . "/{$course_code}-{$backup_date_short}.zip";
    // backup subsystems from main db
    $sql_course = "course_id = {$course_id}";
    $archive_conditions = array('course' => "id = {$course_id}", 'user' => "id IN (SELECT user_id FROM course_user\n                                          WHERE course_id = {$course_id})", 'course_user' => "course_id = {$course_id}", 'course_settings' => "course_id = {$course_id}", 'course_department' => "course = {$course_id}", 'course_module' => $sql_course, 'hierarchy' => "id IN (SELECT department FROM course_department\n                                          WHERE course = {$course_id})", 'announcement' => $sql_course, 'group_properties' => $sql_course, 'group' => $sql_course, 'group_members' => "group_id IN (SELECT id FROM `group`\n                                                    WHERE course_id = {$course_id})", 'document' => $sql_course, 'link_category' => $sql_course, 'link' => $sql_course, 'ebook' => $sql_course, 'ebook_section' => "ebook_id IN (SELECT id FROM ebook\n                                                    WHERE course_id = {$course_id})", 'ebook_subsection' => "section_id IN (SELECT ebook_section.id\n                                                         FROM ebook, ebook_section\n                                                         WHERE ebook.id = ebook_id AND\n                                                               course_id = {$course_id})", 'course_units' => $sql_course, 'unit_resources' => "unit_id IN (SELECT id FROM course_units\n                                                    WHERE course_id = {$course_id})", 'forum' => $sql_course, 'forum_category' => $sql_course, 'forum_topic' => "forum_id IN (SELECT id FROM forum\n                                                  WHERE course_id = {$course_id})", 'forum_post' => "topic_id IN (SELECT forum_topic.id\n                                                 FROM forum, forum_topic\n                                                 WHERE forum.id = forum_id AND\n                                                       course_id = {$course_id})", 'forum_notify' => $sql_course, 'forum_user_stats' => $sql_course, 'course_description' => $sql_course, 'glossary' => $sql_course, 'glossary_category' => $sql_course, 'video_category' => $sql_course, 'video' => $sql_course, 'videolink' => $sql_course, 'dropbox_msg' => $sql_course, 'dropbox_attachment' => "msg_id IN (SELECT id from dropbox_msg WHERE course_id = {$course_id})", 'dropbox_index' => "msg_id IN (SELECT id from dropbox_msg WHERE course_id = {$course_id})", 'lp_learnPath' => $sql_course, 'lp_module' => $sql_course, 'lp_asset' => "module_id IN (SELECT module_id FROM lp_module WHERE course_id = {$course_id})", 'lp_rel_learnPath_module' => "learnPath_id IN (SELECT learnPath_id FROM lp_learnPath WHERE course_id = {$course_id})", 'lp_user_module_progress' => "learnPath_id IN (SELECT learnPath_id FROM lp_learnPath WHERE course_id = {$course_id})", 'wiki_properties' => $sql_course, 'wiki_acls' => "wiki_id IN (SELECT id FROM wiki_properties WHERE course_id = {$course_id})", 'wiki_pages' => "wiki_id IN (SELECT id FROM wiki_properties WHERE course_id = {$course_id})", 'wiki_pages_content' => "pid IN (SELECT id FROM wiki_pages\n                                                    WHERE wiki_id IN (SELECT id FROM wiki_properties\n                                                                             WHERE course_id = {$course_id}))", 'poll' => $sql_course, 'poll_question' => "pid IN (SELECT pid FROM poll WHERE course_id = {$course_id})", 'poll_answer_record' => "pid IN (SELECT pid FROM poll WHERE course_id = {$course_id})", 'poll_question_answer' => "pqid IN (SELECT pqid FROM poll_question\n                                                       WHERE pid IN (SELECT pid FROM poll\n                                                                            WHERE course_id = {$course_id}))", 'assignment' => $sql_course, 'assignment_submit' => "assignment_id IN (SELECT id FROM assignment\n                                                             WHERE course_id = {$course_id})", 'gradebook' => $sql_course, 'gradebook_activities' => "gradebook_id IN (SELECT id FROM gradebook\n                                                             WHERE course_id = {$course_id})", 'gradebook_book' => "gradebook_activity_id IN (SELECT gradebook_activities.id FROM gradebook_activities, gradebook\n                                                             WHERE gradebook.course_id = {$course_id} AND gradebook_activities.gradebook_id = gradebook.id)", 'gradebook_users' => "gradebook_id IN (SELECT id FROM gradebook WHERE course_id = {$course_id})", 'attendance' => $sql_course, 'attendance_activities' => "attendance_id IN (SELECT id FROM attendance\n                                                             WHERE course_id = {$course_id})", 'attendance_book' => "attendance_activity_id IN (SELECT attendance_activities.id FROM attendance_activities, attendance\n                                                             WHERE attendance.course_id = {$course_id} AND attendance_activities.attendance_id = attendance.id)", 'attendance_users' => "attendance_id IN (SELECT id FROM attendance WHERE course_id = {$course_id})", 'agenda' => $sql_course, 'exercise' => $sql_course, 'exercise_question' => $sql_course, 'exercise_answer' => "question_id IN (SELECT id FROM exercise_question\n                                                         WHERE course_id = {$course_id})", 'exercise_user_record' => "eid IN (SELECT id FROM exercise WHERE course_id = {$course_id})", 'exercise_with_questions' => "question_id IN (SELECT id FROM exercise_question\n                                                                 WHERE course_id = {$course_id}) OR\n                                          exercise_id IN (SELECT id FROM exercise\n                                                                 WHERE course_id = {$course_id})", 'bbb_session' => "course_id IN (SELECT id FROM bbb_session WHERE course_id = {$course_id})", 'blog_post' => "id IN (SELECT id FROM blog_post WHERE course_id = {$course_id})", 'comments' => "(rtype = 'blogpost' AND rid IN (SELECT id FROM blog_post WHERE course_id = {$course_id})) OR (rtype = 'course' AND rid = {$course_id})", 'rating' => "(rtype = 'blogpost' AND rid IN (SELECT id FROM blog_post WHERE course_id = {$course_id})) OR (rtype = 'course' AND rid = {$course_id})", 'rating_cache' => "(rtype = 'blogpost' AND rid IN (SELECT id FROM blog_post WHERE course_id = {$course_id})) OR (rtype = 'course' AND rid = {$course_id})", 'note' => "(reference_obj_course IS NOT NULL AND reference_obj_course = {$course_id})");
    foreach ($archive_conditions as $table => $condition) {
        backup_table($archivedir, $table, $condition);
    }
    file_put_contents("{$archivedir}/config_vars", serialize(array('urlServer' => $urlServer, 'urlAppend' => $urlAppend, 'siteName' => $siteName, 'version' => get_config('version'))));
    // $htmldir is not needed anywhere
    //$htmldir = $archivedir . '/html';
    // create zip file
    $zipCourse = new PclZip($zipfile);
    $result1 = $zipCourse->create($archivedir, PCLZIP_OPT_REMOVE_PATH, "{$webDir}/courses/archive");
    $result2 = $zipCourse->add("{$webDir}/courses/{$course_code}", PCLZIP_OPT_REMOVE_PATH, "{$webDir}/courses/{$course_code}", PCLZIP_OPT_ADD_PATH, "{$course_code}/{$backup_date}/html");
    $result3 = $zipCourse->add("{$webDir}/video/{$course_code}", PCLZIP_OPT_REMOVE_PATH, "{$webDir}/video/{$course_code}", PCLZIP_OPT_ADD_PATH, "{$course_code}/{$backup_date}/video_files");
    $success = true;
    if ($result1 === 0 || $result2 === 0 || $result3 === 0) {
        $success = false;
    }
    removeDir($archivedir);
    return $success;
}
 public function export()
 {
     // preload current locale
     $this->locale;
     $tempDir = ClassLoader::getRealPath('cache.tmp.' . rand(1, 10000000));
     $locale = Locale::getInstance($this->request->get('id'));
     $fileDir = ClassLoader::getRealPath('application.configuration.language.en');
     $files = $locale->translationManager()->getDefinitionFiles($fileDir);
     // prepare language files
     $translated = array();
     foreach ($files as $file) {
         $relPath = substr($file, strlen($fileDir) + 1);
         // get language default definitions
         $default = $locale->translationManager()->getFileDefs($relPath, true);
         if (!is_array($default)) {
             $default = array();
         }
         // get translated definitions
         $transl = $locale->translationManager()->getCacheDefs($relPath, true);
         $transl = array_merge($default, $transl);
         $values = array();
         foreach ($transl as $key => $value) {
             $values[] = $key . '=' . $value;
         }
         $path = $tempDir . '/' . $locale->getLocaleCode() . '/' . $relPath;
         if ($values) {
             if (!is_dir(dirname($path))) {
                 mkdir(dirname($path), 0777, true);
             }
             file_put_contents($path, implode("\n", $values));
         }
     }
     // put the files in zip archive
     require_once ClassLoader::getRealPath('library.pclzip') . '/pclzip.lib.php';
     if (!is_dir($tempDir)) {
         return new ActionRedirectResponse('backend.language', 'edit', array('id' => $locale->getLocaleCode()));
     }
     chdir($tempDir);
     $zip = dirname($tempDir) . '/temp_' . rand(1, 10000) . '.zip';
     $archive = new PclZip($zip);
     $archive->add($locale->getLocaleCode());
     // remove the temp directory
     $this->application->rmdir_recurse($tempDir);
     $response = new ObjectFileResponse(ObjectFile::getNewInstance('ObjectFile', $zip, 'LiveCart-' . $locale->getLocaleCode() . '.zip'));
     $response->deleteFileOnComplete();
     return $response;
 }
Exemple #15
0
function packen($filename, $wordtemplatedownloadpath, $temp_dir, $concontent, $stylecontent)
{
    //global $filename, $wordtemplatedownloadpath;
    //write a new content.xml
    $handle = fopen($wordtemplatedownloadpath . '/' . $temp_dir . '/content.xml', "w");
    fwrite($handle, $concontent);
    fclose($handle);
    //write a new styles.xml
    $handle2 = fopen($wordtemplatedownloadpath . '/' . $temp_dir . '/styles.xml', "w");
    fwrite($handle2, $stylecontent);
    fclose($handle2);
    $archive = new PclZip($wordtemplatedownloadpath . '/' . $filename);
    //make a new archive (or .odt file)
    $v_list = $archive->add($wordtemplatedownloadpath . '/' . $temp_dir, PCLZIP_OPT_REMOVE_PATH, $wordtemplatedownloadpath . '/' . $temp_dir);
    if ($v_list == 0) {
        die("Error : " . $archive->errorInfo(true));
    }
}
Exemple #16
0
 function execute(&$controller, &$request)
 {
     $root = mamboCore::get('rootPath');
     $live = mamboCore::get('mosConfig_live_site');
     include $root . '/administrator/includes/pcl/pclzip.lib.php';
     chdir($root);
     $lang = mosGetParam($_POST, 'lang', '');
     $language = new mamboLanguage($lang);
     $language->load(true);
     $zipfile = "{$root}/media/MamboLanguage_{$lang}.zip";
     $archive = new PclZip($zipfile);
     foreach ($language->files as $file) {
         $v_list = $archive->add($root . '/' . $file['filename'], PCLZIP_OPT_REMOVE_PATH, $root . 'language/');
         if ($v_list == 0) {
             die("Error : " . $archive->errorInfo(true));
         }
     }
     if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $UserAgent)) {
         $UserBrowser = "Opera";
     } elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $UserAgent)) {
         $UserBrowser = "IE";
     } else {
         $UserBrowser = '';
     }
     $mime_type = 'application/x-zip';
     $filename = "MamboLanguage_{$lang}.zip";
     @ob_end_clean();
     ob_start();
     header('Content-Type: ' . $mime_type);
     header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
     if ($UserBrowser == 'IE') {
         header('Content-Disposition: inline; filename="' . $filename . '"');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
     } else {
         header('Content-Disposition: attachment; filename="' . $filename . '"');
         header('Pragma: no-cache');
     }
     readfile($zipfile);
     ob_end_flush();
     $fmanager =& mosFileManager::getInstance();
     $fmanager->deleteFile($zipfile);
     exit(0);
 }
Exemple #17
0
 /**
  * This function exports a ZIP archives of several ZIP archives - it is used in the listSurvey controller
  * The SIDs are read from session flashdata.
  *
  */
 public function surveyarchives()
 {
     if (!$this->session->userdata('USER_RIGHT_SUPERADMIN')) {
         die('Access denied.');
     }
     $aSurveyIDs = $this->session->flashdata('sids');
     $aExportedFiles = array();
     foreach ($aSurveyIDs as $iSurveyID) {
         $iSurveyID = (int) $iSurveyID;
         if ($iSurveyID > 0) {
             $aExportedFiles[$iSurveyID] = $this->_exportarchive($iSurveyID, FALSE);
         }
     }
     if (count($aExportedFiles) > 0) {
         $aZIPFileName = $this->config->item("tempdir") . DIRECTORY_SEPARATOR . randomChars(30);
         $this->load->library("admin/pclzip/pclzip", array('p_zipname' => $aZIPFileName));
         $zip = new PclZip($aZIPFileName);
         foreach ($aExportedFiles as $iSurveyID => $sFileName) {
             $zip->add(array(array(PCLZIP_ATT_FILE_NAME => $sFileName, PCLZIP_ATT_FILE_NEW_FULL_NAME => 'survey_archive_' . $iSurveyID . '.zip')));
             unlink($sFileName);
         }
     }
     if (is_file($aZIPFileName)) {
         //Send the file for download!
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Content-Type: application/force-download");
         header("Content-Disposition: attachment; filename=survey_archives_pack.zip");
         header("Content-Description: File Transfer");
         @readfile($aZIPFileName);
         //Delete the temporary file
         unlink($aZIPFileName);
         return;
     }
 }
Exemple #18
0
 /**
  * Add an external file into the current process file
  *
  * GIF images are not supported in WORD 2007
  *
  * @param string $sourcePathname   The pathname of the source file to add
  * @param string $archivePathname  The pathname in the archive
  */
 public function addFile($sourcePathname, $archivePathname)
 {
     if (file_exists($sourcePathname)) {
         switch ($this->getZipMethod()) {
             case 'ziparchive':
                 $zip = new ZipArchive();
                 if ($zip->open($this->getPathname()) === true) {
                     // don't work - archive corrupted
                     // $zip->addFile($sourcePathname, $archivePathname);
                     $zip->addFromString($archivePathname, file_get_contents($sourcePathname, false));
                     $zip->close();
                 }
                 break;
             case 'pclzip':
                 require_once 'pclzip.lib.php';
                 $zip = new PclZip($this->getPathname());
                 $zip->add($sourcePathname, PCLZIP_OPT_ADD_PATH, $archivePathname, PCLZIP_OPT_REMOVE_ALL_PATH);
                 break;
             case 'shell':
             default:
                 $dir = dirname($this->getProcessDir() . DIRECTORY_SEPARATOR . $this->getBasename() . DIRECTORY_SEPARATOR . $archivePathname);
                 if (!file_exists($dir)) {
                     mkdir($dir, 0777, true);
                 }
                 if (copy($sourcePathname, $this->getProcessDir() . DIRECTORY_SEPARATOR . $this->getBasename() . DIRECTORY_SEPARATOR . $archivePathname)) {
                     // change the current directory to basename in process dir
                     $cwd = getcwd();
                     chdir($this->getProcessDir() . DIRECTORY_SEPARATOR . $this->getBasename() . DIRECTORY_SEPARATOR);
                     // zip the file into the archive
                     $cmd = $this->getZipBinary();
                     $cmd .= ' -u';
                     $cmd .= ' ' . escapeshellarg($this->getPathname());
                     $cmd .= ' ' . escapeshellarg($archivePathname);
                     exec($cmd);
                     // get back current directory
                     chdir($cwd);
                 }
                 break;
         }
     }
 }
Exemple #19
0
 $error = false;
 $settings = $dirs['php'] . "components.ini";
 require_once 'classes/class.zip.php';
 $archive = new PclZip($tempdir . $file);
 $v_list = $archive->create($settings, PCLZIP_OPT_REMOVE_PATH, $dirs['php']);
 if ($v_list == 0) {
     $error = true;
 } else {
     foreach ($dirs as $key => $dir) {
         $filelist = array();
         if (isset($ini[$key]) && count($ini[$key]) > 0) {
             foreach ($ini[$key] as $cfile) {
                 $filelist[] = $dir . $cfile;
             }
             $archive = new PclZip($tempdir . $file);
             $v_list = $archive->add($filelist, PCLZIP_OPT_REMOVE_PATH, $dir, PCLZIP_OPT_ADD_PATH, $key);
             if ($v_list == 0) {
                 $error = true;
                 break;
             }
         }
     }
 }
 if ($error) {
     echo head();
     unset($archive);
     $filesystem->unlink($tempdir . $file);
     error('admin.php?action=cms&job=com', $archive->errorInfo(true));
 } else {
     viscacha_header('Content-Type: application/zip');
     viscacha_header('Content-Disposition: attachment; filename="' . $file . '"');
Exemple #20
0
	public static function liveTests(){
		// Set Sandbox to be writable if possible
		@MFile::chmod(_FM_SANDBOX, 755);
		if( ! MFile::isWritable(_FM_SANDBOX)){
			self::$sandboxError = 1;
			return false;
		}
		
		$assets = _FM_SANDBOX .DS . "assets" ;
		$fileSample = _FM_SANDBOX .DS . "assets" . DS ."sample.txt";
		$fileValidate = _FM_SANDBOX .DS . "assets" . DS ."validate.txt";
		$destinationFolder = _FM_SANDBOX . DS . "dest";
		// 1. isDir
		self::$params["live_is_dir"] = (int) @MFile::isDir($assets);
		
		// 2. isFile
		self::$params["live_is_file"] = (int) @MFile::isFile($fileSample);
		
		// 3. Create Dir 
		MFile::createDir($destinationFolder, 0755);
		self::$params["live_create_dir"] = (int) ( @MFile::is($destinationFolder) && @MFile::isDir($destinationFolder));
		
		// 4. Read
		$valid = MFile::readData($fileValidate);
		self::$params["live_read_file"] = (int) $valid == "valid";
		
		// 5. Copy
		MFile::copy($fileValidate, $destinationFolder . DS . basename($fileValidate));
// 		MFile::copy($fileValidate, _FM_SANDBOX . DS . "reserved.txt");
		self::$params["live_copy"] = (int) MFile::is($destinationFolder . DS . basename($fileValidate));
		
		// 6. Rename
		$newValidate = $destinationFolder . DS .  "deleteme.txt";
		MFile::rename($destinationFolder . DS . basename($fileValidate), $newValidate);
		self::$params["live_rename"] = (int) MFile::is($newValidate);
		
		// 7. mode read
		@MFile::chmod($newValidate, 444);
		$mode = MFile::mode($newValidate);
		self::$params["live_mode"] = (int)  (!! $mode);
		
		// 8. CHMOD
		MFile::chmod($newValidate, 666);
		self::$params["live_chmod"] =  (int) ( $mode != MFile::mode($newValidate) );
		
		// 9. Write (Create / Add File)
		MFile::writeData($newValidate,"new",true);
		$validnew = MFile::readData($newValidate);
		self::$params["live_write_file"] = (int) $validnew == "validnew";
		
		// 10. Pack
		$archive = new PclZip(_FM_SANDBOX. DS . 'packed.zip');
		$archive->add($destinationFolder,PCLZIP_OPT_REMOVE_PATH, $destinationFolder);
		self::$params["live_zip"] = (int) MFile::is(_FM_SANDBOX. DS . 'packed.zip');
		
		// 11. Delete File
		MFile::remove($newValidate, 1);
		self::$params["live_delete_file"] = (int) ! MFile::is($newValidate);
		
		// 12. Delete Folder
		MFile::removeDir($destinationFolder);
		self::$params["live_delete_folder"] = (int) ! MFile::is($destinationFolder);
		
		// 13. UNZIP
		$archive = new PclZip(_FM_SANDBOX. DS . 'packed.zip');
		$archive->extract(PCLZIP_OPT_PATH, _FM_SANDBOX);
		self::$params["live_unzip"] = (int) MFile::is(_FM_SANDBOX. DS . 'deleteme.txt');
		
		// 14. Move
		MFile::createDir($destinationFolder, 0777);
		MFile::move(_FM_SANDBOX. DS . 'deleteme.txt', $destinationFolder);
		self::$params["live_move"] = (int) MFile::is($newValidate);
		
		
		// Purge
		MFile::remove(_FM_SANDBOX. DS . 'packed.zip', 1);
		MFile::removeDirAtAllCosts($destinationFolder);
		
		
		
	}
 /**
  * Create a backup of the DataBase
  * @return array result of backup
  */
 private function _createDbBackup()
 {
     Yii::app()->loadHelper("admin/backupdb");
     $backupDb = new stdClass();
     $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true));
     $sfilename = $this->tempdir . DIRECTORY_SEPARATOR . "backup_db_" . randomChars(20) . "_" . dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . ".sql";
     $dfilename = $this->tempdir . DIRECTORY_SEPARATOR . "LimeSurvey_database_backup_" . $basefilename . ".zip";
     outputDatabase('', false, $sfilename);
     if (is_file($sfilename) && filesize($sfilename)) {
         $archive = new PclZip($dfilename);
         $v_list = $archive->add(array($sfilename), PCLZIP_OPT_REMOVE_PATH, $this->tempdir, PCLZIP_OPT_ADD_TEMP_FILE_ON);
         unlink($sfilename);
         if ($v_list == 0) {
             $backupDb->result = FALSE;
             $backupDb->message = 'db_backup_zip_failed';
         } else {
             $backupDb->result = TRUE;
             $backupDb->message = htmlspecialchars($dfilename);
         }
     } else {
         $backupDb->result = FALSE;
         $backupDb->message = htmlspecialchars(db_backup_failed);
     }
     return $backupDb;
 }
Exemple #22
0
function zip_up_lang($language)
{
    global $tp;
    $ret = array();
    $ret['file'] = "";
    if ($_SESSION['lancheck'][$language]['total'] > 0 && !E107_DEBUG_LEVEL) {
        $ret = array();
        $ret['error'] = TRUE;
        $message = defined('LANG_LAN_34') ? LANG_LAN_34 : LANG_LAN_115;
        $ret['message'] = str_replace("[x]", $_SESSION['lancheck'][$language]['total'], $message);
        return $ret;
    }
    if (!isset($_SESSION['lancheck'][$language])) {
        $ret = array();
        $ret['error'] = TRUE;
        $ret['message'] = defined('LANG_LAN_27') ? LANG_LAN_27 : LANG_LAN_116;
        return $ret;
    }
    if (varset($_POST['contribute_pack']) && varset($_SESSION['lancheck'][$language]['total']) != '0') {
        $ret['error'] = TRUE;
        $ret['message'] = defined("LANG_LAN_29") ? LANG_LAN_29 : LANG_LAN_117;
        $ret['message'] .= "<br />";
        $ret['message'] .= defined('LANG_LAN_27') ? LANG_LAN_27 : LANG_LAN_116;
        return $ret;
    }
    if (!is_writable(e_FILE . "public")) {
        $ret['error'] = TRUE;
        $ret['message'] = LAN_UPLOAD_777 . " " . e_FILE . "public";
        return $ret;
    }
    if (is_readable(e_ADMIN . "ver.php")) {
        include e_ADMIN . "ver.php";
    }
    $core_plugins = array("alt_auth", "banner", "blogcalendar_menu", "calendar_menu", "chatbox_menu", "clock_menu", "comment_menu", "download", "faqs", "featurebox", "forum", "gallery", "gsitemap", "import", "links_page", "linkwords", "list_new", "log", "login_menu", "newforumposts_main", "newsfeed", "news", "newsletter", "online", "page", "pm", "poll", "rss_menu", "search_menu", "siteinfo", "tagwords", "tinymce", "trackback", "tree_menu", "user_menu");
    $core_themes = array("bootstrap");
    require_once e_HANDLER . 'pclzip.lib.php';
    list($ver, $tmp) = explode(" ", $e107info['e107_version']);
    if (!($locale = find_locale($language))) {
        $ret['error'] = TRUE;
        $file = "e107_languages/{$language}/{$language}.php";
        $def = defined('LANG_LAN_25') ? LANG_LAN_25 : LANG_LAN_119;
        $ret['message'] = str_replace("[x]", $file, $def);
        //
        return $ret;
    }
    global $THEMES_DIRECTORY, $PLUGINS_DIRECTORY, $LANGUAGES_DIRECTORY, $HANDLERS_DIRECTORY, $HELP_DIRECTORY;
    if ($HANDLERS_DIRECTORY != "e107_handlers/" || $LANGUAGES_DIRECTORY != "e107_languages/" || $THEMES_DIRECTORY != "e107_themes/" || $HELP_DIRECTORY != "e107_docs/help/" || $PLUGINS_DIRECTORY != "e107_plugins/") {
        $ret['error'] = TRUE;
        $ret['message'] = defined('LANG_LAN_26') ? LANG_LAN_26 : LANG_LAN_120;
        return $ret;
    }
    $newfile = e_MEDIA_FILE . "e107_" . $ver . "_" . $language . "_" . $locale . "-utf8.zip";
    $archive = new PclZip($newfile);
    $core = grab_lans(e_LANGUAGEDIR . $language . "/", $language, '', 0);
    $core_admin = grab_lans(e_BASE . $LANGUAGES_DIRECTORY . $language . "/admin/", $language, '', 2);
    $plugs = grab_lans(e_BASE . $PLUGINS_DIRECTORY, $language, $core_plugins);
    // standardized path.
    $theme = grab_lans(e_BASE . $THEMES_DIRECTORY, $language, $core_themes);
    $docs = grab_lans(e_BASE . $HELP_DIRECTORY, $language);
    $handlers = grab_lans(e_BASE . $HANDLERS_DIRECTORY, $language);
    // standardized path.
    $file = array_merge($core, $core_admin, $plugs, $theme, $docs, $handlers);
    $data = implode(",", $file);
    if ($archive->create($data, PCLZIP_OPT_REMOVE_PATH, e_BASE) == 0) {
        $ret['error'] = TRUE;
        $ret['message'] = $archive->errorInfo(true);
        return $ret;
    } else {
        $fileName = e_FILE . "public/" . $language . ".xml";
        if (is_readable($fileName)) {
            @unlink($fileName);
        }
        $fileData = '<?xml version="1.0" encoding="utf-8"?>
<e107Language name="' . $language . '" compatibility="' . $ver . '" date="' . date("Y-m-d") . '" >
<author name ="' . USERNAME . '" email="' . USEREMAIL . '" url="' . SITEURL . '" />
</e107Language>';
        if (file_put_contents($fileName, $fileData)) {
            $addTag = $archive->add($fileName, PCLZIP_OPT_ADD_PATH, 'e107_languages/' . $language, PCLZIP_OPT_REMOVE_PATH, e_FILE . 'public/');
            $_SESSION['lancheck'][$language]['xml'] = "Yes";
        } else {
            $_SESSION['lancheck'][$language]['xml'] = "No";
        }
        @unlink($fileName);
        $ret['file'] = $newfile;
        $ret['message'] = str_replace("../", "", e_MEDIA_FILE) . "<a href='" . $newfile . "' >" . basename($newfile) . "</a>";
        $ret['error'] = FALSE;
        return $ret;
    }
}
Exemple #23
0
}
if ($action == 'del') {
    if (!preg_match('/userData/', $dir)) {
        show_info('info', 'Ошибка: Не верный путь к директории');
    }
    if (is_dir($dir . '/' . $idName)) {
        RemoveDir($dir . '/' . $idName);
    } else {
        unlink($dir . '/' . $idName);
    }
} elseif ($action == 'ziped') {
    if ($dir) {
        require_once THIS_DIR . '/pclzip.lib.php';
        unlink($dir . '/folder.zip');
        $archive = new PclZip($dir . '/folder.zip');
        $archive->add($dir, PCLZIP_OPT_REMOVE_PATH, $dir);
    } else {
        show_info('info', 'Ошибка: директория не найдена');
    }
} elseif ($action == 'createDir') {
    $dirname = isset($_POST['dirname']) ? replase($_POST['dirname']) : false;
    if ($dirname && $dirname !== '') {
        @mkdir($dir . '/' . $dirname);
    } else {
        show_info('info', 'Ошибка при создании директории');
    }
} elseif ($action == 'edit') {
    print @file_get_contents($dir . '/' . $idName);
} elseif ($action == 'save_edit') {
    $dataf = convert_ch(stripcslashes(trim($_POST['data'])));
    print @file_put_contents($dir . '/' . $idName, $dataf);
Exemple #24
0
            if ($res === TRUE) {
                $zip->addFile($save_to, "{$export_name}.xml");
                $zip->close();
            } else {
                die("{$hesklang['eZIP']} <{$save_to_zip}>\n");
            }
        } elseif (class_exists('ZipArchive')) {
            require HESK_PATH . 'inc/zip/Zip.php';
            $zip = new Zip();
            $zip->addLargeFile($save_to, "{$export_name}.xml");
            $zip->finalize();
            $zip->setZipFile($save_to_zip);
        } else {
            require HESK_PATH . 'inc/zip/pclzip.lib.php';
            $zip = new PclZip($save_to_zip);
            $zip->add($save_to, PCLZIP_OPT_REMOVE_ALL_PATH);
        }
        // Delete XML, just leave the Zip archive
        hesk_unlink($save_to);
        // Echo memory peak usage
        $flush_me .= hesk_date() . " | " . sprintf($hesklang['pmem'], @memory_get_peak_usage(true) / 1048576) . "<br />\r\n";
        // We're done!
        $flush_me .= hesk_date() . " | {$hesklang['fZIP']}<br /><br />";
        $flush_me .= '<a href="' . $save_to_zip . '">' . $hesklang['ch2d'] . "</a>\n";
    } else {
        hesk_unlink($save_to);
    }
}
/* Print header */
require_once HESK_PATH . 'inc/header.inc.php';
/* Print main manage users page */
Exemple #25
0
 /**
  * @param array $courseInfo
  * @param int $sessionId
  *
  * @return bool
  */
 public static function downloadAllDeletedDocument($courseInfo, $sessionId)
 {
     // Zip library for creation of the zip file.
     require api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php';
     $files = self::getDeletedDocuments($courseInfo, $sessionId);
     if (empty($files)) {
         return false;
     }
     $coursePath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document';
     // Creating a ZIP file.
     $tempZipFile = api_get_path(SYS_ARCHIVE_PATH) . api_get_unique_id() . ".zip";
     $zip = new PclZip($tempZipFile);
     foreach ($files as $file) {
         $zip->add($coursePath . $file['path'], PCLZIP_OPT_REMOVE_PATH, $coursePath);
     }
     if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
         DocumentManager::file_send_for_download($tempZipFile, true);
         @unlink($tempZipFile);
         exit;
     }
 }
Exemple #26
0
    /**
     * Exports the learning path as a SCORM package. This is the main function that
     * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
     * whole thing and returns the zip.
     *
     * This method needs to be called in PHP5, as it will fail with non-adequate
     * XML package (like the ones for PHP4), and it is *not* a static method, so
     * you need to call it on a learnpath object.
     * @TODO The method might be redefined later on in the scorm class itself to avoid
     * creating a SCORM structure if there is one already. However, if the initial SCORM
     * path has been modified, it should use the generic method here below.
     * @TODO link this function with the export_lp() function in the same class
     * @param	string	Optional name of zip file. If none, title of learnpath is
     * 					domesticated and trailed with ".zip"
     * @return	string	Returns the zip package string, or null if error
     */
    function scorm_export()
    {
        global $_course;
        global $charset;
        if (!class_exists('DomDocument')) {
            error_log('DOM functions not supported for PHP version below 5.0', 0);
            $this->error = 'PHP DOM functions not supported for PHP versions below 5.0';
            return null;
        }
        //remove memory and time limits as much as possible as this might be a long process...
        if (function_exists('ini_set')) {
            $mem = ini_get('memory_limit');
            if (substr($mem, -1, 1) == 'M') {
                $mem_num = substr($mem, 0, -1);
                if ($mem_num < 128) {
                    ini_set('memory_limit', '128M');
                }
            } else {
                ini_set('memory_limit', '128M');
            }
            ini_set('max_execution_time', 600);
            //}else{
            //error_log('Scorm export: could not change memory and time limits',0);
        }
        //Create the zip handler (this will remain available throughout the method)
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
        $temp_dir_short = uniqid();
        $temp_zip_dir = $archive_path . "/" . $temp_dir_short;
        $temp_zip_file = $temp_zip_dir . "/" . md5(time()) . ".zip";
        $zip_folder = new PclZip($temp_zip_file);
        $current_course_path = api_get_path(SYS_COURSE_PATH) . api_get_course_path();
        $root_path = $main_path = api_get_path(SYS_PATH);
        $files_cleanup = array();
        //place to temporarily stash the zipfiles
        //create the temp dir if it doesn't exist
        //or do a cleanup befor creating the zipfile
        if (!is_dir($temp_zip_dir)) {
            mkdir($temp_zip_dir);
        } else {
            //cleanup: check the temp dir for old files and delete them
            $handle = opendir($temp_zip_dir);
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    unlink("{$temp_zip_dir}/{$file}");
                }
            }
            closedir($handle);
        }
        $zip_files = $zip_files_abs = $zip_files_dist = array();
        if (is_dir($current_course_path . '/scorm/' . $this->path) && is_file($current_course_path . '/scorm/' . $this->path . '/imsmanifest.xml')) {
            // remove the possible . at the end of the path
            $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
            $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir . '/scorm/' . $dest_path_to_lp);
            $perm = api_get_setting('permissions_for_new_directories');
            $perm = octdec(!empty($perm) ? $perm : '0770');
            mkdir($dest_path_to_scorm_folder, $perm, true);
            $zip_files_dist = copyr($current_course_path . '/scorm/' . $this->path, $dest_path_to_scorm_folder, array('imsmanifest'), $zip_files);
        }
        //Build a dummy imsmanifest structure. Do not add to the zip yet (we still need it)
        //This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
        //Aggregation Model official document, secion "2.3 Content Packaging"
        $xmldoc = new DOMDocument('1.0', $this->encoding);
        $root = $xmldoc->createElement('manifest');
        $root->setAttribute('identifier', 'SingleCourseManifest');
        $root->setAttribute('version', '1.1');
        $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
        $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
        $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $root->setAttribute('xsi:schemaLocation', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd');
        //Build mandatory sub-root container elements
        $metadata = $xmldoc->createElement('metadata');
        $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
        $metadata->appendChild($md_schema);
        $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
        $metadata->appendChild($md_schemaversion);
        $root->appendChild($metadata);
        $organizations = $xmldoc->createElement('organizations');
        $resources = $xmldoc->createElement('resources');
        //Build the only organization we will use in building our learnpaths
        $organizations->setAttribute('default', 'dokeos_scorm_export');
        $organization = $xmldoc->createElement('organization');
        $organization->setAttribute('identifier', 'dokeos_scorm_export');
        //to set the title of the SCORM entity (=organization), we take the name given
        //in Dokeos and convert it to HTML entities using the Dokeos charset (not the
        //learning path charset) as it is the encoding that defines how it is stored
        //in the database. Then we convert it to HTML entities again as the "&" character
        //alone is not authorized in XML (must be &amp;)
        //The title is then decoded twice when extracting (see scorm::parse_manifest)
        $org_title = $xmldoc->createElement('title', htmlentities(api_htmlentities($this->get_name(), ENT_QUOTES, $charset)));
        $organization->appendChild($org_title);
        //For each element, add it to the imsmanifest structure, then add it to the zip.
        //Always call the learnpathItem->scorm_export() method to change it to the SCORM
        //format
        $link_updates = array();
        foreach ($this->items as $index => $item) {
            if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) {
                //get included documents from this item
                if ($item->type == 'sco') {
                    $inc_docs = $item->get_resources_from_source(null, api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/' . 'scorm/' . $this->path . '/' . $item->get_path());
                } else {
                    $inc_docs = $item->get_resources_from_source();
                }
                //give a child element <item> to the <organization> element
                $my_item_id = $item->get_id();
                $my_item = $xmldoc->createElement('item');
                $my_item->setAttribute('identifier', 'ITEM_' . $my_item_id);
                $my_item->setAttribute('identifierref', 'RESOURCE_' . $my_item_id);
                $my_item->setAttribute('isvisible', 'true');
                //give a child element <title> to the <item> element
                $my_title = $xmldoc->createElement('title', htmlspecialchars($item->get_title(), ENT_QUOTES, $this->encoding));
                $my_item->appendChild($my_title);
                //give a child element <adlcp:prerequisites> to the <item> element
                $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $this->get_scorm_prereq_string($my_item_id));
                $my_prereqs->setAttribute('type', 'aicc_script');
                $my_item->appendChild($my_prereqs);
                //give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported
                //$xmldoc->createElement('adlcp:maxtimeallowed','');
                //give a child element <adlcp:timelimitaction> to the <item> element - not yet supported
                //$xmldoc->createElement('adlcp:timelimitaction','');
                //give a child element <adlcp:datafromlms> to the <item> element - not yet supported
                //$xmldoc->createElement('adlcp:datafromlms','');
                //give a child element <adlcp:masteryscore> to the <item> element
                $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
                $my_item->appendChild($my_masteryscore);
                //attach this item to the organization element or hits parent if there is one
                if (!empty($item->parent) && $item->parent != 0) {
                    $children = $organization->childNodes;
                    $possible_parent =& $this->get_scorm_xml_node($children, 'ITEM_' . $item->parent);
                    if (is_object($possible_parent)) {
                        $possible_parent->appendChild($my_item);
                    } else {
                        if ($this->debug > 0) {
                            error_log('Parent ITEM_' . $item->parent . ' of item ITEM_' . $my_item_id . ' not found');
                        }
                    }
                } else {
                    if ($this->debug > 0) {
                        error_log('No parent');
                    }
                    $organization->appendChild($my_item);
                }
                //get the path of the file(s) from the course directory root
                $my_file_path = $item->get_file_path('scorm/' . $this->path . '/');
                $my_xml_file_path = api_htmlentities($my_file_path, ENT_QUOTES, $this->encoding);
                $my_sub_dir = dirname($my_file_path);
                $my_xml_sub_dir = api_htmlentities($my_sub_dir, ENT_QUOTES, $this->encoding);
                //give a <resource> child to the <resources> element
                $my_resource = $xmldoc->createElement('resource');
                $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id());
                $my_resource->setAttribute('type', 'webcontent');
                $my_resource->setAttribute('href', $my_xml_file_path);
                //adlcp:scormtype can be either 'sco' or 'asset'
                if ($item->type == 'sco') {
                    $my_resource->setAttribute('adlcp:scormtype', 'sco');
                } else {
                    $my_resource->setAttribute('adlcp:scormtype', 'asset');
                }
                //xml:base is the base directory to find the files declared in this resource
                $my_resource->setAttribute('xml:base', '');
                //give a <file> child to the <resource> element
                $my_file = $xmldoc->createElement('file');
                $my_file->setAttribute('href', $my_xml_file_path);
                $my_resource->appendChild($my_file);
                //dependency to other files - not yet supported
                $i = 1;
                foreach ($inc_docs as $doc_info) {
                    if (count($doc_info) < 1 or empty($doc_info[0])) {
                        continue;
                    }
                    $my_dep = $xmldoc->createElement('resource');
                    $res_id = 'RESOURCE_' . $item->get_id() . '_' . $i;
                    $my_dep->setAttribute('identifier', $res_id);
                    $my_dep->setAttribute('type', 'webcontent');
                    $my_dep->setAttribute('adlcp:scormtype', 'asset');
                    $my_dep_file = $xmldoc->createElement('file');
                    //check type of URL
                    //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2],0);
                    if ($doc_info[1] == 'remote') {
                        //remote file. Save url as is
                        $my_dep_file->setAttribute('href', $doc_info[0]);
                        $my_dep->setAttribute('xml:base', '');
                    } elseif ($doc_info[1] == 'local') {
                        switch ($doc_info[2]) {
                            case 'url':
                                //local URL - save path as url for now, don't zip file
                                $abs_path = api_get_path(SYS_PATH) . str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
                                $current_dir = dirname($abs_path);
                                $file_path = realpath($abs_path);
                                $my_dep_file->setAttribute('href', $file_path);
                                $my_dep->setAttribute('xml:base', '');
                                if (strstr($file_path, $main_path) !== false) {
                                    //the calculated real path is really inside the dokeos root path
                                    //reduce file path to what's under the DocumentRoot
                                    $file_path = substr($file_path, strlen($root_path) - 1);
                                    //echo $file_path;echo '<br><br>';
                                    //error_log(__LINE__.'Reduced url path: '.$file_path,0);
                                    $zip_files_abs[] = $file_path;
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                    $my_dep_file->setAttribute('href', $file_path);
                                    $my_dep->setAttribute('xml:base', '');
                                } else {
                                    if (empty($file_path)) {
                                        /* $document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
                                           if(strpos($document_root,-1)=='/')
                                           {
                                           $document_root = substr(0, -1, $document_root);
                                           } */
                                        $file_path = $_SERVER['DOCUMENT_ROOT'] . $abs_path;
                                        $file_path = str_replace('//', '/', $file_path);
                                        if (file_exists($file_path)) {
                                            $file_path = substr($file_path, strlen($current_dir));
                                            // we get the relative path
                                            $zip_files[] = $my_sub_dir . '/' . $file_path;
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                            $my_dep_file->setAttribute('href', $file_path);
                                            $my_dep->setAttribute('xml:base', '');
                                        }
                                    }
                                }
                                break;
                            case 'abs':
                                //absolute path from DocumentRoot. Save file and leave path as is in the zip
                                $my_dep_file->setAttribute('href', $doc_info[0]);
                                $my_dep->setAttribute('xml:base', '');
                                //$current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
                                //the next lines fix a bug when using the "subdir" mode of Dokeos, whereas
                                //an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
                                $abs_img_path_without_subdir = $doc_info[0];
                                $relp = api_get_path(REL_PATH);
                                //the url-append config param
                                $pos = strpos($abs_img_path_without_subdir, $relp);
                                if ($pos === 0) {
                                    $abs_img_path_without_subdir = '/' . substr($abs_img_path_without_subdir, strlen($relp));
                                }
                                //$file_path = realpath(api_get_path(SYS_PATH).$doc_info[0]);
                                $file_path = realpath(api_get_path(SYS_PATH) . $abs_img_path_without_subdir);
                                $file_path = str_replace('\\', '/', $file_path);
                                $file_path = str_replace('//', '/', $file_path);
                                //error_log(__LINE__.'Abs path: '.$file_path,0);
                                //prepare the current directory path (until just under 'document') with a trailing slash
                                $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path . '/';
                                //check if the current document is in that path
                                if (strstr($file_path, $cur_path) !== false) {
                                    //the document is in that path, now get the relative path
                                    //to the containing document
                                    $orig_file_path = dirname($cur_path . $my_file_path) . '/';
                                    $relative_path = '';
                                    if (strstr($file_path, $cur_path) !== false) {
                                        $relative_path = substr($file_path, strlen($orig_file_path));
                                        $file_path = substr($file_path, strlen($cur_path));
                                    } else {
                                        //this case is still a problem as it's difficult to calculate a relative path easily
                                        //might still generate wrong links
                                        //$file_path = substr($file_path,strlen($cur_path));
                                        //calculate the directory path to the current file (without trailing slash)
                                        $my_relative_path = dirname($file_path);
                                        $my_relative_file = basename($file_path);
                                        //calculate the directory path to the containing file (without trailing slash)
                                        $my_orig_file_path = substr($orig_file_path, 0, -1);
                                        $dotdot = '';
                                        $subdir = '';
                                        while (strstr($my_relative_path, $my_orig_file_path) === false && strlen($my_orig_file_path) > 1 && strlen($my_relative_path) > 1) {
                                            $my_relative_path2 = dirname($my_relative_path);
                                            $my_orig_file_path = dirname($my_orig_file_path);
                                            $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1) . "/" . $subdir;
                                            $dotdot += '../';
                                            $my_relative_path = $my_relative_path2;
                                        }
                                        $relative_path = $dotdot . $subdir . $my_relative_file;
                                    }
                                    //put the current document in the zip (this array is the array
                                    //that will manage documents already in the course folder - relative)
                                    $zip_files[] = $file_path;
                                    //update the links to the current document in the containing document (make them relative)
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $relative_path);
                                    $my_dep_file->setAttribute('href', $file_path);
                                    $my_dep->setAttribute('xml:base', '');
                                } elseif (strstr($file_path, $main_path) !== false) {
                                    //the calculated real path is really inside the dokeos root path
                                    //reduce file path to what's under the DocumentRoot
                                    $file_path = substr($file_path, strlen($root_path));
                                    //echo $file_path;echo '<br><br>';
                                    //error_log('Reduced path: '.$file_path,0);
                                    $zip_files_abs[] = $file_path;
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                    $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                    $my_dep->setAttribute('xml:base', '');
                                } else {
                                    if (empty($file_path)) {
                                        /* $document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
                                           if(strpos($document_root,-1)=='/')
                                           {
                                           $document_root = substr(0, -1, $document_root);
                                           } */
                                        $file_path = $_SERVER['DOCUMENT_ROOT'] . $doc_info[0];
                                        $file_path = str_replace('//', '/', $file_path);
                                        if (file_exists($file_path)) {
                                            $file_path = substr($file_path, strlen($current_dir));
                                            // we get the relative path
                                            $zip_files[] = $my_sub_dir . '/' . $file_path;
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                            $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                            $my_dep->setAttribute('xml:base', '');
                                        }
                                    }
                                }
                                break;
                            case 'rel':
                                //path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
                                if (substr($doc_info[0], 0, 2) == '..') {
                                    //relative path going up
                                    $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/';
                                    $file_path = realpath($current_dir . $doc_info[0]);
                                    //error_log($file_path.' <-> '.$main_path,0);
                                    if (strstr($file_path, $main_path) !== false) {
                                        //the calculated real path is really inside the dokeos root path
                                        //reduce file path to what's under the DocumentRoot
                                        $file_path = substr($file_path, strlen($root_path));
                                        //error_log('Reduced path: '.$file_path,0);
                                        $zip_files_abs[] = $file_path;
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                        $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                        $my_dep->setAttribute('xml:base', '');
                                    }
                                } else {
                                    $zip_files[] = $my_sub_dir . '/' . $doc_info[0];
                                    $my_dep_file->setAttribute('href', $doc_info[0]);
                                    $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
                                }
                                break;
                            default:
                                $my_dep_file->setAttribute('href', $doc_info[0]);
                                $my_dep->setAttribute('xml:base', '');
                                break;
                        }
                    }
                    $my_dep->appendChild($my_dep_file);
                    $resources->appendChild($my_dep);
                    $dependency = $xmldoc->createElement('dependency');
                    $dependency->setAttribute('identifierref', $res_id);
                    $my_resource->appendChild($dependency);
                    $i++;
                }
                //$my_dependency = $xmldoc->createElement('dependency');
                //$my_dependency->setAttribute('identifierref','');
                $resources->appendChild($my_resource);
                $zip_files[] = $my_file_path;
                //error_log('File '.$my_file_path. ' added to $zip_files',0);
            } else {
                // if the item is a quiz or a link or whatever non-exportable, we include a step indicating it
                if ($item->type == TOOL_LINK) {
                    $my_item = $xmldoc->createElement('item');
                    $my_item->setAttribute('identifier', 'ITEM_' . $item->get_id());
                    $my_item->setAttribute('identifierref', 'RESOURCE_' . $item->get_id());
                    $my_item->setAttribute('isvisible', 'true');
                    //give a child element <title> to the <item> element
                    $my_title = $xmldoc->createElement('title', htmlspecialchars($item->get_title(), ENT_QUOTES));
                    $my_item->appendChild($my_title);
                    //give a child element <adlcp:prerequisites> to the <item> element
                    $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
                    $my_prereqs->setAttribute('type', 'aicc_script');
                    $my_item->appendChild($my_prereqs);
                    //give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported
                    //$xmldoc->createElement('adlcp:maxtimeallowed','');
                    //give a child element <adlcp:timelimitaction> to the <item> element - not yet supported
                    //$xmldoc->createElement('adlcp:timelimitaction','');
                    //give a child element <adlcp:datafromlms> to the <item> element - not yet supported
                    //$xmldoc->createElement('adlcp:datafromlms','');
                    //give a child element <adlcp:masteryscore> to the <item> element
                    $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
                    $my_item->appendChild($my_masteryscore);
                    //attach this item to the organization element or its parent if there is one
                    if (!empty($item->parent) && $item->parent != 0) {
                        $children = $organization->childNodes;
                        for ($i = 0; $i < $children->length; $i++) {
                            $item_temp = $children->item($i);
                            if ($item_temp->nodeName == 'item') {
                                if ($item_temp->getAttribute('identifier') == 'ITEM_' . $item->parent) {
                                    $item_temp->appendChild($my_item);
                                }
                            }
                        }
                    } else {
                        $organization->appendChild($my_item);
                    }
                    $my_file_path = 'link_' . $item->get_id() . '.html';
                    $sql = 'SELECT url, title FROM ' . Database::get_course_table(TABLE_LINK) . ' WHERE id=' . $item->path;
                    $rs = Database::query($sql, __FILE__, __LINE__);
                    if ($link = Database::fetch_array($rs)) {
                        $url = $link['url'];
                        $title = stripslashes($link['title']);
                        $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url);
                        $my_xml_file_path = api_htmlentities($my_file_path, ENT_QUOTES, $this->encoding);
                        $my_sub_dir = dirname($my_file_path);
                        $my_xml_sub_dir = api_htmlentities($my_sub_dir, ENT_QUOTES, $this->encoding);
                        //give a <resource> child to the <resources> element
                        $my_resource = $xmldoc->createElement('resource');
                        $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id());
                        $my_resource->setAttribute('type', 'webcontent');
                        $my_resource->setAttribute('href', $my_xml_file_path);
                        //adlcp:scormtype can be either 'sco' or 'asset'
                        $my_resource->setAttribute('adlcp:scormtype', 'asset');
                        //xml:base is the base directory to find the files declared in this resource
                        $my_resource->setAttribute('xml:base', '');
                        //give a <file> child to the <resource> element
                        $my_file = $xmldoc->createElement('file');
                        $my_file->setAttribute('href', $my_xml_file_path);
                        $my_resource->appendChild($my_file);
                        $resources->appendChild($my_resource);
                    }
                } elseif ($item->type == TOOL_QUIZ) {
                    require_once api_get_path(SYS_CODE_PATH) . 'exercice/exercise.class.php';
                    $exe_id = $item->path;
                    //should be using ref when everything will be cleaned up in this regard
                    $exe = new Exercise();
                    $exe->read($exe_id);
                    $my_item = $xmldoc->createElement('item');
                    $my_item->setAttribute('identifier', 'ITEM_' . $item->get_id());
                    $my_item->setAttribute('identifierref', 'RESOURCE_' . $item->get_id());
                    $my_item->setAttribute('isvisible', 'true');
                    //give a child element <title> to the <item> element
                    $my_title = $xmldoc->createElement('title', htmlspecialchars($item->get_title(), ENT_QUOTES, $this->encoding));
                    $my_item->appendChild($my_title);
                    $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
                    //$my_item->appendChild($my_max_score);
                    //give a child element <adlcp:prerequisites> to the <item> element
                    $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
                    $my_prereqs->setAttribute('type', 'aicc_script');
                    $my_item->appendChild($my_prereqs);
                    //give a child element <adlcp:masteryscore> to the <item> element
                    $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
                    $my_item->appendChild($my_masteryscore);
                    //attach this item to the organization element or hits parent if there is one
                    if (!empty($item->parent) && $item->parent != 0) {
                        $children = $organization->childNodes;
                        for ($i = 0; $i < $children->length; $i++) {
                            $item_temp = $children->item($i);
                            if ($item_temp->nodeName == 'item') {
                                if ($item_temp->getAttribute('identifier') == 'ITEM_' . $item->parent) {
                                    $item_temp->appendChild($my_item);
                                }
                            }
                        }
                    } else {
                        $organization->appendChild($my_item);
                    }
                    //include export scripts
                    require_once api_get_path(SYS_CODE_PATH) . 'exercice/export/scorm/scorm_export.php';
                    //get the path of the file(s) from the course directory root
                    //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
                    $my_file_path = 'quiz_' . $item->get_id() . '.html';
                    //write the contents of the exported exercise into a (big) html file
                    //to later pack it into the exported SCORM. The file will be removed afterwards
                    $contents = export_exercise($exe_id, true);
                    $tmp_file_path = $archive_path . $temp_dir_short . '/' . $my_file_path;
                    $res = file_put_contents($tmp_file_path, $contents);
                    if ($res === false) {
                        error_log('Could not write into file ' . $tmp_file_path . ' ' . __FILE__ . ' ' . __LINE__, 0);
                    }
                    $files_cleanup[] = $tmp_file_path;
                    //error_log($tmp_path);die();
                    $my_xml_file_path = api_htmlentities($my_file_path, ENT_QUOTES, $this->encoding);
                    $my_sub_dir = dirname($my_file_path);
                    $my_xml_sub_dir = api_htmlentities($my_sub_dir, ENT_QUOTES, $this->encoding);
                    //give a <resource> child to the <resources> element
                    $my_resource = $xmldoc->createElement('resource');
                    $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id());
                    $my_resource->setAttribute('type', 'webcontent');
                    $my_resource->setAttribute('href', $my_xml_file_path);
                    //adlcp:scormtype can be either 'sco' or 'asset'
                    $my_resource->setAttribute('adlcp:scormtype', 'sco');
                    //xml:base is the base directory to find the files declared in this resource
                    $my_resource->setAttribute('xml:base', '');
                    //give a <file> child to the <resource> element
                    $my_file = $xmldoc->createElement('file');
                    $my_file->setAttribute('href', $my_xml_file_path);
                    $my_resource->appendChild($my_file);
                    //get included docs
                    $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
                    //dependency to other files - not yet supported
                    $i = 1;
                    foreach ($inc_docs as $doc_info) {
                        if (count($doc_info) < 1 or empty($doc_info[0])) {
                            continue;
                        }
                        $my_dep = $xmldoc->createElement('resource');
                        $res_id = 'RESOURCE_' . $item->get_id() . '_' . $i;
                        $my_dep->setAttribute('identifier', $res_id);
                        $my_dep->setAttribute('type', 'webcontent');
                        $my_dep->setAttribute('adlcp:scormtype', 'asset');
                        $my_dep_file = $xmldoc->createElement('file');
                        //check type of URL
                        //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2],0);
                        if ($doc_info[1] == 'remote') {
                            //remote file. Save url as is
                            $my_dep_file->setAttribute('href', $doc_info[0]);
                            $my_dep->setAttribute('xml:base', '');
                        } elseif ($doc_info[1] == 'local') {
                            switch ($doc_info[2]) {
                                case 'url':
                                    //local URL - save path as url for now, don't zip file
                                    //save file but as local file (retrieve from URL)
                                    $abs_path = api_get_path(SYS_PATH) . str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
                                    $current_dir = dirname($abs_path);
                                    $file_path = realpath($abs_path);
                                    $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                    $my_dep->setAttribute('xml:base', '');
                                    if (strstr($file_path, $main_path) !== false) {
                                        //the calculated real path is really inside the dokeos root path
                                        //reduce file path to what's under the DocumentRoot
                                        $file_path = substr($file_path, strlen($root_path));
                                        //echo $file_path;echo '<br><br>';
                                        //error_log('Reduced path: '.$file_path,0);
                                        $zip_files_abs[] = $file_path;
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/' . $file_path);
                                        $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                        $my_dep->setAttribute('xml:base', '');
                                    } else {
                                        if (empty($file_path)) {
                                            /* $document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
                                               if(strpos($document_root,-1)=='/')
                                               {
                                               $document_root = substr(0, -1, $document_root);
                                               } */
                                            $file_path = $_SERVER['DOCUMENT_ROOT'] . $abs_path;
                                            $file_path = str_replace('//', '/', $file_path);
                                            if (file_exists($file_path)) {
                                                $file_path = substr($file_path, strlen($current_dir));
                                                // we get the relative path
                                                $zip_files[] = $my_sub_dir . '/' . $file_path;
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/' . $file_path);
                                                $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                                $my_dep->setAttribute('xml:base', '');
                                            }
                                        }
                                    }
                                    break;
                                case 'abs':
                                    //absolute path from DocumentRoot. Save file and leave path as is in the zip
                                    $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/';
                                    $file_path = realpath($doc_info[0]);
                                    $my_dep_file->setAttribute('href', $file_path);
                                    $my_dep->setAttribute('xml:base', '');
                                    if (strstr($file_path, $main_path) !== false) {
                                        //the calculated real path is really inside the dokeos root path
                                        //reduce file path to what's under the DocumentRoot
                                        $file_path = substr($file_path, strlen($root_path));
                                        //echo $file_path;echo '<br><br>';
                                        //error_log('Reduced path: '.$file_path,0);
                                        $zip_files_abs[] = $file_path;
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                        $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                        $my_dep->setAttribute('xml:base', '');
                                    } else {
                                        if (empty($file_path)) {
                                            /* $document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
                                               if(strpos($document_root,-1)=='/')
                                               {
                                               $document_root = substr(0, -1, $document_root);
                                               } */
                                            $file_path = $_SERVER['DOCUMENT_ROOT'] . $doc_info[0];
                                            $file_path = str_replace('//', '/', $file_path);
                                            if (file_exists($file_path)) {
                                                $file_path = substr($file_path, strlen($current_dir));
                                                // we get the relative path
                                                $zip_files[] = $my_sub_dir . '/' . $file_path;
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
                                                $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                                $my_dep->setAttribute('xml:base', '');
                                            }
                                        }
                                    }
                                    break;
                                case 'rel':
                                    //path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
                                    if (substr($doc_info[0], 0, 2) == '..') {
                                        //relative path going up
                                        $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/';
                                        $file_path = realpath($current_dir . $doc_info[0]);
                                        //error_log($file_path.' <-> '.$main_path,0);
                                        if (strstr($file_path, $main_path) !== false) {
                                            //the calculated real path is really inside the dokeos root path
                                            //reduce file path to what's under the DocumentRoot
                                            $file_path = substr($file_path, strlen($root_path));
                                            $file_path_dest = $file_path;
                                            //file path is courses/DOKEOS/document/....
                                            $info_file_path = explode('/', $file_path);
                                            if ($info_file_path[0] == 'courses') {
                                                //add character "/" in file path
                                                $file_path_dest = '/' . $file_path;
                                            }
                                            //error_log('Reduced path: '.$file_path,0);
                                            $zip_files_abs[] = $file_path;
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path_dest);
                                            $my_dep_file->setAttribute('href', 'document/' . $file_path);
                                            $my_dep->setAttribute('xml:base', '');
                                        }
                                    } else {
                                        $zip_files[] = $my_sub_dir . '/' . $doc_info[0];
                                        $my_dep_file->setAttribute('href', $doc_info[0]);
                                        $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
                                    }
                                    break;
                                default:
                                    $my_dep_file->setAttribute('href', $doc_info[0]);
                                    // ../../courses/
                                    $my_dep->setAttribute('xml:base', '');
                                    break;
                            }
                        }
                        $my_dep->appendChild($my_dep_file);
                        $resources->appendChild($my_dep);
                        $dependency = $xmldoc->createElement('dependency');
                        $dependency->setAttribute('identifierref', $res_id);
                        $my_resource->appendChild($dependency);
                        $i++;
                    }
                    $resources->appendChild($my_resource);
                    $zip_files[] = $my_file_path;
                } else {
                    //get the path of the file(s) from the course directory root
                    $my_file_path = 'non_exportable.html';
                    $my_xml_file_path = api_htmlentities($my_file_path, ENT_COMPAT, $this->encoding);
                    $my_sub_dir = dirname($my_file_path);
                    $my_xml_sub_dir = api_htmlentities($my_sub_dir, ENT_COMPAT, $this->encoding);
                    //give a <resource> child to the <resources> element
                    $my_resource = $xmldoc->createElement('resource');
                    $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id());
                    $my_resource->setAttribute('type', 'webcontent');
                    $my_resource->setAttribute('href', 'document/' . $my_xml_file_path);
                    //adlcp:scormtype can be either 'sco' or 'asset'
                    $my_resource->setAttribute('adlcp:scormtype', 'asset');
                    //xml:base is the base directory to find the files declared in this resource
                    $my_resource->setAttribute('xml:base', '');
                    //give a <file> child to the <resource> element
                    $my_file = $xmldoc->createElement('file');
                    $my_file->setAttribute('href', 'document/' . $my_xml_file_path);
                    $my_resource->appendChild($my_file);
                    $resources->appendChild($my_resource);
                }
            }
        }
        $organizations->appendChild($organization);
        $root->appendChild($organizations);
        $root->appendChild($resources);
        $xmldoc->appendChild($root);
        //todo: add a readme file here, with a short description and a link to the Reload player
        //then add the file to the zip, then destroy the file (this is done automatically)
        // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
        //error_log(print_r($zip_files,true),0);
        foreach ($zip_files as $file_path) {
            if (empty($file_path)) {
                continue;
            }
            //error_log(__LINE__.'getting document from '.$sys_course_path.$_course['path'].'/'.$file_path.' removing '.$sys_course_path.$_course['path'].'/',0);
            $dest_file = $archive_path . $temp_dir_short . '/' . $file_path;
            $this->create_path($dest_file);
            //error_log('copy '.api_get_path('SYS_COURSE_PATH').$_course['path'].'/'.$file_path.' to '.api_get_path('SYS_ARCHIVE_PATH').$temp_dir_short.'/'.$file_path,0);
            //echo $main_path.$file_path.'<br>';
            @copy($sys_course_path . $_course['path'] . '/' . $file_path, $dest_file);
            //check if the file needs a link update
            if (in_array($file_path, array_keys($link_updates))) {
                $string = file_get_contents($dest_file);
                unlink($dest_file);
                foreach ($link_updates[$file_path] as $old_new) {
                    //error_log('Replacing '.$old_new['orig'].' by '.$old_new['dest'].' in '.$file_path,0);
                    //this is an ugly hack that allows .flv files to be found by the flv player that
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
                    // ../../.. to return from inc/lib/flv_player to the document/main path
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
                    } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
                        $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
                    }
                    if (substr($old_new['dest'], 0, 1) == '/') {
                        $old_new['dest'] = substr($old_new['dest'], 1);
                    }
                    $string = str_replace($old_new['orig'], $old_new['dest'], $string);
                    $string = str_replace(str_replace('https', 'http', $old_new['orig']), $old_new['dest'], $string);
                }
                file_put_contents($dest_file, $string);
            }
        }
        foreach ($zip_files_abs as $file_path) {
            if (empty($file_path)) {
                continue;
            }
            //error_log(__LINE__.'checking existence of '.$main_path.$file_path.'',0);
            if (!is_file($main_path . $file_path) || !is_readable($main_path . $file_path)) {
                continue;
            }
            //error_log(__LINE__.'getting document from '.$main_path.$file_path.' removing '.api_get_path('SYS_COURSE_PATH').$_course['path'].'/',0);
            $dest_file = $archive_path . $temp_dir_short . '/document/' . $file_path;
            $this->create_path($dest_file);
            //error_log('Created path '.api_get_path(SYS_ARCHIVE_PATH).$temp_dir_short.'/document/'.$file_path,0);
            //error_log('copy '.api_get_path(SYS_COURSE_PATH).$_course['path'].'/'.$file_path.' to '.api_get_path(SYS_ARCHIVE_PATH).$temp_dir_short.'/'.$file_path,0);
            //echo $main_path.$file_path.' - '.$dest_file.'<br>';
            copy($main_path . $file_path, $dest_file);
            //check if the file needs a link update
            if (in_array($file_path, array_keys($link_updates))) {
                $string = file_get_contents($dest_file);
                unlink($dest_file);
                foreach ($link_updates[$file_path] as $old_new) {
                    //error_log('Replacing '.$old_new['orig'].' by '.$old_new['dest'].' in '.$file_path,0);
                    //this is an ugly hack that allows .flv files to be found by the flv player that
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
                    // ../../.. to return from inc/lib/flv_player to the document/main path
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
                    }
                    if (substr($old_new['dest'], 0, 1) == '/') {
                        $old_new['dest'] = substr($old_new['dest'], 1);
                    }
                    $string = str_replace($old_new['orig'], $old_new['dest'], $string);
                    $string = str_replace(str_replace('https', 'http', $old_new['orig']), $old_new['dest'], $string);
                }
                file_put_contents($dest_file, $string);
            }
        }
        if (is_array($links_to_create)) {
            foreach ($links_to_create as $file => $link) {
                $file_content = '<html><body><div style="text-align:center"><a href="' . $link['url'] . '">' . $link['title'] . '</a></div></body></html>';
                file_put_contents($archive_path . $temp_dir_short . '/' . $file, $file_content);
            }
        }
        // add non exportable message explanation
        $lang_not_exportable = get_lang('ThisItemIsNotExportable');
        $file_content = <<<EOD
<html>
\t<head>
\t\t<style>
\t\t\t.error-message {
\t\t\t\tfont-family: arial, verdana, helvetica, sans-serif;
\t\t\t\tborder-width: 1px;
\t\t\t\tborder-style: solid;
\t\t\t\tleft: 50%;
\t\t\t\tmargin: 10px auto;
\t\t\t\tmin-height: 30px;
\t\t\t\tpadding: 5px;
\t\t\t\tright: 50%;
\t\t\t\twidth: 500px;
\t\t\t\tbackground-color: #FFD1D1;
\t\t\t\tborder-color: #FF0000;
\t\t\t\tcolor: #000;
\t\t\t}
\t\t</style>
\t<body>
\t\t<div class="error-message">
\t\t\t{$lang_not_exportable}
\t\t</div>
\t</body>
</html>
EOD;
        if (!is_dir($archive_path . $temp_dir_short . '/document')) {
            @mkdir($archive_path . $temp_dir_short . '/document');
        }
        file_put_contents($archive_path . $temp_dir_short . '/document/non_exportable.html', $file_content);
        //Add the extra files that go along with a SCORM package
        $main_code_path = api_get_path(SYS_CODE_PATH) . 'newscorm/packaging/';
        $extra_files = scandir($main_code_path);
        foreach ($extra_files as $extra_file) {
            if (strpos($extra_file, '.') === 0) {
                continue;
            } else {
                $dest_file = $archive_path . $temp_dir_short . '/' . $extra_file;
                $this->create_path($dest_file);
                copy($main_code_path . $extra_file, $dest_file);
            }
        }
        //Finalize the imsmanifest structure, add to the zip, then return the zip
        $xmldoc->save($archive_path . '/' . $temp_dir_short . '/imsmanifest.xml');
        $zip_folder->add($archive_path . '/' . $temp_dir_short, PCLZIP_OPT_REMOVE_PATH, $archive_path . '/' . $temp_dir_short . '/');
        //clean possible temporary files
        foreach ($files_cleanup as $file) {
            $res = unlink($file);
            if ($res === false) {
                error_log('Could not delete temp file ' . $file . ' ' . __FILE__ . ' ' . __LINE__, 0);
            }
        }
        //Send file to client
        //$name = 'scorm_export_'.$this->lp_id.'.zip';
        require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
        $name = preg_replace('([^a-zA-Z0-9_\\.])', '-', html_entity_decode($this->get_name(), ENT_QUOTES)) . '.zip';
        DocumentManager::file_send_for_download($temp_zip_file, true, $name);
    }
 // ZIP-File
 $tempdir = "temp/";
 $file = $data['internal'] . '.zip';
 require_once 'classes/class.zip.php';
 $error = array();
 $archive = new PclZip($tempdir . $file);
 // Add modules directory
 $v_list = $archive->create("modules/{$id}/", PCLZIP_OPT_REMOVE_PATH, "modules/{$id}/", PCLZIP_OPT_ADD_PATH, "modules/");
 if ($v_list == 0) {
     $error[] = $archive->errorInfo(true);
 }
 $tpl_orig_path = "templates/{$design['template']}/modules/{$id}/";
 // Add template directory
 if (is_dir($tpl_orig_path) && count($error) == 0) {
     $archive = new PclZip($tempdir . $file);
     $v_list = $archive->add($tpl_orig_path, PCLZIP_OPT_REMOVE_PATH, $tpl_orig_path, PCLZIP_OPT_ADD_PATH, "templates/");
     if ($v_list == 0) {
         $error[] = $archive->errorInfo(true);
     }
 }
 // Add languages
 if (count($error) == 0 && $has_component == true) {
     foreach ($dirs as $dir) {
         $v_list = $archive->add($dir['orig'], PCLZIP_OPT_REMOVE_PATH, $dir['orig'], PCLZIP_OPT_ADD_PATH, $dir['new']);
         if ($v_list == 0) {
             $error[] = $archive->errorInfo(true);
         }
     }
 }
 // Add images
 if (count($error) == 0 && $has_component == true) {
 /**
  * Fallback for creating zip archives if zip command and ZipArchive are
  * unavailable.
  *
  * Uses the PclZip library that ships with WordPress
  */
 public function pcl_zip()
 {
     $this->errors_to_warnings($this->get_archive_method());
     $this->archive_method = 'pclzip';
     $this->do_action('hmbkp_archive_started');
     global $_hmbkp_exclude_string;
     $_hmbkp_exclude_string = $this->exclude_string('regex');
     $this->load_pclzip();
     $archive = new \PclZip($this->get_archive_filepath());
     // Add the database
     if ($this->get_type() !== 'file' && file_exists($this->get_database_dump_filepath())) {
         if (!$archive->add($this->get_database_dump_filepath(), \PCLZIP_OPT_REMOVE_PATH, $this->get_path())) {
             $this->warning($this->get_archive_method(), $archive->errorInfo(true));
         }
     }
     // Zip up everything
     if ($this->get_type() !== 'database') {
         if (!$archive->add($this->get_root(), \PCLZIP_OPT_REMOVE_PATH, $this->get_root(), \PCLZIP_CB_PRE_ADD, 'hmbkp_pclzip_callback')) {
             $this->warning($this->get_archive_method(), $archive->errorInfo(true));
         }
     }
     unset($GLOBALS['_hmbkp_exclude_string']);
     $this->verify_archive();
 }
        // Only teachers
        $userCondition = " AND props.insert_user_id = " . api_get_user_id();
    }
    //for other users, we need to create a zipfile with only visible files and folders
    $sql = "SELECT DISTINCT url, title, description, insert_user_id, insert_date, contains_file\n            FROM {$tbl_student_publication} AS work INNER JOIN {$prop_table} AS props\n                ON (props.c_id = {$course_id} AND\n                    work.c_id = {$course_id} AND\n                    work.id = props.ref)\n           WHERE\n                    props.tool='work' AND\n                    work.accepted = 1 AND\n                    work.active = 1 AND\n                    work.parent_id = {$work_id} AND\n                    work.filetype = 'file' AND\n                    props.visibility = '1' AND\n                    work.post_group_id = {$groupId}\n                    {$userCondition}\n            ";
}
$query = Database::query($sql);
//add tem to the zip file
while ($not_deleted_file = Database::fetch_assoc($query)) {
    $user_info = api_get_user_info($not_deleted_file['insert_user_id']);
    $insert_date = api_get_local_time($not_deleted_file['insert_date']);
    $insert_date = str_replace(array(':', '-', ' '), '_', $insert_date);
    $filename = $insert_date . '_' . $user_info['username'] . '_' . basename($not_deleted_file['title']);
    if (file_exists($sys_course_path . $_course['path'] . '/' . $not_deleted_file['url']) && !empty($not_deleted_file['url'])) {
        $files[basename($not_deleted_file['url'])] = $filename;
        $zip_folder->add($sys_course_path . $_course['path'] . '/' . $not_deleted_file['url'], PCLZIP_OPT_REMOVE_PATH, $sys_course_path . $_course['path'] . '/work', PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
    }
    //Convert texts in html files
    if ($not_deleted_file['contains_file'] == 0) {
        $filename = trim($filename) . ".html";
        $work_temp = api_get_path(SYS_ARCHIVE_PATH) . api_get_unique_id() . '_' . $filename;
        file_put_contents($work_temp, $not_deleted_file['description']);
        $files[basename($work_temp)] = $filename;
        $zip_folder->add($work_temp, PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_ARCHIVE_PATH), PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
        @unlink($work_temp);
    }
}
if (!empty($files)) {
    //logging
    event_download(basename($work_data['title']) . '.zip (folder)');
    //start download of created file
 /**
  * Zip the contents of an EPUB following the conventions outlined in Open Publication Structure 2.0.1
  *
  * @param $filename
  *
  * @return bool
  */
 protected function zipEpub($filename)
 {
     $zip = new \PclZip($filename);
     // Open Publication Structure 2.0.1
     // mimetype must be uncompressed, unencrypted, and the first file in the ZIP archive
     $list = $zip->create($this->tmpDir . '/mimetype', PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH);
     if ($list == 0) {
         return false;
     }
     $files = array();
     foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->tmpDir)) as $file) {
         if (!$file->isFile()) {
             continue;
         }
         if ('mimetype' == $file->getFilename()) {
             continue;
         }
         $files[] = $file->getPathname();
     }
     $list = $zip->add($files, '', $this->tmpDir);
     if ($list == 0) {
         return false;
     }
     return true;
 }