Prepare the package for export

@return stored_file object
431071
public function prepare_package() {
        global $DB;
        $leapwriter = null;
        $content = '';
        $filename = '';
        $uid = $this->exporter->get('user')->id;
        $users = array(); //cache
        $onlymine = $this->get_export_config('mineonly');
        if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
            $leapwriter = $this->exporter->get('format')->leap2a_writer();
            $ids = array();
        }

        if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
            return $this->get('exporter')->copy_existing_file($this->singlefile);
        }
        foreach ($this->records  as $key => $record) {
            if ($onlymine && $record->userid != $uid) {
                unset($this->records[$key]); // sha1
                continue;
            }
            list($tmpcontent, $files)  = $this->exportentry($record);
            $content .= $tmpcontent;
            if ($leapwriter) {
                $entry = new portfolio_format_leap2a_entry('dataentry' . $record->id, $this->data->name, 'resource', $tmpcontent);
                $entry->published = $record->timecreated;
                $entry->updated = $record->timemodified;
                if ($record->userid != $uid) {
                    if (!array_key_exists($record->userid, $users)) {
                        $users[$record->userid] = $DB->get_record('user', array('id' => $record->userid), 'id,firstname,lastname');
                    }
                    $entry->author = $users[$record->userid];
                }
                $ids[] = $entry->id;
                $leapwriter->link_files($entry, $files, 'dataentry' . $record->id . 'file');
                $leapwriter->add_entry($entry);
            }
        }
        if ($leapwriter) {
            if (count($this->records) > 1) { // make a selection element to tie them all together
                $selection = new portfolio_format_leap2a_entry('datadb' . $this->data->id,
                    get_string('entries', 'data') . ': ' . $this->data->name, 'selection');
                $leapwriter->add_entry($selection);
                $leapwriter->make_selection($selection, $ids, 'Grouping');
            }
            $filename = $this->exporter->get('format')->manifest_name();
            $content = $leapwriter->to_xml();
        } else {
            if (count($this->records) == 1) {
                $filename = clean_filename($this->cm->name . '-entry.html');
            } else {
                $filename = clean_filename($this->cm->name . '-full.html');
            }
        }
        return $this->exporter->write_new_file(
            $content,
            $filename,
            ($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH) // if we have associate files, this is a 'manifest'
        );
    }
767621
protected function createSqlDbMap()
    {
        if ($this->getSqlDbMap() === null) {
            return;
        }

        // Produce the sql -> database map
        $sqldbmap = new Properties();

        // Check to see if the sqldbmap has already been created.
        if ($this->getSqlDbMap()->exists()) {
            $sqldbmap->load($this->getSqlDbMap());
        }

        if ($this->packageObjectModel) {
            // in this case we'll get the sql file name from the package attribute
            $dataModels = $this->packageDataModels();
            foreach ($dataModels as $package => $dataModel) {
                foreach ($dataModel->getDatabases() as $database) {
                    $name = ($package ? $package . '.' : '') . 'schema.xml';
                    $sqlFile = $this->getMappedFile($name);
                    $sqldbmap->setProperty($sqlFile->getName(), $database->getName());
                }
            }
        } else {
            // the traditional way is to map the schema.xml filenames
            $dmMap = $this->getDataModelDbMap();
            foreach (array_keys($dmMap) as $dataModelName) {
                $sqlFile = $this->getMappedFile($dataModelName);
                if ($this->getDatabase() === null) {
                    $databaseName = $dmMap[$dataModelName];
                } else {
                    $databaseName = $this->getDatabase();
                }
                $sqldbmap->setProperty($sqlFile->getName(), $databaseName);
            }
        }

        try {
            $sqldbmap->store($this->getSqlDbMap(), "Sqlfile -> Database map");
        } catch (IOException $e) {
            throw new IOException("Unable to store properties: " . $e->getMessage());
        }
    }
