Import a Portable element from an uploaded zip file

@param $type
@param $zipFile
@return mixed
@throws PortableElementInconsistencyModelException
168862
public function import($type, $zipFile)
    {
        /** @var PortableElementPackageParser $parser */
        $parser = $this->getPortableModelRegistry()->getModel($type)->getPackageParser();
        $source = $parser->extract($zipFile);
        $object = $parser->getModel()->createDataObject($parser->getManifestContent($zipFile));

        $this->registerModel($object, $source);

        \tao_helpers_File::delTree($source);

        return $object;
    }
309274
public void addFile(String zipEntry, String filename) throws IOException {
		addFile(zipEntry, new File(filename));
	}
926670
function installPackage(zipFileLocation, callback) {
        var formData = {
            'file': fs.createReadStream(zipFileLocation),
            'force': 'true',
            'install': 'true',
        };

        var postUri = uri()
            .scheme(options.deployScheme)
            .host(options.deployHost)
            .port(options.deployPort)
            .path('/crx/packmgr/service.jsp');

        gutil.log(PLUGIN_NAME, 'Installing CRX package to ' + postUri.toString());

        request.post({
            url: postUri.toString(),
            formData: formData,
            headers: {
                'Authorization': 'Basic ' +
                    new Buffer(options.deployUsername + ':' +
                           options.deployPassword).toString('base64')
            }
        }, callback);
    }
439745
public void addFile(String zipEntry, byte[] data) throws IOException  {
		stream.putNextEntry(new ZipEntry(zipEntry));
		stream.write(data);
	}
1329881
public static void unzipToFolder(File inputFile, File outputDir) throws IOException
    {
        if (inputFile == null)
            throw new IllegalArgumentException("Argument inputFile is null.");
        if (outputDir == null)
            throw new IllegalArgumentException("Argument outputDir is null.");

        try (ZipFile zipFile = new ZipFile(inputFile))
        {
            Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
            while (entryEnum.hasMoreElements())
            {
                ZipEntry entry = entryEnum.nextElement();
                String entryName = entry.getName();
                File destFile = new File(outputDir, entryName);
                if (!entry.isDirectory())
                {
                    File parentDir = destFile.getParentFile();
                    if (!parentDir.isDirectory() && !parentDir.mkdirs())
                    {
                        throw new WindupException("Unable to create directory: " + parentDir.getAbsolutePath());
                    }
                    try (InputStream zipInputStream = zipFile.getInputStream(entry))
                    {
                        try (FileOutputStream outputStream = new FileOutputStream(destFile))
                        {
                            Streams.write(zipInputStream, outputStream);
                        }
                    }
                }
            }
        }
    }
