Example #1
0
function pack_files($filesforzipping) {
    global $CFG;

    $tempzip = tempnam($CFG->tempdir . '/', 'local_mail_');
    $zipper = new zip_packer();
    if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
        return $tempzip;
    }
    return false;
}
 public static function extract_archive($archive_path, $to_path = '')
 {
     $to_path = empty($to_path) ? MoodleUtil::create_temp_directory() : $to_path;
     $zipper = new zip_packer();
     if ($zipper->extract_to_pathname($archive_path, $to_path)) {
         return $to_path;
     } else {
         return false;
     }
 }
     if ($draftpath === '/') {
         $filename = get_string('files') . '.zip';
     } else {
         $filename = explode('/', trim($draftpath, '/'));
         $filename = array_pop($filename) . '.zip';
     }
     $newdraftitemid = file_get_unused_draft_itemid();
     if ($newfile = $zipper->archive_to_storage(array('/' => $file), $user_context->id, 'user', 'draft', $newdraftitemid, '/', $filename, $USER->id)) {
         $fileurl = moodle_url::make_draftfile_url($newdraftitemid, '/', $filename)->out();
         header('Location: ' . $fileurl);
     } else {
         print_error('cannotdownloaddir', 'repository');
     }
     break;
 case 'zip':
     $zipper = new zip_packer();
     $file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $draftpath, '.');
     if (!$file->get_parent_directory()) {
         $parent_path = '/';
         $filepath = '/';
         $filename = get_string('files') . '.zip';
     } else {
         $parent_path = $file->get_parent_directory()->get_filepath();
         $filepath = explode('/', trim($file->get_filepath(), '/'));
         $filepath = array_pop($filepath);
         $filename = $filepath . '.zip';
     }
     $filename = repository::get_unused_filename($itemid, $parent_path, $filename);
     $newfile = $zipper->archive_to_storage(array($filepath => $file), $user_context->id, 'user', 'draft', $itemid, $parent_path, $filename, $USER->id);
     $home_url->param('action', 'browse');
     $home_url->param('draftpath', $parent_path);
Example #4
0
 /**
  * Zips all files in the temporary directory
  *
  * @param string $filename name of resulting zipfile (optional, defaults to portfolio-export.zip)
  * @param string $filepath subpath in the filearea (optional, defaults to final)
  * @return stored_file|bool resulting stored_file object, or false
  */
 public function zip_tempfiles($filename = 'portfolio-export.zip', $filepath = '/final/')
 {
     $zipper = new zip_packer();
     list($contextid, $component, $filearea, $itemid) = array_values($this->get_base_filearea());
     if ($newfile = $zipper->archive_to_storage($this->get_tempfiles(), $contextid, $component, $filearea, $itemid, $filepath, $filename, $this->user->id)) {
         return $newfile;
     }
     return false;
 }
 /**
  * @param $list array List of item id's to download. Empty array means all files.
  * @return void
  */
 public function download_items(array $list = array())
 {
     global $CFG, $DB;
     // More efficient to load this here.
     require_once $CFG->libdir . '/filelib.php';
     $filesforzipping = array();
     $fs = get_file_storage();
     $filename = clean_filename('mediagallery-export-' . $this->record->name . '.zip');
     $files = $fs->get_area_files($this->get_collection()->context->id, 'mod_mediagallery', 'item', false, 'id', false);
     $items = $this->get_items();
     $keyed = array_flip($list);
     foreach ($files as $file) {
         $selected = isset($keyed[$file->get_itemid()]) || empty($list);
         if ($selected && isset($items[$file->get_itemid()])) {
             $filesforzipping[$file->get_filename()] = $file;
         }
     }
     if (empty($filesforzipping)) {
         return;
     }
     $tempzip = tempnam($CFG->tempdir . '/', 'mediagallery_');
     $zipper = new \zip_packer();
     $zipper->archive_to_pathname($filesforzipping, $tempzip);
     // Send file and delete after sending.
     send_temp_file($tempzip, $filename);
 }
 public function view_bulk_certificates(moodle_url $url, array $selectedusers = null)
 {
     global $OUTPUT, $CFG, $DB;
     $course_context = context_course::instance($this->get_course()->id);
     $page = $url->get_param('page');
     $perpage = $url->get_param('perpage');
     $issuelist = $url->get_param('issuelist');
     $action = $url->get_param('action');
     $groupid = 0;
     $groupmode = groups_get_activity_groupmode($this->coursemodule);
     if ($groupmode) {
         $groupid = groups_get_activity_group($this->coursemodule, true);
     }
     $page_start = intval($page * $perpage);
     $usercount = 0;
     if (!$selectedusers) {
         $users = get_enrolled_users($course_context, '', $groupid);
         $usercount = count($users);
         $users = array_slice($users, $page_start, $perpage);
     } else {
         list($sqluserids, $params) = $DB->get_in_or_equal($selectedusers);
         $sql = "SELECT * FROM {user} WHERE id {$sqluserids}";
         //Adding sort
         $sort = '';
         $override = new stdClass();
         $override->firstname = 'firstname';
         $override->lastname = 'lastname';
         $fullnamelanguage = get_string('fullnamedisplay', '', $override);
         if ($CFG->fullnamedisplay == 'firstname lastname' or $CFG->fullnamedisplay == 'firstname' or $CFG->fullnamedisplay == 'language' and $fullnamelanguage == 'firstname lastname') {
             $sort = " ORDER BY firstname, lastname";
         } else {
             // ($CFG->fullnamedisplay == 'language' and $fullnamelanguage == 'lastname firstname')
             $sort = " ORDER BY lastname, firstname";
         }
         $users = $DB->get_records_sql($sql . $sort, $params);
     }
     if (!$action) {
         echo $OUTPUT->header();
         $this->show_tabs($url);
         groups_print_activity_menu($this->coursemodule, $url);
         $selectoptions = array('completed' => get_string('completedusers', 'simplecertificate'), 'allusers' => get_string('allusers', 'simplecertificate'));
         $select = new single_select($url, 'issuelist', $selectoptions, $issuelist);
         $select->label = get_string('showusers', 'simplecertificate');
         echo $OUTPUT->render($select);
         echo '<br>';
         echo '<form id="bulkissue" name="bulkissue" method="post" action="view.php">';
         echo html_writer::label(get_string('bulkaction', 'simplecertificate'), 'menutype', true);
         echo '&nbsp;';
         $selectoptions = array('pdf' => get_string('onepdf', 'simplecertificate'), 'zip' => get_string('multipdf', 'simplecertificate'), 'email' => get_string('sendtoemail', 'simplecertificate'));
         echo html_writer::select($selectoptions, 'type', 'pdf');
         $table = new html_table();
         $table->width = "95%";
         $table->tablealign = "center";
         //strgrade
         $table->head = array(' ', get_string('fullname'), get_string('grade'));
         $table->align = array("left", "left", "center");
         $table->size = array('1%', '89%', '10%');
         foreach ($users as $user) {
             $canissue = $this->can_issue($user, $issuelist != 'allusers');
             if (empty($canissue)) {
                 $chkbox = html_writer::checkbox('selectedusers[]', $user->id, false);
                 $name = $OUTPUT->user_picture($user) . fullname($user);
                 $table->data[] = array($chkbox, $name, $this->get_grade($user->id));
             }
         }
         $downloadbutton = $OUTPUT->single_button($url->out_as_local_url(false, array('action' => 'download')), get_string('bulkbuttonlabel', 'simplecertificate'));
         echo $OUTPUT->paging_bar($usercount, $page, $perpage, $url);
         echo '<br />';
         echo html_writer::table($table);
         echo html_writer::tag('div', $downloadbutton, array('style' => 'text-align: center'));
         echo '</form>';
     } else {
         if ($action == 'download') {
             $type = $url->get_param('type');
             // Calculate file name
             $filename = str_replace(' ', '_', clean_filename($this->get_instance()->coursename . ' ' . get_string('modulenameplural', 'simplecertificate') . ' ' . strip_tags(format_string($this->get_instance()->name, true)) . '.' . strip_tags(format_string($type, true))));
             switch ($type) {
                 //One pdf with all certificates
                 case 'pdf':
                     $pdf = $this->create_pdf_object();
                     foreach ($users as $user) {
                         $canissue = $this->can_issue($user, $issuelist != 'allusers');
                         if (empty($canissue)) {
                             //To one pdf file
                             $issuecert = $this->get_issue($user);
                             $this->create_pdf($issuecert, $pdf, true);
                             //Save certificate PDF
                             if (!$this->issue_file_exists($issuecert)) {
                                 //To force file creation
                                 $issuecert->haschage = true;
                                 $this->get_issue_file($issuecert);
                             }
                         }
                     }
                     $pdf->Output($filename, 'D');
                     break;
                     //One zip with all certificates in separated files
                 //One zip with all certificates in separated files
                 case 'zip':
                     $filesforzipping = array();
                     foreach ($users as $user) {
                         $canissue = $this->can_issue($user, $issuelist != 'allusers');
                         if (empty($canissue)) {
                             $issuecert = $this->get_issue($user);
                             if ($file = $this->get_issue_file($issuecert)) {
                                 $fileforzipname = $file->get_filename();
                                 $filesforzipping[$fileforzipname] = $file;
                             } else {
                                 error_log(get_string('filenotfound', 'simplecertificate'));
                                 print_error(get_string('filenotfound', 'simplecertificate'));
                             }
                         }
                     }
                     $tempzip = $this->create_temp_file('issuedcertificate_');
                     //zipping files
                     $zipper = new zip_packer();
                     if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
                         //send file and delete after sending.
                         send_temp_file($tempzip, $filename);
                     }
                     break;
                 case 'email':
                     foreach ($users as $user) {
                         $canissue = $this->can_issue($user, $issuelist != 'allusers');
                         if (empty($canissue)) {
                             $issuecert = $this->get_issue($user);
                             if ($this->get_issue_file($issuecert)) {
                                 $this->send_certificade_email($issuecert);
                             } else {
                                 error_log(get_string('filenotfound', 'simplecertificate'));
                                 print_error('filenotfound', 'simplecertificate');
                             }
                         }
                     }
                     $url->remove_params('action', 'type');
                     redirect($url, get_string('emailsent', 'simplecertificate'), 5);
                     break;
             }
             exit;
         }
     }
     echo $OUTPUT->footer();
 }