1337578
private function prepareRestart()
    {
        $error = '';
        $iniFiles = self::getAllIniFiles();
        $scannedInis = count($iniFiles) > 1;
        $tmpDir = sys_get_temp_dir();

        if (!$this->cli) {
            $error = 'Unsupported SAPI: '.PHP_SAPI;
        } elseif (!defined('PHP_BINARY')) {
            $error = 'PHP version is too old: '.PHP_VERSION;
        } elseif (!$this->checkConfiguration($info)) {
            $error = $info;
        } elseif (!$this->checkScanDirConfig()) {
            $error = 'PHP version does not report scanned inis: '.PHP_VERSION;
        } elseif (!$this->checkMainScript()) {
            $error = 'Unable to access main script: '.$this->script;
        } elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) {
            $error = $error ?: 'Unable to create temp ini file at: '.$tmpDir;
        } elseif (!$this->setEnvironment($scannedInis, $iniFiles)) {
            $error = 'Unable to set environment variables';
        }

        if ($error) {
            $this->notify(Status::ERROR, $error);
        }

        return empty($error);
    }
149809
public function prepare()
    {
        $files = $this->getFilesStack();
        if (!empty($files)) {
            foreach ($files as $_file) {
                $this->addContent(
                    file_get_contents($_file->getRealPath()),
                    $_file->getPathname()
                );
            }
        }
    }
1359865
protected function prepareExecute()
    {
        // Prepare migration path
        $packageName = $this->getOption('p');

        /** @var AbstractPackage $package */
        $package = $this->console->getPackage($packageName);

        if ($package) {
            $dir = $package->getDir() . '/Migration';
        } else {
            $dir = $this->getOption('d');
        }

        $dir = $dir ?: $this->console->get('path.migrations');

        $this->console->set('migration.dir', $dir);

        // DB log
        $this->console->database->setDebug(true);

        $this->console->database->setMonitor(
            new CallbackMonitor(function ($query) {
                $this->console->triggerEvent('onMigrationAfterQuery', ['query' => $query]);
            })
        );
    }
96248
function save()
    {
        $file = $this->_getFilePath();

        $data = $this->data;
        $data = $this->getDataInterchange()->makeForward($data);
        $dataStr = "<?php\n". "return " . var_export($data, true) . ";\n";

        ErrorStack::handleError(E_ALL);
        ##  \\\\\
        ### check for directory tree
        $dirPath = dirname($file);
        if (! file_exists($dirPath) )
            if ( false === mkdir($dirPath, 0777, true) )
                throw new \RuntimeException(sprintf('Cant create store directory on (%s).', $dirPath));

        file_put_contents($file, $dataStr, LOCK_EX);
        ##  /////
        if ($exception = ErrorStack::handleDone())
            throw $exception;

        $this->_setState(self::$STATE_OK);
        return $this;
    }
659181
private function prepareCommandLine()
    {
        $this->commandLine->setExecutable($this->getPhp());
        //We are un-shifting arguments to the beginning of the command line because arguments should be at the end
        $this->commandLine->createArgument(true)->setValue($this->getCommand());
        $this->commandLine->createArgument(true)->setValue($this->getComposer());
        $commandLine = (string) $this->commandLine;
        //Creating new Commandline instance. It allows to handle subsequent calls correctly
        $this->commandLine = new Commandline();

        return $commandLine;
    }
