Created
June 10, 2019 08:04
-
-
Save marxjohnson/d6cf9fdc048dcefd232de23104c4256d to your computer and use it in GitHub Desktop.
Extract and validate zip file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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