Example #7
0
/**
 * Download all user badges in zip archive.
 *
 * @param int $userid ID of badge owner.
 */
function badges_download($userid)
{
    global $CFG, $DB;
    $context = context_user::instance($userid);
    $records = $DB->get_records('badge_issued', array('userid' => $userid));
    // Get list of files to download.
    $fs = get_file_storage();
    $filelist = array();
    foreach ($records as $issued) {
        $badge = new badge($issued->badgeid);
        // Need to make image name user-readable and unique using filename safe characters.
        $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
        $name = str_replace(' ', '_', $name);
        if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
            $filelist[$name . '.png'] = $file;
        }
    }
    // Zip files and sent them to a user.
    $tempzip = tempnam($CFG->tempdir . '/', 'mybadges');
    $zipper = new zip_packer();
    if ($zipper->archive_to_pathname($filelist, $tempzip)) {
        send_temp_file($tempzip, 'badges.zip');
    } else {
        debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
        die;
    }
}
Example #8
0
function mediaboard_pack_files($filesforzipping)
{
    global $CFG;
    //create path for new zip file.
    $tempzip = tempnam($CFG->tempdir . '/', 'mediaboard_');
    //zip files
    $zipper = new zip_packer();
    if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
        return $tempzip;
    }
    return false;
}
                        }
                    }
                }
            }
        } else {
            if ($material_name == 'folder') {
                //for folder
                if (!($tmp_files = $fs->get_file($material_infos->context->id, 'mod_' . $material_name, 'content', '0', '/', '.'))) {
                    $tmp_files = null;
                }
                $sect_id = $material_infos->sectionnum;
                // Chong 20141119
                if ($ccsectid == 0) {
                    $files_zum_downloaden[$filename . '/' . $subfolder . '_' . $sect_id . '/' . str_replace($ersetzen_mit, $ersetzt, clean_filename($material_infos->name))] = $tmp_files;
                } else {
                    if ($ccsectid == $sect_id) {
                        $files_zum_downloaden[$filename . '/' . str_replace($ersetzen_mit, $ersetzt, clean_filename($material_infos->name))] = $tmp_files;
                    }
                }
            }
        }
        // Chong 20141119
    }
}
//zip files
$tempzip = tempnam($CFG->tempdir . '/', get_string('dm_materials', 'block_material_download') . '_' . $course->shortname);
$zipper = new zip_packer();
$filename = $filename . ".zip";
if ($zipper->archive_to_pathname($files_zum_downloaden, $tempzip)) {
    send_temp_file($tempzip, $filename);
}
 /**
  * Packages the entire flavour and returns it
  * @todo Add a checksum
  */
 public function packaging_execute()
 {
     global $USER, $CFG;
     $errorredirect = $this->url . '?sesskey=' . sesskey();
     // Getting selected data
     $selectedingredients = $this->get_ingredients_from_form();
     if (!$selectedingredients) {
         redirect($errorredirect, get_string('nothingselected', 'local_flavours'), 2);
     }
     // Flavour data
     $form = new flavours_packaging_form($this->url);
     if (!($data = $form->get_data())) {
         print_error('errorpackaging', 'local_flavours');
     }
     // Starting <xml>
     $xmloutput = new memory_xml_output();
     $xmltransformer = new flavours_xml_transformer();
     $xmlwriter = new flavours_xml_writer($xmloutput, $xmltransformer);
     $xmlwriter->start();
     $xmlwriter->begin_tag('flavour');
     $xmlwriter->full_tag('name', $data->name);
     $xmlwriter->full_tag('description', $data->description);
     $xmlwriter->full_tag('author', $data->author);
     $xmlwriter->full_tag('timecreated', time());
     $xmlwriter->full_tag('sourceurl', $CFG->wwwroot);
     $xmlwriter->full_tag('sourcemoodlerelease', $CFG->release);
     $xmlwriter->full_tag('sourcemoodleversion', $CFG->version);
     // Random code to store the flavour data
     $hash = sha1('flavour_' . $USER->id . '_' . time());
     $flavourpath = $this->flavourstmpfolder . '/' . $hash;
     if (file_exists($flavourpath) || !mkdir($flavourpath, $CFG->directorypermissions)) {
         print_error('errorpackaging', 'local_flavours');
     }
     // Adding the selected ingredients data
     $xmlwriter->begin_tag('ingredient');
     foreach ($selectedingredients as $ingredienttype => $ingredientsdata) {
         // instance_ingredient_type gets a new flavours_ingredient_* object
         $type = $this->instance_ingredient_type($ingredienttype);
         $xmlwriter->begin_tag($type->id);
         // It executes the ingredient type specific actions to package
         $type->package_ingredients($xmlwriter, $flavourpath, $ingredientsdata);
         $xmlwriter->end_tag($type->id);
     }
     $xmlwriter->end_tag('ingredient');
     // Finishing flavour index
     $xmlwriter->end_tag('flavour');
     $xmlwriter->stop();
     $flavourxml = $xmloutput->get_allcontents();
     // Creating the .xml with the flavour info
     $xmlfilepath = $flavourpath . '/flavour.xml';
     if (!($xmlfh = fopen($xmlfilepath, 'w'))) {
         print_error('errorpackaging', 'local_flavours');
     }
     fwrite($xmlfh, $flavourxml);
     fclose($xmlfh);
     // Flavour contents compression
     $packer = new zip_packer();
     $zipfilepath = $this->flavourstmpfolder . '/' . $hash . '/flavour_' . date('Y-m-d') . '.zip';
     if (!$packer->archive_to_pathname(array('flavour' => $flavourpath), $zipfilepath)) {
         print_error('errorpackaging', 'local_flavours');
     }
     session_get_instance()->write_close();
     send_file($zipfilepath, basename($zipfilepath));
     // To avoid the html headers and all the print* stuff
     die;
 }
 private function pack_files($filesforzipping)
 {
     global $CFG;
     // Create path for new zip file.
     $tempzip = tempnam($CFG->dataroot . '/temp/', 'publication_');
     // Zip files.
     $zipper = new zip_packer();
     if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
         return $tempzip;
     }
     return false;
 }
