Create OPF File.

@param array $book_contents
@param array $metadata

@throws \Exception
973741
protected function createOPF( $book_contents, $metadata ) {

		if ( empty( $this->manifest ) ) {
			throw new \Exception( '$this->manifest cannot be empty. Did you forget to call $this->createOEBPS() ?' );
		}

		// Vars
		$vars = [
			'manifest' => $this->manifest,
			'stylesheet' => $this->stylesheet,
			'lang' => $this->lang,
		];

		$vars['manifest_assets'] = $this->buildManifestAssetsHtml();

		$vars['do_copyright_license'] = sanitize_xml_attribute(
			wp_strip_all_tags( $this->doCopyrightLicense( $metadata ), true )
		);

		// Sanitize metadata for usage in XML template
		foreach ( $metadata as $key => $val ) {
			$metadata[ $key ] = sanitize_xml_attribute( $val );
		}
		$vars['meta'] = $metadata;

		// Put contents
		\Pressbooks\Utility\put_contents(
			$this->tmpDir . '/book.opf',
			$this->loadTemplate( $this->dir . '/templates/epub201/opf.php', $vars )
		);
	}
227159
public function create($params = [], ClassMetadata $metadata = null)
    {
        $params = new ArrayObject($params);
        $builder = $this->getEntityBuilder();
        /** @var Entity $entity */
        $entity = $builder->getEntity();
        $preEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::PRE_HYDRATE, $preEventArgs);
        $builder->create($params, $entity);
        $postEventArgs = new HydrationEvent($params, ['entity' => $entity, 'repository' => $this]);
        $this->event()->dispatch(StorageEvents::POST_HYDRATE, $postEventArgs);

        return $entity;
    }
180509
private static function create($basicMessage, $rpcCode, $metadata, array $decodedMetadata, $previous = null)
    {
        $rpcStatus = ApiStatus::statusFromRpcCode($rpcCode);
        $messageData = [
            'message' => $basicMessage,
            'code' => $rpcCode,
            'status' => $rpcStatus,
            'details' => $decodedMetadata
        ];

        $message = json_encode($messageData, JSON_PRETTY_PRINT);

        return new ApiException($message, $rpcCode, $rpcStatus, [
            'previous' => $previous,
            'metadata' => $metadata,
            'basicMessage' => $basicMessage,
        ]);
    }
321205
function set_file_contents($config_file, $contents)
	{
		$this->_config_data[$config_file] = $this->parse_contents($contents);
		return true;
	}
776369
public function render_print_book_toc($chapters, $book, $cm) {

        $first = true;

        $context = context_module::instance($cm->id);

        $toc = ''; // Representation of toc (HTML).

        switch ($book->numbering) {
            case BOOK_NUM_NONE:
                $toc .= html_writer::start_tag('div', array('class' => 'book_toc_none'));
                break;
            case BOOK_NUM_NUMBERS:
                $toc .= html_writer::start_tag('div', array('class' => 'book_toc_numbered'));
                break;
            case BOOK_NUM_BULLETS:
                $toc .= html_writer::start_tag('div', array('class' => 'book_toc_bullets'));
                break;
            case BOOK_NUM_INDENTED:
                $toc .= html_writer::start_tag('div', array('class' => 'book_toc_indented'));
                break;
        }

        $toc .= html_writer::tag('a', '', array('name' => 'toc')); // Representation of toc (HTML).

        $toc .= html_writer::tag('h2', get_string('toc', 'mod_book'), ['class' => 'text-center p-b-2']);
        $toc .= html_writer::start_tag('ul');
        foreach ($chapters as $ch) {
            if (!$ch->hidden) {
                $title = book_get_chapter_title($ch->id, $chapters, $book, $context);
                if (!$ch->subchapter) {

                    if ($first) {
                        $toc .= html_writer::start_tag('li');
                    } else {
                        $toc .= html_writer::end_tag('ul');
                        $toc .= html_writer::end_tag('li');
                        $toc .= html_writer::start_tag('li');
                    }

                } else {

                    if ($first) {
                        $toc .= html_writer::start_tag('li');
                        $toc .= html_writer::start_tag('ul');
                        $toc .= html_writer::start_tag('li');
                    } else {
                        $toc .= html_writer::start_tag('li');
                    }

                }

                if (!$ch->subchapter) {
                    $toc .= html_writer::link(new moodle_url('#ch' . $ch->id), $title,
                            array('title' => s($title), 'class' => 'font-weight-bold text-decoration-none'));
                    $toc .= html_writer::start_tag('ul');
                } else {
                    $toc .= html_writer::link(new moodle_url('#ch' . $ch->id), $title,
                            array('title' => s($title), 'class' => 'text-decoration-none'));
                    $toc .= html_writer::end_tag('li');
                }
                $first = false;
            }
        }

        $toc .= html_writer::end_tag('ul');
        $toc .= html_writer::end_tag('li');
        $toc .= html_writer::end_tag('ul');
        $toc .= html_writer::end_tag('div');

        $toc = str_replace('<ul></ul>', '', $toc); // Cleanup of invalid structures.

        return $toc;
    }
