Run installation (or update)

@return int 0 on success or a positive error code on failure

@throws \Exception
339788
public function run()
    {
        gc_collect_cycles();
        gc_disable();

        if ($this->dryRun) {
            $this->verbose = true;
            $this->runScripts = false;
            $this->installationManager->addInstaller(new NoopInstaller);
            $this->mockLocalRepositories($this->repositoryManager);
        }

        // TODO remove this BC feature at some point
        // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
        $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
        if ($devRepo->getPackages()) {
            $this->io->writeError('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
            foreach ($devRepo->getPackages() as $package) {
                if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
                    $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
                }
            }
            unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
        }
        unset($devRepo, $package);
        // end BC

        if ($this->runScripts) {
            // dispatch pre event
            $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
            $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
        }

        $this->downloadManager->setPreferSource($this->preferSource);
        $this->downloadManager->setPreferDist($this->preferDist);

        // clone root package to have one in the installed repo that does not require anything
        // we don't want it to be uninstallable, but its requirements should not conflict
        // with the lock file for example
        $installedRootPackage = clone $this->package;
        $installedRootPackage->setRequires(array());
        $installedRootPackage->setDevRequires(array());

        // create installed repo, this contains all local packages + platform packages (php & extensions)
        $localRepo = $this->repositoryManager->getLocalRepository();
        if (!$this->update && $this->locker->isLocked()) {
            $platformOverrides = $this->locker->getPlatformOverrides();
        } else {
            $platformOverrides = $this->config->get('platform') ?: array();
        }
        $platformRepo = new PlatformRepository(array(), $platformOverrides);
        $repos = array(
            $localRepo,
            new InstalledArrayRepository(array($installedRootPackage)),
            $platformRepo,
        );
        $installedRepo = new CompositeRepository($repos);
        if ($this->additionalInstalledRepository) {
            $installedRepo->addRepository($this->additionalInstalledRepository);
        }

        $aliases = $this->getRootAliases();
        $this->aliasPlatformPackages($platformRepo, $aliases);

        try {
            $this->suggestedPackages = array();
            $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
            if ($res !== 0) {
                return $res;
            }
        } catch (\Exception $e) {
            $this->installationManager->notifyInstalls();

            throw $e;
        }
        $this->installationManager->notifyInstalls();

        // output suggestions if we're in dev mode
        if ($this->devMode) {
            foreach ($this->suggestedPackages as $suggestion) {
                $target = $suggestion['target'];
                foreach ($installedRepo->getPackages() as $package) {
                    if (in_array($target, $package->getNames())) {
                        continue 2;
                    }
                }

                $this->io->writeError($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
            }
        }

        # Find abandoned packages and warn user
        foreach ($localRepo->getPackages() as $package) {
            if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
                continue;
            }

            $replacement = (is_string($package->getReplacementPackage()))
                ? 'Use ' . $package->getReplacementPackage() . ' instead'
                : 'No replacement was suggested';

            $this->io->writeError(
                sprintf(
                    "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
                    $package->getPrettyName(),
                    $replacement
                )
            );
        }

        if (!$this->dryRun) {
            // write lock
            if ($this->update || !$this->locker->isLocked()) {
                $localRepo->reload();

                // if this is not run in dev mode and the root has dev requires, the lock must
                // contain null to prevent dev installs from a non-dev lock
                $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;

                // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
                if ($this->devMode && $this->package->getDevRequires()) {
                    $policy = $this->createPolicy();
                    $pool = $this->createPool(true);
                    $pool->addRepository($installedRepo, $aliases);

                    // creating requirements request
                    $request = $this->createRequest($this->package, $platformRepo);
                    $request->updateAll();
                    foreach ($this->package->getRequires() as $link) {
                        $request->install($link->getTarget(), $link->getConstraint());
                    }

                    $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
                    $solver = new Solver($policy, $pool, $installedRepo);
                    $ops = $solver->solve($request, $this->ignorePlatformReqs);
                    $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
                    foreach ($ops as $op) {
                        if ($op->getJobType() === 'uninstall') {
                            $devPackages[] = $op->getPackage();
                        }
                    }
                }

                $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
                $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();

                $updatedLock = $this->locker->setLockData(
                    array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
                    $devPackages,
                    $platformReqs,
                    $platformDevReqs,
                    $aliases,
                    $this->package->getMinimumStability(),
                    $this->package->getStabilityFlags(),
                    $this->preferStable || $this->package->getPreferStable(),
                    $this->preferLowest,
                    $this->config->get('platform') ?: array()
                );
                if ($updatedLock) {
                    $this->io->writeError('<info>Writing lock file</info>');
                }
            }

            if ($this->dumpAutoloader) {
                // write autoloader
                if ($this->optimizeAutoloader) {
                    $this->io->writeError('<info>Generating optimized autoload files</info>');
                } else {
                    $this->io->writeError('<info>Generating autoload files</info>');
                }

                $this->autoloadGenerator->setDevMode($this->devMode);
                $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
            }

            if ($this->runScripts) {
                // dispatch post event
                $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
                $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
            }

            $vendorDir = $this->config->get('vendor-dir');
            if (is_dir($vendorDir)) {
                touch($vendorDir);
            }
        }

        return 0;
    }