72770
function prepare_package() {
        global $CFG;

        // set up the leap2a writer if we need it
        $writingleap = false;
        if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
            $leapwriter = $this->exporter->get('format')->leap2a_writer();
            $writingleap = true;
        }
        if ($this->attachment) { // simplest case first - single file attachment
            $this->copy_files(array($this->singlefile), $this->attachment);
            if ($writingleap) { // if we're writing leap, make the manifest to go along with the file
                $entry = new portfolio_format_leap2a_file($this->singlefile->get_filename(), $this->singlefile);
                $leapwriter->add_entry($entry);
                return $this->exporter->write_new_file($leapwriter->to_xml(), $this->exporter->get('format')->manifest_name(), true);
            }

        } else if (empty($this->post)) {  // exporting whole discussion
            $content = ''; // if we're just writing HTML, start a string to add each post to
            $ids = array(); // if we're writing leap2a, keep track of all entryids so we can add a selection element
            foreach ($this->posts as $post) {
                $posthtml =  $this->prepare_post($post);
                if ($writingleap) {
                    $ids[] = $this->prepare_post_leap2a($leapwriter, $post, $posthtml);
                } else {
                    $content .= $posthtml . '<br /><br />';
                }
            }
            $this->copy_files($this->multifiles);
            $name = 'discussion.html';
            $manifest = ($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH);
            if ($writingleap) {
                // add on an extra 'selection' entry
                $selection = new portfolio_format_leap2a_entry('forumdiscussion' . $this->discussionid,
                    get_string('discussion', 'forum') . ': ' . $this->discussion->name, 'selection');
                $leapwriter->add_entry($selection);
                $leapwriter->make_selection($selection, $ids, 'Grouping');
                $content = $leapwriter->to_xml();
                $name = $this->get('exporter')->get('format')->manifest_name();
            }
            $this->get('exporter')->write_new_file($content, $name, $manifest);

        } else { // exporting a single post
            $posthtml = $this->prepare_post($this->post);

            $content = $posthtml;
            $name = 'post.html';
            $manifest = ($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH);

            if ($writingleap) {
                $this->prepare_post_leap2a($leapwriter, $this->post, $posthtml);
                $content = $leapwriter->to_xml();
                $name = $this->exporter->get('format')->manifest_name();
            }
            $this->copy_files($this->multifiles);
            $this->get('exporter')->write_new_file($content, $name, $manifest);
        }
    }
374365
protected function prepareDatabaseEcosystem()
    {
        $basePath = realpath('../');
        $dbPath = $basePath.'/'.$this->options['dbPath'].'/'.$this->options['database'];

        if (! is_dir($dbPath)) {
            mkdir($dbPath, 0755, true);
        }

        $this->dbPath = realpath($dbPath);
    }
947899
private static function package()
    {
        if (!self::$package) {
            self::$package = new PackageBase('cripfilesys', __DIR__);
            self::$package->publish_database = false;
            self::$package->enable_routes = false;
        }
        return self::$package;
    }
849751
public function prepareLocal() {
    $do_composer_install = TRUE;
    $project_properties = $this->getProjectProperties();
    $grab_database = $this->confirm("Load a database backup?");
    if ($grab_database == 'y') {
      $do_composer_install = $this->getDatabaseOfTruth();
    }
    if ($do_composer_install) {
      $this->taskComposerInstall()
        ->optimizeAutoloader()
        ->run();
      $drush_commands = [
        'drush_clear_cache' => 'drush cr',
        'drush_update_database' => 'drush updb',
        'drush_grab_config_changes' => 'drush config-import -y',
        'drush_grab_config_local_changes' => 'drush config-split:import local -y',
      ];
      $this->taskExec(implode(' && ', $drush_commands))
        ->dir($project_properties['web_root'])
        ->run();
    }
  }
946625
protected function prepareResources()
    {
        // Publish our views
        $this->publishes([
            __DIR__ .  '/views' => base_path("resources/views")
        ]);

        // Publish our lang
        $this->publishes([
            __DIR__ .  '/lang' => base_path("resources/lang")
        ]);

        // Publish our public
        $this->publishes([
            __DIR__ .  '/public' => base_path("public")
        ]);

        // Publish our migrations
        $this->publishes([
            __DIR__ .  '/migrations' => base_path("database/migrations")
        ], 'migrations');

        // Publish our migrations
        $this->publishes([
            __DIR__ .  '/seeds' => base_path("database/seeds")
        ], 'seeds');

        // Publish a config file
        $this->publishes([
            __DIR__ . '/config' => base_path('/config')
        ], 'config');

        // Publish our routes
        $this->publishes([
            __DIR__ .  '/routes.php' => base_path("app/Http/base_routes.php")
        ], 'routes');

        // Include the routes file
        if(file_exists(base_path("app/Http/base_routes.php")))
            include base_path("app/Http/base_routes.php");
    }