/**
 * Execute Javascript that is embedded in the geogebra file, if it exists
 * File must be named geogebra_javascript.js
 * @param  object $context  Of the activity to get the files
 * @param  object $geogebra object with the activity info
 */
function geogebra_get_js_from_geogebra($context, $geogebra)
{
    global $CFG;
    $content = false;
    if (geogebra_is_valid_external_url($geogebra->url)) {
        require_once "{$CFG->libdir}/filestorage/zip_packer.php";
        // Prepare tmp dir (create if not exists, download ggb file...)
        $dirname = 'mod_geogebra_' . time();
        $tmpdir = make_temp_directory($dirname);
        if (!$tmpdir) {
            debugging("Cannot create temp directory {$dirname}");
            return;
        }
        $materialid = geogebra_get_id($geogebra->url);
        if ($materialid) {
            $ggbfile = "http://tube.geogebra.org/material/download/format/file/id/{$materialid}";
        } else {
            $ggbfile = $geogebra->url;
        }
        $filename = pathinfo($ggbfile, PATHINFO_FILENAME);
        $tmpggbfile = tempnam($tmpdir, $filename . '_');
        // Download external GGB and extract javascript file
        if (!download_file_content($ggbfile, null, null, false, 300, 20, false, $tmpggbfile)) {
            debugging("Error copying from {$ggbfile}");
            return;
        }
        // Extract geogebra js from GGB file
        $zip = new zip_packer();
        $extract = $zip->extract_to_pathname($tmpggbfile, $tmpdir, array('geogebra_javascript.js'));
        if ($extract && $extract['geogebra_javascript.js']) {
            unlink($tmpggbfile);
        } else {
            @unlink($tmpggbfile);
            @rmdir($tmpdir);
            debugging("Cannot open zipfile {$tmpggbfile}");
            return;
        }
        $content = file_get_contents($tmpdir . '/geogebra_javascript.js');
        // Delete temporary files
        unlink($tmpdir . '/geogebra_javascript.js');
        rmdir($tmpdir);
    } else {
        $fs = get_file_storage();
        $file = $fs->get_file($context->id, 'mod_geogebra', 'extracted_files', 0, '/', 'geogebra_javascript.js');
        if ($file) {
            $content = $file->get_content();
        }
    }
    if (empty($content)) {
        debugging("Empty content");
        return;
    }
    echo '<script type="text/javascript">
    if (typeof ggbApplet == \'undefined\') {
        ggbApplet = document.ggbApplet;
    }
    ' . $content . '</script>';
}
 /**
  * Exporting is done, wrap things up.
  *
  * @throws \coding_exception
  * @return void
  */
 public function finish()
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $this->format->close();
     if ($this->attachments) {
         $zipname = pathinfo($this->exportfile, PATHINFO_FILENAME) . '.zip';
         $zippath = $this->tempdirectory . '/' . $zipname;
         $zip = new \zip_packer();
         if (!$zip->archive_to_pathname($this->archivefiles, $zippath)) {
             throw new \coding_exception('Failed to create zip archive');
         }
         send_file($zippath, $zipname, 0, 0, false, true, '', true);
     } else {
         send_file($this->exportfile, pathinfo($this->exportfile, PATHINFO_BASENAME), 0, 0, false, true, '', true);
     }
     fulldelete($this->tempdirectory);
 }