1158657
public function start(): int
    {
        $scripts = $this->installManager->install();

        $this->processRunner = new ProcessRunner($scripts->getStubService(), $this->getArguments());

        $processId =  $this->processRunner->run();
        \sleep(1); // wait for server to start

        return $processId;
    }
702327
public function run()
    {
        // from install folder
        if (! file_exists($this->parameters['previous'])) {
            $this->err('Previous tao directory "' . $this->parameters['previous'] . '" found', true);
        }
        
        $outDir = $this->parameters['output'];
        if (! file_exists($outDir)) {
            if (! mkdir($outDir)) {
                $this->err('Could not create directory "' . $outDir, true);
            }
        }
        
        $oldExts = $this->getAllExtensionManifests($this->parameters['previous']);
        $newExts = $this->getAllExtensionManifests(ROOT_PATH);
        
        foreach ($oldExts as $extId => $manifest) {
            $extDiff = new taoDevTools_models_ExtDiff($manifest, isset($newExts[$extId]) ? $newExts[$extId] : null);
            file_put_contents($outDir . DIRECTORY_SEPARATOR . 'diff' . ucfirst($extId) . '.php', $extDiff->exportDiffToPhp());
            file_put_contents($outDir . DIRECTORY_SEPARATOR . 'diff' . ucfirst($extId) . '.sql', $extDiff->exportDiffToSql());
            if (! isset($newExts[$extId])) {
                $this->out('Extension ' . $extId . ' no longer exists.');
            }
        }
    }
1244052
protected function run()
    {
        $this->silentRunActionTrigger(Action::EVENT_START);
        try {
            $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS;
            $this->context->exitCode = 0;
        } catch (ErrorException $errorException) {
            $event = Action::EVENT_ERROR;
            $this->context->exception = $errorException;
            $this->context->exitCode = 2;
        } catch (Exception $exception) {
            $event = Action::EVENT_FAILURE;
            $this->context->exception = $exception;
            $this->context->exitCode = 1;
        }
        $this->context->finishTime = time();
        $this->silentRunActionTrigger($event);
        $this->silentRunActionTrigger(Action::EVENT_FINISH);
    }
265092
public function run()
    {
        $config = $this->config;
        try {
            $this->getFluent()->getPdo()->beginTransaction();
            $this->tree->getFluent()->getPdo()->exec("LOCK TABLES $config[table] WRITE;");
            $return = $this->doRun();
            $this->getFluent()->getPdo()->commit();
            $this->tree->getFluent()->getPdo()->query("UNLOCK TABLES;");
            return $return;
        } catch (Exception $ex) {
            $this->getFluent()->getPdo()->rollBack();
            $this->tree->getFluent()->getPdo()->query("UNLOCK TABLES;");
            throw $ex;
        }
    }
160868
public function run()
	{
		$context = $this->_getContext();
		$serviceManager = MShop_Factory::createManager( $context, 'service' );

		$search = $serviceManager->createSearch();
		$start = 0;

		do
		{
			$serviceItems = $serviceManager->searchItems( $search );

			foreach( $serviceItems as $serviceItem )
			{
				try
				{
					$serviceManager->getProvider( $serviceItem )->updateAsync();
				}
				catch( Exception $e )
				{
					$msg = 'Executing updateAsyc() of "%1$s" failed: %2$s';
					$context->getLogger()->log( sprintf( $msg, $serviceItem->getProvider(), $e->getMessage() ) );
				}
			}

			$count = count( $serviceItems );
			$start += $count;
			$search->setSlice( $start );
		}
		while( $count >= $search->getSliceSize() );
	}