810512
public function import_zip_files($assignment, $fileplugin) {
        global $CFG, $PAGE, $DB;

        core_php_time_limit::raise(ASSIGNFEEDBACK_FILE_MAXFILEUNZIPTIME);
        $packer = get_file_packer('application/zip');

        $feedbackfilesupdated = 0;
        $feedbackfilesadded = 0;
        $userswithnewfeedback = array();
        $contextid = $assignment->get_context()->id;

        $fs = get_file_storage();
        $files = $this->get_import_files($contextid);

        $currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
        $allusers = $assignment->list_participants($currentgroup, false);
        $participants = array();
        foreach ($allusers as $user) {
            $participants[$assignment->get_uniqueid_for_user($user->id)] = $user;
        }

        foreach ($files as $unzippedfile) {
            // Set the timeout for unzipping each file.
            $user = null;
            $plugin = null;
            $filename = '';

            if ($this->is_valid_filename_for_import($assignment, $unzippedfile, $participants, $user, $plugin, $filename)) {
                if ($this->is_file_modified($assignment, $user, $plugin, $filename, $unzippedfile)) {
                    $grade = $assignment->get_user_grade($user->id, true);

                    // In 3.1 the default download structure of the submission files changed so that each student had their own
                    // separate folder, the files were not renamed and the folder structure was kept. It is possible that
                    // a user downloaded the submission files in 3.0 (or earlier) and edited the zip to add feedback or
                    // changed the behavior back to the previous format, the following code means that we will still support the
                    // old file structure. For more information please see - MDL-52489 / MDL-56022.
                    $path = pathinfo($filename);
                    if ($path['dirname'] == '.') { // Student submissions are not in separate folders.
                        $basename = $filename;
                        $dirname = "/";
                        $dirnamewslash = "/";
                    } else {
                        $basename = $path['basename'];
                        $dirname = $path['dirname'];
                        $dirnamewslash = $dirname . "/";
                    }

                    if ($oldfile = $fs->get_file($contextid,
                                                 'assignfeedback_file',
                                                 ASSIGNFEEDBACK_FILE_FILEAREA,
                                                 $grade->id,
                                                 $dirname,
                                                 $basename)) {
                        // Update existing feedback file.
                        $oldfile->replace_file_with($unzippedfile);
                        $feedbackfilesupdated++;
                    } else {
                        // Create a new feedback file.
                        $newfilerecord = new stdClass();
                        $newfilerecord->contextid = $contextid;
                        $newfilerecord->component = 'assignfeedback_file';
                        $newfilerecord->filearea = ASSIGNFEEDBACK_FILE_FILEAREA;
                        $newfilerecord->filename = $basename;
                        $newfilerecord->filepath = $dirnamewslash;
                        $newfilerecord->itemid = $grade->id;
                        $fs->create_file_from_storedfile($newfilerecord, $unzippedfile);
                        $feedbackfilesadded++;
                    }
                    $userswithnewfeedback[$user->id] = 1;

                    // Update the number of feedback files for this user.
                    $fileplugin->update_file_count($grade);

                    // Update the last modified time on the grade which will trigger student notifications.
                    $assignment->notify_grade_modified($grade);
                }
            }
        }

        require_once($CFG->dirroot . '/mod/assign/feedback/file/renderable.php');
        $importsummary = new assignfeedback_file_import_summary($assignment->get_course_module()->id,
                                                            count($userswithnewfeedback),
                                                            $feedbackfilesadded,
                                                            $feedbackfilesupdated);

        $assignrenderer = $assignment->get_renderer();
        $renderer = $PAGE->get_renderer('assignfeedback_file');

        $o = '';

        $o .= $assignrenderer->render(new assign_header($assignment->get_instance(),
                                                        $assignment->get_context(),
                                                        false,
                                                        $assignment->get_course_module()->id,
                                                        get_string('uploadzipsummary', 'assignfeedback_file')));

        $o .= $renderer->render($importsummary);

        $o .= $assignrenderer->render_footer();
        return $o;
    }
1022615
public function importResource($type, $path) {
        $src = '/static/'.$path;
        $template = self::$resTemplate[$type];
        $result = str_replace('{url}', $src, $template);
        return $result;
	}
92242
public function importPortableElements()
    {
        if (count($this->importingFiles) != count($this->requiredFiles)) {
            throw new \common_Exception('Needed files are missing during Portable Element asset files '.print_r($this->requiredFiles, true). ' '.print_r($this->importingFiles, true));
        }

        /** @var PortableElementObject $object */
        foreach ($this->portableObjects as $object) {
            $lastVersionModel = $this->getService()->getPortableElementByIdentifier(
                $object->getModel()->getId(),
                $object->getTypeIdentifier()
            );
            //only register a pci that has not been register yet, subsequent update must be done through pci package import
            if (is_null($lastVersionModel)){
                $this->getService()->registerModel(
                    $object,
                    $object->getRegistrationSourcePath($this->source, $this->itemDir)
                );
            } else {
                \common_Logger::i('The imported item contains the portable element '.$object->getTypeIdentifier()
                    .' in a version '.$object->getVersion().' compatible with the current '.$lastVersionModel->getVersion());
            }
        }
        return true;
    }
