Deploy application

@param array $options
@return array
190649
public static function deploy($options = array()) {
		$result = array(
			'success' => false,
			'error' => array()
		);
		$options['mode'] = $options['mode'] ?? 'production';
		do {
			$temp = rtrim(getcwd(), '/');
			$deployed_dir = $temp . '/../../deployed';
			$code_dir = $temp . '/../../application';
			// for development we handle deployment differently, just symlink to the code
			$data = \System\Dependencies::processDepsAll(['mode' => 'test']);
			if ($options['mode'] == 'development') {
				\Helper\File::delete($deployed_dir);
				symlink($code_dir, $deployed_dir);
				// process components
				if (!empty($data['data']['components'])) {
					// create directories
					\Helper\File::mkdir($code_dir . '/application/Components');
					\Helper\File::mkdir($code_dir . '/application/../public_html/components');
					foreach ($data['data']['components'] as $k => $v) {
						\Helper\File::delete($code_dir . '/application/Components/' . $k . '/');
						\Helper\File::delete($code_dir . '/application/../public_html/components/' . $k . '/');
						\Helper\File::mkdir($code_dir . '/application/Components/' . $k . '/');
						\Helper\File::mkdir($code_dir . '/application/../public_html/components/' . $k . '/');
						foreach (['application', 'public_html'] as $v2) {
							$files = \Helper\File::iterate($v . $v2, ['recursive' => true]);
							foreach ($files as $v3) {
								$temp1 = explode('/' . $v2 . '/', $v3);
								if ($v2 == 'application') {
									\Helper\File::copy($code_dir . '/' . $v2 . '/' . $v3, $code_dir . '/application/Components/' . $k . '/' . $temp1[1]);
								} else {
									\Helper\File::copy($code_dir . '/' . $v2 . '/' . $v3, $code_dir . '/application/../public_html/components/' . $k . '/' . $temp1[1]);
								}
							}
						}
					}
				}
				$result['success'] = true;
				break;
			}
			// determine and create directories
			$all_deps_dir = $temp . '/../../deployments';
			$time = time();
			$dep_id = 'build.' . $time . '.' . rand(100, 999);
			$dep_dir = $all_deps_dir . '/' . $dep_id;
			$media_dir = $dep_dir . '/public_html/numbers';
			if (\Helper\File::mkdir($dep_dir, 0777) === false) {
				$result['error'][] = ' - unable to create new deployment directory ' . $dep_dir;
				break;
			}
			// copying code repository
			if (!\Helper\File::copy($code_dir, $dep_dir, ['skip_directories' => ['.numbers', '.git'], 'skip_files' => ['Makefile', 'Make.cmd', '.gitignore']])) {
				$result['error'][] = ' - unable to copy code!';
				break;
			}
			// copy components
			\Helper\File::mkdir($dep_dir . '/application/Components');
			\Helper\File::mkdir($dep_dir . '/application/../public_html/components');
			foreach ($data['data']['components'] as $k => $v) {
				\Helper\File::mkdir($code_dir . '/application/Components/' . $k . '/');
				\Helper\File::mkdir($code_dir . '/application/../public_html/components/' . $k . '/');
				foreach (['application', 'public_html'] as $v2) {
					$files = \Helper\File::iterate($v . $v2, ['recursive' => true]);
					foreach ($files as $v3) {
						$temp1 = explode('/' . $v2 . '/', $v3);
						if ($v2 == 'application') {
							\Helper\File::copy($code_dir . '/' . $v2 . '/' . $v3, $dep_dir . '/application/Components/' . $k . '/' . $temp1[1]);
						} else {
							\Helper\File::copy($code_dir . '/' . $v2 . '/' . $v3, $dep_dir . '/application/../public_html/components/' . $k . '/' . $temp1[1]);
						}
					}
				}
			}
			// js, css, scss, files here
			$files_to_copy = [];
			$process_extensions = ['js', 'css'];
			if (\Application::get('dep.submodule.numbers.frontend.media.scss')) {
				$process_extensions[] = 'scss';
			}
			$iterator = new \RecursiveIteratorIterator(
				new \RecursiveDirectoryIterator($dep_dir)
			);
			foreach ($iterator as $filename => $cur) {
				$extension = $cur->getExtension();
				if (in_array($extension, $process_extensions)) {
					$parent_dir_name = basename(dirname($filename));
					if (strpos($filename, '/controller/') !== false) {
						$key = str_replace($dep_dir, '', $filename);
						$files_to_copy[$extension][$key] = $filename;
					}
				}
			}
			// create media directory
			$media_dir_full = $media_dir . '/media_generated';
			if (!empty($files_to_copy['js']) || !empty($files_to_copy['css']) || !empty($files_to_copy['scss'])) {
				\Helper\File::mkdir($media_dir_full, 0777);
			}
			// coping javescript files
			if (!empty($files_to_copy['js'])) {
				foreach ($files_to_copy['js'] as $k => $v) {
					$newname = ltrim(str_replace('/', '_', $k), '_');
					\Helper\File::copy($v, "$media_dir_full/$newname");
				}
			}
			// coping css files
			if (!empty($files_to_copy['css'])) {
				foreach ($files_to_copy['css'] as $k => $v) {
					$newname = ltrim(str_replace('/', '_', $k), '_');
					\Helper\File::copy($v, "$media_dir_full/$newname");
				}
			}
			// coping scss files
			if (!empty($files_to_copy['scss'])) {
				foreach ($files_to_copy['scss'] as $k => $v) {
					$newname = ltrim(str_replace('/', '_', $k), '_');
					// processing scss files
					$temp = \Numbers\Frontend\Media\SCSS\Base::serve($v);
					if ($temp['success']) {
						file_put_contents("{$media_dir_full}/{$newname}.css", $temp['data']);
					}
				}
			}
			// we need to load media from dependencies
			$result = \System\Dependencies::processDepsAll(['mode' => 'test']);
			// copying js, css & scss files
			$media_dir_submodule = $dep_dir . '/public_html';
			if (!empty($result['data']['media'])) {
				\Helper\File::mkdir($media_dir_submodule . '/numbers/media_submodules', 0777);
				foreach ($result['data']['media'] as $k => $v) {
					if (!in_array($k, ['js', 'css', 'scss', 'other'])) {
						continue;
					}
					foreach ($v as $k2 => $v2) {
						if (!isset($v2['origin']) || !isset($v2['destination'])) {
							continue;
						}
						// js and css we just copy
						$copy_from = $dep_dir . '/libraries/vendor' . $v2['origin'];
						$copy_to = $media_dir_submodule . $v2['destination'];
						if ($k == 'js' || $k == 'css' || $k == 'other') {
							\Helper\File::copy($copy_from, $copy_to);
						} else if ($k == 'scss' && Application::get('dep.submodule.numbers.frontend.media.scss')) {
							// todo
							// we need to process scss
							$temp = numbers_frontend_media_scss_base::serve($copy_from);
							if ($temp['success']) {
								file_put_contents($copy_to, $temp['data']);
							}
						}
					}
				}
			}
			// setting permissions
			\Helper\File::chmod($dep_dir, 0777);
			// now we need to create a symlink
			if (file_exists($deployed_dir)) {
				\Helper\File::delete($deployed_dir);
			}
			symlink($dep_dir, $deployed_dir);
			// cleanup older deployments,older than 5 days
			$iterator = new \DirectoryIterator($all_deps_dir);
			foreach ($iterator as $filedir => $fileinfo) {
				if ($fileinfo->isDir()) {
					$filename = $fileinfo->getFilename();
					// sanity check
					if ($filename == $dep_id) continue;
					if (strpos($filename, 'build.') === 0) {
						if ($time - $fileinfo->getMTime() > 259200) {
							$temp = $fileinfo->getPathname();
							\Helper\File::delete($temp);
						}
					}
				}
			}
			$result['success'] = true;
		} while(0);
		return $result;
	}