946353
public function run()
	{
		$this->say('Uploading ' . $this->getJConfig()->extension . $this->getJConfig()->version . " via FTP");

		// Todo Move filepath and name to config
		$this->filename = $this->getExtensionName() . "-" . $this->getJConfig()->version . ".zip";
		$this->filepath = JPATH_BASE . "/dist/" . $this->filename;

		// Check if we have a package
		if (in_array("package", explode(" ", $this->getJConfig()->target)))
		{
			$this->target   = "package";
			$this->filename = "pkg-" . $this->getExtensionName() . "-" . $this->getJConfig()->version . ".zip";
			$this->filepath = JPATH_BASE . "/dist/" . $this->filename;
		}

		try
		{
			if ($this->getJConfig()->ftp->ssl == "true")
			{
				$con = ftp_ssl_connect($this->getJConfig()->ftp->host);
			}
			else
			{
				$con = ftp_connect($this->getJConfig()->ftp->host);
			}

			$login_result = ftp_login($con, $this->getJConfig()->ftp->user, $this->getJConfig()->ftp->password);

			// Set passive ftp
			ftp_pasv($con, true);

			if (!$login_result)
			{
				return Result::error($this, 'Failed logging in');
			}

			ftp_chdir($con, $this->getJConfig()->ftp->target);

			$this->say('Uploading ' . $this->filepath);

			if (!ftp_put($con, $this->filename, $this->filepath, FTP_BINARY))
			{
				return Result::error($this, 'Failed uploading package');
			}

			$this->say("Upload finished");
		}
		catch (\Exception $e)
		{
			return Result::error($this, 'Error: ' . $e->getMessage());
		}

		return true;
	}
575076
public function execute()
    {
        $success = false;

        try {
            $file = $this->getDirectory() . DIRECTORY_SEPARATOR . $this->getFilename();
            $phar = new PHPPhar($file, 0, $this->getFilename());
            $phar->buildFromDirectory($this->getPHPCI()->buildPath, $this->getRegExp());

            $stub = $this->getStubContent();
            if ($stub) {
                $phar->setStub($stub);
            }

            $success = true;
        } catch (Exception $e) {
            $this->getPHPCI()->log(Lang::get('phar_internal_error'));
            $this->getPHPCI()->log($e->getMessage());
        }

        return $success;
    }
139083
public function run()
    {
        // Catch all errors and convert to exceptions
        set_error_handler(array('\Diarmuidie\ImageRack\Server', 'handleErrors'));

        // Catch all uncaught exceptions
        set_exception_handler(array($this, 'error'));

        // Send a not found response if the request is not valid
        if (!$this->validRequest()) {
            $this->notFound();

            return $this->response;
        }

        // First try and load the image from the cache
        $cachePath = $this->getCachePath();
        if ($this->serveFromCache($cachePath)) {
            return $this->response;
        }

        // Secondly try load the source image
        $sourcePath = $this->getSourcePath();
        if ($this->serveFromSource($sourcePath)) {
            return $this->response;
        }

        // Finally default to returning a not found response
        $this->notFound();

        return $this->response;
    }
595456
public function run($data)
    {
        $processId = $data['id'];

        $GLOBALS['log']->debug('Installation process ['.$processId.']: start run.');

        if (empty($processId)) {
            throw new Error('Installation package ID was not specified.');
        }

        $this->setProcessId($processId);

        $this->initialize();

        /** check if an archive is unzipped, if no then unzip */
        $packagePath = $this->getPackagePath();
        if (!file_exists($packagePath)) {
            $this->unzipArchive();
            $this->isAcceptable();
        }

        //check permissions copied and deleted files
        $this->checkIsWritable();

        $this->enableMaintenanceMode();

        $this->beforeRunAction();

        $this->backupExistingFiles();

        //beforeInstallFiles
        if (!$this->copyFiles('before')) {
            $this->throwErrorAndRemovePackage('Cannot copy beforeInstall files.');
        }

        /* run before install script */
        if (!isset($data['skipBeforeScript']) || !$data['skipBeforeScript']) {
            $this->runScript('before');
        }

        /* remove files defined in a manifest "deleteBeforeCopy" */
        $this->deleteFiles('deleteBeforeCopy', true);

        /* copy files from directory "Files" to EspoCRM files */
        if (!$this->copyFiles()) {
            $this->throwErrorAndRemovePackage('Cannot copy files.');
        }

        /* remove files defined in a manifest */
        $this->deleteFiles('delete', true);

        $this->deleteFiles('vendor');
        $this->copyFiles('vendor');

        $this->disableMaintenanceMode();

        if (!isset($data['skipSystemRebuild']) || !$data['skipSystemRebuild']) {
            if (!$this->systemRebuild()) {
                $this->throwErrorAndRemovePackage('Error occurred while EspoCRM rebuild.');
            }
        }

        //afterInstallFiles
        if (!$this->copyFiles('after')) {
            $this->throwErrorAndRemovePackage('Cannot copy afterInstall files.');
        }

        /* run after install script */
        if (!isset($data['skipAfterScript']) || !$data['skipAfterScript']) {
            $this->runScript('after');
        }

        $this->afterRunAction();

        $this->finalize();

        /* delete unziped files */
        $this->deletePackageFiles();

        if ($this->getManifestParam('skipBackup')) {
            $this->getFileManager()->removeInDir([$this->getPath('backupPath'), self::FILES]);
        }

        $GLOBALS['log']->debug('Installation process ['.$processId.']: end run.');

        $this->clearCache();
    }