277481
public function addInstanceDocument( $instance_file = null, $taxonomy_file = null )
	{
		$this->log()->info( "$instance_file" );

		if ( $this->hierarchies !== null )
			throw new Exception( "An instance document cannot be added to a report once the report has been prepared" );

		if ( $instance_file === null )
			throw new Exception( "An instance document has not been supplied." );

		if ( isset( $this->instanceDocuments[ $instance_file ] ) )
			throw new Exception( "The instance document has already been loaded" );

		// Load the document
		/**
		 * An instance document instance
		 * @var XBRL_Instance $instance
		 */
		$instance = null;
		if ( ! XBRL_Instance::FromInstanceDocument( $instance_file, $taxonomy_file, $instance ) )
		{
			throw new Exception( $instance->getError() );
		}

		// If no schema file is yet set, record it.  If the name of the taxonomy schema
		// associated with the instance document loaded is different to the schema of
		// a previously loaded instance document then report an error.
		$schemaFilename = $instance->getSchemaFilename();
		if ( $this->schemaFilename === null )
			$this->schemaFilename = $schemaFilename;
		else if ( $this->schemaFilename !== $schemaFilename )
			throw new Exception( "Instance documents being compared must use the the same taxonomy schema." );

		// Record it
		$this->instanceDocuments[ $instance_file ] =& $instance;
		$this->analyzeContexts( $instance );

		// If no taxonomy is set then record it as well.  Only one taxonomy is allowed per report.
		if ( ! isset( $this->taxonomy ) || $this->taxonomy === null )
			$this->taxonomy =& $instance->getInstanceTaxonomy();
	}
978894
public function prepareMetaDescriptionForPersist($meta_description="", $excerpt)
    {
        if ($meta_description == "") return $excerpt;

        $meta_description = html_entity_decode($meta_description);
        $meta_description = strip_tags($meta_description);
        $meta_description = filter_var($meta_description, FILTER_SANITIZE_STRING);

        // remove the encoded blank chars
        $meta_description = str_replace("\xc2\xa0",'',$meta_description);

        $meta_description = trim($meta_description);
        return $meta_description;
    }
662301
public function createQueryBuilderForMetadataAndEnabledsSelection(Metadata $metadata, array $criteria = null, array $orderBy = null, $limit = null, $offset = null, $class = null)
    {
        $qb = $this->createQueryBuilder($criteria, $orderBy, $limit, $offset, $class); // TODO: Change the autogenerated stub

        $qb->leftJoin($qb->getRootAliases()[0] . '.metadata', 'm');
        $qb->leftJoin($qb->getRootAliases()[0] . '.table', 't');
        $qb->andWhere($qb->expr()->eq('m.id', '\'' . $metadata->getId() . '\''));
        $qb->andWhere($qb->expr()->eq($qb->getRootAliases()[0] . '.enabled', true));
        $qb->addOrderBy('t.position', 'ASC');
        $qb->addOrderBy($qb->getRootAliases()[0] . '.title', 'ASC');

        return $qb;
    }
