Start a pipeline

@param array $data
@param DeployForm $form
@param bool $isDryRun
@return \SS_HTTPResponse
553457
protected function beginPipeline($data, $form, $isDryRun = false) {
		$buildName = $form->getSelectedBuild($data);

		// Performs canView permission check by limiting visible projects
		$project = $this->getCurrentProject();
		if(!$project) {
			return new SS_HTTPResponse("Project '" . Convert::raw2xml($this->getRequest()->latestParam('Project')) . "' not found.", 404);
		}

		// Performs canView permission check by limiting visible projects
		$environment = $this->getCurrentEnvironment($project);
		if(!$environment) {
			return new SS_HTTPResponse("Environment '" . Convert::raw2xml($this->getRequest()->latestParam('Environment')) . "' not found.", 404);
		}

		if(!$environment->DryRunEnabled && $isDryRun) {
			return new SS_HTTPResponse("Dry-run for pipelines is not enabled for this environment", 404);
		}

		// Initiate the pipeline
		$sha = $project->DNBuildList()->byName($buildName);
		$pipeline = Pipeline::create();
		$pipeline->DryRun = $isDryRun;
		$pipeline->SkipSnapshot = !empty($data['SkipSnapshot']) && $data['SkipSnapshot'];
		$pipeline->EnvironmentID = $environment->ID;
		$pipeline->AuthorID = Member::currentUserID();
		$pipeline->SHA = $sha->FullName();
		// Record build at time of execution
		if($currentBuild = $environment->CurrentBuild()) {
			$pipeline->PreviousDeploymentID = $currentBuild->ID;
		}
		$pipeline->start(); // start() will call write(), so no need to do it here as well.
		return $this->redirect($environment->Link());
	}
666021
public function send($dry_run = false)
    {
        switch (count($this->messages)) {
            case 0:
                throw new RuntimeException("No messages to send.");
            case 1:
                return $this->sendOne($dry_run);
        }

        $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="utf-8" ?><messages></messages>');
        $xml->addAttribute('xmlns', 'http://www.unwire.com/UM/core/v1.3');
        $xml->addAttribute('xsi:schemaLocation', 'http://www.unwire.com/UM/core/v1.3 https://gw.unwire.com/service/xmlinterface/core-1.3.xsd', 'http://www.w3.org/2001/XMLSchema-instance');
        $xml->addAttribute('count', count($this->messages));
        $xml->addAttribute('service', 'mt');
        $xml->addAttribute('sessionid', (session_id() ?: time()));

        $default = $xml->addChild('defaultvalues');
        $default->addAttribute('type', 'text');

        // set default values
        foreach ($this->getDefaultValues() as $key => $value) {
            if ($key == 'content') {
                $content = $default->addChild($key);
                $content->addChild('text', $value);
            } else if ($key == 'price') {
                $price = $default->addChild('price', $value['amount']);
                $price->addAttribute('currency', $value['currency']);
                if (!is_null($value['vat'])) {
                    $price->addAttribute('vat', $value['vat']);
                }
            } else {
                if ($value) {
                    $default->addChild($key, $value);
                }
            }
        }

        $i=1;

        // add messages
        foreach ($this->messages as $message) {
            $msg = $xml->addChild('sms');
            $msg->addAttribute('id', $i);
            $msg->addAttribute('type', 'text');
            $msg->addChild('msisdn', $message->to);

            if (empty($this->defaults['content'])) {
                $content = $msg->addChild('content');
                $content->addChild('text', $message->message);
            }

            if (empty($this->defaults['operator']) && isset($message->options['smsc'])) {
                $msg->addChild('operator', $message->options['smsc']);
            }

            if (isset($message->options['shortcode'])) {
                $msg->addChild('mediacode', $message->options['shortcode']);
            } else if (empty($this->defaults['shortcode'])) {
                $msg->addChild('shortcode', $this->config['appnr']);
            }

            if (isset($message->options['mediacode'])) {
                $msg->addChild('mediacode', $message->options['mediacode']);
            } else if (empty($this->defaults['mediacode'])) {
                $msg->addChild('mediacode', $this->config['mediacode']);
            }

            if (isset($message->options['price'])) {
                preg_match('/([0-9.]+)([A-Z]{3})/', $message->options['price'], $matches);

                $price = $msg->addChild('price', $matches[1]);
                $price->addAttribute('currency', $matches[2]);
                if (!is_null($this->defaults['price']['vat'])) {
                    $price->addAttribute('vat', $this->defaults['price']['vat']);
                }
            }

            $i++;
        }

        $endpoint = str_replace('://', '://'.$this->config['user'].':'.$this->config['password'].'@', self::BATCH_ENDPOINT);

        $adapter = $this->getAdapter();
        $adapter->setEndpoint($endpoint);
        $adapter->setBody($xml->asXML());

        if ($dry_run) {
            $response = $adapter->dryRun();
        } else {
            $response = $adapter->post();
        }

        // empty query
        $this->messages = array();

        return $response;
    }
