Prepares this task and the package to be installed.

@return bool True on success
761475
protected function _init()
    {
        $this->params['source'] = str_replace('"', '', $this->params['source']);

        if (function_exists('ini_set')) {
            ini_set('max_execution_time', 300);
        } elseif (function_exists('set_time_limit')) {
            set_time_limit(300);
        }

        if (is_readable($this->params['source']) && is_dir($this->params['source'])) {
            $this->_sourceType = self::TYPE_DIR;

            return $this->_getFromDirectory();
        } elseif (is_readable($this->params['source']) && !is_dir($this->params['source'])) {
            $this->_sourceType = self::TYPE_ZIP;

            return $this->_getFromFile();
        } elseif (Validation::url($this->params['source'])) {
            $this->_sourceType = self::TYPE_URL;

            return $this->_getFromUrl();
        }

        $this->err(__d('installer', 'Unable to resolve the given source ({0}).', [$this->params['source']]));

        return false;
    }
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)
                );
            }
        }
    }
665291
private function trueFreshInstall() {
    // Use user environment settings if we have them.
    if ($system_defaults = getenv('PRESSFLOW_SETTINGS')) {
      $settings = json_decode($system_defaults, TRUE);
      $admin_name = $this->projectProperties['admin_name'];
      $db_settings = $settings['databases']['default']['default'];
      $install_cmd = 'site-install --existing-config' .
        ' --db-url=mysql://' . $db_settings['username'] .
        ':' . $db_settings['password'] .
        '@' . $db_settings['host'] .
        ':' . $db_settings['port'] .
        '/' . $db_settings['database'] .
        ' -y  --account-name=' . $admin_name;
    }
    else {
      $install_cmd = 'site-install standard -y';
    }

    // Install dependencies. Only works locally.
    $this->taskComposerInstall()
      ->optimizeAutoloader()
      ->run();

    $this->_chmod($this->projectProperties['web_root'] . '/sites/default', 0755);
    if (file_exists($this->projectProperties['web_root'] . '/sites/default/settings.php')) {
      $this->_chmod($this->projectProperties['web_root'] . '/sites/default/settings.php', 0755);
    }

    $install_cmd = 'drush ' . $install_cmd;

    // Run the installation.
    $result = $this->taskExec($install_cmd)
      ->dir($this->projectProperties['web_root'])
      ->run();

    if ($result->wasSuccessful()) {
      $this->say('Install complete');
    }

    return $result;
  }
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'
        );
    }
538066
protected function _install()
    {
        $message = __d('installer', "Please provide a theme source, it can be either an URL or a filesystem path to a ZIP/directory within your server?\n[Q]uit");
        while (true) {
            $source = $this->in($message);
            if (strtoupper($source) === 'Q') {
                $this->err(__d('installer', 'Installation aborted'));
                break;
            } else {
                $this->out(__d('installer', 'Starting installation...'), 0);
                $task = $this->dispatchShell("Installer.plugins install -s \"{$source}\" --theme -a");

                if ($task === 0) {
                    $this->_io->overwrite(__d('installer', 'Starting installation... successfully installed!'), 2);
                    $this->out();
                    break;
                } else {
                    $this->_io->overwrite(__d('installer', 'Starting installation... failed!'), 2);
                    $this->out();
                }
            }
        }

        $this->out();
    }
420278
protected function setupComposerPackages()
    {
        $platform = $this->getPlatformInstance();

        if ($platform instanceof ComposerPackageInterface) {
            $platform->alterComposer($this->composer);
        }
        $this->saveComposer();

        return $this;
    }
205514
public function prepare()
    {

        $options = $this->options->prepareOptions;

        if( $options & Options::BACKUP or true ) {

            $root = $this->options->pathRoot;
            $pathsToBackup = $this->options->getPathsToBackup();

            // make a fully qualified path relative to $root
            $anchorToRoot = function( $path ) use ($root) {
                return escapeshellarg( "." . substr( $path, strlen($root) ) );
            };

            $pathsToBackup = array_map( $anchorToRoot, $pathsToBackup );
            $pathsToBackup = implode( ' ', $pathsToBackup );

            $backupDir = $this->options->getPath('backup');
            $filename = "{$backupDir}/" . self::fileSystemFriendly(
                date( DateTime::POSTGRES_TIMESTAMP_WITHOUT_TIME_ZONE_NO_MICROSECONDS )
            ) . '.tar.gz';

            $command = sprintf(
                'cd %s; tar cszf %s --exclude=%s -C %s %s; cd -',
                escapeshellarg( $root ),
                escapeshellarg( $filename ),
                $anchorToRoot( $backupDir ),
                escapeshellarg( $root ),
                $pathsToBackup
            );

            exec( $command );

        }

        // trash _all_ previously generated entitys
        /* BROKEN - Too agressive. Doesn't consider $options['match']
        $rebuild = in_array( $option, array( self::REBUILD_AND_BACKUP, self::REBUILD_NO_BACKUP ) );
        if( $rebuild ) {
            foreach( new \DirectoryIterator( $this->paths['entity'] ) as $item ) {
                if( $item->isFile() ) {
                    // unlink( $item->getPathname() );
                }
            }
        }
         */

    }
