Skip to content

Instantly share code, notes, and snippets.

@bitumin
Forked from marxjohnson/validation.php
Created June 11, 2019 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitumin/70b9627d99d8ae166fb42d4d81e817d3 to your computer and use it in GitHub Desktop.
Save bitumin/70b9627d99d8ae166fb42d4d81e817d3 to your computer and use it in GitHub Desktop.
Extract and validate zip file
$packer = new zip_packer();
if ($file) {
$itemid = $file->get_itemid();
$filepath = $file->get_filepath();
$filelist = $file->list_files($packer);
$numberoffiles = 0;
foreach ($filelist as $f) {
if (!$f->is_directory) {
$numberoffiles++;
}
}
// Check that we've got the right number of files.
if ($numberoffiles < 2) {
$errors['attachments'] = get_string('error');
} else if ($numberoffiles > 2) {
$errors['attachments'] = get_string('error');
} else {
// We've got the right number of files, let's check if they appear to be the right types.
$expectedtypes = array('html', 'png');
foreach ($filelist as $contentfile) {
$extension = pathinfo($contentfile->pathname, PATHINFO_EXTENSION);
if (in_array($extension, $expectedtypes) || $contentfile->is_directory) {
$foundtypes = array($extension);
$expectedtypes = array_diff($expectedtypes, $foundtypes);
} else {
$errors['attachments'] = get_string('invalidfile');
}
}
if (!isset($errors['attachments'])) {
// We've got the right number of files and they appear to be of the correct type.
// Now get the content and check it looks right.
$extractedfilenames = $file->extract_to_storage(
$packer,
$usercontext->id,
'user',
'draft',
$itemid,
$filepath
);
$file->set_sortorder(3);
$html = '';
$ipynb = '';
foreach ($extractedfilenames as $extractedfilename => $success) {
if ($success !== true) {
$parts = (object)array('filename' => $extractedfilename, 'message' => $success);
$errors['attachments'] = get_string('error', $parts);
break;
}
$extractedfile = $fs->get_file(
$usercontext->id,
'user',
'draft',
$itemid,
$filepath,
$extractedfilename
);
$content = $extractedfile->get_content();
// Validate the content
}
}
}
} else {
$errors['attachments'] = get_string('invalidfile');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment