/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $this->destinationPath = $input->getArgument('destination'); $this->version = $input->getArgument('version'); if (file_exists($this->destinationPath)) { throw new \InvalidArgumentException(sprintf('The directory %s already exists', $this->destinationPath)); } $this->filesystem = new Filesystem(); $io->writeln(PHP_EOL . ' Downloading Majora Standard Edition...' . PHP_EOL); $this->download($output); $io->writeln(PHP_EOL . PHP_EOL . ' Preparing project...' . PHP_EOL); $io->note('Extracting...'); $this->extract(); $io->note('Installing dependencies (this operation may take a while)...'); $outputCallback = null; if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { $outputCallback = function ($type, $buffer) use($output) { $output->write($buffer); }; } $this->installComposerDependencies($outputCallback); $io->note('Cleaning...'); $this->clean(); $io->success([sprintf('Majora Standard Edition %s was successfully installed', $this->version)]); }
protected function execute(InputInterface $input, OutputInterface $output) { $receipts = Yaml::parse(file_get_contents($input->getArgument('tasks-file'))); $io = new SymfonyStyle($input, $output); foreach ($receipts['instances'] as $key => $instance) { $fs = new Filesystem(); $tmpTime = sys_get_temp_dir() . "/backup_" . time(); if ($fs->exists($tmpTime)) { $fs->remove($tmpTime); } $fs->mkdir($tmpTime); $this->tmpTime = $tmpTime; $io->note("Save : " . $key); /** * Save the database if is defined */ $this->backupDatabase($io, $key, $instance); /** * Save the directories and compress if is defined */ $this->backupDirectories($io, $key, $instance); $fileCompressedPath = $this->compress($io, $key, $instance); $hashFile = $this->generateHashFile($fileCompressedPath); $filesForCloud = [$fileCompressedPath, $hashFile]; if (!array_key_exists('storages', $instance['processor'])) { throw new \RuntimeException("You storages is not defined"); } $cloudStorage = new CloudStorage($io, $instance['processor']['storages'], $instance['cloud_storages'], $key, $filesForCloud); $cloudStorage->execute(); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->title('Check Pre-commit requirements'); $hasError = false; $resultOkVal = '<fg=green>✔</>'; $resultNokVal = '<fg=red>✘</>'; $commands = ['Composer' => array('command' => 'composer', 'result' => $resultOkVal), 'xmllint' => array('command' => 'xmllint', 'result' => $resultOkVal), 'jsonlint' => array('command' => 'jsonlint', 'result' => $resultOkVal), 'eslint' => array('command' => 'eslint', 'result' => $resultOkVal), 'sass-convert' => array('command' => 'sass-convert', 'result' => $resultOkVal), 'scss-lint' => array('command' => 'scss-lint', 'result' => $resultOkVal), 'phpcpd' => array('command' => 'phpcpd', 'result' => $resultOkVal), 'php-cs-fixer' => array('command' => 'php-cs-fixer', 'result' => $resultOkVal), 'phpmd' => array('command' => 'phpmd', 'result' => $resultOkVal), 'phpcs' => array('command' => 'phpcs', 'result' => $resultOkVal), 'box' => array('command' => 'box', 'result' => $resultOkVal)]; foreach ($commands as $label => $command) { if (!$this->checkCommand($label, $command['command'])) { $commands[$label]['result'] = $resultNokVal; $hasError = true; } } // Check Php conf param phar.readonly if (!ini_get('phar.readonly')) { $commands['phar.readonly'] = array('result' => $resultOkVal); } else { $commands['phar.readonly'] = array('result' => 'not OK (set "phar.readonly = Off" on your php.ini)'); } $headers = ['Command', 'check']; $rows = []; foreach ($commands as $label => $cmd) { $rows[] = [$label, $cmd['result']]; } $io->table($headers, $rows); if (!$hasError) { $io->success('All Requirements are OK'); } else { $io->note('Please fix all requirements'); } exit(0); }
/** * @return Changelog */ protected function updateChangelog() { // If the release already exists and we don't want to overwrite it, cancel $question = 'Version <comment>' . $this->version . '</comment> already exists, create anyway?'; if ($this->changelog->hasRelease($this->version) && !$this->output->confirm($question, false)) { return false; } // Summarize commits $this->summarizeCommits(); // Gather changes for new version $this->output->section('Gathering changes for <comment>' . $this->version . '</comment>'); $changes = $this->gatherChanges(); if (!$changes) { $this->output->error('No changes to create version with'); return false; } if ($this->from) { $from = $this->changelog->getRelease($this->from); $this->changelog->removeRelease($this->from); $changes = array_merge_recursive($from['changes'], $changes); } // Add to changelog $this->changelog->addRelease(['name' => $this->version, 'date' => date('Y-m-d'), 'changes' => $changes]); // Show to user and confirm $preview = $this->changelog->toMarkdown(); $this->output->note($preview); if (!$this->output->confirm('This is your new CHANGELOG.md, all good?')) { return false; } // Write out to CHANGELOG.md $this->changelog->save(); return $this->changelog; }
/** * @{inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->application = $this->getApplication()->getApplication(); $this->fixtureLoader = $this->getContainer()->get('demo.website_loader'); $this->dataRepository = $this->getBundle()->getBaseDirectory() . DIRECTORY_SEPARATOR . 'Data' . DIRECTORY_SEPARATOR; $output = new SymfonyStyle($input, $output); $output->title('BackBee Demonstration Website Importer'); $output->progressStart(3); $lines = $this->loadFixtures(); $output->progressAdvance(); $output->note('✓ Updated BackBee Application'); $website = $this->updateWebsite(); $output->progressAdvance(); $output->note(sprintf('✓ Updated Domain to ``%s`` with label ``%s``', $website['domain'], $website['label'])); $this->importAssets(); $output->progressAdvance(); $output->note('✓ Imported pictures assets'); $output->newline(); $output->success('Website loaded with success.'); }
protected function execute(InputInterface $input, OutputInterface $output) { $output = new SymfonyStyle($input, $output); $queue = $this->queueFactory->createQueue($input->getArgument('queue')); if ($input->isInteractive()) { if (!$output->confirm(sprintf(static::CONFIRM_MSG, $queue->getName()), false)) { return; } } $count = $this->queueRegistry->deregister($queue); $output->success('Deleted queue "' . $queue->getName() . '"'); if ($count) { $output->note('Removed ' . $count . ' jobs.'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->io = new SymfonyStyle($input, $output); $this->io->block('Running server...'); $verbosity = $this->io->getVerbosity(); switch ($verbosity) { case 16: $verbosity = 'quiet'; break; case 32: $verbosity = 'normal'; break; case 64: $verbosity = 'verbose'; break; case 128: $verbosity = 'very_verbose'; break; case 256: $verbosity = 'debug'; break; } $this->io->note('Verbosity is "' . $verbosity . '". To set verbosity, add "-v", "-vv" or "-vvv" end the end of this command.'); $this->socketPort = $this->getContainer()->getParameter('socket_port'); $em = $this->getContainer()->get('doctrine.orm.default_entity_manager'); $logger = $this->getContainer()->get('logger'); $socketUrl = $this->getContainer()->getParameter('socket_server_url'); $webUrl = $this->getContainer()->getParameter('web_server_url'); $webHooks = $em->getRepository('AppBundle:WebHook')->findAll(); $logger->info(count($webHooks) . ' webHook(s)'); $server = new Server($em, $webHooks, $webUrl, $socketUrl, $logger); $this->killExistingSocketServer(); $ioServer = IoServer::factory(new HttpServer(new WsServer($server)), $this->socketPort); $logger->info('Run socket server on port ' . $this->socketPort . '...'); $ioServer->run(); }
/** * @param InputInterface $input * @param OutputInterface|Output $output * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->getLogger()->debug('Start', ['command_name' => $this->getName(), 'args' => $input->getArguments(), 'opts' => $input->getOptions()]); $optionDryRun = $input->getOption('dry-run'); $repositories = $this->getRepositoryModelList(); $projectModel = $repositories->getProjectModel(); $xmlFilename = implode(DIRECTORY_SEPARATOR, [$projectModel->getAbsolutePath(), '.idea', 'vcs.xml']); $fileSystem = new Filesystem(); if (!$fileSystem->exists($xmlFilename)) { $this->getSymfonyStyle()->error(sprintf('Config file "%s" not found', $xmlFilename)); } $existsMap = []; $simpleXml = simplexml_load_file($xmlFilename); foreach ($simpleXml->component->children() as $child) { /** @var \SimpleXMLElement $child */ $existsMap[] = (string) $child->attributes()['directory']; } $vendors = []; foreach ($this->getRepositoryModelList()->getAll() as $model) { $tmp = '$PROJECT_DIR$'; if ($model->getPath()) { $tmp .= DIRECTORY_SEPARATOR . $model->getPath(); } $vendors[] = $tmp; } $symfonyStyle = new SymfonyStyle($input, $output); $newDirs = array_diff($vendors, $existsMap); if (count($newDirs)) { $question = sprintf('Script will add %d new dirs, would you like to continue?', count($newDirs)); if ($symfonyStyle->confirm($question, true)) { foreach ($newDirs as $dir) { $mapping = $simpleXml->component->addChild('mapping', ''); $mapping->addAttribute('directory', $dir); $mapping->addAttribute('vcs', 'Git'); } $dom = dom_import_simplexml($simpleXml)->ownerDocument; $dom->preserveWhiteSpace = false; $dom->formatOutput = true; if (!$optionDryRun) { $fileSystem->dumpFile($xmlFilename, $dom->saveXML()); } $symfonyStyle->success(sprintf('File "%s" updated', $xmlFilename)); } } else { $symfonyStyle->note('Changes not found'); } $this->getLogger()->debug('Finish', ['command_name' => $this->getName()]); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $git = new GitVersionControl(); $stagedFiles = $git->getStagedFiles(); $projectBase = $git->getProjectBase(); $reporter = new Reporter($output, count($stagedFiles)); $review = new StaticReview($reporter); $review->addReview(new ComposerLockReview())->addReview(new ComposerLintReview())->addReview(new PhpLintReview())->addReview(new PhpStopWordsReview())->addReview(new JsStopWordsReview())->addReview(new EsLintReview(self::AUTO_ADD_GIT))->addReview(new YmlLintReview())->addReview(new JsonLintReview())->addReview(new XmlLintReview())->addReview(new GitConflictReview()); // -------------------------------------------------------- // Front Dev profile // -------------------------------------------------------- /*$review->addReview(new ScssLintReview()) ->addReview(new SassConvertFixerReview(self::AUTO_ADD_GIT));*/ // -------------------------------------------------------- // Dev PHP profile // -------------------------------------------------------- $phpCodeSniffer = new PhpCodeSnifferReview(); $phpCodeSniffer->setOption('standard', 'Pear'); $phpCodeSniffer->setOption('sniffs', 'PEAR.Commenting.FunctionComment'); $review->addReview(new PhpCPDReview())->addReview(new PhpMDReview())->addReview($phpCodeSniffer); // -------------------------------------------------------- $review->files($stagedFiles); $reporter->displayReport(); $testingReporter = new Reporter($output, 0); // -------------------------------------------------------- // Dev PHP profile // -------------------------------------------------------- if (!$reporter->hasIssueLevel(Issue::LEVEL_ERROR) && count($stagedFiles) > 0) { $testingReview = new TestingReview($testingReporter); if ($input->getOption('phpunit')) { $testingReview->addReview(new PhpUnitReview($input->getOption('phpunit-bin-path'), $input->getOption('phpunit-conf'), $projectBase)); } $testingReview->review(); $testingReporter->displayReport(); } // -------------------------------------------------------- if ($reporter->hasIssueLevel(Issue::LEVEL_ERROR) || $testingReporter->hasIssueLevel(Issue::LEVEL_ERROR)) { $io->error('✘ Please fix the errors above or use --no-verify.'); exit(1); } elseif ($reporter->hasIssueLevel(Issue::LEVEL_WARNING) || $testingReporter->hasIssueLevel(Issue::LEVEL_WARNING)) { $io->note('Try to fix warnings !'); } else { $io->success('✔ Looking good.'); } exit(0); }
/** * Lock the TYPO3 Backend * * @param SymfonyStyle $io * @param InputInterface $input */ protected function lock(SymfonyStyle $io, InputInterface $input) { $lockFile = $this->getLockFileName(); if (@is_file($lockFile)) { $io->note('A lock file already exists. Overwriting it.'); } $output = 'Wrote lock file to "' . $lockFile . '"'; if ($input->getArgument('redirect')) { $lockFileContent = $input->getArgument('redirect'); $output .= LF . 'with content "' . $lockFileContent . '".'; } else { $lockFileContent = ''; $output .= '.'; } GeneralUtility::writeFile($lockFile, $lockFileContent); $io->success($output); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->title('Pre-commit install'); $git = new GitVersionControl(); $projectBase = $git->getProjectBase(); $phpunit = $io->confirm('Enable PhpUnit ?', true); $source = realpath($projectBase); $hookDir = $source . '/.git/hooks'; $defaultPhpUnitConfFile = $source . '/' . self::PHPUNIT_DEFAULT_CONF_FILENAME; $precommitCommand = sprintf('precommit check%s', $phpunit ? ' --phpunit true' : ''); if ($phpunit) { $phpunitPath = $io->ask('Specify Phpunit bin path [example: vendor/bin/phpunit] ? : ', 'phpunit'); $phpunitConfFile = $io->ask('Specify Phpunit config file path ? : ', $defaultPhpUnitConfFile); if ($phpunitPath != '') { if (strpos($phpunitPath, '/') !== false) { $phpunitPath = $source . '/' . $phpunitPath; if (!is_file($phpunitPath)) { $io->error(sprintf('No phpunit bin found "%s"', $phpunitPath)); exit(1); } } } if (!is_file($phpunitConfFile)) { $io->error(sprintf('No phpunit conf file found "%s"', $phpunitConfFile)); exit(1); } $precommitCommand .= $phpunitPath != 'phpunit' ? ' --phpunit-bin-path ' . $phpunitPath : ''; $precommitCommand .= $phpunitConfFile != $defaultPhpUnitConfFile ? ' --phpunit-conf ' . $phpunitConfFile : ''; } if (!is_dir($hookDir)) { $io->error(sprintf('The git hook directory does not exist (%s)', $hookDir)); exit(1); } $target = $hookDir . '/pre-commit'; $fs = new Filesystem(); if (!is_file($target)) { $fileContent = sprintf("#!/bin/sh\n%s", $precommitCommand); $fs->dumpFile($target, $fileContent); chmod($target, 0755); $io->success('pre-commit file correctly updated'); } else { $io->note(sprintf('A pre-commit file is already exist. Please add "%s" at the end !', $precommitCommand)); } exit(0); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->title('Pre-commit workspace check'); $this->workspacePath = $input->getArgument('path'); if ($this->workspacePath == '') { $helper = $this->getHelperSet()->get('question'); $question = new Question('Specify your full workspace directory path please : ', ''); $this->workspacePath = $helper->ask($input, $output, $question); } $this->workspacePath .= substr($this->workspacePath, -1) != '/' ? '/' : ''; if (!is_dir($this->workspacePath)) { $io->error(sprintf('The workspace directory does not exist (%s)', $this->workspacePath)); exit(1); } $output->write('Analyse en cours ... '); $finder = new Finder(); $finder = $finder->directories()->ignoreUnreadableDirs()->ignoreDotFiles(false)->ignoreVCS(false)->in($this->workspacePath); $finder = $finder->notpath('/\\/vendor\\//')->notpath('/\\/log[s]?\\//')->notpath('/\\/cache\\//')->path('/.git\\/config/'); $projects = array(); $files = $finder->files(); if (count($files) > 0) { $progress = new ProgressBar($output, count($files)); $progress->setFormat('normal'); $progress->start(); foreach ($finder->files() as $file) { $precommitStatus = $this->getPrecommitStatus($file); $projectInfoPath = explode('/', str_replace('/.git', '', $file->getPathInfo()->getPathname())); $projects[] = array('name' => end($projectInfoPath), 'path' => str_replace('/.git', '', $this->workspacePath . $file->getRelativePath()), 'precommit' => $precommitStatus); $progress->advance(); } $progress->finish(); $output->writeln(''); $output->writeln(''); } if (count($projects) > 0) { $this->displayProjects($projects, $output); } else { $io->note('No GIT repositories found'); } exit(0); }
/** * Displays a security report as plain text. * * @param OutputInterface $output * @param string $lockFilePath The file path to the checked lock file * @param array $vulnerabilities An array of vulnerabilities */ public function displayResults(OutputInterface $output, $lockFilePath, array $vulnerabilities) { $output = new SymfonyStyle(new ArrayInput(array()), $output); $output->title('Symfony Security Check Report'); $output->comment(sprintf('Checked file: <comment>%s</>', realpath($lockFilePath))); if ($count = count($vulnerabilities)) { $output->error(sprintf('%d packages have known vulnerabilities.', $count)); } else { $output->success('No packages have known vulnerabilities.'); } if (0 !== $count) { foreach ($vulnerabilities as $dependency => $issues) { $output->section(sprintf('%s (%s)', $dependency, $issues['version'])); $details = array_map(function ($value) { return sprintf("<info>%s</>: %s\n %s", $value['cve'] ?: '(no CVE ID)', $value['title'], $value['link']); }, $issues['advisories']); $output->listing($details); } } $output->note('This checker can only detect vulnerabilities that are referenced in the SensioLabs security advisories database. Execute this command regularly to check the newly discovered vulnerabilities.'); }
private function createServerManagers() { /** @var Discord $discord */ /* @var ObjectManager $manager */ $discord = $this->getContainer()->get('discord'); $manager = $this->getContainer()->get('default_manager'); $repo = $manager->getRepository($this->getContainer()->getParameter('server_class')); /** @var Collection $servers */ $servers = $discord->guilds; $ids = []; foreach ($discord->guilds as $guild) { $ids[] = $guild->id; } $dbServers = $repo->findBy(['identifier' => $ids]); $this->output->text('Creating server managers for ' . $servers->count() . ' servers.'); $this->output->progressStart($servers->count()); /** @var ServerManagerFactory $factory */ $factory = $this->getContainer()->get('factory.server_manager'); foreach ($discord->guilds as $server) { $dbServer = $this->findDbServer($dbServers, $server); try { $this->serverManagers[] = $factory->create($server, $dbServer); } catch (\Exception $e) { $this->output->progressFinish(); $this->logError($e->getMessage()); exit(0); } $this->output->progressAdvance(); } $this->output->progressFinish(); $delay = $this->getContainer()->getParameter('database_save_delay'); if ($delay !== false) { $this->getContainer()->get('default_manager')->flush(); $discord->loop->addPeriodicTimer($delay, function () { $this->output->note('Saving current UoW to database.'); $this->getContainer()->get('default_manager')->flush(); }); } }
protected function prepareReportOperationJobs() { /** @var SchedulerReportOperation[] $scheduledReports */ $scheduledReports = $this->em->getRepository('CampaignChainCoreBundle:SchedulerReportOperation')->getScheduledReportJobsForSchedulerCommand($this->scheduler->getPeriodStart(), $this->scheduler->getPeriodEnd()); if (empty($scheduledReports)) { $this->io->text('No scheduled Operation reports.'); $this->logger->info('No scheduled Operation reports.'); return; } // Queue the scheduled reports. $this->io->text('Processing scheduled Operation reports.'); $this->logger->info('Processing scheduled Operation reports.'); foreach ($scheduledReports as $scheduledReport) { $txt = 'Report ID: ' . $scheduledReport->getId(); $this->io->section($txt); $this->logger->info($txt); // Check whether the Action's end date has been modified // since we last ran this report job. $endDateChanged = false; if ($scheduledReport->getEndAction() != $scheduledReport->getEndDate()) { /* * This flag will ensure that the report job will be * executed so that it can handle the end date change. */ $endDateChanged = true; // Update end date of report scheduler entry to Action's end date. $newEndDate = clone $scheduledReport->getEndAction(); $scheduledReport->setEndDate($newEndDate); $txt = "Action's end date changed to " . $newEndDate->format(\DateTime::ISO8601); $this->io->note($txt); $this->logger->info($txt); } // Check whether we're past the prolonged end date if defined. if ($scheduledReport->getProlongation() != null) { $this->io->text('Prolongation: ' . $scheduledReport->getProlongation()); $interval = \DateInterval::createFromDateString($scheduledReport->getProlongation()); $prolongedEndDate = clone $scheduledReport->getEndDate(); $prolongedEndDate->add($interval); // Prolonged end date is older than now. if ($prolongedEndDate < $this->now) { if (!$endDateChanged) { $txt = 'Past prolongation period. Skipping this report job.'; $this->io->text($txt); $this->logger->info($txt); // Don't execute this report job. continue; } else { $txt = "Past prolongation period and end date changed. We'll let the report job handle this."; $this->io->text($txt); $this->logger->info($txt); } } // No prolongation, so check if end date is older than next run. } elseif ($scheduledReport->getEndDate() < $scheduledReport->getNextRun()) { if (!$endDateChanged) { $txt = 'No prolongation and past end date. Skipping this report job.'; $this->io->text($txt); $this->logger->info($txt); continue; } else { $txt = "No prolongation and past end date, but end date changed. We'll let the report job handle this."; $this->io->text($txt); $this->logger->info($txt); } } $this->queueReportJob($scheduledReport); /* * Update next run. */ // Are we within the regular scheduled period? if ($scheduledReport->getEndDate() > $this->now && $scheduledReport->getInterval() != null) { $interval = \DateInterval::createFromDateString($scheduledReport->getInterval()); $nextRun = clone $scheduledReport->getNextRun(); $scheduledReport->setNextRun($nextRun->add($interval)); $txt = 'Regular period. Next run is in ' . $scheduledReport->getInterval(); $this->io->text($txt); $this->logger->info($txt); // ... or are we within the prolonged period? } elseif (isset($prolongedEndDate) && $prolongedEndDate > $this->now && $scheduledReport->getProlongationInterval() != null) { $interval = \DateInterval::createFromDateString($scheduledReport->getProlongationInterval()); /* * The prolongation interval starts with the end date. * Hence, if this is the first interval within the * prolonged period, then we add the interval on top of * the end date. If not, then on top of the next run date. */ if ($scheduledReport->getNextRun() < $scheduledReport->getEndDate()) { $nextRun = clone $scheduledReport->getEndDate(); } else { $nextRun = clone $scheduledReport->getNextRun(); } $scheduledReport->setNextRun($nextRun->add($interval)); $txt = 'Prolonged period. Next run is in ' . $scheduledReport->getProlongationInterval(); $this->io->text($txt); $this->logger->info($txt); } $this->em->persist($scheduledReport); } //update the next run dates for the scheduler $this->em->flush(); }
<?php use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; //Ensure has single blank line between blocks return function (InputInterface $input, OutputInterface $output) { $output = new SymfonyStyle($input, $output); $output->warning('Warning'); $output->caution('Caution'); $output->error('Error'); $output->success('Success'); $output->note('Note'); $output->block('Custom block', 'CUSTOM', 'fg=white;bg=green', 'X ', true); };
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $input->isInteractive() ? $io->title('Symfony Password Encoder Utility') : $io->newLine(); $password = $input->getArgument('password'); $userClass = $input->getArgument('user-class'); $emptySalt = $input->getOption('empty-salt'); $encoder = $this->getContainer()->get('security.encoder_factory')->getEncoder($userClass); $bcryptWithoutEmptySalt = !$emptySalt && $encoder instanceof BCryptPasswordEncoder; if ($bcryptWithoutEmptySalt) { $emptySalt = true; } if (!$password) { if (!$input->isInteractive()) { $io->error('The password must not be empty.'); return 1; } $passwordQuestion = $this->createPasswordQuestion(); $password = $io->askQuestion($passwordQuestion); } $salt = null; if ($input->isInteractive() && !$emptySalt) { $emptySalt = true; $io->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. ' . PHP_EOL . 'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.'); if ($io->confirm('Confirm salt generation ?')) { $salt = $this->generateSalt(); $emptySalt = false; } } elseif (!$emptySalt) { $salt = $this->generateSalt(); } $encodedPassword = $encoder->encodePassword($password, $salt); $rows = array(array('Encoder used', get_class($encoder)), array('Encoded password', $encodedPassword)); if (!$emptySalt) { $rows[] = array('Generated salt', $salt); } $io->table(array('Key', 'Value'), $rows); if (!$emptySalt) { $io->note(sprintf('Make sure that your salt storage field fits the salt length: %s chars', strlen($salt))); } elseif ($bcryptWithoutEmptySalt) { $io->note('Bcrypt encoder used: the encoder generated its own built-in salt.'); } $io->success('Password encoding succeeded'); }
/** * Normal but significant events. * * @param string $message * @param array $context * @return null */ public function notice($message, array $context = array()) { $this->outputStyle->note($message); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $targetArg = rtrim($input->getArgument('target'), '/'); if (!is_dir($targetArg)) { throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target'))); } $this->filesystem = $this->getContainer()->get('filesystem'); // Create the bundles directory otherwise symlink will fail. $bundlesDir = $targetArg . '/bundles/'; $this->filesystem->mkdir($bundlesDir, 0777); $io = new SymfonyStyle($input, $output); $io->newLine(); if ($input->getOption('relative')) { $expectedMethod = self::METHOD_RELATIVE_SYMLINK; $io->text('Trying to install assets as <info>relative symbolic links</info>.'); } elseif ($input->getOption('symlink')) { $expectedMethod = self::METHOD_ABSOLUTE_SYMLINK; $io->text('Trying to install assets as <info>absolute symbolic links</info>.'); } else { $expectedMethod = self::METHOD_COPY; $io->text('Installing assets as <info>hard copies</info>.'); } $io->newLine(); $rows = array(); $copyUsed = false; $exitCode = 0; /** @var BundleInterface $bundle */ foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) { if (!is_dir($originDir = $bundle->getPath() . '/Resources/public')) { continue; } $targetDir = $bundlesDir . preg_replace('/bundle$/', '', strtolower($bundle->getName())); if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $message = sprintf("%s\n-> %s", $bundle->getName(), $targetDir); } else { $message = $bundle->getName(); } try { $this->filesystem->remove($targetDir); if (self::METHOD_RELATIVE_SYMLINK === $expectedMethod) { $method = $this->relativeSymlinkWithFallback($originDir, $targetDir); } elseif (self::METHOD_ABSOLUTE_SYMLINK === $expectedMethod) { $method = $this->absoluteSymlinkWithFallback($originDir, $targetDir); } else { $method = $this->hardCopy($originDir, $targetDir); } if (self::METHOD_COPY === $method) { $copyUsed = true; } if ($method === $expectedMethod) { $rows[] = array(sprintf('<fg=green;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'OK' : "✔"), $message, $method); } else { $rows[] = array(sprintf('<fg=yellow;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'WARNING' : '!'), $message, $method); } } catch (\Exception $e) { $exitCode = 1; $rows[] = array(sprintf('<fg=red;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'ERROR' : "✘"), $message, $e->getMessage()); } } $io->table(array('', 'Bundle', 'Method / Error'), $rows); if (0 !== $exitCode) { $io->error('Some errors occurred while installing assets.'); } else { if ($copyUsed) { $io->note('Some assets were installed via copy. If you make changes to these assets you have to run this command again.'); } $io->success('All assets were successfully installed.'); } return $exitCode; }
/** * Actually cleans the database record fields with a new FlexForm as chosen currently for this record * * @param array $records * @param bool $dryRun * @param SymfonyStyle $io * @return void */ protected function cleanFlexFormRecords(array $records, bool $dryRun, SymfonyStyle $io) { $flexObj = GeneralUtility::makeInstance(FlexFormTools::class); // Set up the data handler instance $dataHandler = GeneralUtility::makeInstance(DataHandler::class); $dataHandler->dontProcessTransformations = true; $dataHandler->bypassWorkspaceRestrictions = true; $dataHandler->bypassFileHandling = true; // Setting this option allows to also update deleted records (or records on deleted pages) within DataHandler $dataHandler->bypassAccessCheckForRecords = true; // Loop through all tables and their records foreach ($records as $recordIdentifier => $fullRecord) { list($table, $uid, $field) = explode(':', $recordIdentifier); if ($io->isVerbose()) { $io->writeln('Cleaning FlexForm XML in "' . $recordIdentifier . '"'); } if (!$dryRun) { // Clean XML now $data = []; if ($fullRecord[$field]) { $data[$table][$uid][$field] = $flexObj->cleanFlexFormXML($table, $field, $fullRecord); } else { $io->note('The field "' . $field . '" in record "' . $table . ':' . $uid . '" was not found.'); continue; } $dataHandler->start($data, []); $dataHandler->process_datamap(); // Return errors if any: if (!empty($dataHandler->errorLog)) { $errorMessage = array_merge(['DataHandler reported an error'], $dataHandler->errorLog); $io->error($errorMessage); } elseif (!$io->isQuiet()) { $io->writeln('Updated FlexForm in record "' . $table . ':' . $uid . '".'); } } } }
/** * Write Finished Message * * @param SymfonyStyle $helper * @param string $commandName */ public static function writeFinishedMessage(SymfonyStyle $helper, $commandName) { $helper->newLine(2); $helper->note([sprintf('Executed %s', $commandName), sprintf('Done within %s seconds', round(microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"], 4))]); }
/** * Database Import * * @param SymfonyStyle $helper * * @return null */ private function actionDatabaseImport(SymfonyStyle $helper) { $timestamp = date('ymdHi'); /* * Select Host */ $remoteHost = $helper->ask('Remote host'); /* * Select external database (default: database_name) */ $remoteDatabase = $helper->ask('Remote database', $this->getContainer()->getParameter('database_name')); /* * Select local database (default: database_name) */ $localDatabase = $helper->ask('New local database', sprintf('%s_%s', $this->getContainer()->getParameter('database_name'), $timestamp)); /* * mysqldump */ $fileName = sprintf('%s_%s_%s.sql', $remoteDatabase, $timestamp, uniqid()); $command = sprintf('ssh %s "mysqldump %s > %s"', $remoteHost, $remoteDatabase, $fileName); $helper->comment($command); $process = new Process($command); $process->setTimeout(600); $process->run(function ($type, $buffer) use($helper) { if (Process::ERR === $type) { $helper->error($buffer); if (false !== strpos($buffer, 'Access denied')) { $helper->note('Missing .my.cnf for mysql access?'); } } else { $helper->comment($buffer); } }); /* * scp */ $command = sprintf('scp %s:%s %s/%s', $remoteHost, $fileName, sys_get_temp_dir(), $fileName); $helper->comment($command); $process = new Process($command); $process->setTimeout(300); $process->run(function ($type, $buffer) use($helper) { if (Process::ERR === $type) { $helper->error($buffer); } else { $helper->comment($buffer); } }); /* * create database database_name_ymdHis * if exists: ask for drop */ $command = sprintf('mysql -e "CREATE DATABASE %s;"', $localDatabase); $helper->comment($command); $process = new Process($command); $process->run(function ($type, $buffer) use($helper) { if (Process::ERR === $type) { $helper->error($buffer); if (false !== strpos($buffer, 'Access denied')) { $helper->note('Missing .my.cnf for mysql access?'); } } else { $helper->comment($buffer); } }); /* * mysql -D database_name_ymdhis < /backup/y-m-d_H-i-s_unique.sql */ $command = sprintf('mysql -D %s < %s/%s', $localDatabase, sys_get_temp_dir(), $fileName); $helper->comment($command); $process = new Process($command); $process->setTimeout(3600); $process->run(function ($type, $buffer) use($helper) { if (Process::ERR === $type) { $helper->error($buffer); } else { $helper->comment($buffer); } }); /** * Remove */ $command = sprintf('ssh %s "rm %s"', $remoteHost, $fileName); $helper->comment($command); $process = new Process($command); $process->run(function ($type, $buffer) use($helper) { if (Process::ERR === $type) { $helper->error($buffer); } else { $helper->comment($buffer); } }); $command = sprintf('%s/%s', sys_get_temp_dir(), $fileName); $helper->comment(sprintf('unlink %s', $command)); unlink($command); /** * Success! New database name: */ $helper->success(['Created new Database', $localDatabase]); return null; }
/** * Function to update the reference index * - if the option --update-refindex is set, do it * - otherwise, if in interactive mode (not having -n set), ask the user * - otherwise assume everything is fine * * @param InputInterface $input holds information about entered parameters * @param SymfonyStyle $io necessary for outputting information * @return void */ protected function updateReferenceIndex(InputInterface $input, SymfonyStyle $io) { // Check for reference index to update $io->note('Finding missing files referenced by TYPO3 requires a clean reference index (sys_refindex)'); if ($input->hasOption('update-refindex') && $input->getOption('update-refindex')) { $updateReferenceIndex = true; } elseif ($input->isInteractive()) { $updateReferenceIndex = $io->confirm('Should the reference index be updated right now?', false); } else { $updateReferenceIndex = false; } // Update the reference index if ($updateReferenceIndex) { $referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class); $referenceIndex->updateIndex(false, !$io->isQuiet()); } else { $io->writeln('Reference index is assumed to be up to date, continuing.'); } }
/** * Check if the core is up to date * * @param InputInterface $input Input stream, used to get the options. * @param SymfonyStyle $io IO handler, for formatted and unified IO * @param string $stability Force a given stability * @param bool $recheck Disallow the use of the cache * @return int */ protected function check_core(InputInterface $input, SymfonyStyle $io, $stability, $recheck) { $version_helper = $this->phpbb_container->get('version_helper'); $version_helper->force_stability($stability); $updates_available = $version_helper->get_suggested_updates($recheck); if ($input->getOption('verbose')) { $io->title('phpBB core'); $io->note($this->language->lang('CURRENT_VERSION') . $this->language->lang('COLON') . ' ' . $this->config['version']); } if (!empty($updates_available)) { $io->caution($this->language->lang('UPDATE_NEEDED')); if ($input->getOption('verbose')) { $this->display_versions($io, $updates_available); } return 1; } else { if ($input->getOption('verbose')) { $io->success($this->language->lang('UPDATE_NOT_NEEDED')); } return 0; } }
/** * @param string $message * @param string $channelId * @param SymfonyStyle $io * @param ProcessedSlackMessage $latest */ private function processMessage($message, $channelId, SymfonyStyle $io, ProcessedSlackMessage $latest) { if (null === $message) { return; } $data = json_decode($message); if (!(new AndX(new IsSlackMessage(), new IsHumanMessage(), new IsInChannel($channelId), new IsOriginalMessage(), new IsNotOld($latest->getDate())))->isSatisfiedBy($data)) { return; } try { $url = $this->container->get('parser.slack_message')->parseUrl($data->text); $tags = $this->container->get('parser.slack_message')->parseTags($data->text); $watchLink = $this->container->get('extractor.watch_link_metadata')->extract($url, $tags); $watchLink->setCreatedAt(\DateTime::createFromFormat('U.u', $data->ts)); $io->note('Parsing ' . $url); $processedMessage = new ProcessedSlackMessage($watchLink->getCreatedAt()); $this->container->get('doctrine')->getManager()->persist($watchLink); $this->container->get('doctrine')->getManager()->persist($processedMessage); $this->container->get('doctrine')->getManager()->flush(); } catch (\InvalidArgumentException $e) { $this->container->get('logger')->addNotice('Unable to insert watchlink', ['exception' => $e, 'message' => $data->text]); } catch (DriverException $e) { $this->container->get('logger')->addError('Database exception', ['exception' => $e, 'message' => $data->text]); exit(1); } catch (\Exception $e) { $this->container->get('logger')->addError('Unknow exception', ['exception' => $e, 'message' => $data->text]); } }
/** * @param $symbol */ private function write($symbol) { $this->io->note('Symbol to draw'); $this->io->write(AsciiHelper::renderSymbol($symbol)); $this->gitProcessor->writeSymbol($symbol, $this->lastSunday); }
/** * @param QueryRequest $query * @param SymfonyStyle $io * @param DateTime $date * @throws \QCharts\CoreBundle\Exception\WriteReadException */ protected function updateQuery(QueryRequest $query, SymfonyStyle $io, DateTime $date) { $modes = QueryUpdateCommand::getModes(); $dateFormat = SnapshotService::FILE_DATE_FORMAT; /** @var SnapshotService $snapshotService */ $snapshotService = $this->getContainer()->get("qcharts.core.snapshot_service"); /** @var QueryRepository $qrRepo */ $qrRepo = $this->getContainer()->get("qcharts.query_repo"); $cron = CronExpression::factory($query->getCronExpression()); $queryDate = $query->getConfig()->getFetchedOn()->format($dateFormat); $io->newLine(); $io->section("QCharts checking: '{$query->getTitle()}' with date: {$queryDate}"); if ($cron->isDue($date)) { //update it! $duration = $snapshotService->updateSnapshot($query); $io->newLine(1); $io->note("QCharts updating:"); $io->table(['Title', 'CronExpression', 'Last fetch', 'Mode', 'Query execution time'], [[$query->getTitle(), $query->getCronExpression(), $query->getConfig()->getFetchedOn()->format($dateFormat), $modes[$query->getConfig()->getIsCached()], "{$duration} secs."]]); $qrRepo->setUpdatedOn($query, $date); } $io->success("QCharts '{$query->getTitle()}' is up to date, next run: {$cron->getNextRunDate()->format($dateFormat)}"); $io->progressAdvance(1); $io->newLine(2); }
/** * @param InputInterface $input * @param OutputInterface $output * @return null */ protected function execute(InputInterface $input, OutputInterface $output) { // Get inputs $from = $input->getArgument('from'); $pjtname = $input->getArgument('pjtname'); // Important vars $container = $this->getContainer(); $router = $container->get('router'); $selfBaseUrl = $container->getParameter('spirit_dev_d_box_portal.app.self_base_url'); $em = $container->get('doctrine')->getManager(); $io = new SymfonyStyle($input, $output); // // API's $apiPM = $container->get('spirit_dev_dbox_portal_bundle.api.redmine'); $apiVCS = $container->get('spirit_dev_dbox_portal_bundle.api.gitlab'); $io->title(sprintf('Import project -- %s -- from -- %s --', $pjtname, $from)); $pmProject = null; $vcsProject = null; $dbProject = null; // Import values from PM if requested if ($from == 'pm' || $from == 'both') { $io->section('PM Check'); $pmProjectId = $apiPM->getProjectIdByName($pjtname); if (intval($pmProjectId)) { $tmpPjt = new Project(); $tmpPjt->setRedmineProjectId($pmProjectId); $pmProject = $apiPM->showProject($tmpPjt); $io->success('Project -- ' . $pjtname . ' -- found in PM'); $io->table(array('Name', 'Id', 'Identifier', 'description'), array(array($pmProject['project']['name'], $pmProject['project']['id'], $pmProject['project']['identifier'], empty($pmProject['project']['description']) ? "none" : $pmProject['project']['description']))); } else { $io->error('This project does not exists in PM, check value case'); if ($from != "both") { exit(0); } } } // Import values from VCS if requested if ($from == 'vcs' || $from == 'both') { $io->section('VCS Check'); $vcsProjectId = $apiVCS->getProjectIdByName($pjtname); if (intval($vcsProjectId)) { $vcsProject = $apiVCS->getProject($vcsProjectId); $io->success('Project -- ' . $pjtname . ' -- found in VCS'); $io->table(array('Name', 'Id', 'description', 'SSH Url', 'HTTP Url', 'WEB Url', 'Namespace', 'Issues', 'Wiki', 'Snippets'), array(array($vcsProject['name'], $vcsProject['id'], $vcsProject['description'], $vcsProject['ssh_url_to_repo'], $vcsProject['http_url_to_repo'], $vcsProject['web_url'], $vcsProject['path_with_namespace'], $vcsProject['issues_enabled'], $vcsProject['wiki_enabled'], $vcsProject['snippets_enabled']))); } else { $io->error('This project does not exists in VCS, check value case'); exit(0); } } // Check if project exists in db $io->section('DB Check'); $dbProject = $em->getRepository('SpiritDevDBoxPortalBundle:Project')->findOneBy(array('canonicalName' => strtolower($pjtname))); if ($dbProject) { $io->note('Project -- ' . $pjtname . ' -- already exists in database!'); $io->caution('Local DB Project will be update'); } else { $io->note('Project -- ' . $pjtname . ' -- does not exists in database!'); $io->note('A local DB Project will be created'); } // Starting import $io->section('Starting Importation'); if ($dbProject) { // Updating entity if ($input->getOption('force-update') && $io->confirm('Do you want to continue ?', true)) { // Import PM Values if ($from == "pm" || $from == "both") { $io->writeln('Importing from PM'); $dbProject->setRedmineProjectId($pmProject['project']['id']); $dbProject->setRedmineProjectIdentifier($pmProject['project']['identifier']); $dbProject->setRedmineWebUrl($apiPM->getProjectWebUrl($dbProject)); $io->writeln('Updating PM remote project'); $dbProject->setName($pjtname); $update = $apiPM->updateProject($dbProject); } // Import VCS Values if ($from == "vcs" || $from == "both") { $io->writeln('Importing from VCS'); $dbProject->setGitLabIssueEnabled($vcsProject['issues_enabled']); $dbProject->setGitLabWikiEnabled($vcsProject['wiki_enabled']); $dbProject->setGitLabSnippetsEnabled($vcsProject['snippets_enabled']); $dbProject->setGitLabProjectId($vcsProject['id']); $dbProject->setGitLabSshUrlToRepo($vcsProject['ssh_url_to_repo']); $dbProject->setGitLabHttpUrlToRepo($vcsProject['http_url_to_repo']); $dbProject->setGitLabWebUrl($vcsProject['web_url']); $dbProject->setGitLabNamespace($vcsProject['path_with_namespace']); $io->writeln('Updating VCS remote project'); // Create hooks $nbCommitHookUrl = $selfBaseUrl != 'none' ? $selfBaseUrl . "web_hook/update/nb_commit/" . $dbProject->getId() : $router->generate('spirit_dev_dbox_portal_bundle_webhook_pjt_update_nbcommits', array('pjt_id' => $dbProject->getId()), true); // var_dump($nbCommitHookUrl); $apiVCS->setProjectWebHook($dbProject, $nbCommitHookUrl); // Push hook to ci server $processor = $container->get('spirit_dev_dbox_admin_bundle.admin.processor'); $jenkinsUrl = $processor->defineJenkinsProjectUrl($dbProject); $apiVCS->setProjectWebHook($dbProject, $jenkinsUrl); } $io->writeln('Updating entity'); $dbProject->setName($pjtname); $dbProject->setActive(true); $em->flush(); $io->success('Done'); } else { $io->error('You may reload the command with the --force-update option'); $io->note('php app/console dbox:portal:pmvcs:import ' . $from . ' ' . $pjtname . ' --force-update'); exit(0); } } else { // Creating entity if ($input->getOption('force') && $io->confirm('Do you want to continue ?', true)) { $project = new Project(); // Import PM Values if ($from == "pm" || $from == "both") { $io->writeln('Importing from PM'); $project->setRedmineProjectId($pmProject['project']['id']); $project->setRedmineProjectIdentifier($pmProject['project']['identifier']); $project->setRedmineWebUrl($apiPM->getProjectWebUrl($project)); $io->writeln('Updating PM remote project'); $project->setName($pjtname); $update = $apiPM->updateProject($project); // dump($update); } // Import VCS Values if ($from == "vcs" || $from == "both") { $io->writeln('Importing from VCS'); $project->setGitLabIssueEnabled($vcsProject['issues_enabled']); $project->setGitLabWikiEnabled($vcsProject['wiki_enabled']); $project->setGitLabSnippetsEnabled($vcsProject['snippets_enabled']); $project->setGitLabProjectId($vcsProject['id']); $project->setGitLabSshUrlToRepo($vcsProject['ssh_url_to_repo']); $project->setGitLabHttpUrlToRepo($vcsProject['http_url_to_repo']); $project->setGitLabWebUrl($vcsProject['web_url']); $project->setGitLabNamespace($vcsProject['path_with_namespace']); $io->writeln('Updating VCS remote project'); // Create hooks $nbCommitHookUrl = $selfBaseUrl != 'none' ? $selfBaseUrl . "web_hook/update/nb_commit/" . $project->getId() : $router->generate('spirit_dev_dbox_portal_bundle_webhook_pjt_update_nbcommits', array('pjt_id' => $project->getId()), true); $apiVCS->setProjectWebHook($project, $nbCommitHookUrl); // Push hook to ci server $processor = $container->get('spirit_dev_dbox_admin_bundle.admin.processor'); $jenkinsUrl = $processor->defineJenkinsProjectUrl($project); $apiVCS->setProjectWebHook($project, $jenkinsUrl); } $io->writeln('Creating entity'); $project->setName($pjtname); $project->setActive(true); $em->persist($project); $em->flush(); $io->success('Done'); } else { $io->error('You may reload the command with the --force option'); $io->note('php app/console dbox:portal:pmvcs:import ' . $from . ' ' . $pjtname . ' --force'); exit(0); } } }