1211173
public function run() {
		if ($this->url === null) {
			throw new \Exception("No URL configured for redirection.");
		}
		if (strpos($this->url, '/') === 0 || strpos($this->url, 'http://') === 0 || strpos($this->url, 'https://') === 0) {
			$url = ValueUtils::val($this->url);
		} else {
			$url = ROOT_URL.ValueUtils::val($this->url);
		}
		header("Location: ".$url);
	}
1297533
public function run()
    {
        foreach ($this->getCommands() as $command)
        {
            $this->transformer->transform($command);

            $this->application->add($command);
        }

        return $this->application->run();
    }
586495
public function execute()
	{
		$query  = $this->factory->builder($this->insert)->process();
		$result = $this->pdo->query($query);
		if(!$result)
		{
			throw new \Exception('An error is while the insertion occurred! (query: "' . $query . '")');
		}

		return $this->pdo->lastInsertId();
	}
1120577
protected function doExecute()
    {
        if ($this->console->getMode() !== 'dev') {
            throw new \RuntimeException(
                '<error>STOP!</error> please run <info>' . $this->getEnvCmd() . '</info>.'
            );
        }

        // backup
        if (!$this->getOption('no-backup')) {
            $this->backup();
        }

        $this->out()->out('<cmd>Rollback to 0 version...</cmd>');

        $this->executeCommand(['migration', 'migrate', '0']);

        $this->out()->out('<cmd>Migrating to latest version...</cmd>');

        $this->executeCommand(['migration', 'migrate']);

        return true;
    }
144818
public function actionInstall()
    {
        $this->stdout("Run composer dump-autoload ... ");
        $this->executeCommand('$ composer dump-autoload');
        $this->stdout("[DONE]\n");

        $scriptComponent = $this->getScript();
        if ($scripts = $scriptComponent->getScript('yii2-yiithings-install-cmd')) {
            if ( ! $this->runScripts($scripts)) {
                return 1;
            }
        }

        return 0;
    }
150835
protected function doUpdate(): int
    {
        /**
         * Run pre-UPDATE logic
         */
        $this->beforeUpdate();

        $data = $this->toArray();

        /**
         * Execute validator logic
         * Can throw ValidatorException
         */
        $this->assert($data);

        $primaryKey = $this->getPrimaryKey();

        /**
         * Compare the data to the modified fields array to discover
         * which columns have been changed.
         */
        $diffData = array_diff_assoc($data, $this->clean);

        $table = $this->getTable();

        $diffData = $table::filterColumns($diffData);

        /**
         * Execute the UPDATE (this may throw an exception)
         * Do this only if data values were changed.
         * Use the $diffData variable, so the UPDATE statement
         * includes SET terms only for data values that changed.
         */
        $result = 0;
        if (\count($diffData) > 0) {
            $result = $table::update($diffData, $primaryKey);
        }

        /**
         * Run post-UPDATE logic.  Do this before the _refresh()
         * so the _afterUpdate() function can tell the difference
         * between changed data and clean (pre-changed) data.
         */
        $this->afterUpdate();

        /**
         * Refresh the data just in case triggers in the RDBMS changed
         * any columns.  Also this resets the "clean".
         */
        $this->clean = $this->toArray();

        return $result;
    }
1025030
public function run() {
		try {
			$vulnerabilities = $this->checker->check_site( $this->options->ignored_packages );

			do_action( 'soter_site_check_complete', $vulnerabilities );

			$this->options->get_store()->set( 'last_scan_hash', $vulnerabilities->hash() );
		} catch ( \RuntimeException $e ) {
			// Gross?
			$options = _soter_instance( 'options_manager' );
			$use_html = 'html' === $options->email_type;

			wp_mail(
				// @todo Should this go straight to admin email instead?
				$options->email_address,
				'HTTP error while checking ' . get_bloginfo( 'name' ) . ' for vulnerabilities',
				$use_html
					? $this->render_html_error_email( $e )
					: $this->render_text_error_email( $e ),
				$use_html ? [ 'Content-type: text/html' ] : []
			);
		}
	}