126706
protected function taskMagentoSetupDiCompile()
    {
        $magentoDir = $this->config(Config::KEY_DEPLOY . '/' . Config::KEY_APP_DIR);

        $task = $this->taskMagentoSetupDiCompileTask();
        $task->dir($magentoDir);

        return $task;
    }
17922
public function install(): OperationResult
    {
        $result = new OperationResult();

        $sourcePath = "{$this->packageInstallDir}/.installer/%s/files";
        foreach ($this->projectType->getProjectDirs() as $projectDir) {
            if (is_dir(sprintf($sourcePath, $projectDir))) {
                /** @var \RecursiveDirectoryIterator $iterator */
                $iterator = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator(
                        sprintf($sourcePath, $projectDir),
                        \RecursiveDirectoryIterator::SKIP_DOTS
                    ),
                    \RecursiveIteratorIterator::SELF_FIRST
                );

                /** @var \SplFileInfo $file */
                foreach ($iterator as $file) {
                    $target = "{$this->projectRootDir}/{$iterator->getSubPathname()}";
                    if ($file->isDir()) {
                        if (!is_dir($target)) {
                            if (!mkdir($target)) {
                                $result->addErrorMessage("<error>Could not create target directory '${target}'</error>");
                            }
                        }
                    } elseif (!file_exists($target)) {
                        assert(is_string($file->getRealPath()));
                        if (!copy($file->getRealPath(), $target)) {
                            $result->addErrorMessage("<error>Could not copy file to '${target}'</error>");
                        }
                    }
                }
            }
        }

        if (!$result->isFailure()) {
            $result->addStatusMessage("Successfully copied files from package {$this->packageName}");
        }

        return $result;
    }