838730
public function prepare_package() {
        $entries = $this->exportdata['entries'];
        $aliases = array();
        $categories = array();
        if (is_array($this->exportdata['aliases'])) {
            foreach ($this->exportdata['aliases'] as $alias) {
                if (!array_key_exists($alias->entryid, $aliases)) {
                    $aliases[$alias->entryid] = array();
                }
                $aliases[$alias->entryid][] = $alias->alias;
            }
        }
        if (is_array($this->exportdata['categoryentries'])) {
            foreach ($this->exportdata['categoryentries'] as $cat) {
                if (!array_key_exists($cat->entryid, $categories)) {
                    $categories[$cat->entryid] = array();
                }
                $categories[$cat->entryid][] = $cat->name;
            }
        }
        if ($this->get('exporter')->get('formatclass') == PORTFOLIO_FORMAT_SPREADSHEET) {
            $csv = glossary_generate_export_csv($entries, $aliases, $categories);
            $this->exporter->write_new_file($csv, clean_filename($this->cm->name) . '.csv', false);
            return;
        } else if ($this->get('exporter')->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
            $ids = array(); // keep track of these to make into a selection later
            global $USER, $DB;
            $writer = $this->get('exporter')->get('format')->leap2a_writer($USER);
            $format = $this->exporter->get('format');
            $filename = $this->get('exporter')->get('format')->manifest_name();
            foreach ($entries as $e) {
                $content = glossary_entry_portfolio_caller::entry_content(
                    $this->course,
                    $this->cm,
                    $this->glossary,
                    $e,
                    (array_key_exists($e->id, $aliases) ? $aliases[$e->id] : array()),
                    $format
                );
                $entry = new portfolio_format_leap2a_entry('glossaryentry' . $e->id, $e->concept, 'entry', $content);
                $entry->author    = $DB->get_record('user', array('id' => $e->userid), 'id,firstname,lastname,email');
                $entry->published = $e->timecreated;
                $entry->updated   = $e->timemodified;
                if (!empty($this->keyedfiles[$e->id])) {
                    $writer->link_files($entry, $this->keyedfiles[$e->id], 'glossaryentry' . $e->id . 'file');
                    foreach ($this->keyedfiles[$e->id] as $file) {
                        $this->exporter->copy_existing_file($file);
                    }
                }
                if (!empty($categories[$e->id])) {
                    foreach ($categories[$e->id] as $cat) {
                        // this essentially treats them as plain tags
                        // leap has the idea of category schemes
                        // but I think this is overkill here
                        $entry->add_category($cat);
                    }
                }
                $writer->add_entry($entry);
                $ids[] = $entry->id;
            }
            $selection = new portfolio_format_leap2a_entry('wholeglossary' . $this->glossary->id, get_string('modulename', 'glossary'), 'selection');
            $writer->add_entry($selection);
            $writer->make_selection($selection, $ids, 'Grouping');
            $content = $writer->to_xml();
        }
        $this->exporter->write_new_file($content, $filename, true);
    }
697386
public function createFile()
    {
        $tmpfile = $this->tmpDir . '/' . $this->hash . '.tex';

        $tex = '\documentclass[12pt]{article}'."\n";
        
        $tex .= '\usepackage[utf8]{inputenc}'."\n";

        // Packages
        foreach ($this->packages as $package) {
            $tex .= '\usepackage{' . $package . "}\n";
        }
        
        $tex .= '\begin{document}'."\n";
        $tex .= '\pagestyle{empty}'."\n";
        $tex .= '\begin{displaymath}'."\n";
        
        $tex .= $this->formula."\n";
        
        $tex .= '\end{displaymath}'."\n";
        $tex .= '\end{document}'."\n";

        if (file_put_contents($tmpfile, $tex) === false) {
            throw new \Exception('Failed to open target file');
        }
    }