575252
protected function runStep( $step, WizardStep $model = null )
    {
        $request    = $this->getRequest();
        $isValid    = false;
        $isPost     = $request->isPost();
        $isCancel   = $isPost && $request->getPost( 'cancel' );
        $isPrevious = $isPost && $request->getPost( 'previous' );
        $isNext     = $isPost && $request->getPost( 'next' );
        $isFinish   = $isPost && $request->getPost( 'finish' );
        $jumpTo     = $request->getQuery( 'jump' );
        $values     = $this->getStepStore( $step );
        $form       = $model ? $model->getStepForm() : null;
        $redirect   = null;

        if ( ! empty( $model ) && $model->canSkip() )
        {
            $this->setStepStore( $step, array() );
            $this->pushStepStack( $step );
            $redirect = $model->getNextStep();
        }
        else if ( empty( $model ) || empty( $form ) )
        {
            $redirect = $this->startStep;
        }
        else
        {
            if ( ! empty( $values ) )
            {
                $form->setData( $values );
            }

            if ( $isPost && ( $isNext || $isFinish ) )
            {
                $form->setData( $request->getPost() );
                $isValid = $form->isValid();
            }

            if ( $isNext && $isValid && ( $redirect = $model->getNextStep() ) )
            {
                $this->setStepStore( $step, $form->getData() );
                $this->pushStepStack( $step );
            }
            else if ( $isPrevious && ( $redirect = $model->getPreviousStep() ) )
            {
                $top = $this->topStepStack();

                if ( $redirect == $top )
                {
                    $this->popStepStack();
                }
            }
            else if ( $jumpTo )
            {
                $store = $this->getStore();

                while ( ! empty( $store['stack'] ) &&
                        $jumpTo != $this->popStepStack() );

                $redirect = empty( $store['stack'] )
                    ? $this->startStep
                    : $jumpTo;
            }
            else if ( $isFinish && $isValid && $model->canFinishWizard() )
            {
                $this->setStepStore( $step, $form->getData() );
                $this->pushStepStack( $step );
                $redirect = self::STEP_FINISH;
            }
            else if ( $isCancel && $model->canCancelWizard() )
            {
                $redirect = self::STEP_CANCEL;
            }
        }

     /* if ( $redirect && $redirect != $step )
        {
            if ( ! $this->stepping( $step, $redirect ) )
            {
                $redirect = null;
            }
        } */

        return $redirect;
    }
950282
public function startJob(ExecuteJobRequest $request)
    {
        $this->worker->setState(Worker::BUSY);

        $requestId = $request->getRequestId();
        $action    = $request->getAction();
        if (!$this->worker->hasAction($action)) {
            $this->getLogger()->debug('Action '.$action.' not found.');
            $this->sendToWorkerHandler(new ActionNotFound($requestId, $action));

            return;
        }

        $this->getLogger()->debug('Sending new request ('.$requestId.') to action '.$action);
        $this->serviceStream->send($request);
    }