Example #14
0
/**
 * generate zip file from array of given files
 * @param array $filesforzipping - array of files to pass into archive_to_pathname
 * @return path of temp file - note this returned file does not have a .zip extension - it is a temp file.
 */
function assignment_pack_files($filesforzipping) {
        global $CFG;
        //create path for new zip file.
        $tempzip = tempnam($CFG->dataroot.'/temp/', 'assignment_');
        //zip files
        $zipper = new zip_packer();
        if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
            return $tempzip;
        }
        return false;
}
        if ($filename != '.') {
            $path = '';
            if (0 === strpos($filename, 'form-')) {
                $path = get_string('questionforms', 'offlinequiz');
            } else {
                if (0 === strpos($filename, 'answer-')) {
                    $path = get_string('answerforms', 'offlinequiz');
                } else {
                    $path = get_string('correctionforms', 'offlinequiz');
                }
            }
            $path = clean_filename($path);
            $filelist[$path . '/' . $filename] = $file;
        }
    }
    $zipper = new zip_packer();
    if ($zipper->archive_to_pathname($filelist, $tempzip)) {
        send_temp_file($tempzip, $zipfilename);
    }
}
// Print the page header.
echo $OUTPUT->header();
// Print the offlinequiz name heading and tabs for teacher.
$currenttab = 'createofflinequiz';
require 'tabs.php';
$hasscannedpages = offlinequiz_has_scanned_pages($offlinequiz->id);
if ($offlinequiz->grade == 0) {
    echo '<div class="linkbox"><strong>';
    echo $OUTPUT->notification(get_string('gradeiszero', 'offlinequiz'), 'notifyproblem');
    echo '</strong></div>';
}
Example #16
0
 /**
  * Generate zip file from array of given files.
  *
  * @param array $filesforzipping - array of files to pass into archive_to_pathname.
  *                                 This array is indexed by the final file name and each
  *                                 element in the array is an instance of a stored_file object.
  * @return path of temp file - note this returned file does
  *         not have a .zip extension - it is a temp file.
  */
 protected function pack_files($filesforzipping)
 {
     global $CFG;
     // Create path for new zip file.
     $tempzip = tempnam($CFG->tempdir . '/', 'assignment_');
     // Zip files.
     $zipper = new zip_packer();
     if ($zipper->archive_to_pathname($filesforzipping, $tempzip)) {
         return $tempzip;
     }
     return false;
 }