1306681
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $options = $this->configureOptions($options);

        $workspacePath = $deployment->getWorkspacePath($application);
        $webDirectory = $application->hasOption('webDirectory') ? $application->getOption('webDirectory') : 'Web';
        $scriptBasePath = $options['scriptBasePath'] ?: Files::concatenatePaths([$workspacePath, $webDirectory]);

        if ($options['scriptIdentifier'] === null) {
            // Store the script identifier as an application option
            $scriptIdentifier = bin2hex($this->randomBytesGenerator->generate(32));
            $application->setOption(WebOpcacheResetExecuteTask::class . '[scriptIdentifier]', $scriptIdentifier);
        } else {
            $scriptIdentifier = $options['scriptIdentifier'];
        }

        $localhost = new Node('localhost');
        $localhost->onLocalhost();

        $commands = [
            'cd ' . escapeshellarg($scriptBasePath),
            'rm -f surf-opcache-reset-*',
        ];

        $this->shell->executeOrSimulate($commands, $localhost, $deployment);

        if (! $deployment->isDryRun()) {
            $scriptFilename = sprintf('%s/surf-opcache-reset-%s.php', $scriptBasePath, $scriptIdentifier);

            $result = $this->filesystem->put($scriptFilename, '<?php
                if (function_exists("opcache_reset")) {
                    opcache_reset();
                }
                @unlink(__FILE__);
                echo "success";
            ');

            if ($result === false) {
                throw TaskExecutionException::webOpcacheResetCreateScriptTaskCouldNotWritFile($scriptFilename);
            }
        }
    }