157721
public function prepareFileSystem()
    {

        // load the directories
        $directories = $this->getDirectories();

        // load user and group from system configuration
        $user = $this->getSystemConfiguration()->getUser();
        $group = $this->getSystemConfiguration()->getGroup();

        // check if the necessary directories already exists, if not, create them
        foreach (DirectoryKeys::getServerDirectoryKeysToBeCreated() as $directoryKey) {
            // prepare the path to the directory to be created
            $toBeCreated = $this->realpath($directories[$directoryKey]);

            // prepare the directory name and check if the directory already exists
            if (is_dir($toBeCreated) === false) {
                // if not, try to create it
                if (mkdir($toBeCreated, 0755, true) === false) {
                    throw new \Exception(
                        sprintf('Can\'t create necessary directory %s while starting application server', $toBeCreated)
                    );
                }

                // set user/group specified from the system configuration
                if ($this->setUserRights(new \SplFileInfo($toBeCreated), $user, $group) === false) {
                    throw new \Exception(
                        sprintf('Can\'t switch user/group to %s/% for directory %s while starting application server', $user, $group, $toBeCreated)
                    );
                }
            }
        }

        // create the container specific directories
        /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
        foreach ($this->getSystemConfiguration()->getContainers() as $containerNode) {
            // iterate over the container host's directories
            foreach ($containerNode->getHost()->getDirectories() as $directory) {
                // prepare the path to the directory to be created
                $toBeCreated = $this->realpath($directory);

                // prepare the directory name and check if the directory already exists
                if (is_dir($toBeCreated) === false) {
                    // if not, try to create it
                    if (mkdir($toBeCreated, 0755, true) === false) {
                        throw new \Exception(
                            sprintf('Can\'t create necessary directory %s while starting application server', $toBeCreated)
                        );
                    }

                    // set user/group specified from the system configuration
                    if ($this->setUserRights(new \SplFileInfo($toBeCreated), $user, $group) === false) {
                        throw new \Exception(
                            sprintf('Can\'t switch user/group to %s/% for directory %s while starting application server', $user, $group, $toBeCreated)
                        );
                    }
                }
            }
        }

        // check if specific directories has to be cleaned up on startup
        foreach (DirectoryKeys::getServerDirectoryKeysToBeCleanedUp() as $directoryKey) {
            // prepare the path to the directory to be cleaned up
            $toBeCleanedUp = $this->realpath($directories[$directoryKey]);

            // if the directory exists, clean it up
            if (is_dir($toBeCleanedUp)) {
                $this->cleanUpDir(new \SplFileInfo($toBeCleanedUp));
            }
        }

        // check if needed files do exist and have the correct user rights
        $files = $this->getFiles();
        foreach (FileKeys::getServerFileKeysToBeCreated() as $fileKeys) {
            // prepare the path to the file to be created
            $toBeCreated = $this->realpath($files[$fileKeys]);

            // touch the file (will lead to its creation if it does not exist by now)
            if (touch($toBeCreated) === false) {
                throw new \Exception(
                    sprintf('Can\'t create necessary file %s while starting application server', $toBeCreated)
                );
            } else {
                chmod($toBeCreated, 0755);
            }

            // set user/group specified from the system configuration
            if ($this->setUserRight(new \SplFileInfo($toBeCreated), $user, $group) === false) {
                throw new \Exception(
                    sprintf('Can\'t switch user/group to %s/% for file %s while starting application server', $user, $group, $toBeCreated)
                );
            }
        }
    }
109128
protected function saveDevelopmentData()
    {
        foreach (array_keys($this->packageManager->getFrozenPackages()) as $packageKey) {
            $pathAndFilename = $this->getPrecompiledReflectionStoragePath() . $packageKey . '.dat';
            if (!file_exists($pathAndFilename)) {
                $this->log(sprintf('Rebuilding precompiled reflection data for frozen package %s.', $packageKey), LogLevel::DEBUG);
                $this->freezePackageReflection($packageKey);
            }
        }
    }
846061
public function prepareExport()
    {
        $oDB = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
        $sHeapTable = $this->_getHeapTableName();

        // #1070 Saulius 2005.11.28
        // check mySQL version
        $oRs = $oDB->select("SHOW VARIABLES LIKE 'version'");
        $sTableCharset = $this->_generateTableCharSet($oRs->fields[1]);

        // create heap table
        if (!($this->_createHeapTable($sHeapTable, $sTableCharset))) {
            // error
            \OxidEsales\Eshop\Core\Registry::getUtils()->showMessageAndExit("Could not create HEAP Table {$sHeapTable}\n<br>");
        }

        $sCatAdd = $this->_getCatAdd(\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("acat"));
        if (!$this->_insertArticles($sHeapTable, $sCatAdd)) {
            \OxidEsales\Eshop\Core\Registry::getUtils()->showMessageAndExit("Could not insert Articles in Table {$sHeapTable}\n<br>");
        }

        $this->_removeParentArticles($sHeapTable);
        $this->_setSessionParams();

        // get total cnt
        return $oDB->getOne("select count(*) from {$sHeapTable}");
    }