1175032
private function executeInstaller()
    {
        $oInput  = $this->oInput;
        $oOutput = $this->oOutput;

        // --------------------------------------------------------------------------

        $oOutput->writeln('');
        $oOutput->writeln('<info>---------------</info>');
        $oOutput->writeln('<info>Nails Installer</info>');
        $oOutput->writeln('<info>---------------</info>');
        $oOutput->writeln('');

        // --------------------------------------------------------------------------

        //  Define app & deploy vars
        $appVars    = $this->defineAppVars();
        $deployVars = $this->defineDeployVars();

        // --------------------------------------------------------------------------

        //  Pre-Install tests
        $preTestErrors = $this->preInstallTests();

        // --------------------------------------------------------------------------

        if (empty($preTestErrors)) {

            if ($oInput->isInteractive()) {
                $oOutput->writeln('');
                $oOutput->writeln('<info>App Settings</info>');
                $this->setVars($appVars);

                // --------------------------------------------------------------------------

                $oOutput->writeln('');
                $oOutput->writeln('<info>Deploy Settings</info>');
                $this->setVars($deployVars);
            }

            // --------------------------------------------------------------------------

            //  Tell user what's about to happen
            $oOutput->writeln('');
            $oOutput->writeln('<info>I\'m about to do the following:</info>');

            //  app.php
            $oOutput->writeln('');
            $oOutput->writeln('1) Write <info>config/app.php</info>');

            foreach ($appVars as &$v) {

                if (is_string($v)) {
                    continue;
                }

                $sValue = $v['value'] ?: '<blank>';
                $oOutput->writeln(' - Set <comment>' . $v['label'] . '</comment> to <comment>' . $sValue . '</comment>');
            }

            //  deploy.php
            $oOutput->writeln('');
            $oOutput->writeln('2) Write <info>config/deploy.php</info>');

            foreach ($deployVars as &$v) {

                if (is_string($v)) {
                    continue;
                }

                $sValue = $v['value'] ?: '<blank>';
                $oOutput->writeln(' - Set <comment>' . $v['label'] . '</comment> to <comment>' . $sValue . '</comment>');
            }

            //  Migrate database and rewrite routes
            $oOutput->writeln('');
            $oOutput->writeln('3) Migrate the database');
            $oOutput->writeln('4) Rewrite app routes');

            $oOutput->writeln('');
            $question  = 'Does this look OK?';
            $doInstall = $this->confirm($question, true);

            if ($doInstall) {

                $curStep  = 1;
                $numSteps = 1;  //  app.php
                $numSteps += 1; //  deploy.php
                $numSteps += 1; //  migrate DB
                $numSteps += 1; //  rewrite routes
                $numSteps += !empty($users) ? 1 : 0;

                $oOutput->writeln('');
                $oOutput->writeln('<info>Installing...</info>');

                //  Write app.php
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Writing <info>config/app.php</info>... ');
                if ($this->writeFile($appVars, 'config/app.php')) {
                    $oOutput->writeln('<info>done!</info>');
                } else {
                    $oOutput->writeln('<error>failed!</error>');
                }
                $curStep++;

                //  Write deploy.php
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Writing <info>config/deploy.php</info>... ');
                if ($this->writeFile($deployVars, 'config/deploy.php')) {
                    $oOutput->writeln('<info>done!</info>');
                } else {
                    $oOutput->writeln('<error>failed!</error>');
                }
                $curStep++;

                /**
                 * Get the current database credential values. If an existing deploy.php is already there then
                 * we can't rely on it having the latest details (as it might have just been updated).
                 */

                $dbHost = $this->getVarValue('DEPLOY_DB_HOST', $deployVars);
                $dbUser = $this->getVarValue('DEPLOY_DB_USERNAME', $deployVars);
                $dbPass = $this->getVarValue('DEPLOY_DB_PASSWORD', $deployVars);
                $dbName = $this->getVarValue('DEPLOY_DB_DATABASE', $deployVars);

                Factory::setProperty('DB_HOST', $dbHost);
                Factory::setProperty('DB_USERNAME', $dbUser);
                Factory::setProperty('DB_PASSWORD', $dbPass);
                Factory::setProperty('DB_DATABASE', $dbName);

                //  Migrate DB
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Migrating database... ');
                $this->migrateDb($dbHost, $dbUser, $dbPass, $dbName);
                $curStep++;

                //  Rewrite routes
                $oOutput->write('<comment>[' . $curStep . '/' . $numSteps . ']</comment> Rewriting routes... ');
                $this->rewriteRoutes();

                // --------------------------------------------------------------------------

                //  Cleaning up
                $oOutput->writeln('');
                $oOutput->writeln('<comment>Cleaning up...</comment>');

                //  And we're done!
                $oOutput->writeln('');
                $oOutput->writeln('Complete!');

                return self::EXIT_CODE_SUCCESS;

            } else {
                return $this->abort();
            }

        } else {

            $exitCode = $this->abort();

            foreach ($preTestErrors as $error) {
                $oOutput->writeln(' - ' . $error);
            }

            return $exitCode;
        }
    }
782325
protected function prepareExecute()
    {
        $packageName = $this->getOption('package');

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

        $class = null;

        if ($package) {
            $class = MvcHelper::getPackageNamespace(get_class($package), 1) . '\\Seed\\DatabaseSeeder';
        }

        if (!class_exists($class)) {
            $class = $this->getOption('class');
        }

        $class = StringNormalise::toClassNamespace($class);

        if (!class_exists($class)) {
            $file = $package ? $package->getDir() . '/Seed/' . $class . '.php' : null;

            if (!$file || !is_file($file)) {
                $file = $this->getOption(
                    'd',
                    Ioc::getConfig()->get('path.seeders')
                ) . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

                if ($file[0] !== '/' && substr($file, 1, 2) !== ':\\') {
                    $file = $this->console->get('path.root') . '/' . $file;
                }
            }

            if (is_file($file)) {
                include_once $file;
            }
        }

        if (!class_exists($class)) {
            throw new \RuntimeException('Class: ' . $class . ' not exists.');
        }

        if (!is_subclass_of($class, 'Windwalker\Core\Seeder\AbstractSeeder')) {
            throw new \RuntimeException('Class: ' . $class . ' should be sub class of Windwalker\Core\Seeder\AbstractSeeder.');
        }

        // Auto include classes
        $path = dirname(ReflectionHelper::getPath($class));

        $files  = Filesystem::files($path);
        $loader = new ClassLoader();
        $loader->register();

        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            $loader->addMap($file->getBasename('.php'), $file->getPathname());
        }

        $this->console->set('seed.class', $class);
    }