846297
def dump_resource_to_zipfile(resource, zipfile, content_type=None):
    
    if content_type is None:
        content_type = CsvMime
    srl = ConnectedResourcesSerializer(content_type)
    srl.to_zipfile(resource, zipfile)
522374
public static void addFileToZipOutputStream(File file, ZipOutputStream zipOs) throws IOException {
        String fileName = file.getName();
        try (FileInputStream fos = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipEntry.setSize(file.length());
            zipEntry.setTime(System.currentTimeMillis());
            zipOs.putNextEntry(zipEntry);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = fos.read(buf)) > 0) {
                zipOs.write(buf, 0, bytesRead);
            }
            zipOs.closeEntry();
            fos.close();
        }
    }
91360
protected function extract($zipFile, $directory)
    {
        $archive = new ZipArchive;

        $archive->open($zipFile);

        $archive->extractTo($directory);

        $archive->close();

        return $this;
    }
219580
protected function download($zipFile)
    {
        $response = (new Client)->get('http://cabinet.laravel.com/latest_lumen.zip');

        file_put_contents($zipFile, $response->getBody());

        return $this;
    }
359596
public function import($class, $form, $userId = null)
    {
        $uploadedFile = $this->fetchUploadedFile($form);

        try {
            $service = MediaService::singleton();
            $classUri = $class->getUri();

            $instanceUri = $form instanceof Form
                ? $form->getValue('instanceUri')
                : (isset($form['instanceUri']) ? $form['instanceUri'] : null);

            $fileInfo = $form instanceof Form ? $form->getValue('source') : $form['source'];

            // importing new media
            if (!$instanceUri || $instanceUri === $classUri) {
                //if the file is a zip do a zip import
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    try {
                        self::isValidSharedStimulus($uploadedFile);

                        $mediaResourceUri = $service->createMediaInstance(
                            $uploadedFile,
                            $classUri,
                            \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                            $fileInfo['name'],
                            'application/qti+xml',
                            $userId
                        );

                        if (!$mediaResourceUri) {
                            $report = Report::createFailure(__('Fail to import Shared Stimulus'));
                            $report->setData(['uriResource' => '']);
                        } else {
                            $report = Report::createSuccess(__('Shared Stimulus imported successfully'));
                            $report->add(Report::createSuccess(
                                __('Imported %s', $fileInfo['name']),
                                ['uriResource' => $mediaResourceUri] // 'uriResource' key is needed by javascript in tao/views/templates/form/import.tpl
                            ));
                        }
                    } catch (XmlStorageException $e) {
                        // The shared stimulus is not qti compliant, display error
                        $report = Report::createFailure($e->getMessage());
                        $report->setData(['uriResource' => '']);
                    }
                } else {
                    $report = $this->getZipImporter()->import($class, $form, $userId);
                }
            } else {
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    self::isValidSharedStimulus($uploadedFile);
                    if (in_array($fileInfo['type'], array('application/xml', 'text/xml'))) {
                        $name = basename($fileInfo['name'], 'xml');
                        $name .= 'xhtml';
                        $filepath = \tao_helpers_File::concat([dirname($fileInfo['name']), $name]);
                        $fileResource = fopen($filepath, 'w');
                        $uploadedFileResource = $uploadedFile->readStream();
                        stream_copy_to_stream($uploadedFileResource, $fileResource);
                        fclose($fileResource);
                        fclose($uploadedFileResource);
                    }

                    if (!$service->editMediaInstance(
                        isset($filepath) ? $filepath : $uploadedFile,
                        $instanceUri,
                        \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                        $userId
                    )) {
                        $report = Report::createFailure(__('Fail to edit shared stimulus'));
                    } else {
                        $report = Report::createSuccess(__('Shared Stimulus edited successfully'));
                    }

                    $report->setData(['uriResource' => $instanceUri]);
                } else {
                    $report = $this->getZipImporter()->edit(new \core_kernel_classes_Resource($instanceUri), $form, $userId);
                }
            }

        } catch (\Exception $e) {
            $message = $e instanceof \common_exception_UserReadableException
                ? $e->getUserMessage()
                : __('An error has occurred. Please contact your administrator.');
            $report = Report::createFailure($message);
            $report->setData(['uriResource' => '']);
            $this->logError($e->getMessage());
        }

        $this->getUploadService()->remove($uploadedFile);

        return $report;
    }