435710
public function createAccount(CreateAccountCommand $command, bool $isDryRun = false): CreateAccountResponse
    {
        $this->prepareTransaction($command);
        $response = $this->driver->executeTransaction($command, $isDryRun);

        return new CreateAccountResponse($response->getRawData());
    }
219726
public function run()
	{
		$this->say('Updating ' . $this->getJConfig()->extension . " to " . $this->getJConfig()->version);

		// Reusing the header config here
		$exclude = explode(",", trim($this->getJConfig()->header->exclude));

		$path      = realpath($this->getJConfig()->source);
		$fileTypes = explode(",", trim($this->getJConfig()->header->files));

		$changedFiles = 0;

		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)) as $filename)
		{
			if (substr($filename, 0, 1) == '.')
			{
				continue;
			}

			$file = new \SplFileInfo($filename);

			if (!in_array($file->getExtension(), $fileTypes))
			{
				continue;
			}

			// Skip directories in exclude list
			if (isset($exclude) && count($exclude))
			{
				$relative = str_replace(realpath($path), "", $file->getPath());

				// It is possible to have multiple exclude directories
				foreach ($exclude as $e)
				{
					if (stripos($relative, $e) !== false)
					{
						$this->say("Excluding " . $filename);
						continue 2;
					}
				}
			}

			// Load the file
			$fileContents = file_get_contents($file->getRealPath());

			if (preg_match('#__DEPLOY_VERSION__#', $fileContents))
			{
				$fileContents = preg_replace('#__DEPLOY_VERSION__#', $this->getJConfig()->version, $fileContents);

				$this->say('Updating file: ' . $file->getRealPath());

				file_put_contents($file->getRealPath(), $fileContents);

				$changedFiles++;
			}
		}

		$this->say('Updated ' . $changedFiles . ' files');

		return true;
	}
511820
public function run($run, array $arguments = [])
    {

        $lambda = new Lambda($run);

        return $this->repository->transaction(function($repo) use ($lambda, $arguments) {

            $taskTemplate = $this->newTask($lambda);

            $this->callBeforeListeners('run', [$taskTemplate, $lambda, $arguments]);

            $task = $this->repository->create($taskTemplate);

            $job = $this->createJob($task, $lambda, $arguments);

            // We can just ignore to write state because typically the job
            // is typically started in another process
            $task->setJob($job);

            $this->callAfterListeners('run', [$taskTemplate, $job]);

            return $task;

        });
    }
1270121
public function doSubmit($data, $form) {
		$controller = Controller::curr();

		$redirect = Director::baseURL() . $this->owner->URLSegment;

		if ((bool) Config::inst()->get('QuickFeedbackExtension', 'redirect_field') && isset($data['Redirect']) && Director::is_site_url($data['Redirect'])) {
			$redirect = Director::absoluteURL($data['Redirect'], true);
		}

		if (!$controller) {
			goto error;
		}

		$request = $controller->getRequest();

		if (!$request) {
			goto error;
		}

		$limit = (int) Config::inst()->get('QuickFeedbackExtension', 'rate_limit');

		$existing = Feedback::get()
			->filter('IP', $request->getIP())
			->sort('Created desc')
			->first();

		if ($existing) {
			$created = $existing->dbObject('Created');

			if (!$created) {
				goto error;
			}

			$seconds = abs(time() - strtotime($created->getValue()));
			$minutes = round($seconds / 60);

			if ($minutes <= $limit) {
				goto rate;
			}
		}

		$feedback = Feedback::create();
		$feedback->Rating = $data['Rating'];
		$feedback->Comment = $data['Comment'];
		$feedback->IP = $request->getIP();

		if (!empty($this->owner->ID)) {
			$feedback->PageID = $this->owner->ID;
		}

		if (!empty($this->owner->URLSegment)) {
			$feedback->URL = $this->owner->RelativeLink();
		}

		if ((bool) Config::inst()->get('QuickFeedbackExtension', 'redirect_field') && isset($data['Redirect'])) {
			$feedback->URL = $data['Redirect'];
		}

		$feedback->write();

		$form->sessionMessage(_t('QuickFeedback.ThanksMessage', 'Thanks for your comment!'),'good');
		return $this->owner->redirect($redirect . '?success=1#Form_QuickFeedbackForm');

		error:
			$form->sessionMessage(_t('QuickFeedback.ErrorMessage', 'An error occurred!'),'error');
			return $this->owner->redirect($redirect . '?error=1#Form_QuickFeedbackForm');

		rate:
			$form->sessionMessage(_t('QuickFeedback.RateMessage', 'Please wait a while before submitting!'),'error');
			return $this->owner->redirect($redirect . '?rate=1#Form_QuickFeedbackForm');
	}