1181617
public function dump(array $options = array())
    {
        return array(
            'listeners'       => $this->raw_listeners,
            'has_application' => null !== $this->application,
            'has_container'   => null !== $this->container,
        );
    }
894169
public function save(array $options = [])
    {
        $data = $this->serialize();

        $this->security->getKuzzle()->query(
            $this->security->buildQueryArgs($this->saveActionName),
            $data,
            $options
        );

        return $this;
    }
799578
public static function createFromOptions(array $options)
    {
        Validate::notNull($options['Name'], 'options[Name]');

        $accessPolicy = new self($options['Name']);
        $accessPolicy->fromArray($options);

        return $accessPolicy;
    }
167252
protected function processOptions(array $options, Deployment $deployment)
    {
        foreach (['tagName', 'description'] as $optionName) {
            $options[$optionName] = str_replace(
                [
                    '{releaseIdentifier}',
                    '{deploymentName}'
                ],
                [
                    $deployment->getReleaseIdentifier(),
                    $deployment->getName()
                ],
                $options[$optionName]
            );
        }

        if (!isset($options['submoduleTagNamePrefix'])) {
            $options['submoduleTagNamePrefix'] = '';
        }

        if (!isset($options['remote'])) {
            $options['remote'] = 'origin';
            return $options;
        }
        return $options;
    }
365939
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        try {
            $options = $this->configureOptions($options);
        } catch (ExceptionInterface $e) {
            return;
        }

        if (empty($options['directories'])) {
            return;
        }

        $baseDirectory = $options['baseDirectory'] ?: $deployment->getApplicationReleasePath($application);

        $commands = array_map(function ($directory) {
            return sprintf('mkdir -p %s', $directory);
        }, $options['directories']);

        array_unshift($commands, sprintf('cd %s', $baseDirectory));

        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }
836426
private static function configure(Array $options) {
		$claims = [];
		foreach ($options as $key => $value) {

			// Parse Options
			switch ($key) {
				case 'admin': $claims['admin'] = $value; break;
				case 'debug': $claims['debug'] = $value; break;
				case 'expires':
				case 'notBefore':
					$code = ($key === 'notBefore') ? 'nbf' : 'exp';

					// (DateTime || int) ?
					switch(gettype($value)) {
						case 'integer':
							$claims[$code] = $value;
							break;
						case 'object':
							if ($value instanceOf \DateTime) $claims[$code] = $value->getTimestamp(); else $this->error(403);
							break;
						default:
							static::error(403);
					}
					break;

				default: static::error(403);
			}

		}
		return $claims;
	}
584015
private function getClientOptions(array $options, DeploymentConfig $deploymentConfig)
    {
        $clientOptions = [];

        if (isset($options[self::INPUT_KEY_ES_HOSTS]) || $deploymentConfig->get(self::CONFIG_PATH_ES_HOSTS)) {
            $clientOptions = [
                'servers'           => $this->readConfiguration($options, $deploymentConfig, self::INPUT_KEY_ES_HOSTS),
                'enable_https_mode' => $this->readConfiguration($options, $deploymentConfig, self::INPUT_KEY_ES_SSL),
                'http_auth_user'    => (string) $this->readConfiguration($options, $deploymentConfig, self::INPUT_KEY_ES_USER),
                'http_auth_pwd'     => (string) $this->readConfiguration($options, $deploymentConfig, self::INPUT_KEY_ES_PASS),
            ];

            $clientOptions['enable_http_auth'] = !empty($clientOptions['http_auth_user']) && !empty($clientOptions['http_auth_pwd']);
        }

        return $clientOptions;
    }
612499
public function getList(array $options = array())
    {
        $uri = $this->buildListResourceUri($this->listId);
        $response = $this->makeApiRequest($uri, $options);
        return $response->list;
    }
101738
protected function options(array $options = null)
    {
        $dataOptions = $this->options;

        if ($options)
        {
            $dataOptions = $this->merge($dataOptions, $options);
        }

        return $dataOptions;
    }
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);
        }
    }
726484
protected function deployToBranch($options) {
    $this->branchName = $this->getBranchName($options);
    $this->prepareDir();
    $this->addGitRemotes();
    $this->checkoutLocalDeployBranch();
    $this->mergeUpstreamChanges();
    $this->build();
    $this->commit();
    $this->push($this->branchName, $options);
  }