664254
public function writeToCache(ClassLikeStorage $storage, $file_path, $file_contents)
    {
        $fq_classlike_name_lc = strtolower($storage->name);
        $cache_location = $this->getCacheLocationForClass($fq_classlike_name_lc, $file_path, true);
        $storage->hash = $this->getCacheHash($file_path, $file_contents);

        if ($this->config->use_igbinary) {
            file_put_contents($cache_location, igbinary_serialize($storage));
        } else {
            file_put_contents($cache_location, serialize($storage));
        }
    }
431757
public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory)
    {
        $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . $this->extension;
        $dir = dirname($path);

        if ( ! is_dir($dir)) {
            mkdir($dir, 0775, true);
        }

        $this->isNew = !file_exists($path) || (file_exists($path) && $this->regenerateEntityIfExists);

        if ( ! $this->isNew) {
            $this->parseTokensInEntityFile(file_get_contents($path));
        } else {
            $this->staticReflection[$metadata->name] = array('properties' => array(), 'methods' => array());
        }

        if ($this->backupExisting && file_exists($path)) {
            $backupPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . "~";
            if (!copy($path, $backupPath)) {
                throw new \RuntimeException("Attempt to backup overwritten entity file but copy operation failed.");
            }
        }

        // If entity doesn't exist or we're re-generating the entities entirely
        if ($this->isNew) {
            file_put_contents($path, $this->generateEntityClass($metadata));
        // If entity exists and we're allowed to update the entity class
        } elseif ( ! $this->isNew && $this->updateEntityIfExists) {
            file_put_contents($path, $this->generateUpdatedEntityClass($metadata, $path));
        }
        chmod($path, 0664);
    }
756999
public static function createFromFile(\SplFileInfo $file_info)
    {
        $contents = file_get_contents($file_info);

        if (!$contents) {
            throw new \RuntimeException(
                sprintf(
                    'Unable to retrieve contents from file (%s).',
                    $file_info->getRealPath()
                )
            );
        }

        return self::createFromString($contents);
    }
38388
def render
      create_epub do
        temp_file = Tempfile.new("ocf")
        self.save(temp_file.path)
        return temp_file.read
      end
    end
817774
public function createContent() {
    $productDetails = $this->productDetails();

    /** @var \Drupal\commerce_product\Entity\Product $product */
    $product = Product::create($productDetails);
    $product->save();

    foreach ($this->productVariations() as $variationAttrs) {
      $variationAttrs['product_id'] = $product->id();
      $variation = ProductVariation::create($variationAttrs);
      $variation->save();
      $product->addVariation($variation);
    }

    $storeId = $this->loadStoreId();
    if ($storeId !== NULL) {
      $product->setStoreIds([$storeId]);
    }

    $product->save();
  }
12587
public function write($content, array $metadata = null)
    {
        $mode = 0666;
        $umask = umask();
        $filesystem = new Filesystem();
        $filesystem->dumpFile($this->file, $content);
        try {
            $filesystem->chmod($this->file, $mode, $umask);
        } catch (IOException $e) {
            // discard chmod failure (some filesystem may not support it)
        }

        if (null !== $metadata) {
            $filesystem->dumpFile($this->getMetaFile(), serialize($metadata));
            try {
                $filesystem->chmod($this->getMetaFile(), $mode, $umask);
            } catch (IOException $e) {
                // discard chmod failure (some filesystem may not support it)
            }
        }

        if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) {
            @opcache_invalidate($this->file, true);
        }
    }
906405
protected void createFile(File stagingDirectory) throws MojoExecutionException {
        File targetDirectory = newSubdirectory(stagingDirectory, "META-INF");
        File newEntry = new File(targetDirectory, filename);

        try (FileOutputStream out = new FileOutputStream(newEntry); PrintStream ps = new PrintStream(out);) {
            
            Iterator<ConfigEntry> iter = entries.values().iterator();
            ConfigEntry entry = null;

            for (int i = 0; i < buffer.size(); i++) {
                if (entry == null && iter.hasNext()) {
                    entry = iter.next();
                }

                if (entry != null && entry.placeholder == i) {
                    for (String line : entry.buffer) {
                        ps.println(line);
                    }

                    entry = null;
                    continue;
                }

                ps.println(buffer.get(i));
            }
        } catch (Exception e) {
            throw new MojoExecutionException("Unexpected error while creating configuration file.", e);
        }
    }