754895
protected function printInitMessage(
        InputInterface $input,
        OutputInterface $output,
        string $path,
        array $excludes
    ) {
        $output->writeln('# PHP Formatter');

        /*
         * Dry-run message
         */
        if ($input->getOption('dry-run')) {
            $output->writeln('# <info> This process has been executed in mode dry-run');
        }

        $output->writeln('# Executing process in ' . $path);
        foreach ($excludes as $exclude) {
            $output->writeln('#     Path excluded - ' . $exclude);
        }
    }
646106
public function start()
    {
        if (!$this->process->isStarted()) {
            $this->setStarted();
            $this->dispatch(RunEvent::STARTED, new RunEvent($this));
            $this->process->start(
                function ($type, $data) {
                    $this->lastType = $type;
                    foreach (explode("\n", $data) as $line) {
                        $line = rtrim($line);
                        if (mb_strlen($line) > 0) {
                            $this->last = $line;
                            if ($this->updateOnProcessOutput) {
                                $this->dispatch(RunEvent::UPDATED, new RunEvent($this));
                            }
                        }
                    }
                }
            );
            $this->completed = false;
        }

        return $this;
    }
547887
public function run(){
        $request = Request::createFromGlobals();
        $request->getPathInfo();
        $jsonResponse = new JsonResponse;
        if($request->getMethod()=='POST'){
            $this->action = $this->sanitize($request->request->get('action'));
            $path = $this->sanitize($request->request->get('path'));
            if($this->validPath($path)==false){
                $result = array("query"=>"BE_RUN_NOT_VALID %s","params"=>array($path));
                $this->setInfo(array("msg"=>$result));
                if( $this->config['debug'] ) $this->_log(__METHOD__.' - No valido $path: '.$path);
            }else{
                if($this->action==='getfolder'){
                    $folders = $this->getAllFiles($path);
                    if(is_array($folders))
                        $this->setInfo(array( "data" => $folders ));
                }elseif($this->action==='uploadfile' ){
                    $files = $this->uploadAll($request->files->get('file'),$path);
                    if($files)
                        $this->setInfo(array( "data" => $files ));
                }elseif($this->action==='newfolder'){
                    $name = $this->sanitize($request->request->get('name'));
                    $this->newFolder($name,$path);

                }elseif($this->action==='renamefile'){
                    $nameold = $this->sanitize($request->request->get('nameold'));
                    $namenew = $this->sanitize($request->request->get('name'));
                    $this->rename($nameold,$namenew,$path);
                }elseif($this->action==='movefile'){
                    $nameold = $this->sanitize($request->request->get('nameold'));
                    $namenew = $this->sanitize($request->request->get('name'));
                    $this->move($nameold,$namenew,$path);
                }elseif($this->action==='deletefile'){
                    $name = $request->request->get('name');
                    $this->delete($name,$path);
                }else{
                    $this->setInfo(array("status"=>0));
                }
            }
        }elseif($request->getMethod()=='GET'){
            $this->action = $this->sanitize($request->query->get('action'));
            $path = $this->sanitize($request->query->get('path'));
            $name = $this->sanitize($request->query->get('name'));
            if($this->validPath($path)==false){
                $result = array("query"=>"BE_RUN_NOT_VALID %s","params"=>array($path));
                $this->setInfo(array("msg"=>$result));
                if( $this->config['debug'] ) $this->_log(__METHOD__.' - No valido $path: '.$path);
            }else{
                if($this->action==='download'){
                    $this->download($name,$path);
                }
            }
        }
        $jsonResponse->setData($this->info);
        if( $this->config['debug'] ) $this->_log(__METHOD__." - END FILEMANAGER");
        return $jsonResponse->sendContent();
    }
