/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $list = []; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $dir = !empty($cmdParams[1]) ? $cmdParams[1] : '.'; $recursive = !empty($cmdParams[2]) ? $cmdParams[2] : false; $varName = !empty($cmdParams[3]) ? $cmdParams[3] : $connectionId . '.list'; if (empty($connectionId)) { Log::throwException('sftpList: Please specify a valid connection id'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Listing directory '); $controller->stdout($dir, Console::FG_CYAN); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); $list = $sftpHelper->nlist($dir, $recursive, true); // TODO: use SftpHelper to store the list } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $params[$varName] = $list; $controller->stdout("\n"); return $res; }
/** * @param string $id the connection id * * @return mixed */ public function getConnection($id) { if (!isset($this->connections[$id])) { Log::throwException('Invalid connection: ' . $id); } return $this->connections[$id]; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = false; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; if (empty($connectionId)) { Log::throwException('sftpDisconnect: Please specify a valid connection id'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Closing connection '); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); switch ($connParams['sftpConnectionType']) { case SftpHelper::TYPE_SFTP: $connection->disconnect(); break; case SftpHelper::TYPE_FTP: ftp_close($connection); break; default: $controller->stdout("\n"); Log::throwException('Unsupported connection type: ' . $connParams['sftpConnectionType']); break; } } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $dir = !empty($cmdParams[1]) ? $cmdParams[1] : ''; $mode = !empty($cmdParams[2]) ? $cmdParams[2] : -1; $recursive = !empty($cmdParams[3]) ? $cmdParams[3] : true; if (empty($connectionId) || empty($dir)) { Log::throwException('sftpMkdir: Please specify a valid connection id and directory'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Creating directory '); $controller->stdout($dir, Console::FG_CYAN); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); $res = $sftpHelper->mkdir($dir, $mode, $recursive); $sftpHelper->flushCache(); } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $controller->stdout("\n"); return $res; }
public static function process(Request $request, Response $response) { self::define($request); Log::debug('Predo processing'); $response->withHeader('Server', Constant::APP_NAME); $response->withHeader('Content-Type', 'application/json;charset=utf-8'); $response->withHeader('X-Request-Id', REQUEST_ID); if (!self::skip($request, $response)) { self::parseHeaderParameters($request, $response); } }
public static function process(Request $request, Response $response) { Lib\Log::debug('Log processing'); Lib\Time::stop('total'); $line = 'REQUEST{% ' . self::requestToString($request) . ' %} RESPONSE{% ' . self::responseToString($response) . ' %} TIME{% ' . Lib\Time::toString() . ' %}'; $status = $response->getStatusCode(); if ($status >= 500) { Lib\Log::error($line); } else { Lib\Log::info($line); } }
private function _get($remotePath, $destRelPathArr = []) { // Remove the first element from the $destRelPathArr since it corresponds to the destination path $destSubFoldersArr = $destRelPathArr; array_shift($destSubFoldersArr); $destRelPath = implode(DIRECTORY_SEPARATOR, $destSubFoldersArr); $localFolderName = basename($this->_destPath); $localFolderName .= !empty($destRelPath) ? DIRECTORY_SEPARATOR . $destRelPath : ''; $destPath = $this->_destPath; $destPath .= !empty($destSubFoldersArr) ? DIRECTORY_SEPARATOR . $destRelPath : ''; $this->controller->stdout("\n - {$localFolderName}\t <= {$remotePath}"); if (!$this->controller->dryRun) { if ($this->_sftpHelper->isDir($remotePath)) { if (!is_dir($this->_destPath)) { $this->controller->stdout("\n"); Log::throwException('sftpGet: remotePath is a directory, therefore destination has to be a directory too'); } $list = $this->_sftpHelper->nlist($remotePath); $remoteDirName = basename($remotePath); $newSubDir = $destPath . DIRECTORY_SEPARATOR . $remoteDirName; $destRelPathArr[] = $remoteDirName; // Creating the sub-directory before recursion to allow creation of empty directories // (excluding the first level as it corresponds to the destination path) if (count($destRelPathArr) > 1 && !is_dir($newSubDir)) { FileHelper::createDirectory($newSubDir); } foreach ($list as $item) { if ($item !== '.' && $item !== '..') { $this->_get($remotePath . '/' . $item, $destRelPathArr); } } } elseif (!empty($destSubFoldersArr) || $this->_sftpHelper->fileExists($remotePath)) { // if $destSubFoldersArr is not empty it means that we've got the list of files // from the nlist command on the remote directory; therefore we don't need to check // if the file exists $destFile = $destPath; if (is_dir($destFile)) { $destFile = $destPath . DIRECTORY_SEPARATOR . basename($remotePath); } if ($this->_overwrite || !file_exists($destFile)) { $this->_sftpHelper->get($remotePath, $destFile); } else { $this->controller->stdout(' [skipped]', Console::FG_PURPLE); } } else { $this->controller->stdout("\n"); $this->controller->warn('Not found: ' . $remotePath); } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } }
private function connect($config) { try { $dsn = "mysql:dbname={$config['database']};host={$config['host']};port={$config['port']};charset={$config['charset']}"; Log::debug('Database/Connection: connecting mysql: ' . $dsn); $pdo = new \PDO($dsn, $config['username'], $config['password'], $this->options); $pdo->exec('set names ' . $config['charset']); } catch (\PDOException $e) { trigger_error('Errors on connecting mysql(' . $dsn . ' username='******'username'] . ')', E_USER_WARNING); throw $e; } return $pdo; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $taskRunner = $this->taskRunner; $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $execCommand = !empty($cmdParams[1]) ? $cmdParams[1] : ''; $execParams = !empty($cmdParams[2]) ? $taskRunner->parseStringParams($cmdParams[2]) : ''; $execHiddenParams = !empty($cmdParams[3]) ? $cmdParams[3] : ''; // not printed out if (empty($connectionId) || empty($execCommand)) { Log::throwException('sftpExec: Please specify a valid connection id and directory'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $cmdString = trim($execCommand . ' ' . $execParams); $cmdFull = trim($execCommand . ' ' . $execParams . ' ' . $execHiddenParams); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); $execOutput = $sftpHelper->exec($cmdFull); $execResult = $sftpHelper->getExecExitStatus(); } else { $execResult = 0; $execOutput = ''; } $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(" "); if ($execResult !== 0) { $this->controller->stderr("Error running " . $cmdString . " ({$execResult})\n", Console::FG_RED); } else { $this->controller->stdout('Running shell command: '); $this->controller->stdout($execCommand . ' ', Console::FG_YELLOW); $this->controller->stdout($execParams, Console::FG_BLUE); if (!empty($execOutput)) { $this->controller->stdout("\n" . '---------------------------------------------------------------' . "\n"); $this->controller->stdout(trim($execOutput)); $this->controller->stdout("\n" . '---------------------------------------------------------------' . "\n"); } elseif ($this->controller->dryRun) { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } } $controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { // TODO: add log info $res = true; $taskRunner = $this->taskRunner; $toBeParsed = []; $fileList = !empty($cmdParams[0]) ? $cmdParams[0] : []; $this->_replaceList = !empty($cmdParams[1]) ? $cmdParams[1] : $this->_replaceList; $baseDir = !empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : ''; $options = !empty($cmdParams[3]) ? $cmdParams[3] : []; if (!empty($baseDir) && (!empty($baseDir) && !is_dir($baseDir))) { Log::throwException('replaceInFiles: baseDir has to be a directory'); } // if $fileList is specified but it is a string, we convert it to an array if (!empty($fileList) && is_string($fileList)) { $fileList = explode(',', $fileList); } foreach ($fileList as $srcPath) { $parsedPath = $taskRunner->parseStringAliases(trim($srcPath)); if (!empty($baseDir)) { $toBeParsed[$parsedPath] = $baseDir . DIRECTORY_SEPARATOR . $parsedPath; } else { $toBeParsed[] = $parsedPath; } } $this->controller->stdout("Replacing in files: "); foreach ($toBeParsed as $srcRelPath => $srcFullPath) { if (file_exists($srcFullPath)) { if (is_dir($srcFullPath)) { $files = FileHelper::findFiles($srcFullPath, $options); foreach ($files as $foundPath) { $this->_replace($foundPath); } } elseif (FileHelper::filterPath($srcFullPath, $options)) { $this->_replace($srcFullPath); } } else { $this->controller->stderr("\n{$srcFullPath} does not exists!\n", Console::FG_RED); } } $this->controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $dir = !empty($cmdParams[1]) ? $cmdParams[1] : ''; if (empty($connectionId) || empty($dir)) { Log::throwException('sftpChdir: Please specify a valid connection id and directory'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Changing directory to '); $controller->stdout($dir, Console::FG_CYAN); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); switch ($connParams['sftpConnectionType']) { case SftpHelper::TYPE_SFTP: $res = $connection->chdir($dir); break; case SftpHelper::TYPE_FTP: $res = @ftp_chdir($connection, $dir); break; default: $controller->stdout("\n"); Log::throwException('Unsupported connection type: ' . $connParams['sftpConnectionType']); break; } if (!$res) { $controller->stdout("\n"); Log::throwException('sftpChdir: error changing directory to ' . $dir, ['dir' => $dir]); } } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $res = false; $taskRunner = $this->taskRunner; $gitCmd = !empty($cmdParams[0]) ? $taskRunner->parseStringAliases($cmdParams[0]) : ''; if (empty($gitCmd)) { throw new Exception('git: Command cannot be empty'); } $this->controller->stdout('Running git ' . $gitCmd . '...'); if (!$this->controller->dryRun) { $wrapper = false; try { $wrapper = new GitWrapper(); } catch (GitException $e) { Log::throwException($e->getMessage()); } if ($wrapper) { switch ($gitCmd) { case 'clone': $repo = !empty($cmdParams[1]) ? $cmdParams[1] : ''; $destDir = !empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : ''; if (empty($repo) || empty($destDir)) { throw new Exception('git: repository and destination directory cannot be empty'); } $gitOptions = !empty($cmdParams[3]) ? $cmdParams[3] : []; $res = $wrapper->cloneRepository($repo, $destDir, $gitOptions); break; default: $this->controller->stdout("\n"); $this->controller->stderr("Command not supported: {$gitCmd}", Console::FG_RED); break; } } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); return !empty($res); }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $res = true; $taskRunner = $this->taskRunner; $filename = !empty($cmdParams[0]) ? $taskRunner->parsePath($cmdParams[0]) : ''; $format = !empty($cmdParams[1]) ? $cmdParams[1] : 'plain'; $append = !empty($cmdParams[2]) ? $cmdParams[2] : false; if (empty($filename)) { Log::throwException('Please specify the path of the file you want to save to'); } elseif (!$append && file_exists($filename)) { unlink($filename); } switch ($format) { case 'plain': $formatter = null; // use the default formatter break; case 'html': $formatter = new HtmlFormatter(); break; default: $formatter = false; $this->controller->stderr("Invalid log format: {$format}\n", Console::FG_RED); break; } $this->controller->stdout("Saving log file: \n " . $filename); if (!$this->controller->dryRun) { $logHandler = new StreamHandler($filename); if (!empty($formatter)) { $logHandler->setFormatter($formatter); } Log::$deployiiHandler->sendToHandler($logHandler); } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $permList = !empty($cmdParams[1]) ? $cmdParams[1] : []; if (empty($connectionId)) { Log::throwException('sftpChmod: Please specify a valid connection id'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); foreach ($permList as $mode => $pathList) { $mode = is_string($mode) ? octdec((int) $mode) : $mode; foreach ($pathList as $path) { // $path = $taskRunner->parsePath($path); // TODO: parse parameters $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(" Changing permissions of {$path} to "); $controller->stdout('0' . decoct($mode), Console::FG_CYAN); if (!$this->controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); $res = $sftpHelper->chmod($mode, $path, false); } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); } } if (!$this->controller->dryRun) { /** @noinspection PhpUndefinedVariableInspection */ $sftpHelper->flushCache('stat'); } return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $file = !empty($cmdParams[1]) ? $cmdParams[1] : ''; if (empty($connectionId) || empty($file)) { Log::throwException('sftpRm: Please specify a valid connection id and file'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Removing file '); $controller->stdout($file, Console::FG_CYAN); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); if ($sftpHelper->isFile($file)) { $res = $sftpHelper->delete($file, false); if (!$res) { Log::logger()->addError('sftpRm: error removing file {file}', ['file' => $file]); } } else { $controller->stdout("\n"); $controller->warn('sftpRm: ' . $file . ' is not a file'); } $sftpHelper->flushCache(); } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $controller->stdout("\n"); return $res; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $controller = $this->controller; $res = true; $connectionId = !empty($cmdParams[0]) ? $cmdParams[0] : ''; $dir = !empty($cmdParams[1]) ? $cmdParams[1] : ''; $recursive = !empty($cmdParams[2]) ? $cmdParams[2] : false; if (empty($connectionId) || empty($dir)) { Log::throwException('sftpRmdir: Please specify a valid connection id and directory'); } /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */ $connParams = $controller->getConnectionParams($connectionId); $controller->stdout(" " . $connectionId . " ", $connParams['sftpLabelColor'], Console::FG_BLACK); $controller->stdout(' Removing directory ' . ($recursive ? '(recursive) ' : '')); $controller->stdout($dir, Console::FG_CYAN); if (!$controller->dryRun) { // the getConnection method is provided by the SftpConnectReqs Behavior /** @noinspection PhpUndefinedMethodInspection */ /** @var $connection Net_SFTP|resource */ $connection = $controller->getConnection($connectionId); $sftpHelper = new SftpHelper($connectionId, $connection, $connParams); if (!$recursive) { $res = $sftpHelper->rmdir($dir); } else { $res = $sftpHelper->delete($dir, true); } if (!$res) { Log::logger()->addError('sftpRmdir: error removing directory {dir} (recursive: {recursive})', ['dir' => $dir, 'recursive' => $recursive ? 'yes' : 'no']); } $sftpHelper->flushCache(); } else { $controller->stdout(' [dry run]', Console::FG_YELLOW); } $controller->stdout("\n"); return $res; }
private function execute($execType, $statement, $inputParameters = null) { $validExecTypes = [self::EXEC_RETURN_ROW_SET, self::EXEC_RETURN_ROW_COUNT, self::EXEC_RETURN_LAST_INSERTED_ID]; if (!in_array($execType, $validExecTypes)) { throw new \RuntimeException('Model: invalid execute type \'' . $execType . '\''); } $this->reset(); if ($execType == self::EXEC_RETURN_ROW_SET) { $database = $this->database . '::read'; } else { $database = $this->database . '::write'; } $pdo = $this->manager->pdo($database); Log::debug('mysql prepare statement \'' . $statement . '\' with inputParameters: ' . json_encode($inputParameters)); Time::start('mysql'); $PDOStatement = $pdo->prepare($statement); $PDOStatement->execute($inputParameters); Time::stop('mysql'); switch ($execType) { case self::EXEC_RETURN_ROW_SET: $result = $PDOStatement->fetchAll(\PDO::FETCH_ASSOC); break; case self::EXEC_RETURN_ROW_COUNT: $result = $PDOStatement->rowCount(); break; case self::EXEC_RETURN_LAST_INSERTED_ID: $result = $pdo->lastInsertId(); break; } Log::debug('mysql result: ' . json_encode($result)); return $result; }
private function _put($srcFullPath, $srcRelPath) { $destRelPath = $this->_destDir . '/' . $srcRelPath; $this->controller->stdout("\n - " . $srcRelPath . "\t => " . $destRelPath); if (!$this->controller->dryRun) { if (is_dir($srcFullPath)) { $files = FileHelper::findFiles($srcFullPath, $this->_options); foreach ($files as $foundPath) { $relativePath = substr($foundPath, strlen($this->_srcBaseDir) + 1); $this->_sftpHelper->mkdir($destRelPath); $this->_put($foundPath, $relativePath, $this->_srcBaseDir, $this->_destDir, $this->_options); } } elseif (FileHelper::filterPath($srcFullPath, $this->_options)) { $this->_sftpHelper->mkdir(dirname($destRelPath), -1, true); if ($this->_overwrite || !$this->_sftpHelper->fileExists($destRelPath)) { $res = $this->_sftpHelper->put($destRelPath, $srcFullPath); if (!$res) { Log::logger()->addError('sftpPut: error uploading file {from} to {to}', ['from' => $srcFullPath, 'to' => $destRelPath]); } } else { $this->controller->stdout(' [skipped]', Console::FG_PURPLE); } } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $res = true; $taskRunner = $this->taskRunner; $toBeAdded = []; $srcList = !empty($cmdParams[0]) ? $cmdParams[0] : []; $destFile = !empty($cmdParams[1]) ? $taskRunner->parsePath($cmdParams[1]) : ''; $srcBaseDir = !empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : ''; $format = !empty($cmdParams[3]) ? strtolower($cmdParams[3]) : self::CMP_GZ; $options = !empty($cmdParams[4]) ? $cmdParams[4] : []; if (!empty($srcBaseDir) && !is_dir($srcBaseDir)) { Log::throwException('compress: srcBaseDir has to be a directory'); } if (empty($destFile) || file_exists($destFile) && is_dir($destFile)) { Log::throwException('compress: Destination has to be a file'); } switch ($format) { case self::CMP_NONE: $extension = '.tar'; $compression = \Phar::NONE; $doCompress = false; break; case self::CMP_GZ: $extension = '.tar.gz'; $compression = \Phar::GZ; $doCompress = true; break; case self::CMP_BZ2: $extension = '.tar.bz2'; $compression = \Phar::BZ2; $doCompress = true; break; default: $extension = ''; $compression = false; $doCompress = false; Log::throwException('compress: Invalid format specified: ' . $format); break; } // if $srcList is specified but it is a string, we convert it to an array if (!empty($srcList) && is_string($srcList)) { $srcList = explode(',', $srcList); } foreach ($srcList as $srcPath) { $parsedPath = $taskRunner->parseStringAliases(trim($srcPath)); if (!empty($srcBaseDir)) { $toBeAdded[$parsedPath] = $srcBaseDir . DIRECTORY_SEPARATOR . $parsedPath; } else { $toBeAdded[] = $parsedPath; } } $this->controller->stdout("Creating archive: "); $this->controller->stdout($destFile, Console::FG_BLUE); $archive = null; $destDir = dirname($destFile); $destBaseFile = $destDir . DIRECTORY_SEPARATOR . basename($destFile, '.tar'); if (!$this->controller->dryRun) { if (!is_dir($destDir)) { FileHelper::createDirectory($destDir); } @unlink($destFile); @unlink($destBaseFile); try { $archive = new \PharData($destFile); } catch (\Exception $e) { Log::throwException($e->getMessage()); } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); $this->controller->stdout("Adding to archive: "); foreach ($toBeAdded as $srcRelPath => $srcFullPath) { if (file_exists($srcFullPath)) { $this->controller->stdout("\n - " . $srcFullPath); if (!$this->controller->dryRun) { if (is_dir($srcFullPath)) { $files = FileHelper::findFiles($srcFullPath, $options); $archive->buildFromIterator(new ArrayIterator($files), !empty($srcBaseDir) ? $srcBaseDir : $srcFullPath); } elseif (FileHelper::filterPath($srcFullPath, $options)) { $archive->addFile($srcFullPath, !empty($srcBaseDir) ? $srcRelPath : basename($srcFullPath)); } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } } else { $this->controller->stderr("\n{$srcFullPath} does not exists!\n", Console::FG_RED); } } $this->controller->stdout("\n"); if ($doCompress) { $this->controller->stdout("Compressing archive: "); $this->controller->stdout($destBaseFile . $extension, Console::FG_CYAN); if (!$this->controller->dryRun) { @unlink($destBaseFile . $extension); try { $archive->compress($compression, $extension); } catch (\Exception $e) { Log::throwException($e->getMessage()); } @unlink($destFile); } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); } return $res; }
/** * @param string $mode * @param string $path * @param bool $recursive * * @return bool */ public function chmod($mode, $path, $recursive = false) { switch ($this->_connType) { case SftpHelper::TYPE_SFTP: default: $res = $this->_connection->chmod($mode, $path, $recursive); break; case SftpHelper::TYPE_FTP: if ($recursive) { Console::stdout("\n"); Log::throwException('Recursive not supported for chmod in ftp mode'); } $res = @ftp_chmod($this->_connection, $mode, $path); break; } return $res; }
/** * For each version that is newer of the current DeploYii home version and that requires * changes, tells the user which changes need to be performed manually and if possible * updates it automatically. * * To update a file it is possible to amend it manually or to remove it; if the file is missing * it will be replaced with the original one from the home-dist folder. * * If some manual changes are required, it is possible to simply delete the VERSION file once * the changes have been applied. * * @param string $homeVersion The DeploYii home version * * @throws \yii\console\Exception if the home folder requires to be updated manually */ public static function checkHomeVersion($homeVersion) { $changeLog = ''; $requiredActions = ''; $home = Shell::getHomeDir(); $homeDist = __DIR__ . '/../home-dist'; $changes = array_reverse(self::$_homeChangeList); foreach ($changes as $version => $list) { if (version_compare($version, $homeVersion, '>')) { // files to be manually updated by the user: if (isset($list['mod'])) { foreach ($list['mod'] as $relFilePath => $logMessage) { // If the destination file does not exists, add it from the dist folder // instead of requesting the user to manually update it: $destFile = $home . DIRECTORY_SEPARATOR . $relFilePath; if (!file_exists($destFile)) { $list['add'][$relFilePath] = $logMessage; unset($list['mod'][$relFilePath]); } else { $requiredActions .= " - [{$version}] {$relFilePath}: {$logMessage}\n"; } } } // files/directories to be added: (if no manual actions are required) if (empty($requiredActions) && isset($list['add'])) { foreach ($list['add'] as $relPath => $logMessage) { $srcPath = $homeDist . DIRECTORY_SEPARATOR . $relPath; $destPath = $home . DIRECTORY_SEPARATOR . $relPath; if (!is_dir($srcPath) && !file_exists($destPath) && file_exists($srcPath)) { $changeLog .= " - [{$version}] Adding {$relPath} ({$logMessage})\n"; copy($srcPath, $destPath); } elseif (is_dir($srcPath) && !is_dir($destPath)) { $changeLog .= " - [{$version}] Adding directory: {$relPath} ({$logMessage})\n"; FileHelper::copyDirectory($srcPath, $destPath); } elseif (is_dir($srcPath) && is_dir($destPath)) { $requiredActions .= " - [{$version}] {$relPath}: {$logMessage}\n"; } } } // files/directories to be removed: (if no manual actions are required) if (empty($requiredActions) && isset($list['rem'])) { foreach ($list['rem'] as $relPath => $logMessage) { $destPath = $home . DIRECTORY_SEPARATOR . $relPath; if (!is_dir($destPath) && file_exists($destPath)) { $changeLog .= " - [{$version}] Removing {$relPath} ({$logMessage})\n"; unlink($destPath); } elseif (is_dir($destPath)) { $requiredActions .= " - [{$version}] {$relPath}: {$logMessage}\n"; } } } } } if (!empty($requiredActions)) { Log::throwException("Your DeploYii home folder needs to be manually updated to " . DEPLOYII_VERSION . ":\n" . $requiredActions . "When done delete the VERSION file and run DeploYii again.\n"); } elseif (!empty($changeLog)) { self::updateHomeVersion(); $message = "Your DeploYii home folder has been updated to: " . DEPLOYII_VERSION . ":\n" . $changeLog; Log::logger()->addInfo($message); Console::stdout("---------------------------------------------------------------\n" . $message . "---------------------------------------------------------------\n"); sleep(2); } }
/** * @param string $path */ private function _checkDirectory($path) { $path = rtrim($path, '/\\'); if (!is_dir($path) && !file_exists($path)) { if (!$this->dryRun) { FileHelper::createDirectory($path); } } elseif (!is_dir($path) && file_exists($path)) { Log::throwException('Invalid directory: ' . $path); } }
/** * Log the error message and throw \yii\console\Exception * * @param string $message * @param array $context * * @throws \yii\console\Exception */ public static function throwException($message, array $context = []) { Log::logger()->addCritical($message, $context); throw new Exception($message); }
/** * Compare the php files of the built-in commands and recipes with the user defined ones. * If the user defined ones have the same name of the built-in ones, throws and exception. * * File names are converted to lower case so that the check is case insensitive. * * @throws \yii\console\Exception if a built-in command or recipe has been overridden */ private function _checkUserScripts() { $buildScripts = Yii::getAlias('@buildScripts'); $home = Shell::getHomeDir(); $builtInCommands = $this->getLowercaseBaseNames(glob(__DIR__ . '/commands/*.php')); $builtInRecipes = $this->getLowercaseBaseNames(glob(__DIR__ . '/recipes/*.php')); $userGlobalCommands = $this->getLowercaseBaseNames(glob($home . '/commands/*.php')); $userGlobalRecipes = $this->getLowercaseBaseNames(glob($home . '/recipes/*.php')); $userBuildCommands = $this->getLowercaseBaseNames(glob($buildScripts . '/commands/*.php')); $userBuildRecipes = $this->getLowercaseBaseNames(glob($buildScripts . '/recipes/*.php')); $userCommands = array_merge($userBuildCommands, $userGlobalCommands); $userRecipes = array_merge($userBuildRecipes, $userGlobalRecipes); $overridingCommands = array_intersect($builtInCommands, $userCommands); $overridingRecipes = array_intersect($builtInRecipes, $userRecipes); if (!empty($overridingCommands) || !empty($overridingRecipes)) { Log::throwException('You cannot override built-in commands or recipes: ' . trim(implode(", ", $overridingCommands) . ", " . implode(".", $overridingRecipes), ', ')); } $overridingUserCommands = array_intersect($userGlobalCommands, $userBuildCommands); $overridingUserRecipes = array_intersect($userGlobalRecipes, $userBuildRecipes); if (!empty($overridingUserCommands) || !empty($overridingUserRecipes)) { $this->controller->warn('You are overriding global commands or recipes: ' . trim(implode(", ", $overridingUserCommands) . ", " . implode(".", $overridingUserRecipes), ', ') . "\n"); } }
/** * Log the given string and send it to stdout * * @param string $string * @param int $level (optional) if null is passed, level will be set to Logger::DEBUG */ public function logStdout($string, $level = Logger::DEBUG) { $level = $level === null ? Logger::DEBUG : $level; Log::logger()->addRecord($level, trim($string)); $args = func_get_args(); unset($args[1]); // remove the $level parameter to be compatible with the stdout method call_user_func_array(['parent', 'stdout'], $args); }
/** * If there are some connection parameters defined specifically for the current connection id, * it will take those instead of the ones available in the build script / config. * * Example: * 'sftpAuthMethod' => 'key', * 'sftpUsername' => 'testuser', * 'conn1.sftpAuthMethod' => 'password', // "conn1" is the connection id * 'conn1.sftpPassword' => '...', * * * @param array $params The build parameters * * @return array */ private function _configureFrom($params) { $res = []; if (empty($this->_connectionId)) { Log::throwException('sftpConnect: caling ' . __METHOD__ . ' without a valid connection id set.'); } $requirements = new SftpConnectReqs(); $cmdOptions = $requirements->getCommandOptions(); foreach ($cmdOptions as $key => $value) { if (isset($params[$this->_connectionId . '.' . $key])) { $res[$key] = $params[$this->_connectionId . '.' . $key]; } else { $res[$key] = $params[$key]; } } return $res; }
/** * Dynamically pass methods to the redis * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { Log::debug('redis ' . $method . ' parameters: ' . json_encode($parameters)); $queryType = 'master'; // TODO: determines by operation if (!$this->link($queryType)) { return false; } try { Time::start('redis'); $result = call_user_func_array([$this->link, $method], $parameters); Time::stop('redis'); Log::debug('redis ' . $method . ' result: ' . $result); } catch (\Exception $e) { trigger_error('Errors on operating redis: ' . Str::exceptionToString($e), E_USER_WARNING); return false; } return $result; }