1032261
public function process()
    {
        // Run the UpdatePackageInfo task
        $updateTask = Injector::inst()->create(UpdatePackageInfoTask::class);
        $updateTask->run(null);

        // mark job as completed
        $this->isComplete = true;
    }
1020093
public function run()
	{
		$this->say('Building template: ' . $this->templateName);

		// Prepare directories
		$this->prepareDirectories();

		$files = $this->copyTarget($this->source, $this->target);

		// Build media (relative path)
		$media = $this->buildMedia("media/" . $this->templateName, $this->templateName);
		$media->run();

		$this->addFiles('media', $media->getResultFiles());

		// Build language files for the component
		$language = $this->buildLanguage('tpl_' . $this->templateName);
		$language->run();

		// Update XML and script.php
		$this->createInstaller($files);

		return true;
	}
305199
private function createInstaller()
	{
		$this->say("Creating package installer");

		// Copy XML and script.php
		$sourceFolder = $this->getSourceFolder() . "/administrator/manifests/packages";
		$targetFolder = $this->getBuildFolder() . "/administrator/manifests/packages";
		$xmlFile      = $targetFolder . "/pkg_" . $this->getExtensionName() . ".xml";
		$scriptFile   = $targetFolder . "/" . $this->getExtensionName() . "/script.php";

		$this->_copy($sourceFolder . "/pkg_" . $this->getExtensionName() . ".xml", $xmlFile);

		// Version & Date Replace
		$this->taskReplaceInFile($xmlFile)
			->from(array('##DATE##', '##YEAR##', '##VERSION##'))
			->to(array($this->getDate(), date('Y'), $this->getJConfig()->version))
			->run();

		if (is_file($sourceFolder . "/" . $this->getExtensionName() . "/script.php"))
		{
			$this->_copy($sourceFolder . "/" . $this->getExtensionName() . "/script.php", $scriptFile);

			$this->taskReplaceInFile($scriptFile)
				->from(array('##DATE##', '##YEAR##', '##VERSION##'))
				->to(array($this->getDate(), date('Y'), $this->getJConfig()->version))
				->run();
		}

		// Language files
		$f = $this->generateLanguageFileList($this->getFiles('frontendLanguage'));

		$this->taskReplaceInFile($xmlFile)
			->from('##LANGUAGE_FILES##')
			->to($f)
			->run();
	}
50475
public function execute()
    {
        // if npm does not work, we cannot use grunt, so we return false
        $cmd = 'cd %s && npm install';
        if (IS_WIN) {
            $cmd = 'cd /d %s && npm install';
        }
        if (!$this->phpci->executeCommand($cmd, $this->directory)) {
            return false;
        }

        // build the grunt command
        $cmd = 'cd %s && ' . $this->grunt;
        if (IS_WIN) {
            $cmd = 'cd /d %s && ' . $this->grunt;
        }
        $cmd .= ' --no-color';
        $cmd .= ' --gruntfile %s';
        $cmd .= ' %s'; // the task that will be executed

        // and execute it
        return $this->phpci->executeCommand($cmd, $this->directory, $this->gruntfile, $this->task);
    }
1231456
private function prepareTmpDir()
    {
        $tempDir = $this->file->get(self::SETTING_DESTINATION_DIR) . DIRECTORY_SEPARATOR . uniqid('install-');

        // If the temporary folder could not be created, error out.
        // @codingStandardsIgnoreStart - we silence on purpose here as we create an exception on error.
        if (!@mkdir($tempDir, 0700)) {
        // @codingStandardsIgnoreEnd
            throw new \RuntimeException('Could not create the temporary directory');
        }

        $this->tempDir = $tempDir;
    }
1158303
public function installAll()
    {
        try {
            $response = $this->manager()->installPackages();
        } catch (\Exception $e) {
            return $this->getJsonException($e);
        }

        if ($response === 0) {
            return new Response($this->manager()->getOutput());
        }

        return $this->getJsonException(new PackageManagerException($this->manager()->getOutput(), $response));
    }