1144057
protected function createContent()
    {
        $this->setCliMessage('Creating content...');

        $this->initConfig();
        $this->createDbConfig();
        $this->createStore();
        $this->createSuperadmin();
        $this->createCountries();
        $this->createLanguages();
        $this->createPages();
    }
182029
protected void buildBookInfoFile(final BuildData buildData, final String bookInfoTemplate) throws BuildProcessingException {
        final ContentSpec contentSpec = buildData.getContentSpec();
        final Map<String, String> overrides = buildData.getBuildOptions().getOverrides();

        String bookInfo = bookInfoTemplate.replaceAll(BuilderConstants.ESCAPED_TITLE_REGEX, buildData.getEscapedBookTitle());

        // DocBook 5 changed the name of <articleinfo>/<bookinfo> to just <info>
        final String rootElementName;
        if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
            rootElementName = "info";
            bookInfo = bookInfo.replaceAll("<(/)?bookinfo", "<$1info").replaceAll("<(/)?articleinfo", "<$1info");

            // Change the corpauthor element to orgname
            bookInfo = bookInfo.replaceAll("<(/)?corpauthor>", "<$1orgname>");

            // change the "id" attribute to "xml:id"
            bookInfo = bookInfo.replace("id=\"", "xml:id=\"");
        } else {
            if (contentSpec.getBookType() == BookType.ARTICLE || contentSpec.getBookType() == BookType.ARTICLE_DRAFT) {
                rootElementName = "articleinfo";
            } else {
                rootElementName = "bookinfo";
            }
        }

        // Replace the book info elements with the data from the content spec
        boolean versionSet = false;
        boolean editionSet = false;
        boolean abstractSet = false;
        boolean subtitleSet = false;
        for (final org.jboss.pressgang.ccms.contentspec.Node node : contentSpec.getNodes()) {
            if (node instanceof KeyValueNode) {
                final KeyValueNode<?> keyValueNode = (KeyValueNode<?>) node;
                if (!(keyValueNode.getValue() instanceof String)) {
                    continue;
                }

                if (CommonConstants.CS_TITLE_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    // Set the book title
                    final String title = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);
                    bookInfo = bookInfo.replaceAll(BuilderConstants.TITLE_REGEX,
                            DocBookBuildUtilities.escapeForReplaceAll(DocBookUtilities.escapeForXML(title)));
                } else if (CommonConstants.CS_SUBTITLE_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    // Set the book subtitle
                    final String subtitle = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);
                    bookInfo = bookInfo.replaceAll(BuilderConstants.SUBTITLE_REGEX,
                            contentSpec.getSubtitle() == null ? BuilderConstants.SUBTITLE_DEFAULT : DocBookBuildUtilities
                                    .escapeForReplaceAll(DocBookUtilities.escapeForXML(subtitle)));
                    subtitleSet = true;
                } else if (CommonConstants.CS_PRODUCT_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    // Set the book product
                    final String product = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);
                    bookInfo = bookInfo.replaceAll(BuilderConstants.PRODUCT_REGEX,
                            DocBookBuildUtilities.escapeForReplaceAll(DocBookUtilities.escapeForXML(product)));
                } else if (CommonConstants.CS_VERSION_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    // Set the book version
                    final String version = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);
                    bookInfo = bookInfo.replaceAll(BuilderConstants.VERSION_REGEX, version == null ? "" : version);
                    versionSet = true;
                } else if (CommonConstants.CS_EDITION_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    // Set the book edition
                    final String edition = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);
                    bookInfo = bookInfo.replaceAll(BuilderConstants.EDITION_REGEX, edition);
                } else if (CommonConstants.CS_ABSTRACT_TITLE.equalsIgnoreCase(keyValueNode.getKey())) {
                    final String description = DocBookBuildUtilities.getKeyValueNodeText(buildData, keyValueNode);

                    final String fixedAbstract;
                    if (description.matches("^<(formal|sim)?para>(.|\\s)*")) {
                        fixedAbstract = "<abstract>\n\t\t" + description + "\n\t</abstract>\n";
                    } else {
                        fixedAbstract = "<abstract>\n\t\t<para>\n\t\t\t" + description + "\n\t\t</para>\n\t</abstract>\n";
                    }

                    // Set the book abstract
                    bookInfo = bookInfo.replaceAll(BuilderConstants.ABSTRACT_REGEX,
                            DocBookBuildUtilities.escapeForReplaceAll(DocBookUtilities.escapeForXML(fixedAbstract)));
                    abstractSet = true;
                }
            }
        }

        // Apply the null value defaults for version, edition and abstract
        if (!subtitleSet) {
            bookInfo = bookInfo.replaceAll(BuilderConstants.SUBTITLE_REGEX, BuilderConstants.SUBTITLE_DEFAULT);
        }
        if (!versionSet) {
            bookInfo = bookInfo.replaceAll(BuilderConstants.VERSION_REGEX, "");
        }
        if (!editionSet) {
            bookInfo = bookInfo.replaceAll("<edition>.*</edition>(\r)?\n", "");
        }
        if (!abstractSet) {
            final String fixedAbstract;
            if (contentSpec.getAbstractTopic() != null) {
                fixedAbstract = DocBookBuildUtilities.convertDocumentToFormattedString(contentSpec.getAbstractTopic().getXMLDocument(),
                        getXMLFormatProperties());
            } else {
                fixedAbstract = BuilderConstants.DEFAULT_ABSTRACT;
            }

            bookInfo = bookInfo.replaceAll(BuilderConstants.ABSTRACT_REGEX, DocBookBuildUtilities.escapeForReplaceAll(fixedAbstract));
        }

        // Get the pubsnumber
        final String pubsNumber = overrides.containsKey(CSConstants.PUBSNUMBER_OVERRIDE) ? overrides.get(
                CSConstants.PUBSNUMBER_OVERRIDE) : (contentSpec.getPubsNumber() == null ? BuilderConstants.DEFAULT_PUBSNUMBER :
                contentSpec.getPubsNumber().toString());

        // pubsnumber is different is docbook 5
        if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
            bookInfo = bookInfo.replaceAll(BuilderConstants.PUBSNUMBER_REGEX, "<biblioid class=\"pubsnumber\">" + pubsNumber +
                    "</biblioid>");
        } else {
            bookInfo = bookInfo.replaceAll(BuilderConstants.PUBSNUMBER_REGEX, "<pubsnumber>" + pubsNumber + "</pubsnumber>");
        }

        // Set the book to have a Legal Notice
        bookInfo = bookInfo.replaceAll(BuilderConstants.LEGAL_NOTICE_REGEX, BuilderConstants.LEGAL_NOTICE_XML);

        if (!isNullOrEmpty(contentSpec.getBrandLogo())) {
            final String fixedLogoPath = contentSpec.getBrandLogo().contains(
                    "Common_Content/images/") ? contentSpec.getBrandLogo() : ("Common_Content/images/" + contentSpec.getBrandLogo());
            bookInfo = bookInfo.replaceFirst("<imagedata.*?/>", "<imagedata fileref=\"" + fixedLogoPath + "\" />");
        }

        // Add the preamble to the book info
        bookInfo = DocBookBuildUtilities.addDocBookPreamble(buildData.getDocBookVersion(), bookInfo, rootElementName,
                buildData.getEntityFileName());

        if (contentSpec.getBookType() == BookType.ARTICLE || contentSpec.getBookType() == BookType.ARTICLE_DRAFT) {
            addToZip(buildData.getBookLocaleFolder() + "Article_Info.xml", bookInfo, buildData);
        } else {
            addToZip(buildData.getBookLocaleFolder() + "Book_Info.xml", bookInfo, buildData);
        }
    }