617116
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        if (empty($options['branch']) || !empty($options['tag'])) {
            return;
        }

        $quietFlag = (isset($options['verbose']) && $options['verbose']) ? '' : '-q';

        $commands = [];
        $commands[] = 'cd '.escapeshellarg($deployment->getApplicationReleasePath($application));
        $commands[] = 'if [ -d \'.git\' ] && hash git 2>/dev/null; then '.
            'git branch -f '.escapeshellarg($options['branch']).' deploy && '.
            'git checkout '.$quietFlag.' '.escapeshellarg($options['branch']).' && '.
            'git branch -D deploy; '.
            'fi;';

        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }
1248917
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $localPackagePath = $deployment->getWorkspacePath($application);
        $releasePath = $deployment->getApplicationReleasePath($application);

        $remotePath = Files::concatenatePaths([$application->getDeploymentPath(), 'cache/transfer']);
        // make sure there is a remote .cache folder
        $command = 'mkdir -p ' . $remotePath;
        $this->shell->executeOrSimulate($command, $node, $deployment);

        $username = $node->hasOption('username') ? $node->getOption('username') . '@' : '';
        $hostname = $node->getHostname();
        $noPubkeyAuthentication = $node->hasOption('password') ? ' -o PubkeyAuthentication=no' : '';
        $port = $node->hasOption('port') ? ' -p ' . escapeshellarg($node->getOption('port')) : '';
        $key = $node->hasOption('privateKeyFile') ? ' -i ' . escapeshellarg($node->getOption('privateKeyFile')) : '';
        $quietFlag = (isset($options['verbose']) && $options['verbose']) ? '' : '-q';
        $rshFlag = ($node->isLocalhost() ? '' : '--rsh="ssh' . $noPubkeyAuthentication . $port . $key . '" ');

        $rsyncExcludes = isset($options['rsyncExcludes']) ? $options['rsyncExcludes'] : ['.git'];
        $excludeFlags = $this->getExcludeFlags($rsyncExcludes);

        $rsyncFlags = (isset($options['rsyncFlags']) ? $options['rsyncFlags'] : '--recursive --times --perms --links --delete --delete-excluded') . $excludeFlags;

        $destinationArgument = ($node->isLocalhost() ? $remotePath : "{$username}{$hostname}:{$remotePath}");

        $command = "rsync {$quietFlag} --compress {$rshFlag} {$rsyncFlags} " . escapeshellarg($localPackagePath . '/.') . ' ' . escapeshellarg($destinationArgument);

        if ($node->hasOption('password')) {
            $passwordSshLoginScriptPathAndFilename = Files::concatenatePaths([dirname(dirname(dirname(__DIR__))), 'Resources', 'Private/Scripts/PasswordSshLogin.expect']);
            if (Phar::running() !== '') {
                $passwordSshLoginScriptContents = file_get_contents($passwordSshLoginScriptPathAndFilename);
                $passwordSshLoginScriptPathAndFilename = Files::concatenatePaths([$deployment->getTemporaryPath(), 'PasswordSshLogin.expect']);
                file_put_contents($passwordSshLoginScriptPathAndFilename, $passwordSshLoginScriptContents);
            }
            $command = sprintf('expect %s %s %s', escapeshellarg($passwordSshLoginScriptPathAndFilename), escapeshellarg($node->getOption('password')), $command);
        }

        $localhost = new Node('localhost');
        $localhost->onLocalhost();
        $this->shell->executeOrSimulate($command, $localhost, $deployment);

        if (isset($passwordSshLoginScriptPathAndFilename) && Phar::running() !== '') {
            unlink($passwordSshLoginScriptPathAndFilename);
        }

        $command = strtr("cp -RPp $remotePath/. $releasePath", "\t\n", '  ');
        // TODO Copy revision file (if it exists) for application to deployment path with release identifier

        $this->shell->executeOrSimulate($command, $node, $deployment);
    }
297569
public function getArray(array $options = array()): array
    {
        $content = $this->getContent();

        if (is_null($content)) {
            return (array)$content;
        }

        return json_decode($this->content, true);
    }
1062934
public static function prepareOptions(array $options) : array
    {
        if (empty($options['fields'])) {
            return [];
        }

        $result = [];
        foreach ($options['fields'] as $field => $params) {
            if (empty($params['column']) && empty($params['default'])) {
                continue;
            }

            $result['fields'][$field] = $params;
        }

        return $result;
    }