<?php

// This script creates a zip file from a specially encoded list

require_once('../config.php');
require_once($CFG->dirroot . '/lib/LAE/xor.php');

$err_base = 'Could not create .zip file: ';

if(!isset($_POST['t'])) {
  die($err_base . 'Your request did not contain the list of source files.');
 } else {
  $str = decrypt_and_decode($_POST['t']);

  if(!($zipinfo = unserialize($str))) {
    die($err_base . 'Unable to decode the list of source files you provided.');
  }
 }

// unpack
$zip_files      = $zipinfo['files'];
$name           = $zipinfo['name'];

// set up file name
$name           = preg_replace("/[^a-zA-Z0-9]/", '', $name);
$zip            = new ZipArchive();
$id             = uniqid();
$date           = date('m-d-y');
$zip_name       = 'Moodle_' . $name . '_' . $date;
$zip_file       = "$zip_name.zip";
$zip_path       = $CFG->dataroot . "/temp/" . $zip_file;

// build the .zip
if($zip->open($zip_path, ZIPARCHIVE::CREATE) !== TRUE) {
  die($err_base . "Check validity of and permissions on $zip_path");
} else {
  $count = 0;
  foreach($zip_files as $filename => $fileinfo) {
    $fullname = $name . '/' . $fileinfo['author'] . '_' . $filename;
    $zip->addFile(chop($fileinfo['path']), $fullname);
    $count++;
  }

  $zip->close();
}

// send file
// TODO: Let web server stream the file instead of tying up a PHP process
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_file . '"');
readfile($zip_path);

// clean up
unlink($zip_path);
?>