1151521
public function doPublish($data, $form)
    {
        /** @var Versioned|RecursivePublishable|DataObject $record */
        $record = $this->getRecord();
        $isNewRecord = $record->ID == 0;

        // Check permission
        if (!$record->canPublish()) {
            return $this->httpError(403);
        }

        // Initial save and reload
        $record = $this->saveFormIntoRecord($data, $form);
        $record->publishRecursive();

        $editURL = $this->Link('edit');
        $xmlTitle = Convert::raw2xml($record->Title);
        $link = "<a href=\"{$editURL}\">{$xmlTitle}</a>";
        $message = _t(
            __CLASS__ . '.Published',
            'Published {name} {link}',
            [
                'name' => $record->i18n_singular_name(),
                'link' => $link
            ]
        );
        $this->setFormMessage($form, $message);

        return $this->redirectAfterSave($isNewRecord);
    }
1161294
function deploy(req, res, next) {
  var dataSource = req.body;

  dataSource._id = req.params.id;

  forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next));
}
1112453
function deploy(req, res, next) {
  var options = req.connectionOptions;
  var form = req.body;
  req.user = req.user || {};

  if (req.appformsResultPayload && _.isObject(req.appformsResultPayload.data)) {
    form = req.appformsResultPayload.data;
  }

  //Expect A Data Source Data Set To Be Available If Deploying A Form.
  var params = {
    userEmail: req.user.email || req.body.updatedBy,
    expectDataSourceCache: true
  };

  options = _.extend(options, params);

  logger.debug("Middleware: Deploy form: ", {options: options});

  forms.updateOrCreateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next));
}
456361
public function run(ProcessListener $listener, array $data)
    {
        try {
            if (empty($data)) {
                throw new Exception\InvalidArgumentException('Invalid method arguments.');
            }
            $validator = null;
            $values    = null;
            if (isset($data['cid'])) {
                $model     = MemoryTests::findOrNew($data['cid']);
                $params    = unserialize($model->value);
                $validator = new $params['validator'];
                $values    = !empty($params['controls']) ? $params['controls'] : array_get($params, 'data');
            }
            if (isset($data['validator'])) {
                $validator = new $data['validator'];
                $values    = $data;
            }
            $response = $validator($values)->getResponse();
            $return   = view('antares/tester::admin.partials._messages')->with(['response' => $response]);
        } catch (\Exception $e) {
            Log::emergency($e);
            $return = view('antares/tester::admin.partials._error')->with(['message' => $e->getMessage(), 'code' => $e->getCode()]);
        }

        return $listener->render($return);
    }
1148006
protected function runDeployies(array $deployies, array $options = [])
    {
        if (count($deployies) == 0) {
            $this->note('<info>Nothing to deploy.</info>');

            return;
        }

        foreach ($deployies as $file) {
            $this->runDeploy($file);
        }
    }
280800
protected function send()
    {
        $this->logger->info(sprintf('Submitting to %s', Jobs::URL));

        try {
            $response = $this->api->send();
            $message = $response
                ? sprintf('Finish submitting. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase())
                : 'Finish dry run';

            $this->logger->info($message);

            if ($response instanceof Response) {
                $this->logResponse($response);
            }

            return true;
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            // connection error
            $message = sprintf("Connection error occurred. %s\n\n%s", $e->getMessage(), $e->getTraceAsString());
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            // 422 Unprocessable Entity
            $response = $e->getResponse();
            $message = sprintf('Client error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase());
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            // 500 Internal Server Error
            // 503 Service Unavailable
            $response = $e->getResponse();
            $message = sprintf('Server error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase());
        }

        $this->logger->error($message);

        if (isset($response)) {
            $this->logResponse($response);
        }

        return false;
    }