112415
public function import_pod_items( $data = null, $type = null ) {

		if ( ! empty( $data ) ) {
			$this->input = $data;
		}

		if ( ! empty( $type ) && in_array( $type, $this->types, true ) ) {
			$this->type = $type;
		}

		return false;
	}
1324830
public function getLoader($type, $locale)
    {
        switch ($type) {
            case 'yaml':
                return $this->newLoaderYaml($locale);
            case 'php':
                return $this->newLoaderPHP($locale);
        }
        throw new \InvalidArgumentException("Unknown loader type '$type'.");
    }
182865
public void instrumentZipFile(File zf) throws IOException {
        if (!zf.canRead() || !zf.canWrite()) {
            throw new IOException(zf + " can not be replaced");
        }

        File tempFile = File.createTempFile(zf.getName(), null, zf.getParentFile());
        if (tempFile.exists() && !tempFile.delete()) {
            throw new IOException("Unable to delete existing temp file " + tempFile.getName());
        }
        if (!zf.renameTo(tempFile)) {
            throw new IOException("Unable to rename existing jar " + zf);
        }

        ZipFile zipFile = new ZipFile(tempFile);
        FileOutputStream fos = new FileOutputStream(zf);
        ZipOutputStream zos = new ZipOutputStream(fos);
        boolean restoreZipFile = false;
        try {
            byte[] buffer = new byte[8192];
            Enumeration<? extends ZipEntry> e = zipFile.entries();
            while (e.hasMoreElements()) {
                ZipEntry oldEntry = e.nextElement();
                InputStream zis = zipFile.getInputStream(oldEntry);
                byte[] transformedClass = null;

                if (oldEntry.getName().endsWith(".class")) {
                    transformedClass = transform(zis);
                    if (transformedClass == null) {
                        zis = zipFile.getInputStream(oldEntry);
                    }
                }

                ZipEntry newEntry = new ZipEntry(oldEntry.getName());
                newEntry.setTime(transformedClass == null ? oldEntry.getTime() : System.currentTimeMillis());
                newEntry.setComment(oldEntry.getComment());
                newEntry.setExtra(oldEntry.getExtra());
                newEntry.setSize(transformedClass == null ? oldEntry.getSize() : transformedClass.length);

                if (newEntry.getSize() > Integer.MAX_VALUE) {
                    throw new IOException("ZipEntry too large: " + newEntry.getSize());
                }

                int entrySize = (int) newEntry.getSize();
                if (entrySize > buffer.length) {
                    buffer = new byte[entrySize];
                }

                if (transformedClass != null) {
                    System.arraycopy(transformedClass, 0, buffer, 0, entrySize);
                } else {
                    int totalBytesRead = 0;
                    while (totalBytesRead < entrySize) {
                        int bytesRead = zis.read(buffer, totalBytesRead, entrySize - totalBytesRead);
                        if (bytesRead == -1) {
                            throw new IOException("End of file encountered");
                        }
                        totalBytesRead += bytesRead;
                    }
                }

                zos.putNextEntry(newEntry);
                zos.write(buffer, 0, entrySize);
            }
        } catch (IOException ioe) {
            restoreZipFile = true;
            throw ioe;
        } catch (Throwable t) {
            restoreZipFile = true;
            IOException ioe = new IOException("Unexpected exception encountered during instrumentation");
            ioe.initCause(t);
            throw ioe;
        } finally {
            zos.close();
            fos.close();
            zipFile.close();
            if (restoreZipFile) {
                zf.delete();
                tempFile.renameTo(zf);
            } else {
                tempFile.delete();
            }
        }
    }
254150
public function import( $data = null, $type = null, $delimiter = null ) {

		$this->parse( $data, $type, $delimiter );

		return $this->import_pod_items();

	}