Example #17
0
require_capability('mod/assignment:grade', get_context_instance(CONTEXT_MODULE, $cm->id));
$uploadform = new responsezip_form();
if ($uploadform->is_cancelled()) {
    // What to do if the button is cancelled
} else {
    if ($fromform = $uploadform->get_data()) {
        //Process the form data so long as it's validated
        $uploadedfile = $uploadform->get_file_content('response_zip');
        require_once $CFG->dirroot . '/mod/assignment/lib.php';
        require_once $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php';
        $assignmentclass = 'assignment_' . $assignment->assignmenttype;
        $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
        $zipfile = $uploadform->save_temp_file('response_zip');
        // Unzip uploaded file to the appropriate storage area
        require_once $CFG->dirroot . '/lib/filestorage/zip_packer.php';
        $ziplib = new zip_packer();
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        print "Course ID: {$id}<br>\n";
        print "Context ID: {$context->id}<br>\n";
        $response_files = $ziplib->extract_to_storage($zipfile, $context->id, 'mod_assignment', 'response', 0, 'feedback');
        // Associate the response files with their appropriate submissions...
        $fs = get_file_storage();
        $users = get_enrolled_users($context);
        $groups = groups_get_all_groups($COURSE->id);
        foreach ($response_files as $file => $value) {
            preg_match('/(.*?)_(.*)_\\d*(\\..*)/', $file, $matches);
            $username = $matches[1];
            $filename = $matches[2];
            $fileextension = $matches[3];
            $userID = '';
            $groupID = '';